From ba96084da489d1f4b690320af348df2ecd1a219a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 03:31:50 +0000 Subject: [PATCH 1/8] tests: restore green main after the SDWA and UAV merges --- docs/experiments/direct-sdwa-profiles.md | 7 ++++--- tests/native_cvt_f16_i16_check.py | 3 ++- tests/native_sdwa_profiles_check.py | 3 ++- tools/startup/gfx2hlsl.py | 14 ++++++++++++++ tools/startup/triage_run.py | 1 + 5 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/experiments/direct-sdwa-profiles.md b/docs/experiments/direct-sdwa-profiles.md index 0190cfb3f9..09d6097443 100644 --- a/docs/experiments/direct-sdwa-profiles.md +++ b/docs/experiments/direct-sdwa-profiles.md @@ -33,8 +33,9 @@ SDWA validation is per operand, mirroring `place_subword` destination placement; no modifier or subword selection is silently ignored. -Still refused in SDWA: `v_sin_f16`/`v_cos_f16` (no direct lowering), -`v_fmac_f32`/`v_fmac_f16` and the rest of `VOP2_SDWA_UNSUPPORTED_OPS`, +The SDWA forms of `v_sin_f16`/`v_cos_f16` are covered by the separate +`native_sin_cos_f16` suite. Still refused in SDWA: `v_fmac_f32`/`v_fmac_f16` +and the rest of `VOP2_SDWA_UNSUPPORTED_OPS`, 64-bit `_f64`/`_b64` forms, and VOP3-only ops (`v_fma_f16`, `v_min3_f16`, `v_med3_f16`, `v_cvt_pknorm_*`). @@ -56,7 +57,7 @@ a second and third program (12, 28 and 6 slots, each under the 32-slot hardware layout) with an independent Python/ISA reference model, plus 15 refusal controls: disallowed VOP2 SDWA ops, float/int modifier violations, omod/clamp on integer destinations, invalid 16-bit destination selection and -unused mode, a byte source pick, literal 255, and `v_sin_f16`. The new +unused mode, a byte source pick, and literal 255. The new profiles also pin the `v_frexp_*_f32` SDWA source pick (a WORD_1 pick reads only the high half, so the picked value is a subnormal) and destination placement (a WORD destination keeps only the result's low half, with the diff --git a/tests/native_cvt_f16_i16_check.py b/tests/native_cvt_f16_i16_check.py index e92cc74afb..dc61801ef5 100644 --- a/tests/native_cvt_f16_i16_check.py +++ b/tests/native_cvt_f16_i16_check.py @@ -209,7 +209,8 @@ def refusal_programs(): programs = [] for op, (vop1_op, vop3_op, _, to_f16) in OPS.items(): programs.append(([vop1(vop1_op, 3, 250), 0xFF00B101, 0xBF810000], 'unsupported DPP arithmetic')) - programs.append(([vop1(vop1_op, 3, 249), 0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile')) + programs.append(([vop1(vop1_op, 3, 249), 0x06060601, 0xBF810000], + 'unsupported SDWA destination modifier')) programs.append((vop3_unary(vop3_op, 3, 257, omod=1) + [0xBF810000], f'unsupported {op} clamp or omod')) programs.append((vop3_unary(vop3_op, 3, 257, op_sel=1) + [0xBF810000], f'unsupported {op} high-half op_sel')) programs.append((vop3_unary(vop3_op, 3, 257, op_sel=8) + [0xBF810000], f'unsupported {op} high-half op_sel')) diff --git a/tests/native_sdwa_profiles_check.py b/tests/native_sdwa_profiles_check.py index 2e114e4aa2..9437c26be1 100644 --- a/tests/native_sdwa_profiles_check.py +++ b/tests/native_sdwa_profiles_check.py @@ -478,7 +478,8 @@ def refusal_cases(): (sdwa_instruction(profile("v_floor_f16", 0x5B, True, 0, src0=DWORD | 0x80, dst=WORD_0), reg0=255), "literal is unavailable in SDWA"), (sdwa_instruction(profile("v_fmac_f32", 0x2B, False, 0, 0)), SDWA_REFUSAL), - (sdwa_instruction(profile("v_sin_f16", 0x60, True, 0)), SDWA_REFUSAL), + # v_sin_f16/v_cos_f16 are admitted by the SDWA path since #3300; the + # separate native_sin_cos_f16 suite pins their positive forms. ) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 0c8bdee786..dbf459541a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -14081,6 +14081,20 @@ def stage_ok(s): fail_name = base_name + '.fail' fail_entry = files.get(fail_name) recheck = lost and (manifest_entry is not None) + + # A watch pass sees a request written after it started even when an + # earlier pass already recorded its failure. Keep that failure + # unchanged: retrying it every second would rewrite .fail and + # make its mtime look like new work. + if watch_since_ns is not None and fail_entry is not None and not recheck: + try: + fail_stat = fail_entry.stat() + if (fail_stat.st_mtime_ns > watch_since_ns and + fail_stat.st_mtime >= max(entry.stat().st_mtime, described or 0)): + continue + except OSError: + pass + if skip_failed and not recheck and fail_entry is not None: try: fail_mtime = fail_entry.stat().st_mtime diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 4ee978ed53..e22aa9fb29 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -178,6 +178,7 @@ 'an output UAV covers only part of a copied placement', 'an output UAV has no supported byte interval', 'an output UAV interval crosses the end of its buffer', + 'an output UAV interval exceeds the D3D12 buffer view element limit', 'an output UAV interval is empty', 'an output UAV interval is not 16-byte aligned in its buffer', 'an output UAV interval is not whole dwords', From 8dfc23d77b96c9539ef74ea20b0f0ceeaedbc09b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 03:28:54 +0000 Subject: [PATCH 2/8] gpu: sync both retire queues before the title settle case6 of startup_resource_retire_title releases the newer wrapper and calls settle() without waiting for the queues. Every release signals a release-time fence on each registered queue, and settle() only resubmits the drain list, so a fence that has not completed leaves both wrappers retained and the stage fails with retained=131072/2 against 65536/1. Sync the direct and gated queues before settle(), as #3457 did for startup_resource_retire. The expectation is unchanged. Refs #3507 --- tests/startup_resource_retire_title.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 23c4f51952..e172024908 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -880,6 +880,9 @@ bool case6_written_generation_preserved(Context& c, void* title_mem) std::puts("FAIL: releasing the newer wrapper erased metadata used by the older wrapper's live SRV"); return false; } + // The release above signalled a release-time fence on every registered queue, and the drains never wait for the + // GPU: let both queues pass before settle(), as the other stages do (#3507). + if (!c.sync(c.direct) || !c.sync(c.gated)) return false; Tnew.freed = true; if (!c.settle("newer wrapper retired with older SRV live", "newer wrapper kept or older SRV retired")) return false; if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 2 || bc7_width != side) { From 949a63ff2ec06325458653c87eb0c37d283a7116 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 03:53:09 +0000 Subject: [PATCH 3/8] shader: lower the exec-writing VOPC SDWA compares Lower the 62 v_cmpx_*_sdwa forms of gfx1013/rdna2 in the pixel translator, reusing the existing v_cmpx EXEC region opener. VOPC SDWA has no destination: the comparison writes EXEC, so the non-SDWA path is unchanged. Add draw-cmpx-sdwa (warp/hardware), the static controls and the coverage assertions, and teach the scanner the new spellings. Tests: draw-cmpx-sdwa warp/hardware, draw-cmpx-regions warp, draw-sdwa-cmp warp, form_coverage_check, rdna2_tools_check. Coverage: 62 of 62 forms in each reference; 1542/1968 gfx1013 and 1533/1863 gfx1030 in the 194-entry WARP replay. --- CMakeLists.txt | 5 + docs/experiments.md | 6 +- tests/form_coverage_check.py | 35 ++++++- tests/pixel_aot_check.py | 147 +++++++++++++++++++++++++++--- tests/rdna2_tools_check.py | 30 ++++-- tools/pixel_aot.py | 100 +++++++++++++++----- tools/scan_unsupported_shaders.py | 20 ++++ 7 files changed, 302 insertions(+), 41 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5da721cd70..900c79cd1a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11153,6 +11153,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_cmpx_e64_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_cmpx_e64_${adapter}.txt") + add_test(NAME pixel_aot_cmpx_sdwa_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-cmpx-sdwa "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_cmpx_sdwa_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_cmpx_sdwa_${adapter}.txt") add_test(NAME pixel_aot_region_body_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-region-body "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 1ff6eb7fe8..e83793ec84 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8927,7 +8927,9 @@ Scalar ALU support also covers the 64-bit SOP1/SOP2 family (`s_cmov_b64`, `s_not The SDWA forms of the 16 `v_cmp_*_f32` predicates are lowered when both `src0_sel` and `src1_sel` are `DWORD`. With whole-dword selections they compare the operands exactly as the e32/e64 forms do; the translator emits identical HLSL for both, and a control asserts it. A byte or word selection would compare a zero-extended field as binary32 and is refused. The predicate draws are repeated with the SDWA compares for all four groups and the same five input pairs, including NaN on either side. A reference that inverts each group's unordered result must report a mismatch. -The 46 non-`v_cmpx` VOPC SDWA comparisons left by lot 1a are lowered: the 16 binary16 predicates and `v_cmp_class_f16_sdwa`, `v_cmp_class_f32_sdwa`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA encodes only `src0_sel` and `src1_sel`; `llvm-mc` rejects `dst_sel`/`dst_unused` on these instructions, so the destination stays `vcc`/`vcc_lo` or one SGPR and the translator refuses an SGPR pair and the destination fields. Sources accept `BYTE_0..3`, `WORD_0..1` and `DWORD`, with `sext()` where LLVM prints it. The selection is zero-extended, or sign-extended under `sext()`, before the existing table applies: binary16 uses the low 16 bits through `widen16`/`num16`, the 16-bit integer forms take the low 16 bits, the 32-bit integer forms compare the selected word as signed or unsigned, and the class forms feed the selected bits to `class16` or `class32`. The comparison result is tracked in the same VCC/SGPR lane-mask state as the e32 and e64 forms, so `v_cndmask_b32` consumes it unchanged. The source-built fixture `tests/pixel_aot_check.py draw-sdwa-cmp` puts all 46 forms in one program, folds each predicate into two exported `R32G32B32A32_UINT` words, and repeats the rows with selections on every field. Its wrong references must each report `pixel_mismatch`: selections ignored (whole dwords), every field reversed (`BYTE_0`/`BYTE_3`, `BYTE_1`/`BYTE_2`, `WORD_0`/`WORD_1`), signedness inverted on the rows containing `0x8000`/`0xffff`, and zero extension in place of `sext()`. A second program writes two comparisons to `s52` and `vcc_lo` before consuming both; a reference that uses the second mask for both channels must mismatch. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts the 46 forms count in both `gfx1013.tsv` and `rdna2.tsv`, while the non-SDWA `v_cmp_*` neighbours and the `v_cmpx_*_sdwa` forms stay out. The same program is part of `check_binary`, so the LLVM 15 `Assemble and translate gfx1013 fixtures` job assembles, disassembles and re-translates it. On base `0aa6522c` the measurement moved from 1255/1968 to 1301/1968 on gfx1013 and from 1246/1863 to 1292/1863 on gfx1030, exactly 46 forms in each reference. The new tests passed on WARP and on `pixel_aot_sdwa_cmp_hardware` on an AMD Radeon RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075, in 1.10 s; the debug layer was unavailable. The separate `pixel_aot_comparisons_hardware` entry still fails on this adapter in its pre-existing strict binary32 subnormal comparison ([issue #958](https://github.com/R0Y00/Xbox2Windows/issues/958)); that failure is outside this lot and does not affect the SDWA draw. This measures translated fixtures, not console behavior or full title execution. Reproduce with `ctest --preset dev --no-tests=error -R '^pixel_aot_sdwa_cmp_' -V`; the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-sdwa-after.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-sdwa-after.xml --records out/build/dev/form_coverage --json out/wave1-sdwa-after.json`. A supplemental per-predicate fixture (`tests/pixel_aot_check.py draw-sdwa-int-compare`, tests `pixel_aot_sdwa_int_compare_{warp,hardware}`) exercises all 16 32-bit integer SDWA comparisons across four 4-channel groups (`i32_lo`, `i32_hi`, `u32_lo`, `u32_hi`) with 41 targeted single-channel negative controls plus static refusal checks for `low16` sources, pending loads, masked regions, float modifiers, `clamp` and SGPR pair destinations. +The 46 non-`v_cmpx` VOPC SDWA comparisons left by lot 1a are lowered: the 16 binary16 predicates and `v_cmp_class_f16_sdwa`, `v_cmp_class_f32_sdwa`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA encodes only `src0_sel` and `src1_sel`; `llvm-mc` rejects `dst_sel`/`dst_unused` on these instructions, so the destination stays `vcc`/`vcc_lo` or one SGPR and the translator refuses an SGPR pair and the destination fields. Sources accept `BYTE_0..3`, `WORD_0..1` and `DWORD`, with `sext()` where LLVM prints it. The selection is zero-extended, or sign-extended under `sext()`, before the existing table applies: binary16 uses the low 16 bits through `widen16`/`num16`, the 16-bit integer forms take the low 16 bits, the 32-bit integer forms compare the selected word as signed or unsigned, and the class forms feed the selected bits to `class16` or `class32`. The comparison result is tracked in the same VCC/SGPR lane-mask state as the e32 and e64 forms, so `v_cndmask_b32` consumes it unchanged. The source-built fixture `tests/pixel_aot_check.py draw-sdwa-cmp` puts all 46 forms in one program, folds each predicate into two exported `R32G32B32A32_UINT` words, and repeats the rows with selections on every field. Its wrong references must each report `pixel_mismatch`: selections ignored (whole dwords), every field reversed (`BYTE_0`/`BYTE_3`, `BYTE_1`/`BYTE_2`, `WORD_0`/`WORD_1`), signedness inverted on the rows containing `0x8000`/`0xffff`, and zero extension in place of `sext()`. A second program writes two comparisons to `s52` and `vcc_lo` before consuming both; a reference that uses the second mask for both channels must mismatch. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts the 46 forms count in both `gfx1013.tsv` and `rdna2.tsv`, while the non-SDWA `v_cmp_*` neighbours stay out (the exec-writing `v_cmpx_*_sdwa` forms follow in lot 1b). The same program is part of `check_binary`, so the LLVM 15 `Assemble and translate gfx1013 fixtures` job assembles, disassembles and re-translates it. On base `0aa6522c` the measurement moved from 1255/1968 to 1301/1968 on gfx1013 and from 1246/1863 to 1292/1863 on gfx1030, exactly 46 forms in each reference. The new tests passed on WARP and on `pixel_aot_sdwa_cmp_hardware` on an AMD Radeon RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075, in 1.10 s; the debug layer was unavailable. The separate `pixel_aot_comparisons_hardware` entry still fails on this adapter in its pre-existing strict binary32 subnormal comparison ([issue #958](https://github.com/R0Y00/Xbox2Windows/issues/958)); that failure is outside this lot and does not affect the SDWA draw. This measures translated fixtures, not console behavior or full title execution. Reproduce with `ctest --preset dev --no-tests=error -R '^pixel_aot_sdwa_cmp_' -V`; the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-sdwa-after.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-sdwa-after.xml --records out/build/dev/form_coverage --json out/wave1-sdwa-after.json`. A supplemental per-predicate fixture (`tests/pixel_aot_check.py draw-sdwa-int-compare`, tests `pixel_aot_sdwa_int_compare_{warp,hardware}`) exercises all 16 32-bit integer SDWA comparisons across four 4-channel groups (`i32_lo`, `i32_hi`, `u32_lo`, `u32_hi`) with 41 targeted single-channel negative controls plus static refusal checks for `low16` sources, pending loads, masked regions, float modifiers, `clamp` and SGPR pair destinations. + +Lot 1b lowers the remaining 62 exec-writing VOPC SDWA comparisons: the 16 binary32 predicates (whole-dword selections only, as their `v_cmp` forms), the 16 binary16 predicates, `v_cmpx_class_f16` and `v_cmpx_class_f32`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA prints no destination and encodes no `dst_sel`/`dst_unused`: the comparison writes EXEC, so each form reuses the existing `v_cmpx` region opener unchanged (the `s_mov_b64 s[a:b], exec` save, the entry-mask intersection, the SKIP/else handling and the two closes), and the non-SDWA path is untouched. Selections are the same `BYTE_0..3`, `WORD_0..1` and `DWORD` fields, zero-extended or sign-extended under `sext()`, applied before the e32 table. The fixture `draw-cmpx-sdwa` (`pixel_aot_cmpx_sdwa_{warp,hardware}`) opens one region per form and adds an exact power of two to one of three exported binary32 accumulators (24 bits per channel, so every partial sum is an exact integer below 2^24); its wrong references must each mismatch: selections ignored, every field reversed, signedness inverted, zero extension instead of `sext()`, and the region applied to every lane. Static controls refuse a missing or non-adjacent EXEC save, `dst_sel`/`dst_unused`, an SGPR pair in the source position, byte/word selections on an f32 predicate, and the nonexistent 64-bit SDWA exec writers. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts its 62 forms are exactly the SDWA `v_cmpx` family of both references, while the non-SDWA exec writers and the `v_cmp_*_sdwa` forms stay out. The same program is part of `check_binary`. The 194-entry WARP replay (`pixel_aot_`/`compute_store_aot_`, `_hardware` excluded) passes with no failure or skip and measures 1542/1968 on gfx1013 and 1533/1863 on gfx1030; removing the 62 forms of this lot leaves 1480/1968 and 1471/1863. The targeted WARP and hardware runs pass on the AMD Radeon RX 9060 XT (driver 32.0.32029.2010); `draw-cmpx-regions` and `draw-sdwa-cmp` also pass on both adapters. This measures translated fixtures, not console behavior or full title execution. Reproduce the target with `python -B tests/pixel_aot_check.py draw-cmpx-sdwa warp` (or `hardware`), `tests/pixel_aot_check.py draw-cmpx-regions`, `tests/pixel_aot_check.py draw-sdwa-cmp` and `python -B tests/form_coverage_check.py`; in a configured tree the CTest entry is `ctest --preset dev --no-tests=error -R '^pixel_aot_cmpx_sdwa_' -V`, and the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-cmpx-sdwa.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-cmpx-sdwa.xml --records out/build/dev/form_coverage --json out/wave1-cmpx-sdwa.json`. In this worktree the CMake configure stops in the `opus` dependency (`LNK1104: m.lib`) before any target, so the 194-entry run replayed the main build's CTest command list with this tree's tests and the main build's `offscreen_check.exe`; the replay helper is untracked under `out/coverage-run/`. Binary32 floating-point vector comparisons (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f32` in e32, e64, and whole-dword SDWA forms) evaluate the 16 IEEE-754 relations against scalar and vector operands, including subnormals, signed zeroes, infinities, and quiet/signaling NaNs. The e32 (VOPC) encoding requires destination `vcc` or `vcc_lo`; SGPR destinations (`s52`, `s[52:53]`) are accepted on suffix-less and explicit `_e64` (VOP3) encodings. Source modifiers (`neg`, `abs`) are accepted on e64 operands (`-s44`, `|v18|`, `-|s44|`), while `clamp` and `op_sel` remain rejected on comparisons. Rejection controls verify that untracked source registers, SGPR destinations on explicit e32, and sub-dword SDWA selections (`src0_sel:WORD_0`, `src1_sel:BYTE_2`) raise `ValueError`. The synthetic fixture `f32_compares()` verifies all 16 predicates across e32, e64, and whole-dword SDWA, validating them against an exact reference oracle (`f32_compares_reference()`). Mutating predicates or modifiers produces a mismatch. @@ -8973,7 +8975,7 @@ The SDWA forms of the exact arithmetic (`add`, `sub`, `subrev`, `mul`, `mul_lega The SDWA forms of the remaining unary binary32 operations (`v_exp_f32`, `v_log_f32`, `v_rcp_f32`, `v_rcp_iflag_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_sin_f32`, `v_cos_f32`, `v_rndne_f32` and `v_frexp_mant_f32`) go through the same path: each reuses its e32/e64 lowering unchanged, with `src0_sel:DWORD` only, and the result is placed with the SDWA move rules. The translator emits the same shader for the whole-dword SDWA spelling and the e32 spelling of each operation, and the controls assert that. A byte or word source, a `src1_sel`, a second operand, an output modifier, `UNUSED_SEXT` on a partial destination and `UNUSED_PRESERVE` over an untracked destination are refused for every one of the ten. Three programs are drawn with two constant rows each. D3D allows `exp2`, `log2`, a reciprocal, `rsqrt`, `sqrt`, `sin` and `cos` an error, so the first two programs choose inputs whose true result is an integer, add 0.5 and take the floor, which returns that integer for any result within 0.5 of it: exp of `-A`, log of `|B|`, rcp of C and rcp_iflag of `-|D|` give 8, 5, 8, -4 and then 16, 3, -2, -16; rsq of `|A|`, sqrt of B, sin of C and cos of `-D` (in revolutions) give 4, 7, 1, -1 and then 2, 3, -1, 1. That checks which operation ran and its source modifiers, not last-place accuracy. The third program is exact and is compared directly: `v_rndne_f32_sdwa` of the ties 2.5 and -3.5 (2 and -4), `v_frexp_mant_f32_sdwa` of `-B` with `clamp`, the low byte of a rounded tie kept in `BYTE_2` of 1.0 under `UNUSED_PRESERVE`, and the low byte of a significand padded into `BYTE_3`. 26 wrong references, each replacing one channel, must report `pixel_mismatch`: a neighbouring operation for each approximate one (natural exponential and logarithm, rsq for rcp, sqrt and rcp for rsq, rsq for sqrt, sin and cos swapped, radians for revolutions), a copied source, a dropped negation, ties rounded up or toward zero, a dropped clamp, padding for preserving, the neighbouring byte and an unplaced result. That is 32 draws from three compiles and three renderer launches. They run as their own tests, `pixel_aot_sdwa_unary_hardware` and `pixel_aot_sdwa_unary_warp` (`tests/pixel_aot_check.py draw-sdwa-unary`), with their own coverage record, and the LLVM 15 round trip covers the three programs. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466), debug layer enabled with no errors or warnings. Not shown: last-place accuracy of the approximate operations on any adapter, a partial destination for an approximate result (its low bits have no single reference), inputs outside these rows (zero, negative arguments to log, rsq and sqrt, infinities, NaN, denormals), the integer-divide flag of `v_rcp_iflag_f32`, and what the console computes. -Signed and unsigned 16-bit integer comparisons (`v_cmp_{eq,ne,lt,le,gt,ge}_{i16,u16}` in e32 and e64 encodings) compare only the low 16 bits of each source: the lowering sign-extends them with `asint(x << 16) >> 16` or masks them with `& 0xffff`, and the result feeds `v_cndmask_b32` through the same tracked lane mask as the other comparisons. A source may be a register, an integer inline constant from -16 to 64 or a literal up to `0xffff`. LLVM prints a float inline constant on a 16-bit integer operand as its binary16 literal (`1.0` as `0x3c00`), so float tokens, wider literals, source modifiers, `clamp` and `op_sel` are refused. The exec-writing `v_cmpx_*` forms stay rejected outside the `v_cmpx` region openers described above, which admit the e32 integer forms (the f16 comparisons and `v_cmp_class_f16` are lowered by their own branches in `tools/pixel_aot.py`), and `tests/form_coverage_check.py` asserts that all 24 16-bit integer forms, the 32 32-bit integer forms, the 32 64-bit integer forms, and the 34 binary16 and 34 binary32 floating-point forms (156 compare forms in all) are counted while those neighbours are not. The binary fixtures cover the 24 forms, and the draws (`tests/pixel_aot_check.py draw-comparisons`) evaluate all six predicates per kind and encoding on six word pairs. Each word is a normal binary32 value whose upper half differs from the lower one where a 32-bit comparison would disagree, and the pairs include `0x8000` against 0, equal low halves, -1 against 1, `0x7fff` against `0x8000` and both ends of the inline-constant range. Three references must report a pixel mismatch: a signed shader against the unsigned reference, `eq` replaced by `ne`, and a 32-bit comparison against the 16-bit reference on equal low halves. +Signed and unsigned 16-bit integer comparisons (`v_cmp_{eq,ne,lt,le,gt,ge}_{i16,u16}` in e32 and e64 encodings) compare only the low 16 bits of each source: the lowering sign-extends them with `asint(x << 16) >> 16` or masks them with `& 0xffff`, and the result feeds `v_cndmask_b32` through the same tracked lane mask as the other comparisons. A source may be a register, an integer inline constant from -16 to 64 or a literal up to `0xffff`. LLVM prints a float inline constant on a 16-bit integer operand as its binary16 literal (`1.0` as `0x3c00`), so float tokens, wider literals, source modifiers, `clamp` and `op_sel` are refused. The exec-writing `v_cmpx_*` forms are admitted only by the `v_cmpx` region openers described above, which cover the e32 and e64 forms (the f16 comparisons and `v_cmp_class_f16` have their own branches in `tools/pixel_aot.py`) and, since lot 1b, the SDWA forms. `tests/form_coverage_check.py` asserts that all 24 16-bit integer forms, the 32 32-bit integer forms, the 32 64-bit integer forms, and the 34 binary16 and 34 binary32 floating-point forms (156 compare forms in all) are counted while the rejected non-SDWA neighbours are not; the 62 SDWA exec writers are counted separately by `check_cmpx_sdwa_coverage`. The binary fixtures cover the 24 forms, and the draws (`tests/pixel_aot_check.py draw-comparisons`) evaluate all six predicates per kind and encoding on six word pairs. Each word is a normal binary32 value whose upper half differs from the lower one where a 32-bit comparison would disagree, and the pairs include `0x8000` against 0, equal low halves, -1 against 1, `0x7fff` against `0x8000` and both ends of the inline-constant range. Three references must report a pixel mismatch: a signed shader against the unsigned reference, `eq` replaced by `ne`, and a 32-bit comparison against the 16-bit reference on equal low halves. Signed and unsigned 64-bit integer comparisons (`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i64,u64}` in e32, suffix-less and e64 spellings, [#794](https://github.com/R0Y00/Xbox2Windows/issues/794)) compare two words per source, so the HLSL needs no 64-bit type. Without a suffix the encoding is chosen as LLVM 15 does: e32 when the destination is `vcc`/`vcc_lo` and src1 is a VGPR pair, e64 otherwise. The high words decide unless they are equal, and then the low words, which always compare unsigned. A signed comparison reads only the high word as `int`. Every word is read as raw bits with `asuint` (`asint` for a signed high word), bound to a local before the comparison, and no arithmetic touches a float view. The result is a tracked lane condition like the other comparisons, so `v_cndmask_b32` consumes it unchanged. A source is a VGPR pair `v[a:a+1]` with `a` from 0 to 254 whose two registers hold tracked numbers, an even-aligned SGPR pair, or an integer inline constant from -16 to 64 sign-extended to 64 bits (`-1` is all ones). On e32 (VOPC) the destination must be `vcc_lo` or `vcc` and src1 must be a VGPR pair, because LLVM 15 rejects an SGPR there. On e64 the destination is `vcc_lo`, `vcc`, an SGPR or an aligned SGPR pair, as for the narrower comparisons, and the wave64 spellings (`vcc`, `s[52:53]`) lower to the same HLSL as the wave32 ones. Refused with a message that names the cause: 32-bit literals, float and hex tokens, constants outside -16..64, register ranges other than a pair, untracked or pending sources, an SGPR destination or SGPR src1 on e32, and misaligned or out-of-range SGPR pairs. Source modifiers, `clamp`, `op_sel`, the `v_cmpx_*` forms, f64 and the unsupported predicates, and the DPP and SDWA forms are refused with the generic `Unsupported instruction` message, which does not name the cause. The 32-bit literal extension rule is not sourced, so literals stay outside this change; refusing float inline constants (LLVM accepts `1.0`) is the translator's choice. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index e46a275565..73533b4874 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -479,7 +479,12 @@ def check_shader_records(): assert compare_forms <= covered, (name, sorted(compare_forms - covered)) assert not {form for _, form in covered} & (compare_neighbours | {f"{n}_e64" for n in compare_neighbours}) assert cmpx_forms <= reference and cmpx_forms <= covered, (name, sorted(cmpx_forms - covered)) - assert {form for _, form in covered if form.startswith("v_cmpx_")} == {form for _, form in cmpx_forms}, name + # The non-SDWA v_cmpx family is the 190 forms above; the 62 exec-writing SDWA forms are a separate + # family, checked by check_cmpx_sdwa_coverage and counted here from the same control run. + assert {form for _, form in covered + if form.startswith("v_cmpx_") and not form.endswith("_sdwa")} == {form for _, form in cmpx_forms}, name + assert {form for _, form in covered if form.startswith("v_cmpx_") and form.endswith("_sdwa")} == \ + {entry["form"] for entry in pixel.CMPX_SDWA_FORMS}, name # The scalar ALU fixture counts its SOP1, SOP2, SOPK and SOPC forms; the neighbours the controls # reject (s_addc_u32, s_cmp_lt_u64) stay out; s_getreg_b32 joined the accepted forms with the mode-register fixture. scalar = {"s_movk_i32", "s_cmovk_i32", "s_not_b32", "s_add_u32", "s_sub_u32", "s_add_i32", "s_sub_i32", @@ -1422,6 +1427,33 @@ def check_sdwa_cmp_coverage(): assert ("SDWA", "v_cmp_lt_f16_sdwa") not in fc.gfx_forms(stripped, reference), name +def check_cmpx_sdwa_coverage(): + """The 62 exec-writing VOPC SDWA comparisons are the complete SDWA v_cmpx family of both references, + counted from this fixture's accepted words. The non-SDWA exec writers and the v_cmp SDWA forms stay out.""" + import pixel_aot_check as pixel + wanted = {("SDWA", entry["form"]) for entry in pixel.CMPX_SDWA_FORMS} + assert len(wanted) == 62 + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + pixel.translate(pixel.uncompressed_export(pixel.cmpx_sdwa_body())) + accepted = set(pixel.ACCEPTED) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + assert not {form for form in accepted if form.startswith("v_cmp_")} + assert not {form for form in accepted if form.startswith("v_cmpx_") and not form.endswith("_sdwa")} + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + family = {entry for entry in reference if entry[0] == "SDWA" and entry[1].startswith("v_cmpx_")} + assert family == wanted, (name, sorted(family ^ wanted)) + covered = fc.gfx_forms(accepted, reference) + assert wanted <= covered, (name, sorted(wanted - covered)) + # Control: removing one accepted SDWA word removes exactly that form from the count. + stripped = accepted - {"v_cmpx_lt_f16_sdwa"} + assert ("SDWA", "v_cmpx_lt_f16_sdwa") not in fc.gfx_forms(stripped, reference), name + + def check_dpp_f16_arith_round_forms(): """The 16 quad-local DPP16/DPP8 binary16 arithmetic and rounding forms count as covered once the translator accepts their fixtures; unlowered f16 DPP/SDWA neighbours stay uncovered.""" @@ -1722,6 +1754,7 @@ def check_f16_cvt_norm_forms(): check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() + check_cmpx_sdwa_coverage() check_sopk_wait_forms() check_s_version_form() check_parsing() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index e5cc0628c3..3e4a3f37a9 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -4876,6 +4876,15 @@ def check_sdwa_predicate_draws(directory, compiler, renderer, backend): for entry in SDWA_CMP_FORMS) assert len(SDWA_CMP_FORMS) == 46 +# The 62 exec-writing VOPC SDWA comparisons of lot 1b: the same 46 forms as v_cmpx (no destination operand) +# plus the 16 binary32 predicates, which take whole-dword selections as their v_cmp forms do. +CMPX_SDWA_FORMS = (tuple({"form": f"v_cmpx_{op}_f32_sdwa", "kind": "f32", "op": op, + "sel0": "DWORD", "sel1": "DWORD", "sext0": False, "sext1": False} + for op in PREDICATES) + + tuple(dict(entry, form="v_cmpx_" + entry["form"][len("v_cmp_"):]) + for entry in SDWA_CMP_FORMS)) +assert len(CMPX_SDWA_FORMS) == 62 and len({entry["form"] for entry in CMPX_SDWA_FORMS}) == 62 + # Runtime words: s44 is A and s45/v18 is B. Their byte, word and dword fields disagree, and the signed # rows put 0x8000/0xffff in the selected halves so a signedness or selection error changes a bit. SDWA_CMP_WORDS = ( @@ -4924,8 +4933,7 @@ def f16_bits_value(bits): return struct.unpack(" and open the v_cmpx EXEC region that it masks.""" + lines.append(f" bool cmp{index} = {expr};") + for reg in pair: + scalar[reg] = ("exec_saved",) + vector.masked = True + scalar.masked = True + return {"save": pair, "cond": f"cmp{index}", "written": {}, "skip": None, "start": index, + "arm_start": index, "else": None, "then": {}, "else_written": {}, + "else_undefined": set(), "skipped": False, "scalar_written": set(), "scc_written": False, + "opener": "cmpx", "width": width, + "arm_outstanding": (set(pending), dict(sample_dest))} + + +def cmpx_save_pair(saved, region, mask, scalar): + """The pair and width of a v_cmpx EXEC save, refusing a missing save or a non-entry mask.""" + if (region is not None or mask != "entry" or saved is None + or [scalar.get(r) for r in saved[0]] != saved[2]): + raise ValueError("Unsupported v_cmpx execution mask save") + return saved[0], saved[1] # Binary32 arithmetic with SDWA forms on gfx1013 (docs/coverage/gfx1013.tsv): the exact operations, then the # remaining unary ones. Each reuses its e32/e64 entry in ALU unchanged. SDWA_ALU = ("add", "sub", "subrev", "mul", "mul_legacy", "max", "min", "floor", "ceil", "fract", "trunc", @@ -4328,18 +4363,7 @@ def match(pattern): fop, iop, kind, op16, kind16, cls, hop, hcls, f64op, enc, src0, src1 = m.groups() if op16 is not None: iop, kind = op16, kind16 - previous = instructions[i - 1] if i else "" - previous = previous[1] if isinstance(previous, tuple) else previous - saved = re.fullmatch(r"s_mov_b64 (s\[\d+:\d+\]), exec", previous) - pair = sgpr_pair(saved[1]) if saved else None - width, entry = 64, [("entry", 0), ("entry", 1)] - # A wave32 guest saves exec_lo, its whole EXEC, into one SGPR; the save branch already refused it - # without the wave32 profile. The region then closes and switches with the wave32 spellings. - if pair is None and guest_wave32 and (saved32 := re.fullmatch(r"s_mov_b32 (s\d+), exec_lo", previous)): - pair, width, entry = [saved32[1]], 32, [("entry", "w32")] - if (region is not None or mask != "entry" or pair is None - or [scalar.get(r) for r in pair] != entry): - raise ValueError("Unsupported v_cmpx execution mask save") + pair, width = cmpx_save_pair(cmpx_exec_save(instructions, i, guest_wave32), region, mask, scalar) # VOPC e32 encodes VSRC1 as a VGPR (a VGPR pair at 64 bits) and carries no source modifiers. wide = kind in ("i64", "u64") or f64op not in (None, "class") vsrc1 = r"v\[\d+:\d+\]" if wide else r"v\d+" @@ -4376,15 +4400,49 @@ def match(pattern): values = [read(t, scalar, vector, pending, sample_dest, signed=kind in ("i32", "i16")) for t in (src0, src1)] expr = INT_COMPARE[iop].format(*values) - lines.append(f" bool cmp{i} = {expr};") - for reg in pair: - scalar[reg] = ("exec_saved",) - region = {"save": pair, "cond": f"cmp{i}", "written": {}, "skip": None, "start": i, "arm_start": i, "else": None, "then": {}, "else_written": {}, - "else_undefined": set(), "skipped": False, - "scalar_written": set(), "scc_written": False, "opener": "cmpx", "width": width, - "arm_outstanding": (set(pending), dict(sample_dest))} - vector.masked = True - scalar.masked = True + region = open_cmpx_region(i, lines, expr, pair, width, pending, sample_dest, vector, scalar) + elif m := match(rf"v_cmpx_({'|'.join(COMPARE)})_f32_sdwa ([^,]+), ([^,]+)" + r" src0_sel:DWORD src1_sel:DWORD"): + # A VOPC SDWA compare that writes EXEC (issue #932). VOPC SDWA encodes only the two source + # selections and no destination: the comparison writes EXEC, which becomes the entry mask + # intersected with the predicate. With whole-dword selections the f32 form is the e32 one; + # byte and word selections would compare zero-extended fields as binary32 and are refused. + op, src0, src1 = m.groups() + pair, width = cmpx_save_pair(cmpx_exec_save(instructions, i, guest_wave32), region, mask, scalar) + tokens = [SDWA_NEG_DECIMAL.sub(r"-\1", token) for token in (src0, src1)] + expr = f32_comparison(op, tokens, scalar, vector, pending, sample_dest) + region = open_cmpx_region(i, lines, expr, pair, width, pending, sample_dest, vector, scalar) + elif m := match(rf"v_cmpx_((?:{'|'.join(COMPARE)})_f16|class_(?:f16|f32)" + rf"|(?:{'|'.join(INT_COMPARE)})_(?:i32|u32)" + rf"|(?:eq|ne|lt|le|gt|ge)_(?:i16|u16))_sdwa (.+)"): + # The remaining VOPC SDWA exec writers: every binary16 predicate and class test, the 32-bit + # signed and unsigned predicates and the six 16-bit relations, each applying its source + # selections before the e32 table. The region opens exactly as the non-SDWA v_cmpx path does. + form, rest = m.groups() + pair, width = cmpx_save_pair(cmpx_exec_save(instructions, i, guest_wave32), region, mask, scalar) + (src0, sel0, sext0), (src1, sel1, sext1) = sdwa_cmp_operands(rest) + if form.startswith("class_"): + kind = form[len("class_"):] + value = sdwa_cmp_bits(src0, sel0, sext0, scalar, vector, pending, sample_dest, + f16=kind == "f16") + classes = sdwa_cmp_bits(src1, sel1, sext1, scalar, vector, pending, sample_dest, f16=False) + expr = (f16_class_bits(value, classes) if kind == "f16" + else f"(class32(asfloat({value})) & {classes}) != 0u") + elif form.endswith("_f16"): + raw = [sdwa_cmp_bits(src0, sel0, sext0, scalar, vector, pending, sample_dest, f16=True), + sdwa_cmp_bits(src1, sel1, sext1, scalar, vector, pending, sample_dest, f16=True)] + expr = f16_comparison_bits(form[:-len("_f16")], raw) + else: + op, kind = form.rsplit("_", 1) + raw = [sdwa_cmp_bits(src0, sel0, sext0, scalar, vector, pending, sample_dest, f16=False), + sdwa_cmp_bits(src1, sel1, sext1, scalar, vector, pending, sample_dest, f16=False)] + if kind in ("i32", "u32"): + values = [f"asint({word})" if kind == "i32" else word for word in raw] + else: + values = [f"(asint({word} << 16) >> 16)" if kind == "i16" else f"({word} & 0xffffu)" + for word in raw] + expr = INT_COMPARE[op].format(*values) + region = open_cmpx_region(i, lines, expr, pair, width, pending, sample_dest, vector, scalar) elif m := S_CALL.fullmatch(line): # The inlined call (inline_calls): the pair receives the address after the call, an opaque value that # only the removed s_setpc_b64 consumed. Neither the callee nor the code after it may name either word. diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 43ffd88784..6fc5cbc3dc 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -233,6 +233,18 @@ def lower_rejection_causes(results: list[dict]) -> dict: SUPPORTED_INSTRUCTIONS_REGEX.append( rf"v_cmp_(?:{cmp_ops})_f32_sdwa\s+{PIXEL_LANE_MASK},\s+[^,]+,\s+[^,]+\s+src0_sel:DWORD\s+src1_sel:DWORD" ) + # The exec-writing VOPC SDWA forms print no destination: the predicate writes EXEC. + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_cmpx_(?:{cmp_ops})_f32_sdwa\s+[^,]+,\s+[^,]+\s+src0_sel:DWORD\s+src1_sel:DWORD" + ) + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_cmpx_(?:{cmp_ops})_f16_sdwa\s+{SDWA_CMP_SOURCE},\s+{SDWA_CMP_SOURCE}" + rf"\s+src0_sel:{SDWA_SEL_PATTERN}\s+src1_sel:{SDWA_SEL_PATTERN}" + ) + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_cmpx_class_(?:f16|f32)_sdwa\s+{SDWA_CMP_SOURCE},\s+{SDWA_CMP_SOURCE}" + rf"\s+src0_sel:{SDWA_SEL_PATTERN}\s+src1_sel:{SDWA_SEL_PATTERN}" + ) SUPPORTED_INSTRUCTIONS_REGEX.append( rf"v_cmp_(?:{cmp_ops})_f16{PIXEL_VOPC_E32_DST},\s+{F16_PLAIN},\s+{F16_PLAIN}" ) @@ -257,10 +269,18 @@ def lower_rejection_causes(results: list[dict]) -> dict: rf"v_cmp_(?:{icmp_ops})_(?:i32|u32)_sdwa\s+{PIXEL_SDWA_DST},\s+{SDWA_CMP_SOURCE},\s+{SDWA_CMP_SOURCE}" rf"\s+src0_sel:{SDWA_SEL_PATTERN}\s+src1_sel:{SDWA_SEL_PATTERN}" ) + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_cmpx_(?:{icmp_ops})_(?:i32|u32)_sdwa\s+{SDWA_CMP_SOURCE},\s+{SDWA_CMP_SOURCE}" + rf"\s+src0_sel:{SDWA_SEL_PATTERN}\s+src1_sel:{SDWA_SEL_PATTERN}" + ) SUPPORTED_INSTRUCTIONS_REGEX.append( rf"v_cmp_(?:eq|ne|lt|le|gt|ge)_(?:i16|u16)_sdwa\s+{PIXEL_SDWA_DST},\s+{SDWA_CMP_SOURCE},\s+{SDWA_CMP_SOURCE}" rf"\s+src0_sel:{SDWA_SEL_PATTERN}\s+src1_sel:{SDWA_SEL_PATTERN}" ) + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_cmpx_(?:eq|ne|lt|le|gt|ge)_(?:i16|u16)_sdwa\s+{SDWA_CMP_SOURCE},\s+{SDWA_CMP_SOURCE}" + rf"\s+src0_sel:{SDWA_SEL_PATTERN}\s+src1_sel:{SDWA_SEL_PATTERN}" + ) # 64-bit comparisons are checked by supports_int64_compare() below: the pair and inline ranges are numeric. INT64_COMPARE_PATTERN = re.compile( rf"v_cmp_(?:{icmp_ops})_(?:i64|u64)(_e32|_e64)?\s+(vcc(?:_lo)?|s\d+|s\[\d+:\d+\]),\s+(\S+),\s+(\S+)" From 0f54799475cbbbe9087fb81cea8d31a2855fef75 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 04:02:00 +0000 Subject: [PATCH 4/8] tests: put the cmpx SDWA addend in src0 --- tests/pixel_aot_check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 3e4a3f37a9..17db72a9b0 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -5189,7 +5189,7 @@ def cmpx_sdwa_body(): for index, entry in enumerate(CMPX_SDWA_FORMS): channel, bit = divmod(index, 24) body += [CMPX_SAVE, cmpx_sdwa_instruction(entry), - f"v_add_f32_e32 v{13 + channel}, v{13 + channel}, {(127 + bit) << 23:#x}", + f"v_add_f32_e32 v{13 + channel}, {(127 + bit) << 23:#x}, v{13 + channel}", CMPX_MOV_RESTORE] return body From 3600208e30f6bd3dba9651af246ddadafdc3cd01 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 04:08:46 +0000 Subject: [PATCH 5/8] tests: define the cmpx SDWA addend outside the region --- tests/pixel_aot_check.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 17db72a9b0..cfc57dc8a4 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -5188,8 +5188,9 @@ def cmpx_sdwa_body(): body += [f"v_mov_b32_e32 v{13 + channel}, 0" for channel in range(3)] for index, entry in enumerate(CMPX_SDWA_FORMS): channel, bit = divmod(index, 24) - body += [CMPX_SAVE, cmpx_sdwa_instruction(entry), - f"v_add_f32_e32 v{13 + channel}, {(127 + bit) << 23:#x}, v{13 + channel}", + body += [f"v_mov_b32_e32 v16, {(127 + bit) << 23:#x}", + CMPX_SAVE, cmpx_sdwa_instruction(entry), + f"v_add_f32_e32 v{13 + channel}, v{13 + channel}, v16", CMPX_MOV_RESTORE] return body From f83514b76b90535304694e85630e13e63684b21b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 04:19:51 +0000 Subject: [PATCH 6/8] tests: keep the cmpx SDWA addends out of inline constants --- docs/experiments.md | 2 +- tests/pixel_aot_check.py | 32 +++++++++++++++++++------------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index e83793ec84..369e8c4fb7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8929,7 +8929,7 @@ The SDWA forms of the 16 `v_cmp_*_f32` predicates are lowered when both `src0_se The 46 non-`v_cmpx` VOPC SDWA comparisons left by lot 1a are lowered: the 16 binary16 predicates and `v_cmp_class_f16_sdwa`, `v_cmp_class_f32_sdwa`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA encodes only `src0_sel` and `src1_sel`; `llvm-mc` rejects `dst_sel`/`dst_unused` on these instructions, so the destination stays `vcc`/`vcc_lo` or one SGPR and the translator refuses an SGPR pair and the destination fields. Sources accept `BYTE_0..3`, `WORD_0..1` and `DWORD`, with `sext()` where LLVM prints it. The selection is zero-extended, or sign-extended under `sext()`, before the existing table applies: binary16 uses the low 16 bits through `widen16`/`num16`, the 16-bit integer forms take the low 16 bits, the 32-bit integer forms compare the selected word as signed or unsigned, and the class forms feed the selected bits to `class16` or `class32`. The comparison result is tracked in the same VCC/SGPR lane-mask state as the e32 and e64 forms, so `v_cndmask_b32` consumes it unchanged. The source-built fixture `tests/pixel_aot_check.py draw-sdwa-cmp` puts all 46 forms in one program, folds each predicate into two exported `R32G32B32A32_UINT` words, and repeats the rows with selections on every field. Its wrong references must each report `pixel_mismatch`: selections ignored (whole dwords), every field reversed (`BYTE_0`/`BYTE_3`, `BYTE_1`/`BYTE_2`, `WORD_0`/`WORD_1`), signedness inverted on the rows containing `0x8000`/`0xffff`, and zero extension in place of `sext()`. A second program writes two comparisons to `s52` and `vcc_lo` before consuming both; a reference that uses the second mask for both channels must mismatch. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts the 46 forms count in both `gfx1013.tsv` and `rdna2.tsv`, while the non-SDWA `v_cmp_*` neighbours stay out (the exec-writing `v_cmpx_*_sdwa` forms follow in lot 1b). The same program is part of `check_binary`, so the LLVM 15 `Assemble and translate gfx1013 fixtures` job assembles, disassembles and re-translates it. On base `0aa6522c` the measurement moved from 1255/1968 to 1301/1968 on gfx1013 and from 1246/1863 to 1292/1863 on gfx1030, exactly 46 forms in each reference. The new tests passed on WARP and on `pixel_aot_sdwa_cmp_hardware` on an AMD Radeon RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075, in 1.10 s; the debug layer was unavailable. The separate `pixel_aot_comparisons_hardware` entry still fails on this adapter in its pre-existing strict binary32 subnormal comparison ([issue #958](https://github.com/R0Y00/Xbox2Windows/issues/958)); that failure is outside this lot and does not affect the SDWA draw. This measures translated fixtures, not console behavior or full title execution. Reproduce with `ctest --preset dev --no-tests=error -R '^pixel_aot_sdwa_cmp_' -V`; the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-sdwa-after.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-sdwa-after.xml --records out/build/dev/form_coverage --json out/wave1-sdwa-after.json`. A supplemental per-predicate fixture (`tests/pixel_aot_check.py draw-sdwa-int-compare`, tests `pixel_aot_sdwa_int_compare_{warp,hardware}`) exercises all 16 32-bit integer SDWA comparisons across four 4-channel groups (`i32_lo`, `i32_hi`, `u32_lo`, `u32_hi`) with 41 targeted single-channel negative controls plus static refusal checks for `low16` sources, pending loads, masked regions, float modifiers, `clamp` and SGPR pair destinations. -Lot 1b lowers the remaining 62 exec-writing VOPC SDWA comparisons: the 16 binary32 predicates (whole-dword selections only, as their `v_cmp` forms), the 16 binary16 predicates, `v_cmpx_class_f16` and `v_cmpx_class_f32`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA prints no destination and encodes no `dst_sel`/`dst_unused`: the comparison writes EXEC, so each form reuses the existing `v_cmpx` region opener unchanged (the `s_mov_b64 s[a:b], exec` save, the entry-mask intersection, the SKIP/else handling and the two closes), and the non-SDWA path is untouched. Selections are the same `BYTE_0..3`, `WORD_0..1` and `DWORD` fields, zero-extended or sign-extended under `sext()`, applied before the e32 table. The fixture `draw-cmpx-sdwa` (`pixel_aot_cmpx_sdwa_{warp,hardware}`) opens one region per form and adds an exact power of two to one of three exported binary32 accumulators (24 bits per channel, so every partial sum is an exact integer below 2^24); its wrong references must each mismatch: selections ignored, every field reversed, signedness inverted, zero extension instead of `sext()`, and the region applied to every lane. Static controls refuse a missing or non-adjacent EXEC save, `dst_sel`/`dst_unused`, an SGPR pair in the source position, byte/word selections on an f32 predicate, and the nonexistent 64-bit SDWA exec writers. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts its 62 forms are exactly the SDWA `v_cmpx` family of both references, while the non-SDWA exec writers and the `v_cmp_*_sdwa` forms stay out. The same program is part of `check_binary`. The 194-entry WARP replay (`pixel_aot_`/`compute_store_aot_`, `_hardware` excluded) passes with no failure or skip and measures 1542/1968 on gfx1013 and 1533/1863 on gfx1030; removing the 62 forms of this lot leaves 1480/1968 and 1471/1863. The targeted WARP and hardware runs pass on the AMD Radeon RX 9060 XT (driver 32.0.32029.2010); `draw-cmpx-regions` and `draw-sdwa-cmp` also pass on both adapters. This measures translated fixtures, not console behavior or full title execution. Reproduce the target with `python -B tests/pixel_aot_check.py draw-cmpx-sdwa warp` (or `hardware`), `tests/pixel_aot_check.py draw-cmpx-regions`, `tests/pixel_aot_check.py draw-sdwa-cmp` and `python -B tests/form_coverage_check.py`; in a configured tree the CTest entry is `ctest --preset dev --no-tests=error -R '^pixel_aot_cmpx_sdwa_' -V`, and the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-cmpx-sdwa.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-cmpx-sdwa.xml --records out/build/dev/form_coverage --json out/wave1-cmpx-sdwa.json`. In this worktree the CMake configure stops in the `opus` dependency (`LNK1104: m.lib`) before any target, so the 194-entry run replayed the main build's CTest command list with this tree's tests and the main build's `offscreen_check.exe`; the replay helper is untracked under `out/coverage-run/`. +Lot 1b lowers the remaining 62 exec-writing VOPC SDWA comparisons: the 16 binary32 predicates (whole-dword selections only, as their `v_cmp` forms), the 16 binary16 predicates, `v_cmpx_class_f16` and `v_cmpx_class_f32`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA prints no destination and encodes no `dst_sel`/`dst_unused`: the comparison writes EXEC, so each form reuses the existing `v_cmpx` region opener unchanged (the `s_mov_b64 s[a:b], exec` save, the entry-mask intersection, the SKIP/else handling and the two closes), and the non-SDWA path is untouched. Selections are the same `BYTE_0..3`, `WORD_0..1` and `DWORD` fields, zero-extended or sign-extended under `sext()`, applied before the e32 table. The fixture `draw-cmpx-sdwa` (`pixel_aot_cmpx_sdwa_{warp,hardware}`) opens one region per form and adds one of 2^8..2^23 to one of four exported binary32 accumulators (16 bits per channel; every partial sum is an exact integer below 2^24, and the constants avoid LLVM's float inline-constant spellings); its wrong references must each mismatch: selections ignored, every field reversed, signedness inverted, zero extension instead of `sext()`, and the region applied to every lane. Static controls refuse a missing or non-adjacent EXEC save, `dst_sel`/`dst_unused`, an SGPR pair in the source position, byte/word selections on an f32 predicate, and the nonexistent 64-bit SDWA exec writers. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts its 62 forms are exactly the SDWA `v_cmpx` family of both references, while the non-SDWA exec writers and the `v_cmp_*_sdwa` forms stay out. The same program is part of `check_binary`. The 194-entry WARP replay (`pixel_aot_`/`compute_store_aot_`, `_hardware` excluded) passes with no failure or skip and measures 1542/1968 on gfx1013 and 1533/1863 on gfx1030; removing the 62 forms of this lot leaves 1480/1968 and 1471/1863. The targeted WARP and hardware runs pass on the AMD Radeon RX 9060 XT (driver 32.0.32029.2010); `draw-cmpx-regions` and `draw-sdwa-cmp` also pass on both adapters. This measures translated fixtures, not console behavior or full title execution. Reproduce the target with `python -B tests/pixel_aot_check.py draw-cmpx-sdwa warp` (or `hardware`), `tests/pixel_aot_check.py draw-cmpx-regions`, `tests/pixel_aot_check.py draw-sdwa-cmp` and `python -B tests/form_coverage_check.py`; in a configured tree the CTest entry is `ctest --preset dev --no-tests=error -R '^pixel_aot_cmpx_sdwa_' -V`, and the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-cmpx-sdwa.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-cmpx-sdwa.xml --records out/build/dev/form_coverage --json out/wave1-cmpx-sdwa.json`. In this worktree the CMake configure stops in the `opus` dependency (`LNK1104: m.lib`) before any target, so the 194-entry run replayed the main build's CTest command list with this tree's tests and the main build's `offscreen_check.exe`; the replay helper is untracked under `out/coverage-run/`. Binary32 floating-point vector comparisons (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f32` in e32, e64, and whole-dword SDWA forms) evaluate the 16 IEEE-754 relations against scalar and vector operands, including subnormals, signed zeroes, infinities, and quiet/signaling NaNs. The e32 (VOPC) encoding requires destination `vcc` or `vcc_lo`; SGPR destinations (`s52`, `s[52:53]`) are accepted on suffix-less and explicit `_e64` (VOP3) encodings. Source modifiers (`neg`, `abs`) are accepted on e64 operands (`-s44`, `|v18|`, `-|s44|`), while `clamp` and `op_sel` remain rejected on comparisons. Rejection controls verify that untracked source registers, SGPR destinations on explicit e32, and sub-dword SDWA selections (`src0_sel:WORD_0`, `src1_sel:BYTE_2`) raise `ValueError`. The synthetic fixture `f32_compares()` verifies all 16 predicates across e32, e64, and whole-dword SDWA, validating them against an exact reference oracle (`f32_compares_reference()`). Mutating predicates or modifiers produces a mismatch. diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index cfc57dc8a4..02abc16815 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -5024,7 +5024,8 @@ def sdwa_cmp_expected_words(word0, word1, *, select=None, signed=None, sext=True for index, entry in enumerate(SDWA_CMP_FORMS): if sdwa_cmp_expected(entry, word0, word1, select=select, signed=signed, sext=sext): words[index // 32] |= 1 << (index % 32) - return tuple(words) + # Each addend is 2^(8 + bit), so the accumulator holds the bitmap shifted left by 8. + return tuple(word << 8 for word in words) def sdwa_cmp_destination_body(): @@ -5183,34 +5184,39 @@ def cmpx_sdwa_instruction(entry): def cmpx_sdwa_body(): - """All 62 forms, each folded into bit i of three exported binary32 words (24 bits per channel).""" + """All 62 forms, each folded into one bit of four exported binary32 words. + + The four accumulators carry bits 8..23 of each word, so every addend is an exact power of two + that LLVM prints as a hex literal (small values become float inline constants and would not + round-trip). Each word holds 16 bits; the fourth uses 14. + """ body = ["v_mov_b32_e32 v18, v12"] - body += [f"v_mov_b32_e32 v{13 + channel}, 0" for channel in range(3)] + body += [f"v_mov_b32_e32 v{12 + channel}, 0" for channel in range(4)] for index, entry in enumerate(CMPX_SDWA_FORMS): - channel, bit = divmod(index, 24) - body += [f"v_mov_b32_e32 v16, {(127 + bit) << 23:#x}", + channel, bit = divmod(index, 16) + body += [f"v_mov_b32_e32 v16, {(135 + bit) << 23:#x}", CMPX_SAVE, cmpx_sdwa_instruction(entry), - f"v_add_f32_e32 v{13 + channel}, v{13 + channel}, v16", + f"v_add_f32_e32 v{12 + channel}, v{12 + channel}, v16", CMPX_MOV_RESTORE] return body def cmpx_sdwa_expected_words(word0, word1, *, select=None, signed=None, sext=True, unmasked=False): - words = [0, 0, 0] + words = [0, 0, 0, 0] for index, entry in enumerate(CMPX_SDWA_FORMS): if unmasked or sdwa_cmp_expected(entry, word0, word1, select=select, signed=signed, sext=sext): - words[index // 24] |= 1 << (index % 24) - return tuple(words) + words[index // 16] |= 1 << (index % 16) + # Each addend is 2^(8 + bit), so the accumulator holds the bitmap shifted left by 8. + return tuple(word << 8 for word in words) def cmpx_sdwa_pixels(word0, **kwargs): pixels = [] for g in MASKED_RAMP: for r in MASKED_RAMP: - x = single(r / 255) - bits, = struct.unpack(" Date: Mon, 30 Nov 2026 04:33:49 +0000 Subject: [PATCH 7/8] tests: restore the lot 1a sdwa compare words --- tests/pixel_aot_check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 02abc16815..1180568f0d 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -5025,7 +5025,7 @@ def sdwa_cmp_expected_words(word0, word1, *, select=None, signed=None, sext=True if sdwa_cmp_expected(entry, word0, word1, select=select, signed=signed, sext=sext): words[index // 32] |= 1 << (index % 32) # Each addend is 2^(8 + bit), so the accumulator holds the bitmap shifted left by 8. - return tuple(word << 8 for word in words) + return tuple(words) def sdwa_cmp_destination_body(): From 667ba46c5e4d465e0df82051c42c4789773180b1 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 05:12:28 +0000 Subject: [PATCH 8/8] shader: lower binary16 VOP1 reciprocal and square root Add v_rcp_f16 and v_sqrt_f16 to the plain pixel VOP1 path in e32 and e64, matching the direct compute binary32 operation and binary16 narrowing. Cover finite-source proofs, mode and modifier refusals, exact and rounded values, chains, readers, scanner agreement, and form coverage. Refs #839 --- CMakeLists.txt | 6 + docs/experiments.md | 6 +- tests/form_coverage_check.py | 39 +++- tests/pixel_aot_check.py | 364 +++++++++++++++++++++++++++++- tests/rdna2_tools_check.py | 19 +- tools/pixel_aot.py | 152 +++++++++++++ tools/scan_unsupported_shaders.py | 11 +- 7 files changed, 580 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 900c79cd1a..5c1f2a6e81 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11349,6 +11349,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-round "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(pixel_aot_f16_round_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME pixel_aot_f16_rcp_sqrt_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-rcp-sqrt "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_f16_rcp_sqrt_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME pixel_aot_f16_fmac_ldexp_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-fmac-ldexp "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -11635,6 +11639,8 @@ if(EXISTS "${INTAKE_PYTHON}") ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_arith_${adapter}.txt") set_tests_properties(pixel_aot_f16_round_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_round_${adapter}.txt") + set_tests_properties(pixel_aot_f16_rcp_sqrt_${adapter} PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rcp_sqrt_${adapter}.txt") set_tests_properties(pixel_aot_f16_fmac_ldexp_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_fmac_ldexp_${adapter}.txt") set_tests_properties(pixel_aot_f16_cvt_int16_${adapter} PROPERTIES diff --git a/docs/experiments.md b/docs/experiments.md index 369e8c4fb7..56548e97e7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8997,7 +8997,11 @@ The three-operand 16-bit integer `VOP3` ops (issue #669) `v_mad_u16`, `v_mad_i16 Plain non-fused binary16 `VOP2` arithmetic (issue #839) `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`, in the unsuffixed, `_e32` and `_e64` spellings, computes on the low 16 bits of two sources. `v_subrev_f16` is `src1 - src0` (LLVM 15.0.7 `VOP2Instructions.td`: `V_SUBREV_F16` is the reversed operand form of `v_sub_f16`; the order is not measured natively). Each half is widened exactly with `widen16`, one binary32 add, subtract or multiply is evaluated under `precise`, and `narrow16` rounds once to nearest even, keeping binary16 subnormals and signed zeros. A product of two 11-bit significands is exact in binary32, and a sum rounded to 24 bits before the 11-bit rounding is innocuous because 24 >= 2 * 11 + 2. A one-off exhaustive numpy run (every pair of finite binary16 values, 63,488 squared = 4,030,726,144 pairs, for add and for mul: the binary32 result narrowed to binary16 against the binary64 result narrowed to binary16, 0 mismatches) is not part of CI; the repository check repeats the claim with a pure-Python model over several hundred operands against a set of boundary values for all four ops, and the translator's own exact reference agrees with it. Nothing is claimed beyond finite operands and results. A source is accepted only when its low half is statically proven finite: a binary16 inline constant (`0.5`, `-0.5`, `1.0`, `-1.0`, `2.0`, `-2.0`, `4.0`, `-4.0`, `0.15915494`; the negative ones are read before a leading minus counts as a modifier), the integer inline constant `0`, a 16-bit literal up to `0xffff`, an SGPR holding a known integer, a VGPR copied by `v_mov_b32` from a literal or an inline constant (also through further `v_mov_b32` copies), or the result of an earlier accepted op, whose value the translator computes with an exact integer reference (`f16_vop2_result`) so that a chain stays proven. Anything else (a constant-buffer word, a sample, an interpolant, an uninitialized register, a 16-bit integer result) is refused with `binary16 operand lacks a finite proof: `, a NaN or infinity encoding with `binary16 operand is not finite: `, and a result that rounds to infinity with `binary16 result overflows: v__f16` (the boundary is 65520, so `0x7bff + 0x4bff` is accepted and `0x7bff + 0x4c00` is refused, for both signs and for all four ops). Integer inline constants other than `0` are refused (`Unsupported binary16 integer inline constant`): LLVM 15 prints a 16-bit literal that equals an integer inline constant as that integer (`v_add_f16 v1, 0xffff, v3` prints `-1` and `0x0001` prints `1`, pinned in `check_binary`), so `-16..-1` can be NaN patterns and `1..64` subnormals whose hardware reading as an inline constant is not established; subnormal operands therefore enter through `v_mov_b32` of a 32-bit literal. Source modifiers (`Unsupported binary16 source modifier`), other floats and operands such as `vcc_lo`, `m0` and `exec` (`Unsupported binary16 operand`), a literal wider than 16 bits, an e32 or unsuffixed form whose src1 is not a VGPR, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and a wrong operand count are refused as well (the last group with `Unsupported instruction`), and so are the neighbouring `v_min_f16`, `v_max_f16`, `v_fmac_f16` and `v_ldexp_f16`. The entry profile is explicit: `lower(..., half_denorm="preserve")` (CLI `--half-denorm preserve`; `pixel_aot.HALF_DENORM_PRESERVE`) declares that MODE[7:6] holds binary16 denormals as preserved at shader entry, taken by the caller from validated guest state. The default `None` means unknown, and the four forms are then refused with `binary16 denormal mode unknown at entry`; any other value is refused with `Invalid binary16 denormal entry state`. This is a declaration, not a tracked MODE write: `s_denorm_mode`, `s_setreg_b32` and every `s_setreg_imm32_b32` of MODE other than bits 3:2 stay refused (`s_round_mode` writes only the rounding fields, see below), so the declaration holds for the whole program, and the existing rounding gate refuses the forms under round toward zero. The lowering itself never reads MODE, so the claim is that the translated result equals nearest-even arithmetic with binary16 denormals preserved, not that the console runs in that mode; the console's denormal state is not measured (`F16_DENORM_MODE` in the tests is asserted equal to the constant). The result is tagged `("half16", alu)`, distinct from `("low16", alu)`: bits 15:0 are defined and bits 31:16 are not, the destination's old value is not merged, and no integer reader (the 16-bit ops, the 16-bit compares, `v_mov_b32_sdwa` `BYTE_0` and `BYTE_1`) can see it. The readers are `v_cvt_f32_f16` (`_e32` and `_e64`, no modifiers and no `clamp`), `v_cvt_f32_f16_sdwa` with `src0_sel:WORD_0`, `v_mov_b32_sdwa` with `src0_sel:WORD_0` (no `sext()`) and the four ops themselves (a chain). Every other reader refuses the tag (`Expected a numeric register`, `Expected a numeric VGPR in DPP`, `Unsupported pack operand`, `Unsupported conversion destination`, `Unsupported export` for both export forms, `Reads the undefined high half of a 16-bit result` for `WORD_1`, `BYTE_0` to `BYTE_3`, `DWORD`, `sext()` and an `UNUSED_PRESERVE` into a binary16 destination, and `Modifiers on a binary16 arithmetic result are not lowered`); the tag name must not start with `sample` or `alu`, which the compressed export and pack checks accept for string pairs, and a control pins that. The controls (`tests/pixel_aot_check.py`, no GPU; `check_f16_arith_controls`) cover each spelling, every operand kind, the refusals above with their exact messages (unknown and invalid entry state, a dynamic operand, NaN and infinity in every provenance, overflow at both boundaries and signs, modifiers, integers, floats, registers, the pending, sample and mask checks, the mode instructions before and after the op, all readers) and the Python reference against pinned rows. The draw (`tests/pixel_aot_check.py draw-f16-arith`, tests `pixel_aot_f16_arith_hardware` and `pixel_aot_f16_arith_warp`, 120 s limit, capability skip 77) bakes every operand into the program, so the constant buffer is unused: 20 programs run the 40 operand pairs through all four ops in a rotation of e32, e64, SGPR and literal forms and pack two results per word with SDWA `WORD_0` and `WORD_1`; six programs read the four results through the four readers, and two programs chain four ops. The pairs cover halfway cases that round down and up to even, just above and below a tie, a sticky bit beyond binary32 (`0x7bff + 0x0001`), multiplication ties into subnormals, results that become subnormal, the carry from the largest subnormal into `0x0400`, positive and negative subnormal inputs, the signed zero of every sum, difference and product (`-0 + -0`, `+0 + -0`, exact cancellation, underflow signs) and plain values; no pair overflows. Bits 31:16 of every source word hold junk. The readback is the lossless `R32G32B32A32_UINT` target against `f16_arith_reference`, an integer implementation written from the semantics without `pixel_aot`. The programs with subnormal operands also run under a binary32 `-denorm ftz` build and must still pass. Eleven deviations must each mismatch, one batch per mutation with the statuses printed (truncation, ties away from zero, flushed subnormal results, flushed subnormal inputs, negative subnormal inputs read as positive, the sign of a tiny result dropped, a source read from bits 31:16, `v_subrev_f16` lowered as `v_sub_f16`, `v_sub_f16` as `v_add_f16`, `v_mul_f16` as `v_add_f16`, and a sum that turns `-0` into `+0`), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. A `WORD_1` widening of a result is refused at lowering. Not measured: the high half of the destination (the draw cannot detect a leak, and only the refusal controls guard the readers), the console's denormal state, NaN and infinity operands, overflow and the NaN payload rules, runtime operands, the hardware reading of integer inline constants on binary16 operands, the `v_subrev_f16` order natively, and binary32 round to nearest even on the desktop adapters beyond what the draw shows. -Plain binary16 `VOP1` rounding (issue #839) `v_floor_f16`, `v_ceil_f16`, `v_trunc_f16` and `v_rndne_f16`, in the unsuffixed, `_e32` and `_e64` spellings, rounds the low 16 bits of one source to an integer under the rules of the `VOP2` arithmetic above. LLVM 15.0.7 `VOP1Instructions.td` (lines 449-452) selects `ffloor`, `fceil`, `ftrunc` and `frint` for them; `frint` is round to nearest even under the default rounding mode. The half is widened exactly with `widen16`, one binary32 `floor`, `ceil`, `trunc` or `round` is evaluated under `precise` (HLSL `round` is round-half-to-even in DXIL, as the binary32 `rndne` entry already relies on), and `narrow16` narrows the result. The integer of a finite binary16 is at most 65504 in magnitude and therefore representable, so the narrowing is exact and no rounding rule for the result is needed; an exact zero keeps the sign of the source (`trunc(-0.5)`, `ceil(-0.3)` and `rndne(-0.4)` are `-0`, `floor(-0)` is `-0`). The source proof, the entry profile, the result tag and the audited readers are those of the `VOP2` arithmetic: a source is accepted only when its low half is statically proven finite (a binary16 inline constant, `0`, a 16-bit literal, a tracked SGPR, a VGPR copied from a constant, or the result of an earlier accepted binary16 op), `lower(..., half_denorm="preserve")` must declare the entry state (`binary16 denormal mode unknown at entry` otherwise, `Invalid binary16 denormal entry state` for another value), the destination is tagged `("half16", alu)`, and the translator computes the result with an exact integer reference (`f16_round_result`) so that a chain stays proven (`v_floor_f16 v24, 0x7bff` followed by `v_add_f16 v25, v24, 0x4bff` is accepted and `0x4c00` is refused as an overflow). The refusals carry exact messages: `binary16 operand lacks a finite proof: `, `binary16 operand is not finite: ` for a NaN or infinity constant in any provenance, `Unsupported binary16 source modifier `, `Unsupported binary16 integer inline constant `, `Unsupported binary16 operand `, `Invalid binary16 rounding operation` outside the entry mask, `Unsupported binary16 or binary64 operation under round toward zero: `, and `Unsupported instruction` for `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA, a second source and the neighbouring `v_fract_f16`, `v_rcp_f16` and `v_sqrt_f16`. `clamp` and the output modifiers assemble on `_e64` (pinned in `check_f16_round_binary`, together with the encodings `v_floor_f16_e32 v1, v2` = `02 b7 02 7e`, `v_ceil_f16_e64 v1, v2` = `01 00 dc d5 02 01 00 00`, `v_trunc_f16_e32 v1, 1.0` and `v_rndne_f16_e32 v1, v2` = `02 bd 02 7e` from LLVM 15) and are refused. Every other reader of the tag refuses it as for the arithmetic results (`Expected a numeric register`, `Reads the undefined high half of a 16-bit result`, `Modifiers on a binary16 arithmetic result are not lowered`, `Unsupported export`). The controls (`check_f16_round_controls`, no GPU) cover each spelling, every operand kind, the refusals above, the scheduling and mask checks, the mode instructions before and after the op, the readers, pinned rows of the Python reference and a full comparison of the reference with `struct` format `e` plus `math.floor`, `math.ceil`, `math.trunc` and Python `round` (half-even) over every finite binary16 value, including the sign of zero, and with the translator's own copy. The draw (`tests/pixel_aot_check.py draw-f16-round`, tests `pixel_aot_f16_round_hardware` and `pixel_aot_f16_round_warp`, 60 s limit, capability skip 77) bakes every operand into the program: 21 programs run 42 values through all four ops in a rotation of e32, e64, SGPR and literal forms and pack two results per word with SDWA `WORD_0` and `WORD_1`; four programs read the four results through the four audited readers; two programs chain a `v_mul_f16` result into `v_trunc_f16` and `v_rndne_f16` and the `v_trunc_f16` result into `v_sub_f16`. The values cover both signs of zero, negative inputs that round to `-0`, the halfway cases 0.5, 1.5, 2.5, 3.5 and their negatives, 0.5 plus and minus one ulp, 1022.5 and 1023.5 (ulp 0.5, so halfway cases still exist), values from 1024 up (already integers, ulp 1, then ulp 2 from 2048) and +-65504, the subnormals `0x0001` and `0x03ff` with both signs and the smallest normal. A half-integer such as 2047.5 is not representable, the largest halfway case is 1023.5. Bits 31:16 of every source word hold junk. The readback is the lossless `R32G32B32A32_UINT` target against `f16_round_reference`, an integer implementation without `pixel_aot`; the programs with subnormal operands also run under a binary32 `-denorm ftz` build and must still pass. Five deviations must each mismatch, one batch per mutation with the statuses printed (`floor` and `ceil` swapped, `trunc` lowered as `floor`, `rndne` lowered as round half away from zero, the sign of a `-0` result lost, and a source read from bits 31:16), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands, the hardware reading of integer inline constants on binary16 operands, and the `frint` rounding mode of the console beyond the default mode that the entry assumption names. +Plain binary16 `VOP1` rounding (issue #839) `v_floor_f16`, `v_ceil_f16`, `v_trunc_f16` and `v_rndne_f16`, in the unsuffixed, `_e32` and `_e64` spellings, rounds the low 16 bits of one source to an integer under the rules of the `VOP2` arithmetic above. LLVM 15.0.7 `VOP1Instructions.td` (lines 449-452) selects `ffloor`, `fceil`, `ftrunc` and `frint` for them; `frint` is round to nearest even under the default rounding mode. The half is widened exactly with `widen16`, one binary32 `floor`, `ceil`, `trunc` or `round` is evaluated under `precise` (HLSL `round` is round-half-to-even in DXIL, as the binary32 `rndne` entry already relies on), and `narrow16` narrows the result. The integer of a finite binary16 is at most 65504 in magnitude and therefore representable, so the narrowing is exact and no rounding rule for the result is needed; an exact zero keeps the sign of the source (`trunc(-0.5)`, `ceil(-0.3)` and `rndne(-0.4)` are `-0`, `floor(-0)` is `-0`). The source proof, the entry profile, the result tag and the audited readers are those of the `VOP2` arithmetic: a source is accepted only when its low half is statically proven finite (a binary16 inline constant, `0`, a 16-bit literal, a tracked SGPR, a VGPR copied from a constant, or the result of an earlier accepted binary16 op), `lower(..., half_denorm="preserve")` must declare the entry state (`binary16 denormal mode unknown at entry` otherwise, `Invalid binary16 denormal entry state` for another value), the destination is tagged `("half16", alu)`, and the translator computes the result with an exact integer reference (`f16_round_result`) so that a chain stays proven (`v_floor_f16 v24, 0x7bff` followed by `v_add_f16 v25, v24, 0x4bff` is accepted and `0x4c00` is refused as an overflow). The refusals carry exact messages: `binary16 operand lacks a finite proof: `, `binary16 operand is not finite: ` for a NaN or infinity constant in any provenance, `Unsupported binary16 source modifier `, `Unsupported binary16 integer inline constant `, `Unsupported binary16 operand `, `Invalid binary16 rounding operation` outside the entry mask, `Unsupported binary16 or binary64 operation under round toward zero: `, and `Unsupported instruction` for `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA, a second source and the neighbouring `v_fract_f16` and `v_rsq_f16`. `clamp` and the output modifiers assemble on `_e64` (pinned in `check_f16_round_binary`, together with the encodings `v_floor_f16_e32 v1, v2` = `02 b7 02 7e`, `v_ceil_f16_e64 v1, v2` = `01 00 dc d5 02 01 00 00`, `v_trunc_f16_e32 v1, 1.0` and `v_rndne_f16_e32 v1, v2` = `02 bd 02 7e` from LLVM 15) and are refused. Every other reader of the tag refuses it as for the arithmetic results (`Expected a numeric register`, `Reads the undefined high half of a 16-bit result`, `Modifiers on a binary16 arithmetic result are not lowered`, `Unsupported export`). The controls (`check_f16_round_controls`, no GPU) cover each spelling, every operand kind, the refusals above, the scheduling and mask checks, the mode instructions before and after the op, the readers, pinned rows of the Python reference and a full comparison of the reference with `struct` format `e` plus `math.floor`, `math.ceil`, `math.trunc` and Python `round` (half-even) over every finite binary16 value, including the sign of zero, and with the translator's own copy. The draw (`tests/pixel_aot_check.py draw-f16-round`, tests `pixel_aot_f16_round_hardware` and `pixel_aot_f16_round_warp`, 60 s limit, capability skip 77) bakes every operand into the program: 21 programs run 42 values through all four ops in a rotation of e32, e64, SGPR and literal forms and pack two results per word with SDWA `WORD_0` and `WORD_1`; four programs read the four results through the four audited readers; two programs chain a `v_mul_f16` result into `v_trunc_f16` and `v_rndne_f16` and the `v_trunc_f16` result into `v_sub_f16`. The values cover both signs of zero, negative inputs that round to `-0`, the halfway cases 0.5, 1.5, 2.5, 3.5 and their negatives, 0.5 plus and minus one ulp, 1022.5 and 1023.5 (ulp 0.5, so halfway cases still exist), values from 1024 up (already integers, ulp 1, then ulp 2 from 2048) and +-65504, the subnormals `0x0001` and `0x03ff` with both signs and the smallest normal. A half-integer such as 2047.5 is not representable, the largest halfway case is 1023.5. Bits 31:16 of every source word hold junk. The readback is the lossless `R32G32B32A32_UINT` target against `f16_round_reference`, an integer implementation without `pixel_aot`; the programs with subnormal operands also run under a binary32 `-denorm ftz` build and must still pass. Five deviations must each mismatch, one batch per mutation with the statuses printed (`floor` and `ceil` swapped, `trunc` lowered as `floor`, `rndne` lowered as round half away from zero, the sign of a `-0` result lost, and a source read from bits 31:16), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands, the hardware reading of integer inline constants on binary16 operands, and the `frint` rounding mode of the console beyond the default mode that the entry assumption names. + +Plain binary16 `VOP1` reciprocal and square root (issue #839) `v_rcp_f16` and `v_sqrt_f16`, in the unsuffixed, `_e32` and `_e64` spellings, reproduce the direct compute lowering under the source-proof and entry-profile rules of the binary16 forms above. The 16-bit source is widened exactly with `widen16`, `v_rcp_f16` evaluates `1.0f / S0` in binary32, `v_sqrt_f16` evaluates the direct compute path's square root (`unary.f32` opcode 24), and `narrow16` performs one binary16 round to nearest even. The intermediate binary32 round is significant: the translator tracks the result with `f16_rcp_sqrt_result`, which rounds the exact quotient or root once to binary32 and then to binary16 instead of double-rounding the exact value straight to binary16. A reciprocal at or above the binary16 overflow threshold is a signed infinity; zero gives the signed infinity; the negative square root is a NaN whose payload is not modelled, so it can be read but does not stay a proven value for a chain. `2.0` gives `0.5` for `rcp` and `4.0` gives `2.0` for `sqrt`; the draw also covers values that exercise the two rounding steps, subnormals, the largest finite half and an overflowing reciprocal. Sources must be statically proven finite (binary16 inline constants, `0`, a 16-bit literal, a tracked SGPR, a VGPR copy, or an earlier accepted binary16 result), `lower(..., half_denorm="preserve")` must declare the entry state, the destination is limited to `v0` through `v255` and may not overlap an outstanding sample, and the result is tagged `("half16", alu)`. Source modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA, an extra operand and the neighbouring `v_rsq_f16`, `v_exp_f16` and `v_log_f16` stay refused; the exact messages are the binary16 source, range and modifier refusals above plus `Invalid binary16 unary operation` outside the entry mask and `Unsupported instruction` for the unmodelled forms. Round toward zero refuses both spellings through the shared binary16 mode check. + +The controls (`check_f16_rcp_sqrt_controls`, no GPU) cover the bare, `_e32` and `_e64` spellings, every source kind, the finite, register, modifier, mode, scheduling, sample and reader refusals, and chains of both operations. The Python reference (`f16_rcp_sqrt_reference`) applies the same two rounds from the semantics without `pixel_aot`, handles the binary16 overflow threshold and compares with the translator's `f16_rcp_sqrt_result` on every finite encoding. The draw (`tests/pixel_aot_check.py draw-f16-rcp-sqrt`, tests `pixel_aot_f16_rcp_sqrt_hardware` and `pixel_aot_f16_rcp_sqrt_warp`, 60 s limit, capability skip 77) runs five baked programs over 20 source values through both ops in a rotation of e32, e64, SGPR and literal forms and packs two results per word with SDWA `WORD_0` and `WORD_1`; four reader programs and two chains read both result tags. Bits 31:16 of every source word hold junk. The lossless `R32G32B32A32_UINT` readback is compared with the Python reference. Two deviations must each mismatch, one batch per mutation with the statuses printed (reciprocal and square root swapped, and a source read from bits 31:16), and a source with no finite proof is refused at translation. Both tests passed on WARP and on the RX 9060 XT. In `gfx1013.tsv` and `rdna2.tsv` the two operations add their VOP1 and VOP3 rows, so the fixture records four newly covered forms (rcp and sqrt, each e32 and e64); the two operations themselves are the +2. `tests/form_coverage_check.py check_f16_rcp_sqrt_forms` pins that the DPP, SDWA and rsq neighbours stay uncovered. `tools/scan_unsupported_shaders.py` accepts the syntactic source forms and `tests/rdna2_tools_check.py test_binary16_e64_scanner_translator_agreement` checks that its acceptance agrees with `pixel_aot.lower`. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN payloads and special-function results beyond the modelled infinities, runtime sources, the DPP and SDWA spellings, the hardware behaviour of integer inline constants on binary16 operands, and whether any title executes these paths. Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 73533b4874..0333ca4b0d 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -656,7 +656,8 @@ def check_f16_arith_forms(): def check_f16_round_forms(): """The eight plain binary16 VOP1 rounding forms (e32 and e64 spellings of floor, ceil, trunc and rndne) count as - covered once the translator accepts their fixtures; fract, rcp, sqrt and the DPP and SDWA spellings stay uncovered.""" + covered once the translator accepts their fixtures; fract and the DPP and SDWA spellings stay uncovered here, and + rcp and sqrt have their own fixture.""" import pixel_aot_check as pixel saved = set(pixel.ACCEPTED) pixel.ACCEPTED.clear() @@ -685,6 +686,41 @@ def check_f16_round_forms(): pixel.ACCEPTED.update(saved) +def check_f16_rcp_sqrt_forms(): + """The four plain binary16 VOP1 reciprocal and square root forms (e32 and e64 spellings of rcp and sqrt) count as + covered once the translator accepts their fixtures; their DPP, SDWA and rsq neighbours stay uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for key in pixel.F16_RCP_SQRT_PROGRAMS: + pixel.translate_f16(pixel.f16_rcp_sqrt_program(*key)) + ops = ("rcp", "sqrt") + forms = {("VOP1", f"v_{op}_f16") for op in ops} | {("VOP3", f"v_{op}_f16_e64") for op in ops} + assert len(forms) == 4 + neighbours = { + ("VOP1", "v_rsq_f16"), ("VOP3", "v_rsq_f16_e64"), + ("DPP16", "v_rcp_f16_dpp"), ("DPP16", "v_sqrt_f16_dpp"), + ("DPP8", "v_rcp_f16_dpp"), ("DPP8", "v_sqrt_f16_dpp"), + ("SDWA", "v_rcp_f16_sdwa"), ("SDWA", "v_sqrt_f16_sdwa"), + } + # The two operations add one VOP1 and one VOP3 row to each reference table. + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not neighbours & covered, (name, sorted(neighbours & covered)) + pixel.ACCEPTED.clear() + for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + assert not forms & fc.gfx_forms(pixel.ACCEPTED, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + def check_f16_fmac_ldexp_forms(): """The two plain e32 binary16 forms v_fmac_f16 and v_ldexp_f16 count as covered once the translator accepts their fixtures; their e64, DPP and SDWA spellings and the arithmetic they resemble stay uncovered.""" @@ -1741,6 +1777,7 @@ def check_f16_cvt_norm_forms(): check_int16_ternary_forms() check_f16_arith_forms() check_f16_round_forms() + check_f16_rcp_sqrt_forms() check_f16_fmac_ldexp_forms() check_f16_cvt_int16_forms() check_f16_to_int16_forms() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 1180568f0d..79b3f37e25 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -7824,7 +7824,7 @@ def refuse(line, message): for line in ("v_add_nc_u16 v24, v18, v19 op_sel:[0,0,1]", "v_add_nc_u16 v24, v18, v19 clamp", "v_add_nc_u16_dpp v24, v18, v19 quad_perm:[0,1,2,3]", "v_add_nc_u16_sdwa v24, v18, v19 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - "v_rcp_f16_e64 v24, v18"): + "v_rsq_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") refuse("v_add_nc_u16 v24, v18, -v19", "Unsupported 16-bit integer operand") refuse("v_add_nc_u16 v24, v18, 1.0", "Unsupported 16-bit integer operand") @@ -16906,7 +16906,7 @@ def refuse(line, message, translator=translate_f16): for line in ("v_add_f16_e64 v24, v18, v19 clamp", "v_mul_f16_e64 v24, v18, v19 mul:2", "v_mul_f16_e64 v24, v18, v19 div:2", "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_sqrt_f16_e64 v24, v18", + "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_rsq_f16_e64 v24, v18", "v_exp_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -17735,8 +17735,8 @@ def refuse(line, message, translator=translate_f16): "v_floor_f16_e64 v24, -v18 clamp", "v_floor_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_rcp_f16_e32 v24, v18", - "v_sqrt_f16_e64 v24, v18", "v_exp_f16_e64 v24, v18"): + "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_rsq_f16_e32 v24, v18", + "v_rsq_f16_e64 v24, v18", "v_exp_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -17798,6 +17798,309 @@ def reader(line): expect_value_error(translate_f16, export, "Unsupported export") +# Plain binary16 VOP1 reciprocal and square root (issue #839): v_rcp_f16 and v_sqrt_f16, e32 and e64. The lowering +# follows the direct compute path: widen16, one binary32 division or sqrt, then narrow16. The Python reference applies +# the same two rounds explicitly, from binary16 to binary32 and from binary32 to binary16, with ties to even. +F16_RCP_SQRT_OPS = ("rcp", "sqrt") +F16_RCP_SQRT_VALUES = ( + 0x0001, 0x0003, 0x0400, 0x0401, 0x3555, # subnormals, binade edges, a plain fraction + 0x3800, 0x3c00, 0x3c01, 0x3c02, 0x3e00, # 0.5, 1, and near 1 where the two rounds matter + 0x4000, 0x4080, 0x4248, 0x4400, 0x4500, # 2, 2.5, pi-ish, 4 and 5 + 0x4900, 0x5100, 0x5b00, 0x6400, 0x7bff, # 10, 40, 112, 1024 and 65504 +) +F16_RCP_SQRT_READER_VALUES = (0x4000, 0x4400, 0x3c02, 0x7bff) +# Chains (a, b): sqrt(a), rcp(sqrt(a)), rcp(b), sqrt(rcp(b)). Both operations feed a result of the other. +F16_RCP_SQRT_CHAINS = ((0x4400, 0x4000), (0x0400, 0x3c02)) +F16_RCP_SQRT_MUTATIONS = ("ops_swapped", "src_high") + + +def f16_rcp_sqrt_reference(op, word, *, mutation=None): + """Binary16 result bits of v_rcp_f16 or v_sqrt_f16 on the low half of word, from the semantics only. + + The source is widened exactly, the real quotient or root is rounded once to binary32 nearest even, and that + binary32 value is rounded to binary16 nearest even. The final rounding uses the sorted finite binary16 grid, so no + formula is shared with the translator. A reciprocal below the binary16 overflow threshold becomes a signed zero; + at or above it, infinity. The negative square root is not used by a fixture and returns a canonical NaN. + """ + if mutation == "ops_swapped": + op = "sqrt" if op == "rcp" else "rcp" + half = (word >> 16 if mutation == "src_high" else word) & 0xffff + value = f16_grid_value(half) + sign = half & 0x8000 + if op == "rcp": + if value == 0: + return sign | 0x7c00 + exact = 1.0 / float(value) + else: + if value < 0: + return 0x7e00 + if value == 0: + return half + exact = math.sqrt(float(value)) + binary32 = struct.unpack("> 16u) & 0xffffu;", text) + assert mutated != text, mutation + return mutated + + +def f16_rcp_sqrt_detecting_program(mutation): + """The first program whose expected words the modelled mutation changes.""" + for kind, index in F16_RCP_SQRT_PROGRAMS: + if f16_rcp_sqrt_expected(kind, index, mutation) != f16_rcp_sqrt_expected(kind, index): + return kind, index + raise AssertionError(f"No program separates {mutation}") + + +def check_f16_rcp_sqrt_reference(): + """The Python side of the draw: pinned rows, the baked values, and the translator's own result on every finite + binary16 source (all 65,536 encodings, of which the negative half of sqrt has no modelled NaN payload).""" + assert len(F16_RCP_SQRT_VALUES) == 20 and len(set(F16_RCP_SQRT_VALUES)) == 20 + assert all((half >> 10) & 31 != 31 for half in F16_RCP_SQRT_VALUES) + for op, half, expected in ( + ("rcp", 0x4000, 0x3800), ("rcp", 0x4400, 0x3400), ("rcp", 0x6400, 0x1400), + ("rcp", 0x0001, 0x7c00), ("rcp", 0x0400, 0x7400), ("rcp", 0x3c01, 0x3bfe), + ("sqrt", 0x4400, 0x4000), ("sqrt", 0x4000, 0x3da8), ("sqrt", 0x4080, 0x3e00), + ("sqrt", 0x0001, 0x0c00), ("sqrt", 0x6400, 0x5000), ("sqrt", 0x7bff, 0x5bff)): + assert f16_rcp_sqrt_reference(op, 0xa5c3_0000 | half) == expected, (op, hex(half), hex(expected)) + for half in range(0x10000): + if (half >> 10) & 31 == 31: + continue + for op in F16_RCP_SQRT_OPS: + ours = f16_rcp_sqrt_reference(op, 0x1234_0000 | half) + theirs = pixel_aot.f16_rcp_sqrt_result(op, half) + if op == "sqrt" and half & 0x8000 and half & 0x7fff: + assert theirs is None, (op, hex(half), theirs) + else: + assert ours == theirs, (op, hex(half), hex(ours), theirs) + assert len(pixel_aot.VOP1_F16_UNARY) == 2 + + +def check_f16_rcp_sqrt_mutation_coverage(): + """Every deviation changes an expected word of some program.""" + for kind, index in F16_RCP_SQRT_PROGRAMS: + assert len(f16_rcp_sqrt_expected(kind, index)) == 4, (kind, index) + for mutation in F16_RCP_SQRT_MUTATIONS: + f16_rcp_sqrt_detecting_program(mutation) + assert f16_rcp_sqrt_reference("rcp", 0x4000) == 0x3800 + assert f16_rcp_sqrt_reference("rcp", 0x4000, mutation="ops_swapped") == 0x3da8 + assert f16_rcp_sqrt_reference("sqrt", 0x4400) == 0x4000 + assert f16_rcp_sqrt_reference("sqrt", 0x4400, mutation="ops_swapped") == 0x3400 + + +def check_f16_rcp_sqrt_controls(): + """Lowering, spelling, input proof, mode, modifier and reader refusals of v_rcp_f16 and v_sqrt_f16.""" + check_f16_rcp_sqrt_reference() + check_f16_rcp_sqrt_mutation_coverage() + prefix = ["v_mov_b32_e32 v18, 0x35554000", "v_mov_b32_e32 v19, 0xd1a74400", "s_mov_b32 s60, 0x35550400"] + calls = {"rcp": "(1.0f / ", "sqrt": "sqrt("} + + def program(*lines): + return uncompressed_export([*prefix, *lines]) + + def refuse(line, message, translator=translate_f16): + expect_value_error(translator, program(line), message) + + # Lowering and spelling: the bare, _e32 and _e64 spellings are one lowering. + for op in F16_RCP_SQRT_OPS: + spelled = [translate_f16(program(f"v_{op}_f16{suffix} v24, v18")) for suffix in ("", "_e32", "_e64")] + assert spelled[0] == spelled[1] == spelled[2], op + body = spelled[0].split("uint4 main", 1)[1] + assert calls[op] + "widen16(hf" in body, (op, body) + assert "narrow16(hs" in body, op + for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): + assert forbidden not in body, (op, forbidden) + # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals. + for token, bits in (*pixel_aot.INLINE_F16.items(), ("0", 0), ("0x3555", 0x3555), ("0x8000", 0x8000), + ("0x7bff", 0x7bff)): + for op in F16_RCP_SQRT_OPS: + for encoding in ("_e32", "_e64"): + assert f"_0 = ({bits}u) & 0xffffu;" in translate_f16(program(f"v_{op}_f16{encoding} v24, {token}")), token + for line in ("v_rcp_f16_e64 v24, s60", "v_sqrt_f16_e32 v24, s60", "v_rcp_f16_e32 v24, v18"): + translate_f16(program(line)) + # A finite source is enough even when the result is not finite: rcp(0) is a signed infinity, and sqrt(-2) is a NaN. + for op, token in (("rcp", "0x0001"), ("rcp", "0"), ("rcp", "0x8000"), ("rcp", "-2.0"), ("sqrt", "-2.0")): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + translate_f16(program("v_mov_b32_e32 v20, v18", "v_rcp_f16 v24, v20")) + translate_f16(program("s_mov_b32 s61, s60", "v_sqrt_f16_e64 v24, s61")) + translate_f16(program("v_sqrt_f16 v24, 0x4400", "v_rcp_f16 v25, v24", "v_sqrt_f16 v26, v25", + "v_cvt_f32_f16 v12, v26")) + expect_value_error(translate_f16, program("v_rcp_f16 v24, 0", "v_sqrt_f16 v25, v24"), + "binary16 operand is not finite: v24") + # Entry profile: unknown or an unsupported declaration refuses every spelling. + for op in F16_RCP_SQRT_OPS: + for suffix in ("", "_e32", "_e64"): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), + program(f"v_{op}_f16{suffix} v24, v18"), "binary16 denormal mode unknown at entry") + for state in ("flush", "ftz", "", False): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, + half_denorm=state), program("v_rcp_f16 v24, v18"), + "Invalid binary16 denormal entry state") + # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. + for line, token in (("v_rcp_f16_e64 v24, s44", "s44"), ("v_sqrt_f16 v24, v30", "v30"), + ("v_rcp_f16_e64 v24, v12", "v12")): + refuse(line, f"binary16 operand lacks a finite proof: {token}") + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, s44", "v_sqrt_f16 v24, v20"), + "binary16 operand lacks a finite proof: v20") + expect_value_error(translate_f16, program("v_add_nc_u16 v25, v18, v19", "v_rcp_f16 v24, v25"), + "binary16 operand lacks a finite proof: v25") + # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. + for op in F16_RCP_SQRT_OPS: + for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"binary16 operand is not finite: {token}") + for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, 0x7e00", "v_rcp_f16 v24, v20"), + "binary16 operand is not finite: v20") + # Source modifiers, integer inline constants, floats and other operands. + for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): + refuse(f"v_rcp_f16_e64 v24, {token}", f"Unsupported binary16 source modifier {token}") + refuse(f"v_sqrt_f16_e32 v24, {token}", f"Unsupported binary16 source modifier {token}") + for token in ("1", "64", "-1", "-16", "5"): + refuse(f"v_sqrt_f16_e64 v24, {token}", f"Unsupported binary16 integer inline constant {token}") + for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): + refuse(f"v_rcp_f16_e64 v24, {token}", f"Unsupported binary16 operand {token}") + refuse("v_sqrt_f16_e64 v24, 0x10000", "16-bit literal out of range: 0x10000") + refuse("v_rcp_f16_e64 v256, 1.0", "Register out of range: v256") + refuse("v_sqrt_f16_e64 v24, v256", "Register out of range: v256") + refuse("v_rcp_f16_e64 v24, s106", "Register out of range: s106") + # Unmodelled modifiers and neighbouring forms fall through to the generic refusal. + for line in ("v_rcp_f16_e64 v24, v18 clamp", "v_sqrt_f16_e64 v24, v18 clamp", + "v_rcp_f16_e64 v24, v18 mul:2", "v_sqrt_f16_e64 v24, v18 div:2", + "v_rcp_f16_e64 v24, v18 mul:4", "v_sqrt_f16_e64 v24, v18 op_sel:[0,1]", + "v_rcp_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_sqrt_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", "v_rsq_f16_e32 v24, v18", + "v_exp_f16_e64 v24, v18", "v_log_f16_e32 v24, v18"): + refuse(line, "Unsupported instruction") + + # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. + def float_f16(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, half_denorm=pixel_aot.HALF_DENORM_PRESERVE) + + base = with_constants([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(float_f16, base[:load + 1] + ["v_rcp_f16_e64 v24, s44"] + base[load + 1:], + "Constant read before load completion") + expect_value_error(float_f16, base[:sample + 1] + ["v_sqrt_f16_e64 v12, 1.0"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(float_f16, base[:sample + 1] + ["v_rcp_f16_e64 v24, v12"] + base[sample + 1:], + "Sample used before vmcnt wait") + float_f16(base[:sample + 1] + ["v_sqrt_f16_e64 v20, 1.0"] + base[sample + 1:]) + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(float_f16, base[:masked] + ["v_rcp_f16_e64 v24, 1.0"] + base[masked:], + "Invalid binary16 unary operation") + # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. + for spelling in (f"v_{op}_f16{suffix}" for op in F16_RCP_SQRT_OPS for suffix in ("_e32", "_e64")): + line = f"{spelling} v24, v18" + expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), + f"under round toward zero: {spelling}") + assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( + uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) + # Readers. The audited ones read a unary result; every other reader of the tag refuses it. + produced = [*prefix, "v_rcp_f16_e32 v24, v18", "v_sqrt_f16_e64 v25, v18"] + for register in (24, 25): + for line in (f"v_cvt_f32_f16_e32 v12, v{register}", f"v_cvt_f32_f16_e64 v12, v{register}", + f"v_cvt_f32_f16_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + f"v_mov_b32_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): + translate_f16(program(*produced, line)) + sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + for line, message in ((f"v_cvt_f32_f16_sdwa v12, v{register} {sdwa}WORD_1", + "Reads the undefined high half of a 16-bit result"), + (f"v_mov_b32_e32 v12, v{register}", "Expected a numeric register"), + (f"v_add_nc_u16 v12, v{register}, v18", "Expected a numeric register")): + expect_value_error(translate_f16, program(*produced, line), message) + + # Integer to binary16 (issue #839): v_cvt_f16_i16 and v_cvt_f16_u16, e32 and e64 (LLVM 15.0.7 VOP1Instructions.td L432-433: # sint_to_fp and uint_to_fp, round to nearest even). The source is the low 16 bits through the audited low-16 integer # reader: a runtime i16 source needs no proof (every i16 is finite) but its result carries no known value; a u16 source must @@ -18161,7 +18464,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", - "v_rcp_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", + "v_rsq_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -18524,7 +18827,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", - "v_rcp_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): + "v_rsq_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") # Entry profile: unknown or an unsupported declaration refuses every spelling of both kinds. for kind in ("i16", "u16"): @@ -19429,9 +19732,9 @@ def _check_controls_inline(directory): for expected in ("= ceil(alu", "= round(alu", "= round(params[1].x);", "= ceil((-params[1].y));"): assert expected in source, expected # Neighbouring forms: other widths, output modifiers, a second source and the IEEE-flag reciprocal. - for old, new in (("v_ceil_f32_e32 v12, v18", "v_rcp_f16_e32 v12, v18"), + for old, new in (("v_ceil_f32_e32 v12, v18", "v_rsq_f16_e32 v12, v18"), ("v_ceil_f32_e32 v12, v18", "v_ceil_f64_e32 v[12:13], v[18:19]"), - ("v_rndne_f32_e32 v13, v19", "v_rcp_f16_e32 v13, v19"), + ("v_rndne_f32_e32 v13, v19", "v_rsq_f16_e32 v13, v19"), ("v_rndne_f32_e32 v13, v19", "v_rndne_f32_e32 v13, v19, v18"), ("v_rndne_f32_e64 v14, s45", "v_rndne_f32_e64 v14, s45 mul:2"), ("v_ceil_f32_e64 v15, -s46", "v_ceil_f32_e64 v15, -s46 div:2"), @@ -20688,6 +20991,7 @@ def _check_controls_inline(directory): "check_int16_ternary_controls", "check_f16_arith_controls", "check_f16_round_controls", + "check_f16_rcp_sqrt_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -20696,6 +21000,7 @@ def _check_controls_inline(directory): _PRIORITY_SUBCHECKS = ( "check_s_version", "check_f16_round_controls", + "check_f16_rcp_sqrt_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -27766,6 +28071,46 @@ def case(kind, index, tag): expect_value_error(translate_f16, refused, "Reads the undefined high half of a 16-bit result") +def check_f16_rcp_sqrt_draw(directory, compiler, renderer, backend): + """v_rcp_f16 and v_sqrt_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. + + Five baked programs run 20 sources through both ops in a rotation of e32, e64, SGPR and literal forms and pack two + results per word; four reader programs and two chains cover the audited readers and both result orders. Two + deviations must each mismatch (one batch per mutation; the statuses are printed): rcp and sqrt swapped, and a source + read from bits 31:16. A source nothing proves is refused at translation. + + Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's + high half is not measured here; the source-high mutation is the high-half control for the sources. + """ + check_f16_rcp_sqrt_mutation_coverage() + source = directory / "f16_rcp_sqrt.hlsl" + shader = directory / "f16_rcp_sqrt.cso" + constants = bytes(256) + + def build(text): + source.write_text(text, encoding="ascii") + compile_shader(compiler, source, shader) + + def case(kind, index, tag): + path = directory / f"f16_rcp_sqrt-{tag}-{kind}-{index}.case" + write_case(path, constants, tuple(as_float(word) for word in f16_rcp_sqrt_expected(kind, index)), integer_rt=True) + return path + + programs = {key: f16_rcp_sqrt_program(*key) for key in F16_RCP_SQRT_PROGRAMS} + for key in F16_RCP_SQRT_PROGRAMS: + build(translate_f16(programs[key])) + run_pixel_batch(renderer, backend, shader, [(case(*key, "ref"), "pass")]) + for mutation in F16_RCP_SQRT_MUTATIONS: + key = f16_rcp_sqrt_detecting_program(mutation) + build(f16_rcp_sqrt_mutated(mutation, programs[key])) + statuses, _ = run_pixel_batch_statuses(renderer, backend, shader, [case(*key, "mut")]) + print(f"f16_rcp_sqrt mutation {mutation}: program {key} statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"Mutating {mutation} escaped detection") + expect_value_error(translate_f16, uncompressed_export(["v_rcp_f16_e64 v24, s44"]), + "binary16 operand lacks a finite proof: s44") + + def check_f16_fmac_ldexp_draw(directory, compiler, renderer, backend): """v_fmac_f16 and v_ldexp_f16 against the independent Python reference: 24 baked fused multiply-accumulate rows (cancellation, rows where rounding the product first gives another result, signed zero results, ties into the @@ -28027,7 +28372,7 @@ def main(): "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", "draw-cmpx-e64", "draw-cmpx-sdwa", "draw-scc-skip", "draw-s-call", "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", - "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", + "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-f16-cvt-norm", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, @@ -28064,6 +28409,7 @@ def main(): "draw-int16-ternary": check_int16_ternary_draw, "draw-f16-arith": check_f16_arith_draw, "draw-f16-round": check_f16_round_draw, + "draw-f16-rcp-sqrt": check_f16_rcp_sqrt_draw, "draw-f16-fmac-ldexp": check_f16_fmac_ldexp_draw, "draw-f16-cvt-int16": check_f16_cvt_int16_draw, "draw-f16-to-int16": check_f16_to_int16_draw, diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 77827649f7..bcd6178a77 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6270,7 +6270,7 @@ def test_shift64_scanner_support(self): self.assertFalse(is_instruction_supported(line), line) def test_low16_binary16_e32_scanner_support(self): - """The twelve plain binary16 e32 forms pixel_aot lowers (low 16 bits only) are supported; modifiers, the e64 + """The plain binary16 e32 forms pixel_aot lowers (low 16 bits only) are supported; modifiers, the e64 spelling of the integer conversions and sources the translator refuses are not.""" supported = [] for op in ("add", "sub", "subrev", "mul"): @@ -6282,6 +6282,8 @@ def test_low16_binary16_e32_scanner_support(self): f"v_{op}_f16_e32 v24, 0x3c00, v19", f"v_{op}_f16_e32 v24, 0, v19"] for op in ("floor", "ceil", "trunc", "rndne"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] + for op in ("rcp", "sqrt"): + supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] for kind in ("i16", "u16"): supported += [f"v_cvt_f16_{kind}_e32 v24, v18", f"v_cvt_f16_{kind}_e32 v24, s45", f"v_cvt_f16_{kind}_e32 v24, 5", f"v_cvt_f16_{kind}_e32 v24, 0x1234"] @@ -6308,6 +6310,8 @@ def test_low16_binary16_e32_scanner_support(self): "v_fmac_f16_e32 v24, 3, v19", "v_floor_f16_e32 v24, -v18", "v_floor_f16_e32 v24, v18 clamp", + "v_rcp_f16_e32 v24, -v18", + "v_sqrt_f16_e32 v24, v18 clamp", "v_fract_f16_e32 v24, v18", "v_cvt_f16_i16_e32 v24, 65", "v_cvt_f16_u16_e32 v24, 0x10000", @@ -6317,11 +6321,13 @@ def test_low16_binary16_e32_scanner_support(self): ] for line in refused: self.assertFalse(is_instruction_supported(line), line) - for opcode in ("v_add_f16", "v_subrev_f16", "v_rndne_f16", "v_cvt_f16_u16", "v_fmac_f16", "v_ldexp_f16"): + for opcode in ("v_add_f16", "v_subrev_f16", "v_rndne_f16", "v_rcp_f16", "v_sqrt_f16", + "v_cvt_f16_u16", "v_fmac_f16", "v_ldexp_f16"): self.assertIn(opcode, KNOWN_RDNA2_BASE_OPCODES) def test_binary16_e64_scanner_translator_agreement(self): - """The scanner accepts the plain binary16 VOP2 and VOP1 rounding e64 forms exactly when pixel_aot lowers them.""" + """The scanner accepts the plain binary16 VOP2, VOP1 rounding and VOP1 unary e64 forms exactly when pixel_aot + lowers them.""" import pixel_aot from pixel_aot_check import uncompressed_export @@ -6344,6 +6350,9 @@ def translator_accepts(line): for op in ("floor", "ceil", "trunc", "rndne"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] + for op in ("rcp", "sqrt"): + accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", + f"v_{op}_f16_e64 v24, 0x4248"] refused = [ "v_add_f16_e64 v24, -v18, v19", "v_add_f16_e64 v24, v18, -v19", "v_add_f16_e64 v24, |v18|, v19", "v_add_f16_e64 v24, abs(v18), v19", "v_add_f16_e64 v24, neg(v18), v19", @@ -6352,10 +6361,12 @@ def translator_accepts(line): "v_add_f16_e64 v24, 3, v19", "v_add_f16_e64 v24, v18, 3", "v_add_f16_e64 v24, 3.0, v19", "v_add_f16_e64 v24, 0x10000, v19", "v_add_f16_e64 v24, v256, v19", "v_add_f16_e64 v256, v18, v19", "v_add_f16_e64 v24, s106, v19", "v_add_f16_e64 v24, v18", "v_add_f16_e64 v24, v18, v19, v19", - "v_fma_f16_e64 v24, v18, v19, v19", "v_rcp_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", + "v_fma_f16_e64 v24, v18, v19, v19", "v_rsq_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", "v_floor_f16_e64 v24, -v18", "v_floor_f16_e64 v24, |v18|", "v_floor_f16_e64 v24, v18 clamp", "v_floor_f16_e64 v24, v18 mul:2", "v_floor_f16_e64 v24, 3", "v_floor_f16_e64 v24, 0x10000", "v_floor_f16_e64 v24, v256", "v_floor_f16_e64 v24, v18, v19", "v_rndne_f16_e64 v24", + "v_rcp_f16_e64 v24, -v18", "v_sqrt_f16_e64 v24, |v18|", "v_rcp_f16_e64 v24, v18 clamp", + "v_sqrt_f16_e64 v24, v18 mul:2", "v_rcp_f16_e64 v24, 3", "v_sqrt_f16_e64 v24, 0x10000", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 4ea724487d..9ad32beaea 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -2107,6 +2107,137 @@ def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bi # rounding mode, and HLSL round is round-half-to-even in DXIL (the binary32 rndne entry of ALU relies on it). VOP1_F16_ROUND = {"floor": "floor({0})", "ceil": "ceil({0})", "trunc": "trunc({0})", "rndne": "round({0})"} +# Plain binary16 VOP1 unary arithmetic (issue #839). These follow the direct compute lowering: widen the low half +# exactly, evaluate one binary32 operation, then narrow with the same integer nearest-even conversion v_cvt_f16_f32 +# uses. AMD RDNA 2 section 12.8 defines D.f16 = 1.0 / S0.f16 and D.f16 = sqrt(S0.f16). +VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})"} + + +def _f16_fraction(bits): + """The exact value of a finite binary16 encoding.""" + exponent, mantissa = (bits >> 10) & 0x1f, bits & 0x3ff + if exponent == 0x1f: + raise ValueError(f"binary16 operand is not finite: {bits:#06x}") + magnitude = Fraction(mantissa, 1 << 24) if exponent == 0 else Fraction(mantissa | 0x400) * Fraction(2) ** (exponent - 25) + return -magnitude if bits & 0x8000 else magnitude + + +def _round_fraction_integer(numerator, denominator): + """Round a non-negative rational to the nearest integer, ties to even.""" + quotient, remainder = divmod(numerator, denominator) + if remainder * 2 > denominator or (remainder * 2 == denominator and quotient & 1): + quotient += 1 + return quotient + + +def _floor_log2_fraction(value): + """floor(log2(value)) for a positive Fraction.""" + exponent = value.numerator.bit_length() - value.denominator.bit_length() + if value < Fraction(2) ** exponent: + exponent -= 1 + elif value >= Fraction(2) ** (exponent + 1): + exponent += 1 + return exponent + + +def _fraction_to_f32(value): + """Binary32 bits nearest to a finite Fraction, ties to even. The binary16 unary results need no binary32 subnormal.""" + sign = 0x80000000 if value < 0 else 0 + magnitude = abs(value) + if magnitude == 0: + return sign + exponent = _floor_log2_fraction(magnitude) + if exponent < -126: + scaled = magnitude * (1 << 149) + significand = _round_fraction_integer(scaled.numerator, scaled.denominator) + if significand == 0: + return sign + if significand >= 1 << 23: + return sign | (1 << 23) + return sign | significand + scaled = magnitude / (Fraction(2) ** (exponent - 23)) + significand = _round_fraction_integer(scaled.numerator, scaled.denominator) + if significand == 1 << 24: + significand, exponent = 1 << 23, exponent + 1 + if exponent > 127: + return sign | 0x7f800000 + return sign | ((exponent + 127) << 23) | (significand - (1 << 23)) + + +def _f32_fraction(bits): + """The exact positive value of a finite non-negative binary32 encoding.""" + exponent, mantissa = (bits >> 23) & 0xff, bits & 0x7fffff + assert not bits & 0x80000000 and exponent != 0xff + if exponent == 0: + return Fraction(mantissa, 1 << 149) + return Fraction(mantissa | 0x800000, 1) * Fraction(2) ** (exponent - 150) + + +def _f32_sqrt_bits(value): + """Nearest binary32 encoding of the square root of a non-negative Fraction, ties to even.""" + if value == 0: + return 0 + low, high = 0, 0x7f7fffff + while low < high: + middle = (low + high + 1) // 2 + if _f32_fraction(middle) ** 2 <= value: + low = middle + else: + high = middle - 1 + square = _f32_fraction(low) ** 2 + if square == value: + return low + upper = low + 1 + midpoint = (_f32_fraction(low) + _f32_fraction(upper)) / 2 + if value < midpoint ** 2: + return low + if value > midpoint ** 2: + return upper + return low if low & 1 == 0 else upper + + +def _fraction_to_f16(value): + """Binary16 encoding nearest to a finite Fraction, ties to even, with narrow16's overflow and zero rules.""" + sign = 0x8000 if value < 0 else 0 + magnitude = abs(value) + if magnitude == 0: + return sign + if magnitude >= 65520: + return sign | 0x7c00 + if magnitude < Fraction(2) ** -14: + scaled = magnitude * (1 << 24) + return sign | _round_fraction_integer(scaled.numerator, scaled.denominator) + exponent = _floor_log2_fraction(magnitude) + scaled = magnitude / (Fraction(2) ** (exponent - 10)) + significand = _round_fraction_integer(scaled.numerator, scaled.denominator) + if significand == 1 << 11: + significand, exponent = 1 << 10, exponent + 1 + if exponent >= 16: + return sign | 0x7c00 + return sign | ((exponent + 15) << 10) | (significand - (1 << 10)) + + +def f16_rcp_sqrt_result(name, bits): + """Binary16 result bits of v_rcp_f16 or v_sqrt_f16 on a finite operand, or None for an unknown NaN. + + The direct compute lowering divides in binary32 or calls its square-root intrinsic (opcode 24), then narrows with + packed_half_rne. The intermediate binary32 rounding therefore matters: rounding the exact quotient or root straight + to binary16 would double-round. A reciprocal of zero gives the signed infinity. The square root of a negative operand + is a NaN whose payload is not modelled, so None is returned for it. + """ + value = _f16_fraction(bits) + sign = bits & 0x8000 + if name == "rcp": + if value == 0: + return sign | 0x7c00 + return _fraction_to_f16(_f32_fraction(_fraction_to_f32(1 / abs(value))) * (-1 if sign else 1)) + assert name == "sqrt" + if value == 0: + return bits + if sign: + return None + return _fraction_to_f16(_f32_fraction(_f32_sqrt_bits(value))) + def f16_round_result(name, bits): """Exact binary16 result bits of one VOP1_F16_ROUND op on a finite operand. @@ -7798,6 +7929,27 @@ def known_sample_float(reg): lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result + elif m := match(rf"v_({'|'.join(VOP1_F16_UNARY)})_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): + # Plain binary16 VOP1 reciprocal and square root under the rules of the VOP2 arithmetic above: a statically + # proven finite source, the declared entry profile, no modifier, clamp or omod. These match the direct + # compute lowering: widen16, one binary32 division or sqrt, then narrow16. The result is ("half16", alu). + name, encoding, dst, token = m.groups() + if mask != "entry": + raise ValueError("Invalid binary16 unary operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if not 0 <= int(dst[1:]) <= 255: + raise ValueError(f"Register out of range: {dst}") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + word, proven = half16_arith_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_rcp_sqrt_result(name, proven) + lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") + lines.append(f" precise float hs{i} = {VOP1_F16_UNARY[name].format(f'widen16(hf{i}_0)')};") + lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + vector[dst] = ("half16", f"alu{i}") + if result is not None: + known_half[f"alu{i}"] = result elif m := match(rf"v_({'|'.join(VOP1_F16_ROUND)})_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): # Plain binary16 VOP1 rounding under the rules of the VOP2 arithmetic above: a statically proven finite # source, the declared entry profile, no modifier, clamp or omod (those fall through to the generic diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 6fc5cbc3dc..c376543339 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -77,6 +77,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: PIXEL_VOP3_INT16 = pixel_aot.VOP3_INT16 if pixel_aot is not None else {} PIXEL_VOP2_F16 = tuple(pixel_aot.VOP2_F16) if pixel_aot is not None else () PIXEL_VOP1_F16_ROUND = tuple(pixel_aot.VOP1_F16_ROUND) if pixel_aot is not None else () +PIXEL_VOP1_F16_UNARY = tuple(pixel_aot.VOP1_F16_UNARY) if pixel_aot is not None else () PIXEL_VOP2_F16_FUSED_SCALE = tuple(pixel_aot.VOP2_F16_FUSED_SCALE) if pixel_aot is not None else () PIXEL_INLINE_F16 = tuple(pixel_aot.INLINE_F16) if pixel_aot is not None else () PIXEL_VCC = r"(?:vcc(?:_lo)?)" @@ -308,6 +309,11 @@ def lower_rejection_causes(results: list[dict]) -> dict: SUPPORTED_INSTRUCTIONS_REGEX.append( rf"v_(?:{_vop1_f16_round})_f16_(?:e32|e64)\s+{INT16_VGPR},\s+{F16_ARITH_SOURCE}" ) +if PIXEL_VOP1_F16_UNARY: + _vop1_f16_unary = "|".join(map(re.escape, PIXEL_VOP1_F16_UNARY)) + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_(?:{_vop1_f16_unary})_f16_(?:e32|e64)\s+{INT16_VGPR},\s+{F16_ARITH_SOURCE}" + ) if pixel_aot is not None: SUPPORTED_INSTRUCTIONS_REGEX.append( rf"v_cvt_f16_(?:i16|u16)_e32\s+{INT16_VGPR},\s+{INT16_SOURCE}" @@ -460,13 +466,14 @@ def lower_rejection_causes(results: list[dict]) -> dict: | {f"v_pk_{name}" for name in PIXEL_VOP3P_INT16} | {f"v_{name}" for name in PIXEL_VOP3_INT16} | {f"v_{name}" for name in PIXEL_VOP3_INT16_TERNARY} - | {f"v_{name}_f16" for name in PIXEL_VOP2_F16 + PIXEL_VOP2_F16_FUSED_SCALE + PIXEL_VOP1_F16_ROUND} + | {f"v_{name}_f16" for name in + PIXEL_VOP2_F16 + PIXEL_VOP2_F16_FUSED_SCALE + PIXEL_VOP1_F16_ROUND + PIXEL_VOP1_F16_UNARY} | {"v_cvt_f16_i16", "v_cvt_f16_u16"} | { # Decoding only: no translator lowers these binary16 VOP1/VOP2 forms. "v_cvt_u16_f16", "v_cvt_i16_f16", "v_fract_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", - "v_rcp_f16", "v_sqrt_f16", "v_rsq_f16", "v_log_f16", "v_exp_f16", "v_sin_f16", "v_cos_f16", + "v_rsq_f16", "v_log_f16", "v_exp_f16", "v_sin_f16", "v_cos_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_fmac_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", "v_pk_fmac_f16", }