Tests: an RDNA2 wave64 reference interpreter, every wave64 form against it, and a fuzzer #3716

Open
Royalflamejlh wants to merge 6 commits from upstream-pr/3716 into main
Royalflamejlh commented 2026-12-02 19:24:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T19:24:54Z.


(Edited: head de05c50e. After thehollowedone's and CharlyRien's latest reviews: v_sad_u32 wraps; the known fuzz classes now check the mismatch itself or its cause; OMOD stops until the program writes MODE; a NaN from float arithmetic is exact to the next float instruction; a gap at the start of the code stops the run; s_buffer_load masks the summed address. After the reviews of fyreic-dev, CharlyRien and Foniass: every (case, form) outcome is pinned per adapter, the fuzz counts and floors what it compares and knows mismatches by class, a panic is a failure, the float tolerance is narrowed, and the reference rules CharlyRien found wrong are fixed, each with a test. The test counts and the pinned table's size below are new; the earlier "40,000 seeds, 0 mismatches" compared almost nothing and is withdrawn.)

A CPU interpreter of RDNA2 code with true wave64 semantics (gpu::rdna2_ref, test-only), and a harness that runs each wave64 form XCL has against it. Until now every wave64 check compared a form with another form, or with our own lowering run on the CPU, so a rule that both get wrong passes. The reference is written from AMD's RDNA2 ISA guide (document 70648) and uses nothing of recomp/ or dxil/ except the runner's ABI types and rdna2's decoder. An instruction, operand or modifier it does not model stops the run; it never skips one. On a GPU with 32-lane waves it found 4 mismatches in main's forms (listed below). No translator code is changed here.

This is one PR of about 5,000 lines rather than a stack of ~400-line parts, because the interpreter, its tests, the harness and the fuzzer can't be judged apart: the harness is what shows the interpreter right wherever the forms agree with each other, and two interpreter bugs were found only that way (ds_swizzle's source operand, v_bfe_i32's arithmetic shift). Each commit builds and passes on its own, one ISA area per commit.

What is in it

  • rdna2_ref/{mod,salu}.rs: the core (one wave of 32 or 64 lanes, VCC and EXEC as SGPR pairs, a step limit, Stop::Unsupported, a word that does not decode stops the run), grown from the 64-lane Machine of the folded-form tests in #3562; SOPP/SOPK/SOP1/SOP2/SOPC. The decoder check is in the same commit: the opcode name of one encoding of every modelled instruction against llvm-mc --disassemble where llvm-mc runs, or against a listing (XCL_LLVM_DISASM); skipped otherwise, and in CI. It checks the opcode-to-name table, not field positions or semantics.
  • valu.rs, lanes.rs: integer VALU, carries, DPP16/DPP8/SDWA, readlane/writelane/readfirstlane, mbcnt, permlane16/x16, movrel. Tests that go red when a rule is flipped (Flip): lane select modulo 32, permlanex16 on its own row, EXEC ignored, VCC read as its low half.
  • mem.rs: SMEM, buffer/tbuffer with formats and atomics and the range checks of each OOB_SELECT mode (8.1, Table 35), global, LDS (64 KB a group), ds_swizzle/permute/bpermute within each 32-lane half (10.4.4); run_compute with groups of waves meeting at s_barrier.
  • float.rs, image.rs: the f32 set exactly (legacy multiply, zero and NaN rules of min/max/med3, conversions, fma_mix, OMOD/CLAMP under MODE's IEEE, DX10_CLAMP and denormal bits, OMOD only once the program has written MODE; a MODE bit it does not model stops the run, as do v_fmac_legacy/v_fma_legacy until their rounding is measured). Transcendentals are tainted: rcp/rsq/sqrt with a ULP bound on their own result only, sin/cos with D3D's absolute 0.0008, exp/log not compared; a copy keeps the taint, a value computed from it is not compared, and a NaN from float arithmetic agrees with any NaN and is exact to the next float instruction. The taint does not reach addresses or control flow: a load from a tainted address, or EXEC from a compare of a tainted value, is compared exactly; no case or fuzz program does either today. Image load/store/atomics/resinfo, sample_lz/sample_l/gather4 at level 0.
  • forms.rs: the harness (HLSL split, direct split, per-lane split; the native wave64 forms on a 64-lane GPU; on the CPU, the lowering run by its own interpreter, for which lower::tests::run_insts is split out of run_mem). 15 cases, among them a 64-lane OR/AND/MIN reduction in the shape of a tile classifier over 6 groups of 16 x 16; EXEC, VCC and SCC are copied to SGPRs at the end of each kernel case. EXPECTED pins the outcome of every (case, form) pair per adapter, 58 lines (13 for the lowering on the CPU, 45 for the split forms on NVIDIA): a match, a known mismatch from a named dword, or a refusal with its reason. Any change fails with the line it would need; on an adapter without lines (AMD, Intel) the test prints them and skips, as do the flip test and the GPU fuzz. Negative controls: each of the four flipped rules changes a compared word of its cases, and every form agrees with the reference on a case of every flip. wave64_pack_programs_the_reference_models (XCL_SAMPLE_RPF, ignored by default) counts the pack's wave64 compute programs the reference models whole.
  • fuzz.rs: seeded random wave64 programs (if/else to depth 3, loops each lane leaves on its own pass, whole-wave sections, lane exchanges under a partial EXEC, masks as data, LDS across the waves of a group, partial waves; float inputs with signed zeros, infinities, a NaN and rounding products), a shrinker that keeps a mismatch in its class and prints the smallest program as rdna2::encode lines. CPU: 1,000 programs through the reference alone and 1,000 of what the lowering translates against its interpreter; GPU: 100 seeds in every form; XCL_FUZZ_WAVE64_SEEDS for longer runs. Each test prints per form the seeds compared, refusals by reason and mismatches by class, and fails on a mismatch of no class in fuzz.rs's KNOWN (classes of mismatch, not seeds), a refusal not in REFUSALS, a failure, or fewer comparisons than the form's floor in MIN_COMPARED_PERCENT (lowering on the CPU 12 %, HLSL and direct split 90 %, per-lane split 10 %), all keyed by adapter.

Mismatches in main's forms (RTX 2070 SUPER, the reference's value / the form's)

  1. ds_bpermute_b32 in a wave64 reads across the halves in the HLSL split form: the index is taken modulo 64, not within the lane's own 32-lane half as the ISA guide says in 10.4.4. Case "ds_swizzle, ds_bpermute and ds_permute", v11 of lane 0: 31684507 / 24204809, 44 lanes. The direct split form refuses the case (ds_permute_b32 ... atomic); with a program that has only ds_bpermute it gives the same wrong lanes as HLSL (the local check below, 3 of 8 words).
  2. A whole-wave section (s_or_saveexec_b64 -1, an identity from v_cndmask, v_readlane 32 and 63) in a wave whose upper half has no threads (a 96-thread group): v_readlane 32 gives 0 instead of the identity the section wrote there. All three split forms; memory dword 128: 7 / 0, 64 dwords. Fuzz seed 1000014 shows it in HLSL and direct split.
  3. HLSL split: -0 instead of +0 (CharlyRien found the cause: DXC's default fast-math folds 0 - x to -x; -Gis keeps it). The new generator also shows x - x of an infinity giving 0 instead of a NaN in HLSL split, likely the same cause.
  4. Per-lane split, and the lowering on the CPU: a whole-wave section while lanes are elsewhere (inside an if/else or a loop, or after a partial EXEC) does not write the lanes that are elsewhere; at 5,000 CPU seeds a base, 12 of 10,000 programs.

CharlyRien's 2,000-seed run on an RTX 3090 adds s_mul_i32 emitted as a signed multiply (HLSL split), direct split with one EXEC half empty at the start, and fma(+0, -4, +0) giving -0. None of these is fixed here; they are open for anyone to take. Only the second is a known class in fuzz.rs (a whole-wave section in an if, one EXEC half empty, confirmed by the section's removal), and CharlyRien measured it as an NVIDIA driver miscompile: the same DXIL is right on WARP. s_mul_i32 and his compute nested if/else group for direct split (fixed on the RTX 3090 by XCL_DXIL_NO_OPT=all, so XCL's DXIL optimiser; WARP crashes on it) are not classes, so a long run on NVIDIA still fails on them.

Also seen: AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have (the decoder check allows that one); and VOP2 0x06 / VOP3 0x140 decode as the fused v_fmac_legacy_f32 / v_fma_legacy_f32 (gfx10.3 names) where gfx10.1 has the unfused mac/mad_legacy. Which one the console has is not settled, so the reference stops on them.

Tested

  • RTX 2070 SUPER (driver 621.01), Ryzen 7 5700X3D, Windows 11 26200, rustc 1.100.0, debug, at de05c50e: cargo test --workspace -- rdna2_ref --test-threads=4: 53 passed, 0 failed, 1 ignored (the pack census); 1 SKIPPED (no llvm-mc). Harness cases: HLSL split 13 match, 2 known mismatches; direct split 13 match, 1 known mismatch, 1 refused; per-lane split 9 match, 1 known mismatch, 5 refused; all four flips checked by all three forms. Fuzzer, 100 seeds: HLSL split 100 compared (5 known: 1 empty upper half, 1 -0, 3 a number for a NaN); direct split 100 compared (1 known); per-lane split 29 compared, 71 refused.
  • The whole suite (cargo test --workspace) was not run at this head; it last ran before the reviews, on this PR's first head: 3032 passed, 0 failed, 53 ignored.
  • Linux, x86_64-pc-windows-gnu under Wine with CPU Vulkan only (GPU tests skip): cargo check -p xcl --release with and without --tests and cargo test -p xcl --lib --release rdna2_ref at every commit (7, 17, 23, 38, 43 and 53 passed, 0 failed, commit by commit); at the head 53 passed, 0 failed, 1 ignored. CPU fuzz: the lowering compared 149 of the 1,000 default seeds (at d2293dcb, 1); XCL_FUZZ_WAVE64_SEEDS=5000: 1,535 of 10,000 compared, 12 mismatches; 9 confirmed as mismatch 4's class, and 3 reported because the lowering refuses the program without its sections, so the cause cannot be confirmed.
  • Shown red: the lowering made to refuse "permlane16 and permlanex16" fails the CPU harness test (expected Match, got Refused); made to refuse 9 of 10 fuzz seeds, both CPU fuzz tests fail ("8 of 500 seeds compared, under its floor of 12 %").
  • The decoder check against llvm-mc 22.1.8 (-mcpu=gfx1013, wave64) through XCL_LLVM_DISASM, after this round's changes: 823 opcode names agree.
  • Before the reviews (on this PR's first head, not rerun): 12 wave64 programs from another GPL-3.0 project's test set, checked locally and not part of this PR: the reference gives the expected words in 12 of 12, HLSL and direct split in 11 (mismatch 1), per-lane split in 7 (5 refused). XCL_SAMPLE_RPF on a retail pack: the reference models 728 of 1,151 distinct wave64 compute programs whole.

Regression run

  • None: test-only. Outside rdna2_ref/ it adds the #[cfg(test)] module line in gpu/mod.rs and splits run_insts out of run_mem inside recomp/lower.rs's test module.

Not tested

  • AMD: there is no AMD card here, so the reference was never compared with hardware and EXPECTED has no AMD lines; cargo test -p xcl --lib rdna2_ref -- --nocapture on an RDNA2/3/4 card prints the per-form counts and the lines to add. The rules not measured by us rest on the ISA text and on measurements others published (DPP and permlane with a source lane off, ds_swizzle/bpermute reading 0 from a lane off, ds_permute's highest sender, readfirstlane under EXEC 0). The native wave64 forms did not run (NVIDIA has no 64-lane waves).
  • The decoder check with llvm-mc run by the test itself: llvm-mc is not installed on the Windows PC, and a Windows test binary under Wine cannot start the Linux one.
  • The RTX 5070 Ti; Linux GPU runs (the lib test binary aborts on our cards under Wine until #3707).

AI use

  • Claude Code, Claude Opus 5.5: wrote the interpreter, the tests, the harness, the fuzzer, the changes after review, the commit messages and this description, and ran the tests listed above.

The description check needs the maintainer's test-only waiver for this head.

<!-- greyfinch-sync:ivall/xcl:issue:5613200806 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T19:24:54Z. --- (Edited: head `de05c50e`. After thehollowedone's and CharlyRien's latest reviews: v_sad_u32 wraps; the known fuzz classes now check the mismatch itself or its cause; OMOD stops until the program writes MODE; a NaN from float arithmetic is exact to the next float instruction; a gap at the start of the code stops the run; s_buffer_load masks the summed address. After the reviews of fyreic-dev, CharlyRien and Foniass: every (case, form) outcome is pinned per adapter, the fuzz counts and floors what it compares and knows mismatches by class, a panic is a failure, the float tolerance is narrowed, and the reference rules CharlyRien found wrong are fixed, each with a test. The test counts and the pinned table's size below are new; the earlier "40,000 seeds, 0 mismatches" compared almost nothing and is withdrawn.) A CPU interpreter of RDNA2 code with true wave64 semantics (`gpu::rdna2_ref`, test-only), and a harness that runs each wave64 form XCL has against it. Until now every wave64 check compared a form with another form, or with our own lowering run on the CPU, so a rule that both get wrong passes. The reference is written from AMD's RDNA2 ISA guide (document 70648) and uses nothing of `recomp/` or `dxil/` except the runner's ABI types and `rdna2`'s decoder. An instruction, operand or modifier it does not model stops the run; it never skips one. On a GPU with 32-lane waves it found 4 mismatches in main's forms (listed below). No translator code is changed here. This is one PR of about 5,000 lines rather than a stack of ~400-line parts, because the interpreter, its tests, the harness and the fuzzer can't be judged apart: the harness is what shows the interpreter right wherever the forms agree with each other, and two interpreter bugs were found only that way (ds_swizzle's source operand, v_bfe_i32's arithmetic shift). Each commit builds and passes on its own, one ISA area per commit. **What is in it** - `rdna2_ref/{mod,salu}.rs`: the core (one wave of 32 or 64 lanes, VCC and EXEC as SGPR pairs, a step limit, `Stop::Unsupported`, a word that does not decode stops the run), grown from the 64-lane `Machine` of the folded-form tests in #3562; SOPP/SOPK/SOP1/SOP2/SOPC. The decoder check is in the same commit: the opcode name of one encoding of every modelled instruction against `llvm-mc --disassemble` where llvm-mc runs, or against a listing (`XCL_LLVM_DISASM`); skipped otherwise, and in CI. It checks the opcode-to-name table, not field positions or semantics. - `valu.rs`, `lanes.rs`: integer VALU, carries, DPP16/DPP8/SDWA, readlane/writelane/readfirstlane, mbcnt, permlane16/x16, movrel. Tests that go red when a rule is flipped (`Flip`): lane select modulo 32, permlanex16 on its own row, EXEC ignored, VCC read as its low half. - `mem.rs`: SMEM, buffer/tbuffer with formats and atomics and the range checks of each OOB_SELECT mode (8.1, Table 35), global, LDS (64 KB a group), ds_swizzle/permute/bpermute within each 32-lane half (10.4.4); `run_compute` with groups of waves meeting at `s_barrier`. - `float.rs`, `image.rs`: the f32 set exactly (legacy multiply, zero and NaN rules of min/max/med3, conversions, fma_mix, OMOD/CLAMP under MODE's IEEE, DX10_CLAMP and denormal bits, OMOD only once the program has written MODE; a MODE bit it does not model stops the run, as do v_fmac_legacy/v_fma_legacy until their rounding is measured). Transcendentals are tainted: rcp/rsq/sqrt with a ULP bound on their own result only, sin/cos with D3D's absolute 0.0008, exp/log not compared; a copy keeps the taint, a value computed from it is not compared, and a NaN from float arithmetic agrees with any NaN and is exact to the next float instruction. The taint does not reach addresses or control flow: a load from a tainted address, or EXEC from a compare of a tainted value, is compared exactly; no case or fuzz program does either today. Image load/store/atomics/resinfo, sample_lz/sample_l/gather4 at level 0. - `forms.rs`: the harness (HLSL split, direct split, per-lane split; the native wave64 forms on a 64-lane GPU; on the CPU, the lowering run by its own interpreter, for which `lower::tests::run_insts` is split out of `run_mem`). 15 cases, among them a 64-lane OR/AND/MIN reduction in the shape of a tile classifier over 6 groups of 16 x 16; EXEC, VCC and SCC are copied to SGPRs at the end of each kernel case. `EXPECTED` pins the outcome of every (case, form) pair per adapter, 58 lines (13 for the lowering on the CPU, 45 for the split forms on NVIDIA): a match, a known mismatch from a named dword, or a refusal with its reason. Any change fails with the line it would need; on an adapter without lines (AMD, Intel) the test prints them and skips, as do the flip test and the GPU fuzz. Negative controls: each of the four flipped rules changes a compared word of its cases, and every form agrees with the reference on a case of every flip. `wave64_pack_programs_the_reference_models` (`XCL_SAMPLE_RPF`, ignored by default) counts the pack's wave64 compute programs the reference models whole. - `fuzz.rs`: seeded random wave64 programs (if/else to depth 3, loops each lane leaves on its own pass, whole-wave sections, lane exchanges under a partial EXEC, masks as data, LDS across the waves of a group, partial waves; float inputs with signed zeros, infinities, a NaN and rounding products), a shrinker that keeps a mismatch in its class and prints the smallest program as `rdna2::encode` lines. CPU: 1,000 programs through the reference alone and 1,000 of what the lowering translates against its interpreter; GPU: 100 seeds in every form; `XCL_FUZZ_WAVE64_SEEDS` for longer runs. Each test prints per form the seeds compared, refusals by reason and mismatches by class, and fails on a mismatch of no class in `fuzz.rs`'s `KNOWN` (classes of mismatch, not seeds), a refusal not in `REFUSALS`, a failure, or fewer comparisons than the form's floor in `MIN_COMPARED_PERCENT` (lowering on the CPU 12 %, HLSL and direct split 90 %, per-lane split 10 %), all keyed by adapter. **Mismatches in main's forms** (RTX 2070 SUPER, the reference's value / the form's) 1. `ds_bpermute_b32` in a wave64 reads across the halves in the HLSL split form: the index is taken modulo 64, not within the lane's own 32-lane half as the ISA guide says in 10.4.4. Case "ds_swizzle, ds_bpermute and ds_permute", v11 of lane 0: 31684507 / 24204809, 44 lanes. The direct split form refuses the case (`ds_permute_b32 ... atomic`); with a program that has only ds_bpermute it gives the same wrong lanes as HLSL (the local check below, 3 of 8 words). 2. A whole-wave section (`s_or_saveexec_b64 -1`, an identity from `v_cndmask`, `v_readlane` 32 and 63) in a wave whose upper half has no threads (a 96-thread group): `v_readlane` 32 gives 0 instead of the identity the section wrote there. All three split forms; memory dword 128: 7 / 0, 64 dwords. Fuzz seed 1000014 shows it in HLSL and direct split. 3. HLSL split: -0 instead of +0 (CharlyRien found the cause: DXC's default fast-math folds `0 - x` to `-x`; `-Gis` keeps it). The new generator also shows `x - x` of an infinity giving 0 instead of a NaN in HLSL split, likely the same cause. 4. Per-lane split, and the lowering on the CPU: a whole-wave section while lanes are elsewhere (inside an if/else or a loop, or after a partial EXEC) does not write the lanes that are elsewhere; at 5,000 CPU seeds a base, 12 of 10,000 programs. CharlyRien's 2,000-seed run on an RTX 3090 adds `s_mul_i32` emitted as a signed multiply (HLSL split), direct split with one EXEC half empty at the start, and `fma(+0, -4, +0)` giving -0. None of these is fixed here; they are open for anyone to take. Only the second is a known class in `fuzz.rs` (a whole-wave section in an if, one EXEC half empty, confirmed by the section's removal), and CharlyRien measured it as an NVIDIA driver miscompile: the same DXIL is right on WARP. `s_mul_i32` and his compute nested if/else group for direct split (fixed on the RTX 3090 by `XCL_DXIL_NO_OPT=all`, so XCL's DXIL optimiser; WARP crashes on it) are not classes, so a long run on NVIDIA still fails on them. Also seen: AMD's tables give `v_readfirstlane_b32` a VOP3 form, which LLVM's gfx10 does not have (the decoder check allows that one); and VOP2 0x06 / VOP3 0x140 decode as the fused `v_fmac_legacy_f32` / `v_fma_legacy_f32` (gfx10.3 names) where gfx10.1 has the unfused mac/mad_legacy. Which one the console has is not settled, so the reference stops on them. **Tested** - RTX 2070 SUPER (driver 621.01), Ryzen 7 5700X3D, Windows 11 26200, rustc 1.100.0, debug, at `de05c50e`: `cargo test --workspace -- rdna2_ref --test-threads=4`: 53 passed, 0 failed, 1 ignored (the pack census); 1 SKIPPED (no llvm-mc). Harness cases: HLSL split 13 match, 2 known mismatches; direct split 13 match, 1 known mismatch, 1 refused; per-lane split 9 match, 1 known mismatch, 5 refused; all four flips checked by all three forms. Fuzzer, 100 seeds: HLSL split 100 compared (5 known: 1 empty upper half, 1 -0, 3 a number for a NaN); direct split 100 compared (1 known); per-lane split 29 compared, 71 refused. - The whole suite (`cargo test --workspace`) was not run at this head; it last ran before the reviews, on this PR's first head: 3032 passed, 0 failed, 53 ignored. - Linux, x86_64-pc-windows-gnu under Wine with CPU Vulkan only (GPU tests skip): `cargo check -p xcl --release` with and without `--tests` and `cargo test -p xcl --lib --release rdna2_ref` at every commit (7, 17, 23, 38, 43 and 53 passed, 0 failed, commit by commit); at the head 53 passed, 0 failed, 1 ignored. CPU fuzz: the lowering compared 149 of the 1,000 default seeds (at d2293dcb, 1); `XCL_FUZZ_WAVE64_SEEDS=5000`: 1,535 of 10,000 compared, 12 mismatches; 9 confirmed as mismatch 4's class, and 3 reported because the lowering refuses the program without its sections, so the cause cannot be confirmed. - Shown red: the lowering made to refuse "permlane16 and permlanex16" fails the CPU harness test (`expected Match, got Refused`); made to refuse 9 of 10 fuzz seeds, both CPU fuzz tests fail ("8 of 500 seeds compared, under its floor of 12 %"). - The decoder check against llvm-mc 22.1.8 (`-mcpu=gfx1013`, wave64) through `XCL_LLVM_DISASM`, after this round's changes: 823 opcode names agree. - Before the reviews (on this PR's first head, not rerun): 12 wave64 programs from another GPL-3.0 project's test set, checked locally and not part of this PR: the reference gives the expected words in 12 of 12, HLSL and direct split in 11 (mismatch 1), per-lane split in 7 (5 refused). `XCL_SAMPLE_RPF` on a retail pack: the reference models 728 of 1,151 distinct wave64 compute programs whole. **Regression run** - None: test-only. Outside `rdna2_ref/` it adds the `#[cfg(test)]` module line in `gpu/mod.rs` and splits `run_insts` out of `run_mem` inside `recomp/lower.rs`'s test module. **Not tested** - AMD: there is no AMD card here, so the reference was never compared with hardware and `EXPECTED` has no AMD lines; `cargo test -p xcl --lib rdna2_ref -- --nocapture` on an RDNA2/3/4 card prints the per-form counts and the lines to add. The rules not measured by us rest on the ISA text and on measurements others published (DPP and permlane with a source lane off, ds_swizzle/bpermute reading 0 from a lane off, ds_permute's highest sender, readfirstlane under EXEC 0). The native wave64 forms did not run (NVIDIA has no 64-lane waves). - The decoder check with llvm-mc run by the test itself: llvm-mc is not installed on the Windows PC, and a Windows test binary under Wine cannot start the Linux one. - The RTX 5070 Ti; Linux GPU runs (the lib test binary aborts on our cards under Wine until #3707). **AI use** - Claude Code, Claude Opus 5.5: wrote the interpreter, the tests, the harness, the fuzzer, the changes after review, the commit messages and this description, and ran the tests listed above. The description check needs the maintainer's test-only waiver for this head.
gut0to commented 2026-12-02 19:45:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-12-02T19:45:54Z.

Review: COMMENTED


AI-assisted review: GPT-6 helped inspect the conversion path; I verified the overflow branch.

<!-- greyfinch-sync:ivall/xcl:review:6157722255 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#pullrequestreview-6157722255). Originally posted by [gut0to](https://github.com/gut0to) on 2026-12-02T19:45:54Z. **Review:** COMMENTED --- AI-assisted review: GPT-6 helped inspect the conversion path; I verified the overflow branch.
gut0to commented 2026-12-02 19:45:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-12-02T19:45:54Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 73

@@ -0,0 +1,286 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {

Medium: f32_to_f16 sends an input that is already infinite through the finite-overflow path. For f32::INFINITY, log2 produces an infinite exponent, so this branch returns 0x7BFF when rtz is true; negative infinity similarly returns 0xFBFF. An exactly representable infinity should remain 0x7C00 or 0xFC00, regardless of rounding direction. Could infinities be handled before finite overflow, with tests for both signs and a finite-overflow control? AI-assisted review: GPT-6 helped inspect the conversion path; I verified the overflow branch.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775026061 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775026061). Originally posted by [gut0to](https://github.com/gut0to) on 2026-12-02T19:45:54Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 73 ~~~~diff @@ -0,0 +1,286 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { ~~~~ --- **Medium**: `f32_to_f16` sends an input that is already infinite through the finite-overflow path. For `f32::INFINITY`, `log2` produces an infinite exponent, so this branch returns `0x7BFF` when `rtz` is true; negative infinity similarly returns `0xFBFF`. An exactly representable infinity should remain `0x7C00` or `0xFC00`, regardless of rounding direction. Could infinities be handled before finite overflow, with tests for both signs and a finite-overflow control? AI-assisted review: GPT-6 helped inspect the conversion path; I verified the overflow branch.
Royalflamejlh commented 2026-12-02 20:19:26 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T20:19:26Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 73

@@ -0,0 +1,286 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {

Right, thanks: an infinite input went through the finite-overflow branch, so round-toward-zero gave 0x7BFF / 0xFBFF. f32_to_f16 now returns ±0x7C00 for infinities before the overflow test (float.rs). an_infinity_stays_infinite_in_f16_whatever_the_rounding covers both signs in both rounding modes, plus a finite overflow (±1e6) that still stops at 0x7BFF / 0xFBFF toward zero and goes to 0x7C00 to nearest; it fails without the change (0x7BFF for +inf) and passes with it. Squashed into the f32 commit; head d2293dcb (also rebased onto main 5ad98adb). rdna2_ref: 29 passed, 0 failed, 1 ignored (CPU, under Wine).

AI use: Claude Code (Claude Opus 5.5) made the fix and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775451558 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775451558). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T20:19:26Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 73 ~~~~diff @@ -0,0 +1,286 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { ~~~~ --- Right, thanks: an infinite input went through the finite-overflow branch, so round-toward-zero gave 0x7BFF / 0xFBFF. `f32_to_f16` now returns ±0x7C00 for infinities before the overflow test (`float.rs`). `an_infinity_stays_infinite_in_f16_whatever_the_rounding` covers both signs in both rounding modes, plus a finite overflow (±1e6) that still stops at 0x7BFF / 0xFBFF toward zero and goes to 0x7C00 to nearest; it fails without the change (0x7BFF for +inf) and passes with it. Squashed into the f32 commit; head `d2293dcb` (also rebased onto `main` `5ad98adb`). `rdna2_ref`: 29 passed, 0 failed, 1 ignored (CPU, under Wine). AI use: Claude Code (Claude Opus 5.5) made the fix and wrote this reply.
fyreic-dev commented 2026-12-02 20:23:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by fyreic-dev on 2026-12-02T20:23:48Z.

Review: CHANGES_REQUESTED


I’d like to land the independent wave64 reference, but the harness can currently stay green when comparisons disappear. In forms.rs, a known output mismatch can become a DXC or dispatch failure and still pass, and a previously working case can become Refused. Could we pin the expected outcome per supported case/form pair and narrow exceptions to the known wrong outputs?

On CPU, fuzz_cpu only fails on Mismatch, while the runner maps interpreter panics to Refused. Please report compared versus reference-only seeds, fail on unexpected refusals and execution failures, and require actual comparisons. The float tolerance also needs a cancellation test or a narrower scope, since an input ULP bound does not carry through subtraction as the same number of output ULPs.

Once those are addressed and the f16 thread is resolved, please share an AMD run with native wave64 results and per-form counts. The description check also needs the maintainer’s test-only waiver for the revised head.

(No agent was used for my review)

<!-- greyfinch-sync:ivall/xcl:review:6158316333 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#pullrequestreview-6158316333). Originally posted by [fyreic-dev](https://github.com/fyreic-dev) on 2026-12-02T20:23:48Z. **Review:** CHANGES_REQUESTED --- I’d like to land the independent wave64 reference, but the harness can currently stay green when comparisons disappear. In `forms.rs`, a known output mismatch can become a DXC or dispatch failure and still pass, and a previously working case can become Refused. Could we pin the expected outcome per supported case/form pair and narrow exceptions to the known wrong outputs? On CPU, fuzz_cpu only fails on Mismatch, while the runner maps interpreter panics to Refused. Please report compared versus reference-only seeds, fail on unexpected refusals and execution failures, and require actual comparisons. The float tolerance also needs a cancellation test or a narrower scope, since an input ULP bound does not carry through subtraction as the same number of output ULPs. Once those are addressed and the f16 thread is resolved, please share an AMD run with native wave64 results and per-form counts. The description check also needs the maintainer’s test-only waiver for the revised head. (No agent was used for my review)
CharlyRien commented 2026-12-02 20:43:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:05Z.

Review: COMMENTED


Thank you for this. A reference that does not share code with the forms is the piece that was missing, and the harness numbers reproduce here. I reviewed it at d2293dcb, by reading the code (five reviewers, see AI use below), and spot-checked by hand every point marked as confirmed. The inline comments are the details; this is the summary.

Tested here

  • RTX 3090 (driver 616.56, wave32 only), Ryzen 9 5950X, Windows 11 22631, rustc 1.100.0, debug, at 9ceea007 (its rdna2_ref differs from d2293dcb only by the f16 infinity fix): cargo test -p xcl --lib rdna2_ref -- --nocapture --test-threads=4.
  • The harness gives the same counts as on your RTX 2070 SUPER: HLSL split 13 match, 2 known; direct split 13 match, 1 known, 1 refused; per-lane split 9 match, 1 known, 5 refused. The two forms tests and the CPU fuzz pass. A GPU fuzz run with 2,000 seeds (XCL_FUZZ_WAVE64_SEEDS=2000) was still running after 20 minutes when I posted this.

Reference rules that look wrong (each can blame a correct form or let a wrong one pass)

  • Against the RDNA2 ISA guide (sections cited inline): S_ABSDIFF_I32 overflow, S_LOAD address alignment, the zero sign and sNaN in V_MIN/V_MAX_F32, RCP/RSQ/SQRT flushing denormals, OMOD ignored with output denormals on, DX10_CLAMP, buffer bounds (OOB_SELECT modes, per component for DWORDxN), W = 1 out of range.
  • Bugs in the code itself: V_CMP_CLASS_F16 converting twice, V_FRACT_F32(NaN), an undecodable word skipped instead of stopping, an 8-bit format shift overflow.
  • Open, with no clear source: the high half of V_CVT_F16_F32 (LLVM says gfx10 keeps it, the guide does not say), the lane order of contending LDS atomics.
  • Fused or unfused V_FMAC_LEGACY / V_FMA_LEGACY: in LLVM the unfused gfx10.1 forms sit under the same MadMacF32 feature as v_mac_f32 / v_mad_f32, which the console keeps; the fused ones come with gfx10.3. That leans toward unfused, without proving it. The reference and XCL both assume fused, so the harness cannot settle it. Stopping (Unsupported) on them until it is measured would be safer.

The harness can stay green on a regression

  • KNOWN is keyed by (case, form) and accepts any mismatch or failure; Refused passes everywhere; a panic counts as Refused; the negative control does not depend on the forms. Details inline.
  • CI has no GPU (ci.yml: Windows runner, Basic Render Driver), so the GPU forms and the "100 GPU seeds" do not run there; only the CPU part does.
  • I expect the forms test to go red on the first GPU with 64-lane waves: the native wave64 HLSL and direct forms take the ds_bpermute index & 63 as well (recomp/emit.rs:4697, dxil/lower_mem.rs:2272), and KNOWN lists only split forms. Not run (no AMD card here).
  • Test gaps: SDWA is modelled but used by no test, case or fuzz program; DPP row and bank masks are always 15, FI = 1, row_ror, movrel and v_swap are never exercised; about twenty SALU rules (setreg/getreg, round/denorm mode, getpc/setpc, 64-bit bfe/bitset, movrel, pack, subb, cmp_u64) have no test.

ds_bpermute in wave64
The reference is right. The ISA guide says it in 10.4.4 (LDS lane-permute ops, p. 96): in wave64 both DS_PERMUTE and DS_BPERMUTE work on each half as two independent wave32s, and only index bits [6:2] are used. The per-instruction pseudocode in 12.13 writes mod 64, which contradicts that paragraph, so citing 10.4.4 would avoid the confusion. Mesa ACO (aco_lower_to_hw_instr.cpp, which emulates a full-wave bpermute on gfx10-10.3) and LLVM (GCNSubtarget::supportsWaveWideBPermute(), false for gfx10/11 in wave64) agree. XCL's own docs/wave64-on-wave32.md:43 says "ds_bpermute (any lane)", which would need fixing with the forms.

Where the four mismatches come from in XCL (read, not run)

  1. ds_bpermute across the halves: recomp/emit.rs:4697-4703 masks the index with 63 and reads through xcl_x_rla_any; the direct form does the same in dxil/lower_mem.rs:2270-2282 and dxil/lanes.rs:746-790. ds_permute just below stays in its half.
  2. Empty upper half: with 96 threads no hardware thread runs for the missing half, so xcl_x_meet() is false (emit.rs:6667) and xcl_x_rla_uniform returns 0 (emit.rs:6717-6722); direct in dxil/lanes.rs:631-647.
  3. -0 in HLSL split (likely, not checked): the HLSL is a plain a - b (emit.rs:4041) compiled without -Gis, so DXC's default fast-math (no signed zeros) can rewrite e.g. x - (x + y) into -y; the direct path sets no fast-math flags, which fits it showing only in HLSL split. Recompiling seed 1000001's HLSL with -Gis would settle it.
  4. Per-lane split loop: the per-lane form handles the saveexec family at recomp/lower.rs:681-690, and as far as I can see nothing refuses an EXEC write that turns lanes back on after they left the loop, which recomp/lower/wave.rs assumes does not happen. Less sure of this one.

What looks right (checked against LLVM and the guide): the SALU core and the saveexec family, integer VALU carries in wave64, the refusal of NEG/ABS/CLAMP/OMOD on integers, DPP16/DPP8 decoding including row_share / row_xmask, the fi / bound_ctrl rule, readlane modulo 64, mbcnt, permlane16/x16, mul_legacy / fma_legacy giving +0 on a zero, the med3 NaN rule, the gfx10 buffer format table, read2/write2/st64 offsets, the LDS atomic rules, gather4 texel order, s_barrier with ended waves, and the deterministic fuzz seeds with re-checked shrinking.

AI use: Claude Code (Claude Opus 5.5, four reviewers by area) and OpenAI Codex (GPT-6) reviewed the code; Claude Code ran the tests and wrote this review; checked and posted by me.

<!-- greyfinch-sync:ivall/xcl:review:6158646560 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#pullrequestreview-6158646560). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:05Z. **Review:** COMMENTED --- Thank you for this. A reference that does not share code with the forms is the piece that was missing, and the harness numbers reproduce here. I reviewed it at d2293dcb, by reading the code (five reviewers, see AI use below), and spot-checked by hand every point marked as confirmed. The inline comments are the details; this is the summary. **Tested here** - RTX 3090 (driver 616.56, wave32 only), Ryzen 9 5950X, Windows 11 22631, rustc 1.100.0, debug, at 9ceea007 (its `rdna2_ref` differs from d2293dcb only by the f16 infinity fix): `cargo test -p xcl --lib rdna2_ref -- --nocapture --test-threads=4`. - The harness gives the same counts as on your RTX 2070 SUPER: HLSL split 13 match, 2 known; direct split 13 match, 1 known, 1 refused; per-lane split 9 match, 1 known, 5 refused. The two forms tests and the CPU fuzz pass. A GPU fuzz run with 2,000 seeds (`XCL_FUZZ_WAVE64_SEEDS=2000`) was still running after 20 minutes when I posted this. **Reference rules that look wrong** (each can blame a correct form or let a wrong one pass) - Against the RDNA2 ISA guide (sections cited inline): S_ABSDIFF_I32 overflow, S_LOAD address alignment, the zero sign and sNaN in V_MIN/V_MAX_F32, RCP/RSQ/SQRT flushing denormals, OMOD ignored with output denormals on, DX10_CLAMP, buffer bounds (OOB_SELECT modes, per component for DWORDxN), W = 1 out of range. - Bugs in the code itself: V_CMP_CLASS_F16 converting twice, V_FRACT_F32(NaN), an undecodable word skipped instead of stopping, an 8-bit format shift overflow. - Open, with no clear source: the high half of V_CVT_F16_F32 (LLVM says gfx10 keeps it, the guide does not say), the lane order of contending LDS atomics. - Fused or unfused V_FMAC_LEGACY / V_FMA_LEGACY: in LLVM the unfused gfx10.1 forms sit under the same MadMacF32 feature as v_mac_f32 / v_mad_f32, which the console keeps; the fused ones come with gfx10.3. That leans toward unfused, without proving it. The reference and XCL both assume fused, so the harness cannot settle it. Stopping (Unsupported) on them until it is measured would be safer. **The harness can stay green on a regression** - KNOWN is keyed by (case, form) and accepts any mismatch or failure; Refused passes everywhere; a panic counts as Refused; the negative control does not depend on the forms. Details inline. - CI has no GPU (`ci.yml`: Windows runner, Basic Render Driver), so the GPU forms and the "100 GPU seeds" do not run there; only the CPU part does. - I expect the forms test to go red on the first GPU with 64-lane waves: the native wave64 HLSL and direct forms take the ds_bpermute index `& 63` as well (`recomp/emit.rs:4697`, `dxil/lower_mem.rs:2272`), and KNOWN lists only split forms. Not run (no AMD card here). - Test gaps: SDWA is modelled but used by no test, case or fuzz program; DPP row and bank masks are always 15, FI = 1, row_ror, movrel and v_swap are never exercised; about twenty SALU rules (setreg/getreg, round/denorm mode, getpc/setpc, 64-bit bfe/bitset, movrel, pack, subb, cmp_u64) have no test. **ds_bpermute in wave64** The reference is right. The ISA guide says it in 10.4.4 (LDS lane-permute ops, p. 96): in wave64 both DS_PERMUTE and DS_BPERMUTE work on each half as two independent wave32s, and only index bits [6:2] are used. The per-instruction pseudocode in 12.13 writes `mod 64`, which contradicts that paragraph, so citing 10.4.4 would avoid the confusion. Mesa ACO (`aco_lower_to_hw_instr.cpp`, which emulates a full-wave bpermute on gfx10-10.3) and LLVM (`GCNSubtarget::supportsWaveWideBPermute()`, false for gfx10/11 in wave64) agree. XCL's own `docs/wave64-on-wave32.md:43` says "ds_bpermute (any lane)", which would need fixing with the forms. **Where the four mismatches come from in XCL** (read, not run) 1. ds_bpermute across the halves: `recomp/emit.rs:4697-4703` masks the index with 63 and reads through `xcl_x_rla_any`; the direct form does the same in `dxil/lower_mem.rs:2270-2282` and `dxil/lanes.rs:746-790`. ds_permute just below stays in its half. 2. Empty upper half: with 96 threads no hardware thread runs for the missing half, so `xcl_x_meet()` is false (`emit.rs:6667`) and `xcl_x_rla_uniform` returns 0 (`emit.rs:6717-6722`); direct in `dxil/lanes.rs:631-647`. 3. -0 in HLSL split (likely, not checked): the HLSL is a plain `a - b` (`emit.rs:4041`) compiled without `-Gis`, so DXC's default fast-math (no signed zeros) can rewrite e.g. `x - (x + y)` into `-y`; the direct path sets no fast-math flags, which fits it showing only in HLSL split. Recompiling seed 1000001's HLSL with `-Gis` would settle it. 4. Per-lane split loop: the per-lane form handles the saveexec family at `recomp/lower.rs:681-690`, and as far as I can see nothing refuses an EXEC write that turns lanes back on after they left the loop, which `recomp/lower/wave.rs` assumes does not happen. Less sure of this one. **What looks right** (checked against LLVM and the guide): the SALU core and the saveexec family, integer VALU carries in wave64, the refusal of NEG/ABS/CLAMP/OMOD on integers, DPP16/DPP8 decoding including row_share / row_xmask, the fi / bound_ctrl rule, readlane modulo 64, mbcnt, permlane16/x16, mul_legacy / fma_legacy giving +0 on a zero, the med3 NaN rule, the gfx10 buffer format table, read2/write2/st64 offsets, the LDS atomic rules, gather4 texel order, s_barrier with ended waves, and the deterministic fuzz seeds with re-checked shrinking. AI use: Claude Code (Claude Opus 5.5, four reviewers by area) and OpenAI Codex (GPT-6) reviewed the code; Claude Code ran the tests and wrote this review; checked and posted by me.
CharlyRien commented 2026-12-02 20:43:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:05Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/salu.rs; line 299

@@ -0,0 +1,328 @@
+//! Scalar ALU and program control (ISA chapters 4 and 5): SOPP, SOPK, SOP1, SOP2, SOPC.
+
+use super::{fault, field, unsupported, Ctx, Program, State, Stop, Wave};
+use crate::gpu::rdna2::{self, Decoded};
+
+pub(super) fn sopp(w: &mut Wave, d: &Decoded, p: &Program, cx: &mut Ctx) -> Result<(), Stop> {
+    let simm = field(d, "SIMM16") as u32;
+    let taken = match d.inst.name {
+        "S_NOP" | "S_WAITCNT" | "S_WAITCNT_DEPCTR" | "S_INST_PREFETCH" | "S_SETPRIO" | "S_CLAUSE" | "S_SLEEP" | "S_ICACHE_INV" | "S_TTRACEDATA" | "S_TTRACEDATA_IMM" => false,
+        "S_ENDPGM" => {
+            w.state = State::Done;
+            return Ok(());
+        }
+        "S_BARRIER" => {
+            w.state = State::Barrier;
+            return Ok(());
+        }
+        // MODE: FP_ROUND [3:0], FP_DENORM [7:4]
+        "S_ROUND_MODE" => {
+            w.mode = w.mode & !0xF | simm & 0xF;
+            false
+        }
+        "S_DENORM_MODE" => {
+            w.mode = w.mode & !0xF0 | (simm & 0xF) << 4;
+            false
+        }
+        "S_BRANCH" => true,
+        "S_CBRANCH_SCC0" => !w.scc,
+        "S_CBRANCH_SCC1" => w.scc,
+        "S_CBRANCH_VCCZ" => w.vcc(cx.flip) == 0,
+        "S_CBRANCH_VCCNZ" => w.vcc(cx.flip) != 0,
+        "S_CBRANCH_EXECZ" => w.exec() == 0,
+        "S_CBRANCH_EXECNZ" => w.exec() != 0,
+        _ => return Err(unsupported(d)),
+    };
+    if taken {
+        let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no branch target"))?;
+        w.jump_to(d, p, t)?;
+    }
+    Ok(())
+}
+
+fn bits(x: u32, off: u32, width: u32) -> u32 {
+    if width == 0 { 0 } else { (x >> (off & 31)) & (((1u64 << width.min(32)) - 1) as u32) }
+}
+
+/// The MODE bits `simm16` (hwreg id, offset, size) names: MODE is the only register modelled
+/// (None: FLAT_SCR_LO / HI, which only scratch access reads, and that is not modelled).
+fn hwreg(d: &Decoded, simm: u32) -> Result<Option<u32>, Stop> {
+    let (id, off, size) = (simm & 63, simm >> 6 & 31, (simm >> 11 & 31) + 1);
+    match id {
+        1 => Ok(Some((((1u64 << size) - 1) as u32) << off)),
+        20 | 21 => Ok(None),
+        _ => Err(unsupported(d)),
+    }
+}
+
+pub(super) fn run(w: &mut Wave, d: &Decoded, p: &Program) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let f = |n: &str| field(d, n);
+    let wide = w.lanes == 64;
+    if d.enc.name == "ENC_SOPK" {
+        let simm = f("SIMM16") as u16;
+        let (k, ku) = (simm as i16 as i32, u32::from(simm));
+        let dst = f("SDST");
+        let cur = w.scalar(d, dst).unwrap_or(0);
+        match name {
+            "S_MOVK_I32" => w.set_s(d, dst, k as u32)?,
+            "S_CMOVK_I32" if w.scc => w.set_s(d, dst, k as u32)?,
+            "S_CMOVK_I32" => {}
+            "S_ADDK_I32" => {
+                let (r, o) = (cur as i32).overflowing_add(k);
+                w.set_s(d, dst, r as u32)?;
+                w.scc = o;
+            }
+            "S_MULK_I32" => w.set_s(d, dst, (cur as i32).wrapping_mul(k) as u32)?,
+            "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_EXPCNT" | "S_WAITCNT_LGKMCNT" => {}
+            "S_SETREG_IMM32_B32" | "S_SETREG_B32" => {
+                let Some(m) = hwreg(d, ku)? else { return Ok(()) };
+                let x = if name == "S_SETREG_B32" { cur } else { d.literal.ok_or_else(|| fault(d, "no literal"))? };
+                w.mode = w.mode & !m | (x << (ku >> 6 & 31)) & m;
+            }
+            "S_GETREG_B32" => {
+                let m = hwreg(d, ku)?.ok_or_else(|| unsupported(d))?;
+                w.set_s(d, dst, (w.mode & m) >> (ku >> 6 & 31))?;
+            }
+            "S_CALL_B64" => {
+                w.set_pair(dst as usize, d.pc + 4);
+                let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no call target"))?;
+                w.jump_to(d, p, t)?;
+            }
+            _ if name.starts_with("S_CMPK_") => {
+                let signed = name.ends_with("_I32");
+                let (a, b) = if signed { (i64::from(cur as i32), i64::from(k)) } else { (i64::from(cur), i64::from(ku)) };
+                w.scc = compare(d, &name[7..9], a, b)?;
+            }
+            _ => return Err(unsupported(d)),
+        }
+        return Ok(());
+    }
+    if d.enc.name == "ENC_SOPC" {
+        let (c0, c1) = (f("SSRC0"), f("SSRC1"));
+        w.scc = match name {
+            "S_BITCMP0_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 0,
+            "S_BITCMP1_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 1,
+            "S_BITCMP0_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 0,
+            "S_BITCMP1_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 1,
+            "S_CMP_EQ_U64" => w.scalar64(d, c0, false)? == w.scalar64(d, c1, false)?,
+            "S_CMP_LG_U64" => w.scalar64(d, c0, false)? != w.scalar64(d, c1, false)?,
+            _ if name.starts_with("S_CMP_") => {
+                let (a, b) = (w.scalar(d, c0)?, w.scalar(d, c1)?);
+                let (a, b) = if name.ends_with("_I32") { (i64::from(a as i32), i64::from(b as i32)) } else { (i64::from(a), i64::from(b)) };
+                compare(d, &name[6..8], a, b)?
+            }
+            _ => return Err(unsupported(d)),
+        };
+        return Ok(());
+    }
+    let dst = f("SDST");
+    let (c0, c1) = (f("SSRC0"), if d.enc.name == "ENC_SOP2" { f("SSRC1") } else { 0 });
+    let s32 = |w: &Wave, c| w.scalar(d, c);
+    let s64 = |w: &Wave, c| w.scalar64(d, c, false);
+    // exec-mask families: D = EXEC, EXEC = S0 op EXEC (WREXEC: D = the new EXEC), SCC = EXEC != 0
+    if name.contains("SAVEEXEC") || name.contains("WREXEC") {
+        let b64 = name.ends_with("_B64");
+        if b64 != wide {
+            return Err(fault(d, "a mask instruction of the other wave size"));
+        }
+        let (s, e) = (if b64 { s64(w, c0)? } else { u64::from(s32(w, c0)?) }, w.exec());
+        let op = name.trim_start_matches("S_").split("_SAVEEXEC").next().unwrap().split("_WREXEC").next().unwrap();
+        let mut new = match op {
+            "AND" => s & e,
+            "OR" => s | e,
+            "XOR" => s ^ e,
+            "ANDN2" => s & !e,
+            "ORN2" => s | !e,
+            "NAND" => !(s & e),
+            "NOR" => !(s | e),
+            "XNOR" => !(s ^ e),
+            "ANDN1" => !s & e,
+            "ORN1" => !s | e,
+            _ => return Err(unsupported(d)),
+        };
+        if !wide {
+            new &= 0xFFFF_FFFF;
+        }
+        let saved = if name.contains("WREXEC") { new } else { e };
+        if b64 { w.set_pair(dst as usize, saved) } else { w.set_s(d, dst, saved as u32)? }
+        w.set_mask(126, new);
+        w.scc = new != 0;
+        return Ok(());
+    }
+    let b64 = matches!(name.rsplit('_').next(), Some("B64" | "I64" | "U64")) && !name.contains("_I32_");
+    if b64 {
+        let (a, b) = (s64(w, c0)?, s64(w, c1).unwrap_or(0));
+        let sh = s32(w, c1).unwrap_or(0) & 63;
+        let (r, scc) = match name {
+            "S_MOV_B64" => (a, None),
+            "S_CMOV_B64" => (if w.scc { a } else { s64(w, dst)? }, None),
+            "S_NOT_B64" => (!a, Some(!a != 0)),
+            "S_WQM_B64" => {
+                let r = (0..16).fold(0u64, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m });
+                (r, Some(r != 0))
+            }
+            "S_BREV_B64" => (a.reverse_bits(), None),
+            "S_QUADMASK_B64" => {
+                let r = (0..16).fold(0u64, |m, q| m | u64::from(a >> (4 * q) & 15 != 0) << q);
+                (r, Some(r != 0))
+            }
+            "S_BITREPLICATE_B64_B32" => ((0..32).fold(0u64, |m, i| m | (a >> i & 1) * 3 << (2 * i)), None),
+            "S_GETPC_B64" => (d.pc + 4, None),
+            "S_SETPC_B64" => return w.jump_to(d, p, a),
+            "S_SWAPPC_B64" => {
+                w.set_pair(dst as usize, d.pc + 4);
+                return w.jump_to(d, p, a);
+            }
+            "S_AND_B64" => (a & b, Some(a & b != 0)),
+            "S_OR_B64" => (a | b, Some(a | b != 0)),
+            "S_XOR_B64" => (a ^ b, Some(a ^ b != 0)),
+            "S_ANDN2_B64" => (a & !b, Some(a & !b != 0)),
+            "S_ORN2_B64" => (a | !b, Some(a | !b != 0)),
+            "S_NAND_B64" => (!(a & b), Some(!(a & b) != 0)),
+            "S_NOR_B64" => (!(a | b), Some(!(a | b) != 0)),
+            "S_XNOR_B64" => (!(a ^ b), Some(!(a ^ b) != 0)),
+            "S_CSELECT_B64" => (if w.scc { a } else { b }, None),
+            "S_LSHL_B64" => (a << sh, Some(a << sh != 0)),
+            "S_LSHR_B64" => (a >> sh, Some(a >> sh != 0)),
+            "S_ASHR_I64" => (((a as i64) >> sh) as u64, Some((a as i64) >> sh != 0)),
+            "S_BFM_B64" => {
+                let (n, o) = (s32(w, c0)? & 63, s32(w, c1)? & 63);
+                ((if n == 0 { 0 } else { u64::MAX >> (64 - n) }) << o, None)
+            }
+            "S_BFE_U64" | "S_BFE_I64" => {
+                let x = s32(w, c1)?;
+                let (o, n) = (x & 63, (x >> 16) & 127);
+                let n = n.min(64);
+                let x = if name == "S_BFE_I64" { ((a as i64) >> o) as u64 } else { a >> o };
+                let mut r = if n == 0 { 0 } else { x & (u64::MAX >> (64 - n)) };
+                if name == "S_BFE_I64" && n > 0 && n < 64 && r >> (n - 1) & 1 == 1 {
+                    r |= u64::MAX << n;
+                }
+                (r, Some(r != 0))
+            }
+            "S_BITSET0_B64" | "S_BITSET1_B64" => {
+                let bit = s32(w, c0)? & 63;
+                let cur = w.pair(dst as usize);
+                (if name.contains("SET1") { cur | 1 << bit } else { cur & !(1 << bit) }, None)
+            }
+            "S_MOVRELS_B64" => (w.pair((c0 as usize + w.s[124] as usize).min(126)), None),
+            _ => return Err(unsupported(d)),
+        };
+        if name == "S_MOVRELD_B64" {
+            return Err(unsupported(d));
+        }
+        w.set_pair(dst as usize, r);
+        if let Some(c) = scc {
+            w.scc = c;
+        }
+        return Ok(());
+    }
+    let a = s32(w, c0)?;
+    let b = if d.enc.name == "ENC_SOP2" { s32(w, c1)? } else { 0 };
+    let (sa, sb) = (a as i32, b as i32);
+    let src64 = || s64(w, c0);
+    let nz = |r: u32| (r, Some(r != 0));
+    let (r, scc): (u32, Option<bool>) = match name {
+        "S_MOV_B32" => (a, None),
+        "S_CMOV_B32" => (if w.scc { a } else { s32(w, dst)? }, None),
+        "S_NOT_B32" => nz(!a),
+        "S_WQM_B32" => nz((0..8).fold(0u32, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m })),
+        "S_BREV_B32" => (a.reverse_bits(), None),
+        "S_BCNT0_I32_B32" => nz(a.count_zeros()),
+        "S_BCNT0_I32_B64" => nz(src64()?.count_zeros()),
+        "S_BCNT1_I32_B32" => nz(a.count_ones()),
+        "S_BCNT1_I32_B64" => nz(src64()?.count_ones()),
+        "S_FF0_I32_B32" => (if a == u32::MAX { u32::MAX } else { a.trailing_ones() }, None),
+        "S_FF0_I32_B64" => (match src64()? { u64::MAX => u32::MAX, x => x.trailing_ones() }, None),
+        "S_FF1_I32_B32" => (if a == 0 { u32::MAX } else { a.trailing_zeros() }, None),
+        "S_FF1_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.trailing_zeros() }, None),
+        "S_FLBIT_I32_B32" => (if a == 0 { u32::MAX } else { a.leading_zeros() }, None),
+        "S_FLBIT_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.leading_zeros() }, None),
+        "S_FLBIT_I32" => (if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }, None),
+        "S_FLBIT_I32_I64" => {
+            let x = src64()?;
+            (if x == 0 || x == u64::MAX { u32::MAX } else { (if (x as i64) < 0 { !x } else { x }).leading_zeros() }, None)
+        }
+        "S_SEXT_I32_I8" => (a as i8 as i32 as u32, None),
+        "S_SEXT_I32_I16" => (a as i16 as i32 as u32, None),
+        "S_BITSET0_B32" => (s32(w, dst)? & !(1 << (a & 31)), None),
+        "S_BITSET1_B32" => (s32(w, dst)? | 1 << (a & 31), None),
+        "S_ABS_I32" => nz(sa.unsigned_abs()),
+        "S_QUADMASK_B32" => nz((0..8).fold(0u32, |m, q| m | u32::from(a >> (4 * q) & 15 != 0) << q)),
+        "S_MOVRELS_B32" => {
+            let r = c0 as usize + w.s[124] as usize;
+            (*w.s.get(r).ok_or_else(|| fault(d, "s_movrels past s127"))?, None)
+        }
+        "S_MOVRELD_B32" => {
+            let r = dst + u64::from(w.s[124]);
+            return w.set_s(d, r, a);
+        }
+        "S_ADD_U32" => (a.wrapping_add(b), Some(a.checked_add(b).is_none())),
+        "S_SUB_U32" => (a.wrapping_sub(b), Some(b > a)),
+        "S_ADD_I32" => (sa.wrapping_add(sb) as u32, Some(sa.checked_add(sb).is_none())),
+        "S_SUB_I32" => (sa.wrapping_sub(sb) as u32, Some(sa.checked_sub(sb).is_none())),
+        "S_ADDC_U32" => {
+            let r = u64::from(a) + u64::from(b) + u64::from(w.scc);
+            (r as u32, Some(r >> 32 != 0))
+        }
+        "S_SUBB_U32" => {
+            let r = i64::from(a) - i64::from(b) - i64::from(w.scc);
+            (r as u32, Some(r < 0))
+        }
+        "S_MIN_I32" => (sa.min(sb) as u32, Some(sa < sb)),
+        "S_MIN_U32" => (a.min(b), Some(a < b)),
+        "S_MAX_I32" => (sa.max(sb) as u32, Some(sa > sb)),
+        "S_MAX_U32" => (a.max(b), Some(a > b)),
+        "S_CSELECT_B32" => (if w.scc { a } else { b }, None),
+        "S_AND_B32" => nz(a & b),
+        "S_OR_B32" => nz(a | b),
+        "S_XOR_B32" => nz(a ^ b),
+        "S_ANDN2_B32" => nz(a & !b),
+        "S_ORN2_B32" => nz(a | !b),
+        "S_NAND_B32" => nz(!(a & b)),
+        "S_NOR_B32" => nz(!(a | b)),
+        "S_XNOR_B32" => nz(!(a ^ b)),
+        "S_LSHL_B32" => nz(a << (b & 31)),
+        "S_LSHR_B32" => nz(a >> (b & 31)),
+        "S_ASHR_I32" => nz((sa >> (b & 31)) as u32),
+        "S_BFM_B32" => ((((1u64 << (a & 31)) - 1) as u32) << (b & 31), None),
+        "S_MUL_I32" => (sa.wrapping_mul(sb) as u32, None),
+        "S_MUL_HI_U32" => ((u64::from(a) * u64::from(b) >> 32) as u32, None),
+        "S_MUL_HI_I32" => ((i64::from(sa) * i64::from(sb) >> 32) as u32, None),
+        "S_BFE_U32" => nz(bits(a, b, (b >> 16) & 127)),
+        "S_BFE_I32" => {
+            let n = ((b >> 16) & 127).min(32);
+            let r = bits((sa >> (b & 31)) as u32, 0, n);
+            nz(if n > 0 && n < 32 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r })
+        }
+        "S_ABSDIFF_I32" => nz((i64::from(sa) - i64::from(sb)).unsigned_abs() as u32),

S_ABSDIFF_I32 subtracts in i64 here. The hardware subtracts in 32 bits and wraps, which is also how LLVM selects it (abs of a 32-bit sub) and how XCL emits it. For (0x80000000, 1) the reference gives 0x80000001; the ISA guide's own example in the S_ABSDIFF_I32 entry (SOP2, p. 105) gives 0x7fffffff. No test or fuzz program uses it yet, so it is latent.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758701 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758701). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:05Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/salu.rs`; line 299 ~~~~diff @@ -0,0 +1,328 @@ +//! Scalar ALU and program control (ISA chapters 4 and 5): SOPP, SOPK, SOP1, SOP2, SOPC. + +use super::{fault, field, unsupported, Ctx, Program, State, Stop, Wave}; +use crate::gpu::rdna2::{self, Decoded}; + +pub(super) fn sopp(w: &mut Wave, d: &Decoded, p: &Program, cx: &mut Ctx) -> Result<(), Stop> { + let simm = field(d, "SIMM16") as u32; + let taken = match d.inst.name { + "S_NOP" | "S_WAITCNT" | "S_WAITCNT_DEPCTR" | "S_INST_PREFETCH" | "S_SETPRIO" | "S_CLAUSE" | "S_SLEEP" | "S_ICACHE_INV" | "S_TTRACEDATA" | "S_TTRACEDATA_IMM" => false, + "S_ENDPGM" => { + w.state = State::Done; + return Ok(()); + } + "S_BARRIER" => { + w.state = State::Barrier; + return Ok(()); + } + // MODE: FP_ROUND [3:0], FP_DENORM [7:4] + "S_ROUND_MODE" => { + w.mode = w.mode & !0xF | simm & 0xF; + false + } + "S_DENORM_MODE" => { + w.mode = w.mode & !0xF0 | (simm & 0xF) << 4; + false + } + "S_BRANCH" => true, + "S_CBRANCH_SCC0" => !w.scc, + "S_CBRANCH_SCC1" => w.scc, + "S_CBRANCH_VCCZ" => w.vcc(cx.flip) == 0, + "S_CBRANCH_VCCNZ" => w.vcc(cx.flip) != 0, + "S_CBRANCH_EXECZ" => w.exec() == 0, + "S_CBRANCH_EXECNZ" => w.exec() != 0, + _ => return Err(unsupported(d)), + }; + if taken { + let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no branch target"))?; + w.jump_to(d, p, t)?; + } + Ok(()) +} + +fn bits(x: u32, off: u32, width: u32) -> u32 { + if width == 0 { 0 } else { (x >> (off & 31)) & (((1u64 << width.min(32)) - 1) as u32) } +} + +/// The MODE bits `simm16` (hwreg id, offset, size) names: MODE is the only register modelled +/// (None: FLAT_SCR_LO / HI, which only scratch access reads, and that is not modelled). +fn hwreg(d: &Decoded, simm: u32) -> Result<Option<u32>, Stop> { + let (id, off, size) = (simm & 63, simm >> 6 & 31, (simm >> 11 & 31) + 1); + match id { + 1 => Ok(Some((((1u64 << size) - 1) as u32) << off)), + 20 | 21 => Ok(None), + _ => Err(unsupported(d)), + } +} + +pub(super) fn run(w: &mut Wave, d: &Decoded, p: &Program) -> Result<(), Stop> { + let name = d.inst.name; + let f = |n: &str| field(d, n); + let wide = w.lanes == 64; + if d.enc.name == "ENC_SOPK" { + let simm = f("SIMM16") as u16; + let (k, ku) = (simm as i16 as i32, u32::from(simm)); + let dst = f("SDST"); + let cur = w.scalar(d, dst).unwrap_or(0); + match name { + "S_MOVK_I32" => w.set_s(d, dst, k as u32)?, + "S_CMOVK_I32" if w.scc => w.set_s(d, dst, k as u32)?, + "S_CMOVK_I32" => {} + "S_ADDK_I32" => { + let (r, o) = (cur as i32).overflowing_add(k); + w.set_s(d, dst, r as u32)?; + w.scc = o; + } + "S_MULK_I32" => w.set_s(d, dst, (cur as i32).wrapping_mul(k) as u32)?, + "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_EXPCNT" | "S_WAITCNT_LGKMCNT" => {} + "S_SETREG_IMM32_B32" | "S_SETREG_B32" => { + let Some(m) = hwreg(d, ku)? else { return Ok(()) }; + let x = if name == "S_SETREG_B32" { cur } else { d.literal.ok_or_else(|| fault(d, "no literal"))? }; + w.mode = w.mode & !m | (x << (ku >> 6 & 31)) & m; + } + "S_GETREG_B32" => { + let m = hwreg(d, ku)?.ok_or_else(|| unsupported(d))?; + w.set_s(d, dst, (w.mode & m) >> (ku >> 6 & 31))?; + } + "S_CALL_B64" => { + w.set_pair(dst as usize, d.pc + 4); + let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no call target"))?; + w.jump_to(d, p, t)?; + } + _ if name.starts_with("S_CMPK_") => { + let signed = name.ends_with("_I32"); + let (a, b) = if signed { (i64::from(cur as i32), i64::from(k)) } else { (i64::from(cur), i64::from(ku)) }; + w.scc = compare(d, &name[7..9], a, b)?; + } + _ => return Err(unsupported(d)), + } + return Ok(()); + } + if d.enc.name == "ENC_SOPC" { + let (c0, c1) = (f("SSRC0"), f("SSRC1")); + w.scc = match name { + "S_BITCMP0_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 0, + "S_BITCMP1_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 1, + "S_BITCMP0_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 0, + "S_BITCMP1_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 1, + "S_CMP_EQ_U64" => w.scalar64(d, c0, false)? == w.scalar64(d, c1, false)?, + "S_CMP_LG_U64" => w.scalar64(d, c0, false)? != w.scalar64(d, c1, false)?, + _ if name.starts_with("S_CMP_") => { + let (a, b) = (w.scalar(d, c0)?, w.scalar(d, c1)?); + let (a, b) = if name.ends_with("_I32") { (i64::from(a as i32), i64::from(b as i32)) } else { (i64::from(a), i64::from(b)) }; + compare(d, &name[6..8], a, b)? + } + _ => return Err(unsupported(d)), + }; + return Ok(()); + } + let dst = f("SDST"); + let (c0, c1) = (f("SSRC0"), if d.enc.name == "ENC_SOP2" { f("SSRC1") } else { 0 }); + let s32 = |w: &Wave, c| w.scalar(d, c); + let s64 = |w: &Wave, c| w.scalar64(d, c, false); + // exec-mask families: D = EXEC, EXEC = S0 op EXEC (WREXEC: D = the new EXEC), SCC = EXEC != 0 + if name.contains("SAVEEXEC") || name.contains("WREXEC") { + let b64 = name.ends_with("_B64"); + if b64 != wide { + return Err(fault(d, "a mask instruction of the other wave size")); + } + let (s, e) = (if b64 { s64(w, c0)? } else { u64::from(s32(w, c0)?) }, w.exec()); + let op = name.trim_start_matches("S_").split("_SAVEEXEC").next().unwrap().split("_WREXEC").next().unwrap(); + let mut new = match op { + "AND" => s & e, + "OR" => s | e, + "XOR" => s ^ e, + "ANDN2" => s & !e, + "ORN2" => s | !e, + "NAND" => !(s & e), + "NOR" => !(s | e), + "XNOR" => !(s ^ e), + "ANDN1" => !s & e, + "ORN1" => !s | e, + _ => return Err(unsupported(d)), + }; + if !wide { + new &= 0xFFFF_FFFF; + } + let saved = if name.contains("WREXEC") { new } else { e }; + if b64 { w.set_pair(dst as usize, saved) } else { w.set_s(d, dst, saved as u32)? } + w.set_mask(126, new); + w.scc = new != 0; + return Ok(()); + } + let b64 = matches!(name.rsplit('_').next(), Some("B64" | "I64" | "U64")) && !name.contains("_I32_"); + if b64 { + let (a, b) = (s64(w, c0)?, s64(w, c1).unwrap_or(0)); + let sh = s32(w, c1).unwrap_or(0) & 63; + let (r, scc) = match name { + "S_MOV_B64" => (a, None), + "S_CMOV_B64" => (if w.scc { a } else { s64(w, dst)? }, None), + "S_NOT_B64" => (!a, Some(!a != 0)), + "S_WQM_B64" => { + let r = (0..16).fold(0u64, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m }); + (r, Some(r != 0)) + } + "S_BREV_B64" => (a.reverse_bits(), None), + "S_QUADMASK_B64" => { + let r = (0..16).fold(0u64, |m, q| m | u64::from(a >> (4 * q) & 15 != 0) << q); + (r, Some(r != 0)) + } + "S_BITREPLICATE_B64_B32" => ((0..32).fold(0u64, |m, i| m | (a >> i & 1) * 3 << (2 * i)), None), + "S_GETPC_B64" => (d.pc + 4, None), + "S_SETPC_B64" => return w.jump_to(d, p, a), + "S_SWAPPC_B64" => { + w.set_pair(dst as usize, d.pc + 4); + return w.jump_to(d, p, a); + } + "S_AND_B64" => (a & b, Some(a & b != 0)), + "S_OR_B64" => (a | b, Some(a | b != 0)), + "S_XOR_B64" => (a ^ b, Some(a ^ b != 0)), + "S_ANDN2_B64" => (a & !b, Some(a & !b != 0)), + "S_ORN2_B64" => (a | !b, Some(a | !b != 0)), + "S_NAND_B64" => (!(a & b), Some(!(a & b) != 0)), + "S_NOR_B64" => (!(a | b), Some(!(a | b) != 0)), + "S_XNOR_B64" => (!(a ^ b), Some(!(a ^ b) != 0)), + "S_CSELECT_B64" => (if w.scc { a } else { b }, None), + "S_LSHL_B64" => (a << sh, Some(a << sh != 0)), + "S_LSHR_B64" => (a >> sh, Some(a >> sh != 0)), + "S_ASHR_I64" => (((a as i64) >> sh) as u64, Some((a as i64) >> sh != 0)), + "S_BFM_B64" => { + let (n, o) = (s32(w, c0)? & 63, s32(w, c1)? & 63); + ((if n == 0 { 0 } else { u64::MAX >> (64 - n) }) << o, None) + } + "S_BFE_U64" | "S_BFE_I64" => { + let x = s32(w, c1)?; + let (o, n) = (x & 63, (x >> 16) & 127); + let n = n.min(64); + let x = if name == "S_BFE_I64" { ((a as i64) >> o) as u64 } else { a >> o }; + let mut r = if n == 0 { 0 } else { x & (u64::MAX >> (64 - n)) }; + if name == "S_BFE_I64" && n > 0 && n < 64 && r >> (n - 1) & 1 == 1 { + r |= u64::MAX << n; + } + (r, Some(r != 0)) + } + "S_BITSET0_B64" | "S_BITSET1_B64" => { + let bit = s32(w, c0)? & 63; + let cur = w.pair(dst as usize); + (if name.contains("SET1") { cur | 1 << bit } else { cur & !(1 << bit) }, None) + } + "S_MOVRELS_B64" => (w.pair((c0 as usize + w.s[124] as usize).min(126)), None), + _ => return Err(unsupported(d)), + }; + if name == "S_MOVRELD_B64" { + return Err(unsupported(d)); + } + w.set_pair(dst as usize, r); + if let Some(c) = scc { + w.scc = c; + } + return Ok(()); + } + let a = s32(w, c0)?; + let b = if d.enc.name == "ENC_SOP2" { s32(w, c1)? } else { 0 }; + let (sa, sb) = (a as i32, b as i32); + let src64 = || s64(w, c0); + let nz = |r: u32| (r, Some(r != 0)); + let (r, scc): (u32, Option<bool>) = match name { + "S_MOV_B32" => (a, None), + "S_CMOV_B32" => (if w.scc { a } else { s32(w, dst)? }, None), + "S_NOT_B32" => nz(!a), + "S_WQM_B32" => nz((0..8).fold(0u32, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m })), + "S_BREV_B32" => (a.reverse_bits(), None), + "S_BCNT0_I32_B32" => nz(a.count_zeros()), + "S_BCNT0_I32_B64" => nz(src64()?.count_zeros()), + "S_BCNT1_I32_B32" => nz(a.count_ones()), + "S_BCNT1_I32_B64" => nz(src64()?.count_ones()), + "S_FF0_I32_B32" => (if a == u32::MAX { u32::MAX } else { a.trailing_ones() }, None), + "S_FF0_I32_B64" => (match src64()? { u64::MAX => u32::MAX, x => x.trailing_ones() }, None), + "S_FF1_I32_B32" => (if a == 0 { u32::MAX } else { a.trailing_zeros() }, None), + "S_FF1_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.trailing_zeros() }, None), + "S_FLBIT_I32_B32" => (if a == 0 { u32::MAX } else { a.leading_zeros() }, None), + "S_FLBIT_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.leading_zeros() }, None), + "S_FLBIT_I32" => (if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }, None), + "S_FLBIT_I32_I64" => { + let x = src64()?; + (if x == 0 || x == u64::MAX { u32::MAX } else { (if (x as i64) < 0 { !x } else { x }).leading_zeros() }, None) + } + "S_SEXT_I32_I8" => (a as i8 as i32 as u32, None), + "S_SEXT_I32_I16" => (a as i16 as i32 as u32, None), + "S_BITSET0_B32" => (s32(w, dst)? & !(1 << (a & 31)), None), + "S_BITSET1_B32" => (s32(w, dst)? | 1 << (a & 31), None), + "S_ABS_I32" => nz(sa.unsigned_abs()), + "S_QUADMASK_B32" => nz((0..8).fold(0u32, |m, q| m | u32::from(a >> (4 * q) & 15 != 0) << q)), + "S_MOVRELS_B32" => { + let r = c0 as usize + w.s[124] as usize; + (*w.s.get(r).ok_or_else(|| fault(d, "s_movrels past s127"))?, None) + } + "S_MOVRELD_B32" => { + let r = dst + u64::from(w.s[124]); + return w.set_s(d, r, a); + } + "S_ADD_U32" => (a.wrapping_add(b), Some(a.checked_add(b).is_none())), + "S_SUB_U32" => (a.wrapping_sub(b), Some(b > a)), + "S_ADD_I32" => (sa.wrapping_add(sb) as u32, Some(sa.checked_add(sb).is_none())), + "S_SUB_I32" => (sa.wrapping_sub(sb) as u32, Some(sa.checked_sub(sb).is_none())), + "S_ADDC_U32" => { + let r = u64::from(a) + u64::from(b) + u64::from(w.scc); + (r as u32, Some(r >> 32 != 0)) + } + "S_SUBB_U32" => { + let r = i64::from(a) - i64::from(b) - i64::from(w.scc); + (r as u32, Some(r < 0)) + } + "S_MIN_I32" => (sa.min(sb) as u32, Some(sa < sb)), + "S_MIN_U32" => (a.min(b), Some(a < b)), + "S_MAX_I32" => (sa.max(sb) as u32, Some(sa > sb)), + "S_MAX_U32" => (a.max(b), Some(a > b)), + "S_CSELECT_B32" => (if w.scc { a } else { b }, None), + "S_AND_B32" => nz(a & b), + "S_OR_B32" => nz(a | b), + "S_XOR_B32" => nz(a ^ b), + "S_ANDN2_B32" => nz(a & !b), + "S_ORN2_B32" => nz(a | !b), + "S_NAND_B32" => nz(!(a & b)), + "S_NOR_B32" => nz(!(a | b)), + "S_XNOR_B32" => nz(!(a ^ b)), + "S_LSHL_B32" => nz(a << (b & 31)), + "S_LSHR_B32" => nz(a >> (b & 31)), + "S_ASHR_I32" => nz((sa >> (b & 31)) as u32), + "S_BFM_B32" => ((((1u64 << (a & 31)) - 1) as u32) << (b & 31), None), + "S_MUL_I32" => (sa.wrapping_mul(sb) as u32, None), + "S_MUL_HI_U32" => ((u64::from(a) * u64::from(b) >> 32) as u32, None), + "S_MUL_HI_I32" => ((i64::from(sa) * i64::from(sb) >> 32) as u32, None), + "S_BFE_U32" => nz(bits(a, b, (b >> 16) & 127)), + "S_BFE_I32" => { + let n = ((b >> 16) & 127).min(32); + let r = bits((sa >> (b & 31)) as u32, 0, n); + nz(if n > 0 && n < 32 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r }) + } + "S_ABSDIFF_I32" => nz((i64::from(sa) - i64::from(sb)).unsigned_abs() as u32), ~~~~ --- S_ABSDIFF_I32 subtracts in i64 here. The hardware subtracts in 32 bits and wraps, which is also how LLVM selects it (abs of a 32-bit sub) and how XCL emits it. For (0x80000000, 1) the reference gives 0x80000001; the ISA guide's own example in the S_ABSDIFF_I32 entry (SOP2, p. 105) gives 0x7fffffff. No test or fuzz program uses it yet, so it is latent.
CharlyRien commented 2026-12-02 20:43:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:05Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 44

@@ -0,0 +1,496 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None)

The two low bits are dropped after base + offset + SOFFSET are added (here and at line 58). The ISA guide (7.2.1, S_LOAD_DWORD) treats the two LSBs of every address component as zero, so before the add; XCL main does that since 1a447e60, with a GPU test. With base 0x1002 and SOFFSET 2 the reference reads 0x1004 and XCL 0x1000, so the reference would blame a correct form. For S_BUFFER_LOAD (line 50/57) both sides add first, so a wrong rule there passes on both.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758715 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758715). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:05Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 44 ~~~~diff @@ -0,0 +1,496 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None) ~~~~ --- The two low bits are dropped after base + offset + SOFFSET are added (here and at line 58). The ISA guide (7.2.1, S_LOAD_DWORD) treats the two LSBs of every address component as zero, so before the add; XCL main does that since 1a447e60, with a GPU test. With base 0x1002 and SOFFSET 2 the reference reads 0x1004 and XCL 0x1000, so the reference would blame a correct form. For S_BUFFER_LOAD (line 50/57) both sides add first, so a wrong rule there passes on both.
CharlyRien commented 2026-12-02 20:43:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:05Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 95

@@ -0,0 +1,458 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept.
+pub(crate) const MODE: u32 = 0xF0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stop {
+    /// an instruction (or an operand or modifier of one) outside the modelled set
+    Unsupported { pc: u64, name: String },
+    /// the program did something the console would not survive: a branch into nothing, an
+    /// access outside `mem`, an unaligned LDS dword
+    Fault { pc: u64, why: String },
+    /// the step limit
+    Steps(u64),
+}
+
+impl std::fmt::Display for Stop {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"),
+            Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"),
+            Stop::Steps(n) => write!(f, "no end after {n} steps"),
+        }
+    }
+}
+
+/// A rule of the ISA turned the wrong way, for tests that prove a check sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub(crate) enum Flip {
+    #[default]
+    None,
+    /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would
+    Lane31,
+    /// v_permlanex16 reads its own row instead of the other row of its half
+    PermlaneOwnRow,
+    /// vector instructions write the lanes EXEC has off
+    ExecIgnored,
+    /// VCC reads and branches see only its low half
+    VccLow,
+}
+
+pub(crate) fn unsupported(d: &Decoded) -> Stop {
+    Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) }
+}
+
+pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop {
+    Stop::Fault { pc: d.pc, why: why.into() }
+}
+
+pub(crate) fn field(d: &Decoded, name: &str) -> u64 {
+    field_value(d.enc, &d.words, name).unwrap_or(0)
+}
+
+/// A program decoded once: its instructions and where each starts.
+pub(crate) struct Program {
+    pub list: Vec<Decoded>,
+    pub index: HashMap<u64, usize>,
+}
+
+impl Program {
+    /// Words that do not decode (constants after the code) are left out; reaching one faults.
+    pub fn new(code: &[u8]) -> Program {
+        let mut list = Vec::new();
+        let mut off = 0;
+        while off + 4 <= code.len() {
+            match rdna2::decode(&code[off..], off as u64) {
+                Ok(d) => {
+                    off += d.len;
+                    list.push(d);
+                }
+                Err(_) => off += 4,

An undecodable word is dropped from the list, and step() goes to the next decoded instruction. So straight-line execution walks over a decode error, and the second dword of an unknown 64-bit instruction can run as another instruction. It only faults as a branch target. Could you keep the gaps and stop when execution reaches one? The description says the reference never skips an instruction.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758725 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758725). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:05Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 95 ~~~~diff @@ -0,0 +1,458 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept. +pub(crate) const MODE: u32 = 0xF0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stop { + /// an instruction (or an operand or modifier of one) outside the modelled set + Unsupported { pc: u64, name: String }, + /// the program did something the console would not survive: a branch into nothing, an + /// access outside `mem`, an unaligned LDS dword + Fault { pc: u64, why: String }, + /// the step limit + Steps(u64), +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"), + Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"), + Stop::Steps(n) => write!(f, "no end after {n} steps"), + } + } +} + +/// A rule of the ISA turned the wrong way, for tests that prove a check sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub(crate) enum Flip { + #[default] + None, + /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would + Lane31, + /// v_permlanex16 reads its own row instead of the other row of its half + PermlaneOwnRow, + /// vector instructions write the lanes EXEC has off + ExecIgnored, + /// VCC reads and branches see only its low half + VccLow, +} + +pub(crate) fn unsupported(d: &Decoded) -> Stop { + Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) } +} + +pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop { + Stop::Fault { pc: d.pc, why: why.into() } +} + +pub(crate) fn field(d: &Decoded, name: &str) -> u64 { + field_value(d.enc, &d.words, name).unwrap_or(0) +} + +/// A program decoded once: its instructions and where each starts. +pub(crate) struct Program { + pub list: Vec<Decoded>, + pub index: HashMap<u64, usize>, +} + +impl Program { + /// Words that do not decode (constants after the code) are left out; reaching one faults. + pub fn new(code: &[u8]) -> Program { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + list.push(d); + } + Err(_) => off += 4, ~~~~ --- An undecodable word is dropped from the list, and step() goes to the next decoded instruction. So straight-line execution walks over a decode error, and the second dword of an unknown 64-bit instruction can run as another instruction. It only faults as a branch target. Could you keep the gaps and stop when execution reaches one? The description says the reference never skips an instruction.
CharlyRien commented 2026-12-02 20:43:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:05Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/valu.rs; line 413

@@ -0,0 +1,446 @@
+//! Vector ALU (ISA chapter 6): VOP1, VOP2, VOP3, VOPC and their DPP and SDWA forms. Integer
+//! operations live here, float operations in `float`, lane reads and DPP in `lanes`.
+
+use super::{fault, field, float, lanes, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::{self, Decoded, Variant};
+
+/// One lane's result: `v` (64 bits when `wide`) and its carry-out.
+pub(super) struct Out {
+    pub v: u64,
+    pub wide: bool,
+    pub carry: bool,
+}
+
+fn out(v: u32) -> Option<Out> {
+    Some(Out { v: u64::from(v), wide: false, carry: false })
+}
+
+fn sext24(x: u32) -> i64 {
+    i64::from((x << 8) as i32 >> 8)
+}
+
+fn bfe(x: u32, off: u32, width: u32) -> u32 {
+    let (o, n) = (off & 31, width & 31);
+    if n == 0 { 0 } else { (x >> o) & ((1u32 << n) - 1).max(if n == 32 { u32::MAX } else { 0 }) }
+}
+
+fn med3<T: Ord + Copy>(a: T, b: T, c: T) -> T {
+    a.max(b).min(a.min(b).max(c))
+}
+
+/// v_perm_b32: each selector byte of `s` picks a byte of {a, b} (b the low dword), a sign
+/// replicated from it, 0x00 or 0xff.
+fn perm(a: u32, b: u32, s: u32) -> u32 {
+    let x = u64::from(a) << 32 | u64::from(b);
+    (0..4).fold(0, |r, i| {
+        let sel = s >> (8 * i) & 0xFF;
+        let byte = match sel {
+            0..=7 => (x >> (8 * sel)) as u8,
+            8 => 0xFF * (x >> 15 & 1) as u8,
+            9 => 0xFF * (x >> 31 & 1) as u8,
+            10 => 0xFF * (x >> 47 & 1) as u8,
+            11 => 0xFF * (x >> 63 & 1) as u8,
+            12 => 0,
+            _ => 0xFF,
+        };
+        r | u32::from(byte) << (8 * i)
+    })
+}
+
+/// An integer operation of one lane; `sel` is the lane's bit of the select or carry-in mask.
+fn int(name: &str, [a, b, c]: [u32; 3], [_, b64, c64]: [u64; 3], lane: usize, sel: bool) -> Option<Out> {
+    let (sa, sb, sc) = (a as i32, b as i32, c as i32);
+    let before = (1u64 << lane) - 1;
+    let wide = |v: u64| Some(Out { v, wide: true, carry: false });
+    let carry = |r: i64| Some(Out { v: u64::from(r as u32), wide: false, carry: !(0..=u32::MAX as i64).contains(&r) });
+    match name {
+        "V_MOV_B32" => out(a),
+        "V_NOT_B32" => out(!a),
+        "V_BFREV_B32" => out(a.reverse_bits()),
+        "V_FFBH_U32" => out(if a == 0 { u32::MAX } else { a.leading_zeros() }),
+        "V_FFBL_B32" => out(if a == 0 { u32::MAX } else { a.trailing_zeros() }),
+        "V_FFBH_I32" => out(if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }),
+        "V_CNDMASK_B32" => out(if sel { b } else { a }),
+        "V_ADD_NC_U32" => out(a.wrapping_add(b)),
+        "V_SUB_NC_U32" => out(a.wrapping_sub(b)),
+        "V_SUBREV_NC_U32" => out(b.wrapping_sub(a)),
+        "V_ADD_NC_I32" => out(sa.wrapping_add(sb) as u32),
+        "V_SUB_NC_I32" => out(sa.wrapping_sub(sb) as u32),
+        "V_ADD_CO_U32" => carry(i64::from(a) + i64::from(b)),
+        "V_SUB_CO_U32" => carry(i64::from(a) - i64::from(b)),
+        "V_SUBREV_CO_U32" => carry(i64::from(b) - i64::from(a)),
+        "V_ADD_CO_CI_U32" => carry(i64::from(a) + i64::from(b) + i64::from(sel)),
+        "V_SUB_CO_CI_U32" => carry(i64::from(a) - i64::from(b) - i64::from(sel)),
+        "V_SUBREV_CO_CI_U32" => carry(i64::from(b) - i64::from(a) - i64::from(sel)),
+        "V_MUL_I32_I24" => out((sext24(a) * sext24(b)) as u32),
+        "V_MUL_HI_I32_I24" => out(((sext24(a) * sext24(b)) >> 32) as u32),
+        "V_MUL_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF)),
+        "V_MUL_HI_U32_U24" => out((u64::from(a & 0xFF_FFFF) * u64::from(b & 0xFF_FFFF) >> 32) as u32),
+        "V_MAD_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF).wrapping_add(c)),
+        "V_MAD_I32_I24" => out((sext24(a) * sext24(b) + i64::from(sc)) as u32),
+        "V_MUL_LO_U32" => out(a.wrapping_mul(b)),
+        "V_MUL_HI_U32" => out((u64::from(a) * u64::from(b) >> 32) as u32),
+        "V_MUL_HI_I32" => out((i64::from(sa) * i64::from(sb) >> 32) as u32),
+        "V_MIN_I32" => out(sa.min(sb) as u32),
+        "V_MAX_I32" => out(sa.max(sb) as u32),
+        "V_MIN_U32" => out(a.min(b)),
+        "V_MAX_U32" => out(a.max(b)),
+        "V_MIN3_I32" => out(sa.min(sb).min(sc) as u32),
+        "V_MAX3_I32" => out(sa.max(sb).max(sc) as u32),
+        "V_MED3_I32" => out(med3(sa, sb, sc) as u32),
+        "V_MIN3_U32" => out(a.min(b).min(c)),
+        "V_MAX3_U32" => out(a.max(b).max(c)),
+        "V_MED3_U32" => out(med3(a, b, c)),
+        "V_LSHRREV_B32" => out(b >> (a & 31)),
+        "V_ASHRREV_I32" => out((sb >> (a & 31)) as u32),
+        "V_LSHLREV_B32" => out(b << (a & 31)),
+        "V_AND_B32" => out(a & b),
+        "V_OR_B32" => out(a | b),
+        "V_XOR_B32" => out(a ^ b),
+        "V_XNOR_B32" => out(!(a ^ b)),
+        "V_BFE_U32" => out(bfe(a, b, c)),
+        // the shift is arithmetic: a field past bit 31 holds copies of the sign
+        "V_BFE_I32" => {
+            let n = c & 31;
+            let r = bfe((sa >> (b & 31)) as u32, 0, n);
+            out(if n > 0 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r })
+        }
+        "V_BFI_B32" => out((a & b) | (!a & c)),
+        "V_BFM_B32" => out((((1u64 << (a & 31)) - 1) as u32) << (b & 31)),
+        "V_ALIGNBIT_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (c & 31)) as u32),
+        "V_ALIGNBYTE_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (8 * (c & 3))) as u32),
+        "V_LSHL_ADD_U32" => out((a << (b & 31)).wrapping_add(c)),
+        "V_ADD_LSHL_U32" => out(a.wrapping_add(b) << (c & 31)),
+        "V_ADD3_U32" => out(a.wrapping_add(b).wrapping_add(c)),
+        "V_LSHL_OR_B32" => out((a << (b & 31)) | c),
+        "V_AND_OR_B32" => out((a & b) | c),
+        "V_OR3_B32" => out(a | b | c),
+        "V_XOR3_B32" => out(a ^ b ^ c),
+        "V_XAD_U32" => out((a ^ b).wrapping_add(c)),
+        "V_PERM_B32" => out(perm(a, b, c)),
+        "V_BCNT_U32_B32" => out(a.count_ones().wrapping_add(b)),
+        "V_MBCNT_LO_U32_B32" => out((a & before as u32).count_ones().wrapping_add(b)),
+        "V_MBCNT_HI_U32_B32" => out((a & (before >> 32) as u32).count_ones().wrapping_add(b)),
+        "V_SAD_U32" => out((i64::from(a) - i64::from(b)).unsigned_abs() as u32 + c),
+        "V_LSHLREV_B64" => wide(b64 << (a & 63)),
+        "V_LSHRREV_B64" => wide(b64 >> (a & 63)),
+        "V_ASHRREV_I64" => wide(((b64 as i64) >> (a & 63)) as u64),
+        "V_MAD_U64_U32" => {
+            let r = u128::from(a) * u128::from(b) + u128::from(c64);
+            Some(Out { v: r as u64, wide: true, carry: r >> 64 != 0 })
+        }
+        "V_MAD_I64_I32" => {
+            let r = i128::from(sa) * i128::from(sb) + i128::from(c64 as i64);
+            Some(Out { v: r as u64, wide: true, carry: r != i128::from(r as i64) })
+        }
+        _ => None,
+    }
+}
+
+/// Instructions whose sources are 64 bits wide: (src0, src1, src2).
+fn wide_srcs(name: &str) -> [bool; 3] {
+    match name {
+        "V_LSHLREV_B64" | "V_LSHRREV_B64" | "V_ASHRREV_I64" => [false, true, false],
+        "V_MAD_U64_U32" | "V_MAD_I64_I32" => [false, false, true],
+        _ => [false; 3],
+    }
+}
+
+/// An SDWA operand select: BYTE_0..3, WORD_0..1, DWORD.
+fn select(d: &Decoded, x: u32, sel: u64, sext: bool) -> Result<u32, Stop> {
+    let (off, width) = match sel {
+        0..=3 => (8 * sel as u32, 8),
+        4 | 5 => (16 * (sel as u32 - 4), 16),
+        6 => (0, 32),
+        _ => return Err(unsupported(d)),
+    };
+    let v = if width == 32 { x } else { x >> off & ((1 << width) - 1) };
+    Ok(if sext && width < 32 && v >> (width - 1) & 1 == 1 { v | u32::MAX << width } else { v })
+}
+
+pub(super) fn run(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    if let Some(r) = lanes::run(w, d, cx) {
+        return r;
+    }
+    if name.starts_with("V_CMP") {
+        return compare(w, d, cx);
+    }
+    if d.enc.name == "ENC_VOP3P" {
+        return float::vop3p(w, d, cx);
+    }
+    if matches!(name, "V_NOP" | "V_PIPEFLUSH") {
+        return Ok(());
+    }
+    let f = |n: &str| field(d, n);
+    let vop3 = matches!(d.enc.name, "ENC_VOP3" | "VOP3_SDST_ENC");
+    let sdst = d.enc.name == "VOP3_SDST_ENC";
+    let is_float = float::is_float(name);
+    let fsrc = float::float_srcs(name);
+    // the extension dword's layout for DPP / SDWA
+    let base = d.enc.name.trim_start_matches("ENC_");
+    let ext = |kind: &str| rdna2::encoding(&format!("{base}_VOP_{kind}")).ok_or_else(|| unsupported(d));
+    let xf = |e: &'static rdna2::Encoding, n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0);
+    let (mut abs, mut neg, mut omod, mut clamp) = (0u64, 0u64, 0u64, false);
+    let mut codes = if vop3 { [f("SRC0"), f("SRC1"), f("SRC2")] } else { [f("SRC0"), if d.enc.name == "ENC_VOP2" { 256 + f("VSRC1") } else { 0 }, 0] };
+    if vop3 {
+        abs = if sdst { 0 } else { f("ABS") };
+        neg = f("NEG");
+        omod = f("OMOD");
+        clamp = f("CLAMP") == 1;
+        if !sdst && f("OP_SEL") != 0 {
+            return Err(unsupported(d));
+        }
+    }
+    let mut sdwa = None;
+    let mut dpp16 = None;
+    let mut dpp8 = None;
+    match d.variant {
+        Variant::Plain => {}
+        Variant::Sdwa => {
+            let e = ext("SDWA")?;
+            codes[0] = xf(e, "VSRC0") + if xf(e, "S0") == 1 { 0 } else { 256 };
+            if d.enc.name == "ENC_VOP2" && xf(e, "S1") == 1 {
+                codes[1] -= 256;
+            }
+            abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1;
+            neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1;
+            omod = xf(e, "OMOD");
+            clamp = xf(e, "CLAMP") == 1;
+            sdwa = Some((xf(e, "SRC0_SEL"), xf(e, "SRC0_SEXT") == 1, xf(e, "SRC1_SEL"), xf(e, "SRC1_SEXT") == 1, xf(e, "DST_SEL"), xf(e, "DST_UNUSED")));
+        }
+        Variant::Dpp16 => {
+            let e = ext("DPP16")?;
+            codes[0] = 256 + xf(e, "VSRC0");
+            abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1;
+            neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1;
+            dpp16 = Some((xf(e, "DPP_CTRL"), xf(e, "ROW_MASK"), xf(e, "BANK_MASK"), xf(e, "BOUND_CTRL") == 1, xf(e, "FI") == 1));
+        }
+        Variant::Dpp8 => {
+            let e = ext("DPP8")?;
+            codes[0] = 256 + xf(e, "VSRC0");
+            let sel: Vec<u64> = (0..8).map(|k| xf(e, &format!("LANE_SEL_{k}"))).collect();
+            dpp8 = Some((sel, f("SRC0") == 0xEA));
+        }
+    }
+    if (abs | neg) & !(fsrc as u64) != 0 || ((omod != 0 || clamp) && !(is_float && float::float_dst(name))) {
+        return Err(unsupported(d));
+    }
+    let literal = d.literal;
+    // the second / third operand of the VOP2 forms that read the literal or the destination
+    let k = || literal.ok_or_else(|| fault(d, "no literal"));
+    let vdst = f("VDST");
+    let wsrc = wide_srcs(name);
+    let exec = w.exec();
+    let vcc = w.vcc(cx.flip);
+    let select_mask = if vop3 && matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") {
+        if codes[2] > 127 {
+            return Err(unsupported(d));
+        }
+        w.mask(codes[2] as usize)
+    } else {
+        vcc
+    };
+    let mut carry = 0u64;
+    let mut writes: Vec<(usize, Out)> = Vec::new();
+    for l in 0..w.lanes {
+        let on = exec >> l & 1 == 1;
+        if !on && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        // the DPP source of src0: None leaves the lane unwritten (masked by its row or bank,
+        // or an invalid source with BOUND_CTRL 0); an invalid source reads 0 otherwise
+        let mut dpp_src = None;
+        if let Some((ctrl, row, bank, bound, fi)) = &dpp16 {
+            let masked = row >> (l / 16) & 1 == 0 || bank >> ((l >> 2) & 3) & 1 == 0;
+            let s = lanes::dpp16_source(d, *ctrl, l, w.lanes)?.filter(|&s| exec >> s & 1 == 1 || *fi);
+            if masked || (s.is_none() && !bound) {
+                continue;
+            }
+            dpp_src = Some(s.map_or(0, |s| w.v[s][codes[0] as usize - 256]));
+        }
+        if let Some((sel, fi)) = &dpp8 {
+            let s = (l & !7) + sel[l & 7] as usize;
+            dpp_src = Some(if exec >> s & 1 == 1 || *fi { w.v[s][codes[0] as usize - 256] } else { 0 });
+        }
+        let mut src = [0u32; 3];
+        let mut src64 = [0u64; 3];
+        for i in 0..3 {
+            let present = i == 0 || (i == 1 && (vop3 || d.enc.name == "ENC_VOP2")) || (i == 2 && vop3);
+            if !present {
+                continue;
+            }
+            if wsrc[i] {
+                src64[i] = w.vsrc64(d, codes[i], l)?;
+            } else if i == 0 && dpp_src.is_some() {
+                src[0] = dpp_src.unwrap();
+            } else {
+                src[i] = w.vsrc(d, codes[i], l)?;
+            }
+        }
+        if let Some((s0, x0, s1, x1, ..)) = sdwa {
+            src[0] = select(d, src[0], s0, x0)?;
+            if d.enc.name == "ENC_VOP2" {
+                src[1] = select(d, src[1], s1, x1)?;
+            }
+        }
+        match name {
+            "V_FMAC_F32" | "V_MAC_F32" | "V_FMAC_LEGACY_F32" => src[2] = w.v[l][vdst as usize],
+            "V_FMAAK_F32" | "V_MADAK_F32" => src[2] = k()?,
+            "V_FMAMK_F32" | "V_MADMK_F32" => src = [src[0], k()?, src[1]],
+            _ => {}
+        }
+        let half = float::f16_srcs(name);
+        for i in 0..3 {
+            let sign = if half { 0x8000 } else { 0x8000_0000 };
+            if abs >> i & 1 == 1 {
+                src[i] &= !sign;
+            }
+            if neg >> i & 1 == 1 {
+                src[i] ^= sign;
+            }
+        }
+        let sel = select_mask >> l & 1 == 1;
+        let mut r = match float::eval(d, name, src, w.mode, l)? {
+            Some(v) => Out { v: u64::from(v), wide: false, carry: false },
+            None => int(name, src, src64, l, sel).ok_or_else(|| unsupported(d))?,
+        };
+        if is_float && float::float_dst(name) {
+            r.v = u64::from(float::output(d, r.v as u32, omod, clamp, w.mode)?);
+        }
+        if r.carry && on {
+            carry |= 1 << l;
+        }
+        if let Some((.., dsel, unused)) = sdwa {
+            let old = w.v[l][vdst as usize];
+            let (off, width) = match dsel {
+                0..=3 => (8 * dsel as u32, 8u32),
+                4 | 5 => (16 * (dsel as u32 - 4), 16),
+                6 => (0, 32),
+                _ => return Err(unsupported(d)),
+            };
+            if width < 32 {
+                let m = ((1u32 << width) - 1) << off;
+                let v = (r.v as u32) << off & m;
+                r.v = u64::from(match unused {
+                    0 => v,
+                    1 if off + width < 32 && (v >> (off + width - 1)) & 1 == 1 => v | (u32::MAX << (off + width)),
+                    1 => v,
+                    2 => old & !m | v,
+                    _ => return Err(unsupported(d)),
+                });
+            }
+        }
+        writes.push((l, r));
+    }
+    for (l, r) in writes {
+        let reg = vdst as usize;
+        w.v[l][reg] = r.v as u32;
+        if r.wide {
+            if reg == 255 {
+                return Err(fault(d, "a pair past v255"));
+            }
+            w.v[l][reg + 1] = (r.v >> 32) as u32;
+        }
+    }
+    let carries = matches!(name, "V_ADD_CO_U32" | "V_SUB_CO_U32" | "V_SUBREV_CO_U32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32" | "V_MAD_U64_U32" | "V_MAD_I64_I32");
+    if carries {
+        if sdst {
+            w.set_mask(f("SDST") as usize, carry);
+        } else if vop3 {
+            return Err(unsupported(d));
+        } else {
+            w.set_mask(106, carry);
+        }
+    }
+    Ok(())
+}
+
+/// V_CMP / V_CMPX: a bit for each active lane, 0 for the others, to VCC (VOPC),
+/// to the SGPRs VDST names (VOP3), or to EXEC alone (V_CMPX).
+fn compare(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    if d.variant != Variant::Plain {
+        return Err(unsupported(d));
+    }
+    let name = d.inst.name;
+    let vop3 = d.enc.name == "ENC_VOP3";
+    let f = |n: &str| field(d, n);
+    let codes = if vop3 { [f("SRC0"), f("SRC1")] } else { [f("SRC0"), 256 + f("VSRC1")] };
+    let (abs, neg) = if vop3 { (f("ABS"), f("NEG")) } else { (0, 0) };
+    if vop3 && (f("OP_SEL") != 0 || f("OMOD") != 0 || f("CLAMP") != 0) {
+        return Err(unsupported(d));
+    }
+    let x = name.starts_with("V_CMPX_");
+    let rest = name.trim_start_matches(if x { "V_CMPX_" } else { "V_CMP_" });
+    let (rel, ty) = rest.rsplit_once('_').ok_or_else(|| unsupported(d))?;
+    let float = ty.starts_with('F');
+    if (abs | neg) != 0 && (!float || (rel == "CLASS" && (abs | neg) & 2 != 0)) {
+        return Err(unsupported(d));
+    }
+    let exec = w.exec();
+    let mut m = 0u64;
+    for l in 0..w.lanes {
+        if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        let c = match ty {
+            "I32" | "U32" => {
+                let (a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?);
+                if ty == "I32" { int_rel(d, rel, i64::from(a as i32), i64::from(b as i32))? } else { int_rel(d, rel, i64::from(a), i64::from(b))? }
+            }
+            "I64" | "U64" => {
+                let (a, b) = (w.vsrc64(d, codes[0], l)?, w.vsrc64(d, codes[1], l)?);
+                if ty == "I64" { int_rel(d, rel, i128::from(a as i64), i128::from(b as i64))? } else { int_rel(d, rel, i128::from(a), i128::from(b))? }
+            }
+            "I16" | "U16" => {
+                let (a, b) = (w.vsrc(d, codes[0], l)? as u16, w.vsrc(d, codes[1], l)? as u16);
+                if ty == "I16" { int_rel(d, rel, a as i16, b as i16)? } else { int_rel(d, rel, a, b)? }
+            }
+            "F32" | "F16" => {
+                let (mut a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?);
+                let get = |x: u32, i: u64| -> f32 {
+                    let mut v = if ty == "F16" { float::f16_to_f32(x as u16) } else { f32::from_bits(x) };
+                    if abs >> i & 1 == 1 {
+                        v = v.abs();
+                    }
+                    if neg >> i & 1 == 1 {
+                        v = -v;
+                    }
+                    v
+                };
+                if rel == "CLASS" {
+                    if ty == "F16" {
+                        a = float::f16_to_f32(a as u16).to_bits();

For V_CMP_CLASS_F16 this converts the f16 to f32, then get() (line 402) reads the low 16 bits of that f32 as an f16 again. For +1.0 (0x3C00) that gives +0. The class should also be taken on the f16 bits themselves: an f16 denormal is a normal f32, and an sNaN can become a qNaN on the way.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758733 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758733). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:05Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/valu.rs`; line 413 ~~~~diff @@ -0,0 +1,446 @@ +//! Vector ALU (ISA chapter 6): VOP1, VOP2, VOP3, VOPC and their DPP and SDWA forms. Integer +//! operations live here, float operations in `float`, lane reads and DPP in `lanes`. + +use super::{fault, field, float, lanes, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +/// One lane's result: `v` (64 bits when `wide`) and its carry-out. +pub(super) struct Out { + pub v: u64, + pub wide: bool, + pub carry: bool, +} + +fn out(v: u32) -> Option<Out> { + Some(Out { v: u64::from(v), wide: false, carry: false }) +} + +fn sext24(x: u32) -> i64 { + i64::from((x << 8) as i32 >> 8) +} + +fn bfe(x: u32, off: u32, width: u32) -> u32 { + let (o, n) = (off & 31, width & 31); + if n == 0 { 0 } else { (x >> o) & ((1u32 << n) - 1).max(if n == 32 { u32::MAX } else { 0 }) } +} + +fn med3<T: Ord + Copy>(a: T, b: T, c: T) -> T { + a.max(b).min(a.min(b).max(c)) +} + +/// v_perm_b32: each selector byte of `s` picks a byte of {a, b} (b the low dword), a sign +/// replicated from it, 0x00 or 0xff. +fn perm(a: u32, b: u32, s: u32) -> u32 { + let x = u64::from(a) << 32 | u64::from(b); + (0..4).fold(0, |r, i| { + let sel = s >> (8 * i) & 0xFF; + let byte = match sel { + 0..=7 => (x >> (8 * sel)) as u8, + 8 => 0xFF * (x >> 15 & 1) as u8, + 9 => 0xFF * (x >> 31 & 1) as u8, + 10 => 0xFF * (x >> 47 & 1) as u8, + 11 => 0xFF * (x >> 63 & 1) as u8, + 12 => 0, + _ => 0xFF, + }; + r | u32::from(byte) << (8 * i) + }) +} + +/// An integer operation of one lane; `sel` is the lane's bit of the select or carry-in mask. +fn int(name: &str, [a, b, c]: [u32; 3], [_, b64, c64]: [u64; 3], lane: usize, sel: bool) -> Option<Out> { + let (sa, sb, sc) = (a as i32, b as i32, c as i32); + let before = (1u64 << lane) - 1; + let wide = |v: u64| Some(Out { v, wide: true, carry: false }); + let carry = |r: i64| Some(Out { v: u64::from(r as u32), wide: false, carry: !(0..=u32::MAX as i64).contains(&r) }); + match name { + "V_MOV_B32" => out(a), + "V_NOT_B32" => out(!a), + "V_BFREV_B32" => out(a.reverse_bits()), + "V_FFBH_U32" => out(if a == 0 { u32::MAX } else { a.leading_zeros() }), + "V_FFBL_B32" => out(if a == 0 { u32::MAX } else { a.trailing_zeros() }), + "V_FFBH_I32" => out(if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }), + "V_CNDMASK_B32" => out(if sel { b } else { a }), + "V_ADD_NC_U32" => out(a.wrapping_add(b)), + "V_SUB_NC_U32" => out(a.wrapping_sub(b)), + "V_SUBREV_NC_U32" => out(b.wrapping_sub(a)), + "V_ADD_NC_I32" => out(sa.wrapping_add(sb) as u32), + "V_SUB_NC_I32" => out(sa.wrapping_sub(sb) as u32), + "V_ADD_CO_U32" => carry(i64::from(a) + i64::from(b)), + "V_SUB_CO_U32" => carry(i64::from(a) - i64::from(b)), + "V_SUBREV_CO_U32" => carry(i64::from(b) - i64::from(a)), + "V_ADD_CO_CI_U32" => carry(i64::from(a) + i64::from(b) + i64::from(sel)), + "V_SUB_CO_CI_U32" => carry(i64::from(a) - i64::from(b) - i64::from(sel)), + "V_SUBREV_CO_CI_U32" => carry(i64::from(b) - i64::from(a) - i64::from(sel)), + "V_MUL_I32_I24" => out((sext24(a) * sext24(b)) as u32), + "V_MUL_HI_I32_I24" => out(((sext24(a) * sext24(b)) >> 32) as u32), + "V_MUL_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF)), + "V_MUL_HI_U32_U24" => out((u64::from(a & 0xFF_FFFF) * u64::from(b & 0xFF_FFFF) >> 32) as u32), + "V_MAD_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF).wrapping_add(c)), + "V_MAD_I32_I24" => out((sext24(a) * sext24(b) + i64::from(sc)) as u32), + "V_MUL_LO_U32" => out(a.wrapping_mul(b)), + "V_MUL_HI_U32" => out((u64::from(a) * u64::from(b) >> 32) as u32), + "V_MUL_HI_I32" => out((i64::from(sa) * i64::from(sb) >> 32) as u32), + "V_MIN_I32" => out(sa.min(sb) as u32), + "V_MAX_I32" => out(sa.max(sb) as u32), + "V_MIN_U32" => out(a.min(b)), + "V_MAX_U32" => out(a.max(b)), + "V_MIN3_I32" => out(sa.min(sb).min(sc) as u32), + "V_MAX3_I32" => out(sa.max(sb).max(sc) as u32), + "V_MED3_I32" => out(med3(sa, sb, sc) as u32), + "V_MIN3_U32" => out(a.min(b).min(c)), + "V_MAX3_U32" => out(a.max(b).max(c)), + "V_MED3_U32" => out(med3(a, b, c)), + "V_LSHRREV_B32" => out(b >> (a & 31)), + "V_ASHRREV_I32" => out((sb >> (a & 31)) as u32), + "V_LSHLREV_B32" => out(b << (a & 31)), + "V_AND_B32" => out(a & b), + "V_OR_B32" => out(a | b), + "V_XOR_B32" => out(a ^ b), + "V_XNOR_B32" => out(!(a ^ b)), + "V_BFE_U32" => out(bfe(a, b, c)), + // the shift is arithmetic: a field past bit 31 holds copies of the sign + "V_BFE_I32" => { + let n = c & 31; + let r = bfe((sa >> (b & 31)) as u32, 0, n); + out(if n > 0 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r }) + } + "V_BFI_B32" => out((a & b) | (!a & c)), + "V_BFM_B32" => out((((1u64 << (a & 31)) - 1) as u32) << (b & 31)), + "V_ALIGNBIT_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (c & 31)) as u32), + "V_ALIGNBYTE_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (8 * (c & 3))) as u32), + "V_LSHL_ADD_U32" => out((a << (b & 31)).wrapping_add(c)), + "V_ADD_LSHL_U32" => out(a.wrapping_add(b) << (c & 31)), + "V_ADD3_U32" => out(a.wrapping_add(b).wrapping_add(c)), + "V_LSHL_OR_B32" => out((a << (b & 31)) | c), + "V_AND_OR_B32" => out((a & b) | c), + "V_OR3_B32" => out(a | b | c), + "V_XOR3_B32" => out(a ^ b ^ c), + "V_XAD_U32" => out((a ^ b).wrapping_add(c)), + "V_PERM_B32" => out(perm(a, b, c)), + "V_BCNT_U32_B32" => out(a.count_ones().wrapping_add(b)), + "V_MBCNT_LO_U32_B32" => out((a & before as u32).count_ones().wrapping_add(b)), + "V_MBCNT_HI_U32_B32" => out((a & (before >> 32) as u32).count_ones().wrapping_add(b)), + "V_SAD_U32" => out((i64::from(a) - i64::from(b)).unsigned_abs() as u32 + c), + "V_LSHLREV_B64" => wide(b64 << (a & 63)), + "V_LSHRREV_B64" => wide(b64 >> (a & 63)), + "V_ASHRREV_I64" => wide(((b64 as i64) >> (a & 63)) as u64), + "V_MAD_U64_U32" => { + let r = u128::from(a) * u128::from(b) + u128::from(c64); + Some(Out { v: r as u64, wide: true, carry: r >> 64 != 0 }) + } + "V_MAD_I64_I32" => { + let r = i128::from(sa) * i128::from(sb) + i128::from(c64 as i64); + Some(Out { v: r as u64, wide: true, carry: r != i128::from(r as i64) }) + } + _ => None, + } +} + +/// Instructions whose sources are 64 bits wide: (src0, src1, src2). +fn wide_srcs(name: &str) -> [bool; 3] { + match name { + "V_LSHLREV_B64" | "V_LSHRREV_B64" | "V_ASHRREV_I64" => [false, true, false], + "V_MAD_U64_U32" | "V_MAD_I64_I32" => [false, false, true], + _ => [false; 3], + } +} + +/// An SDWA operand select: BYTE_0..3, WORD_0..1, DWORD. +fn select(d: &Decoded, x: u32, sel: u64, sext: bool) -> Result<u32, Stop> { + let (off, width) = match sel { + 0..=3 => (8 * sel as u32, 8), + 4 | 5 => (16 * (sel as u32 - 4), 16), + 6 => (0, 32), + _ => return Err(unsupported(d)), + }; + let v = if width == 32 { x } else { x >> off & ((1 << width) - 1) }; + Ok(if sext && width < 32 && v >> (width - 1) & 1 == 1 { v | u32::MAX << width } else { v }) +} + +pub(super) fn run(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + if let Some(r) = lanes::run(w, d, cx) { + return r; + } + if name.starts_with("V_CMP") { + return compare(w, d, cx); + } + if d.enc.name == "ENC_VOP3P" { + return float::vop3p(w, d, cx); + } + if matches!(name, "V_NOP" | "V_PIPEFLUSH") { + return Ok(()); + } + let f = |n: &str| field(d, n); + let vop3 = matches!(d.enc.name, "ENC_VOP3" | "VOP3_SDST_ENC"); + let sdst = d.enc.name == "VOP3_SDST_ENC"; + let is_float = float::is_float(name); + let fsrc = float::float_srcs(name); + // the extension dword's layout for DPP / SDWA + let base = d.enc.name.trim_start_matches("ENC_"); + let ext = |kind: &str| rdna2::encoding(&format!("{base}_VOP_{kind}")).ok_or_else(|| unsupported(d)); + let xf = |e: &'static rdna2::Encoding, n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + let (mut abs, mut neg, mut omod, mut clamp) = (0u64, 0u64, 0u64, false); + let mut codes = if vop3 { [f("SRC0"), f("SRC1"), f("SRC2")] } else { [f("SRC0"), if d.enc.name == "ENC_VOP2" { 256 + f("VSRC1") } else { 0 }, 0] }; + if vop3 { + abs = if sdst { 0 } else { f("ABS") }; + neg = f("NEG"); + omod = f("OMOD"); + clamp = f("CLAMP") == 1; + if !sdst && f("OP_SEL") != 0 { + return Err(unsupported(d)); + } + } + let mut sdwa = None; + let mut dpp16 = None; + let mut dpp8 = None; + match d.variant { + Variant::Plain => {} + Variant::Sdwa => { + let e = ext("SDWA")?; + codes[0] = xf(e, "VSRC0") + if xf(e, "S0") == 1 { 0 } else { 256 }; + if d.enc.name == "ENC_VOP2" && xf(e, "S1") == 1 { + codes[1] -= 256; + } + abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1; + neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1; + omod = xf(e, "OMOD"); + clamp = xf(e, "CLAMP") == 1; + sdwa = Some((xf(e, "SRC0_SEL"), xf(e, "SRC0_SEXT") == 1, xf(e, "SRC1_SEL"), xf(e, "SRC1_SEXT") == 1, xf(e, "DST_SEL"), xf(e, "DST_UNUSED"))); + } + Variant::Dpp16 => { + let e = ext("DPP16")?; + codes[0] = 256 + xf(e, "VSRC0"); + abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1; + neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1; + dpp16 = Some((xf(e, "DPP_CTRL"), xf(e, "ROW_MASK"), xf(e, "BANK_MASK"), xf(e, "BOUND_CTRL") == 1, xf(e, "FI") == 1)); + } + Variant::Dpp8 => { + let e = ext("DPP8")?; + codes[0] = 256 + xf(e, "VSRC0"); + let sel: Vec<u64> = (0..8).map(|k| xf(e, &format!("LANE_SEL_{k}"))).collect(); + dpp8 = Some((sel, f("SRC0") == 0xEA)); + } + } + if (abs | neg) & !(fsrc as u64) != 0 || ((omod != 0 || clamp) && !(is_float && float::float_dst(name))) { + return Err(unsupported(d)); + } + let literal = d.literal; + // the second / third operand of the VOP2 forms that read the literal or the destination + let k = || literal.ok_or_else(|| fault(d, "no literal")); + let vdst = f("VDST"); + let wsrc = wide_srcs(name); + let exec = w.exec(); + let vcc = w.vcc(cx.flip); + let select_mask = if vop3 && matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + if codes[2] > 127 { + return Err(unsupported(d)); + } + w.mask(codes[2] as usize) + } else { + vcc + }; + let mut carry = 0u64; + let mut writes: Vec<(usize, Out)> = Vec::new(); + for l in 0..w.lanes { + let on = exec >> l & 1 == 1; + if !on && cx.flip != Flip::ExecIgnored { + continue; + } + // the DPP source of src0: None leaves the lane unwritten (masked by its row or bank, + // or an invalid source with BOUND_CTRL 0); an invalid source reads 0 otherwise + let mut dpp_src = None; + if let Some((ctrl, row, bank, bound, fi)) = &dpp16 { + let masked = row >> (l / 16) & 1 == 0 || bank >> ((l >> 2) & 3) & 1 == 0; + let s = lanes::dpp16_source(d, *ctrl, l, w.lanes)?.filter(|&s| exec >> s & 1 == 1 || *fi); + if masked || (s.is_none() && !bound) { + continue; + } + dpp_src = Some(s.map_or(0, |s| w.v[s][codes[0] as usize - 256])); + } + if let Some((sel, fi)) = &dpp8 { + let s = (l & !7) + sel[l & 7] as usize; + dpp_src = Some(if exec >> s & 1 == 1 || *fi { w.v[s][codes[0] as usize - 256] } else { 0 }); + } + let mut src = [0u32; 3]; + let mut src64 = [0u64; 3]; + for i in 0..3 { + let present = i == 0 || (i == 1 && (vop3 || d.enc.name == "ENC_VOP2")) || (i == 2 && vop3); + if !present { + continue; + } + if wsrc[i] { + src64[i] = w.vsrc64(d, codes[i], l)?; + } else if i == 0 && dpp_src.is_some() { + src[0] = dpp_src.unwrap(); + } else { + src[i] = w.vsrc(d, codes[i], l)?; + } + } + if let Some((s0, x0, s1, x1, ..)) = sdwa { + src[0] = select(d, src[0], s0, x0)?; + if d.enc.name == "ENC_VOP2" { + src[1] = select(d, src[1], s1, x1)?; + } + } + match name { + "V_FMAC_F32" | "V_MAC_F32" | "V_FMAC_LEGACY_F32" => src[2] = w.v[l][vdst as usize], + "V_FMAAK_F32" | "V_MADAK_F32" => src[2] = k()?, + "V_FMAMK_F32" | "V_MADMK_F32" => src = [src[0], k()?, src[1]], + _ => {} + } + let half = float::f16_srcs(name); + for i in 0..3 { + let sign = if half { 0x8000 } else { 0x8000_0000 }; + if abs >> i & 1 == 1 { + src[i] &= !sign; + } + if neg >> i & 1 == 1 { + src[i] ^= sign; + } + } + let sel = select_mask >> l & 1 == 1; + let mut r = match float::eval(d, name, src, w.mode, l)? { + Some(v) => Out { v: u64::from(v), wide: false, carry: false }, + None => int(name, src, src64, l, sel).ok_or_else(|| unsupported(d))?, + }; + if is_float && float::float_dst(name) { + r.v = u64::from(float::output(d, r.v as u32, omod, clamp, w.mode)?); + } + if r.carry && on { + carry |= 1 << l; + } + if let Some((.., dsel, unused)) = sdwa { + let old = w.v[l][vdst as usize]; + let (off, width) = match dsel { + 0..=3 => (8 * dsel as u32, 8u32), + 4 | 5 => (16 * (dsel as u32 - 4), 16), + 6 => (0, 32), + _ => return Err(unsupported(d)), + }; + if width < 32 { + let m = ((1u32 << width) - 1) << off; + let v = (r.v as u32) << off & m; + r.v = u64::from(match unused { + 0 => v, + 1 if off + width < 32 && (v >> (off + width - 1)) & 1 == 1 => v | (u32::MAX << (off + width)), + 1 => v, + 2 => old & !m | v, + _ => return Err(unsupported(d)), + }); + } + } + writes.push((l, r)); + } + for (l, r) in writes { + let reg = vdst as usize; + w.v[l][reg] = r.v as u32; + if r.wide { + if reg == 255 { + return Err(fault(d, "a pair past v255")); + } + w.v[l][reg + 1] = (r.v >> 32) as u32; + } + } + let carries = matches!(name, "V_ADD_CO_U32" | "V_SUB_CO_U32" | "V_SUBREV_CO_U32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32" | "V_MAD_U64_U32" | "V_MAD_I64_I32"); + if carries { + if sdst { + w.set_mask(f("SDST") as usize, carry); + } else if vop3 { + return Err(unsupported(d)); + } else { + w.set_mask(106, carry); + } + } + Ok(()) +} + +/// V_CMP / V_CMPX: a bit for each active lane, 0 for the others, to VCC (VOPC), +/// to the SGPRs VDST names (VOP3), or to EXEC alone (V_CMPX). +fn compare(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + if d.variant != Variant::Plain { + return Err(unsupported(d)); + } + let name = d.inst.name; + let vop3 = d.enc.name == "ENC_VOP3"; + let f = |n: &str| field(d, n); + let codes = if vop3 { [f("SRC0"), f("SRC1")] } else { [f("SRC0"), 256 + f("VSRC1")] }; + let (abs, neg) = if vop3 { (f("ABS"), f("NEG")) } else { (0, 0) }; + if vop3 && (f("OP_SEL") != 0 || f("OMOD") != 0 || f("CLAMP") != 0) { + return Err(unsupported(d)); + } + let x = name.starts_with("V_CMPX_"); + let rest = name.trim_start_matches(if x { "V_CMPX_" } else { "V_CMP_" }); + let (rel, ty) = rest.rsplit_once('_').ok_or_else(|| unsupported(d))?; + let float = ty.starts_with('F'); + if (abs | neg) != 0 && (!float || (rel == "CLASS" && (abs | neg) & 2 != 0)) { + return Err(unsupported(d)); + } + let exec = w.exec(); + let mut m = 0u64; + for l in 0..w.lanes { + if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored { + continue; + } + let c = match ty { + "I32" | "U32" => { + let (a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?); + if ty == "I32" { int_rel(d, rel, i64::from(a as i32), i64::from(b as i32))? } else { int_rel(d, rel, i64::from(a), i64::from(b))? } + } + "I64" | "U64" => { + let (a, b) = (w.vsrc64(d, codes[0], l)?, w.vsrc64(d, codes[1], l)?); + if ty == "I64" { int_rel(d, rel, i128::from(a as i64), i128::from(b as i64))? } else { int_rel(d, rel, i128::from(a), i128::from(b))? } + } + "I16" | "U16" => { + let (a, b) = (w.vsrc(d, codes[0], l)? as u16, w.vsrc(d, codes[1], l)? as u16); + if ty == "I16" { int_rel(d, rel, a as i16, b as i16)? } else { int_rel(d, rel, a, b)? } + } + "F32" | "F16" => { + let (mut a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?); + let get = |x: u32, i: u64| -> f32 { + let mut v = if ty == "F16" { float::f16_to_f32(x as u16) } else { f32::from_bits(x) }; + if abs >> i & 1 == 1 { + v = v.abs(); + } + if neg >> i & 1 == 1 { + v = -v; + } + v + }; + if rel == "CLASS" { + if ty == "F16" { + a = float::f16_to_f32(a as u16).to_bits(); ~~~~ --- For V_CMP_CLASS_F16 this converts the f16 to f32, then get() (line 402) reads the low 16 bits of that f32 as an f16 again. For +1.0 (0x3C00) that gives +0. The class should also be taken on the f16 bits themselves: an f16 denormal is a normal f32, and an sNaN can become a qNaN on the way.
CharlyRien commented 2026-12-02 20:43:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:05Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 157

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a < b { a } else { b })
+}
+
+fn max(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a > b { a } else { b })
+}
+
+fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> {
+    if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) }
+}
+
+/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out.
+fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> {
+    match mode >> 4 & 3 {
+        3 => Ok(x),
+        0 if x.is_subnormal() => Ok(0.0f32.copysign(x)),
+        0 => Ok(x),
+        _ => Err(unsupported(d)),
+    }
+}
+
+/// A float operation of one lane, or None when `name` is not one.
+pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> {
+    if !is_float(name) {
+        return Ok(None);
+    }
+    round_ok(d, mode)?;
+    let fs = float_srcs(name);
+    let mut x = [0f32; 3];
+    for i in 0..3 {
+        x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) };
+    }
+    let [a, b, c] = x;
+    let i = |v: f32| v.to_bits();
+    let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b };
+    let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 };
+    let r = match name {
+        "V_ADD_F32" => i(a + b),
+        "V_SUB_F32" => i(a - b),
+        "V_SUBREV_F32" => i(b - a),
+        "V_MUL_F32" => i(a * b),
+        "V_MUL_LEGACY_F32" => i(legacy(a, b)),
+        "V_MIN_F32" => i(min(a, b)),
+        "V_MAX_F32" => i(max(a, b)),
+        "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)),
+        "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }),
+        // not fused: the product is rounded first
+        "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c),
+        "V_MIN3_F32" => i(min(min(a, b), c)),
+        "V_MAX3_F32" => i(max(max(a, b), c)),
+        "V_MED3_F32" => {
+            if a.is_nan() || b.is_nan() || c.is_nan() {
+                i(min(min(a, b), c))
+            } else {
+                i(max(a, b).min(max(min(a, b), c)))
+            }
+        }
+        "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32),
+        "V_FLOOR_F32" => i(a.floor()),
+        "V_CEIL_F32" => i(a.ceil()),
+        "V_TRUNC_F32" => i(a.trunc()),
+        "V_RNDNE_F32" => i(a.round_ties_even()),
+        "V_FRACT_F32" => {
+            if a.is_infinite() {
+                i(f32::NAN)
+            } else {
+                i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF)))

With a NaN input, a - a.floor() is NaN and Rust's f32::min returns the other operand, so V_FRACT_F32(NaN) gives 0x3F7FFFFF. It should stay NaN (LLVM folds fract with minimum, which propagates it).

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758743 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758743). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:05Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 157 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a < b { a } else { b }) +} + +fn max(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a > b { a } else { b }) +} + +fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> { + if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) } +} + +/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out. +fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> { + match mode >> 4 & 3 { + 3 => Ok(x), + 0 if x.is_subnormal() => Ok(0.0f32.copysign(x)), + 0 => Ok(x), + _ => Err(unsupported(d)), + } +} + +/// A float operation of one lane, or None when `name` is not one. +pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> { + if !is_float(name) { + return Ok(None); + } + round_ok(d, mode)?; + let fs = float_srcs(name); + let mut x = [0f32; 3]; + for i in 0..3 { + x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) }; + } + let [a, b, c] = x; + let i = |v: f32| v.to_bits(); + let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b }; + let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 }; + let r = match name { + "V_ADD_F32" => i(a + b), + "V_SUB_F32" => i(a - b), + "V_SUBREV_F32" => i(b - a), + "V_MUL_F32" => i(a * b), + "V_MUL_LEGACY_F32" => i(legacy(a, b)), + "V_MIN_F32" => i(min(a, b)), + "V_MAX_F32" => i(max(a, b)), + "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)), + "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }), + // not fused: the product is rounded first + "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c), + "V_MIN3_F32" => i(min(min(a, b), c)), + "V_MAX3_F32" => i(max(max(a, b), c)), + "V_MED3_F32" => { + if a.is_nan() || b.is_nan() || c.is_nan() { + i(min(min(a, b), c)) + } else { + i(max(a, b).min(max(min(a, b), c))) + } + } + "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32), + "V_FLOOR_F32" => i(a.floor()), + "V_CEIL_F32" => i(a.ceil()), + "V_TRUNC_F32" => i(a.trunc()), + "V_RNDNE_F32" => i(a.round_ties_even()), + "V_FRACT_F32" => { + if a.is_infinite() { + i(f32::NAN) + } else { + i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF))) ~~~~ --- With a NaN input, a - a.floor() is NaN and Rust's f32::min returns the other operand, so V_FRACT_F32(NaN) gives 0x3F7FFFFF. It should stay NaN (LLVM folds fract with minimum, which propagates it).
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 181

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a < b { a } else { b })
+}
+
+fn max(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a > b { a } else { b })
+}
+
+fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> {
+    if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) }
+}
+
+/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out.
+fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> {
+    match mode >> 4 & 3 {
+        3 => Ok(x),
+        0 if x.is_subnormal() => Ok(0.0f32.copysign(x)),
+        0 => Ok(x),
+        _ => Err(unsupported(d)),
+    }
+}
+
+/// A float operation of one lane, or None when `name` is not one.
+pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> {
+    if !is_float(name) {
+        return Ok(None);
+    }
+    round_ok(d, mode)?;
+    let fs = float_srcs(name);
+    let mut x = [0f32; 3];
+    for i in 0..3 {
+        x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) };
+    }
+    let [a, b, c] = x;
+    let i = |v: f32| v.to_bits();
+    let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b };
+    let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 };
+    let r = match name {
+        "V_ADD_F32" => i(a + b),
+        "V_SUB_F32" => i(a - b),
+        "V_SUBREV_F32" => i(b - a),
+        "V_MUL_F32" => i(a * b),
+        "V_MUL_LEGACY_F32" => i(legacy(a, b)),
+        "V_MIN_F32" => i(min(a, b)),
+        "V_MAX_F32" => i(max(a, b)),
+        "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)),
+        "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }),
+        // not fused: the product is rounded first
+        "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c),
+        "V_MIN3_F32" => i(min(min(a, b), c)),
+        "V_MAX3_F32" => i(max(max(a, b), c)),
+        "V_MED3_F32" => {
+            if a.is_nan() || b.is_nan() || c.is_nan() {
+                i(min(min(a, b), c))
+            } else {
+                i(max(a, b).min(max(min(a, b), c)))
+            }
+        }
+        "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32),
+        "V_FLOOR_F32" => i(a.floor()),
+        "V_CEIL_F32" => i(a.ceil()),
+        "V_TRUNC_F32" => i(a.trunc()),
+        "V_RNDNE_F32" => i(a.round_ties_even()),
+        "V_FRACT_F32" => {
+            if a.is_infinite() {
+                i(f32::NAN)
+            } else {
+                i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF)))
+            }
+        }
+        "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32),
+        "V_RSQ_F32" => i((1.0 / f64::from(a).sqrt()) as f32),
+        "V_SQRT_F32" => i(f64::from(a).sqrt() as f32),
+        "V_EXP_F32" => i(f64::from(a).exp2() as f32),
+        "V_LOG_F32" => i(f64::from(a).log2() as f32),
+        "V_SIN_F32" => i((f64::from(a) * std::f64::consts::TAU).sin() as f32),
+        "V_COS_F32" => i((f64::from(a) * std::f64::consts::TAU).cos() as f32),
+        "V_CVT_F32_I32" => i(src[0] as i32 as f32),
+        "V_CVT_F32_U32" => i(src[0] as f32),
+        "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => {
+            let k = u32::from(name.as_bytes()[name.len() - 1] - b'0');
+            i((src[0] >> (8 * k) & 0xFF) as f32)
+        }
+        "V_CVT_I32_F32" => to_i32(a.trunc()),
+        "V_CVT_FLR_I32_F32" => to_i32(a.floor()),
+        "V_CVT_RPI_I32_F32" => to_i32((a + 0.5).floor()),
+        "V_CVT_U32_F32" => if a.is_nan() { 0 } else { a.trunc().clamp(0.0, u32::MAX as f32) as u32 },
+        "V_CVT_F16_F32" => {
+            if mode >> 2 & 3 != 0 {
+                return Err(unsupported(d));
+            }
+            u32::from(f32_to_f16(a, false))

Question: this writes the f16 with bits 31:16 cleared. LLVM's GCNSubtarget::zeroesHigh16BitsOfDest lists V_CVT_F16_F32 as keeping the high half on gfx10, and XCL keeps it too. If LLVM is right, any program that packs two halves with it gets a false mismatch.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758752 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758752). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 181 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a < b { a } else { b }) +} + +fn max(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a > b { a } else { b }) +} + +fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> { + if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) } +} + +/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out. +fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> { + match mode >> 4 & 3 { + 3 => Ok(x), + 0 if x.is_subnormal() => Ok(0.0f32.copysign(x)), + 0 => Ok(x), + _ => Err(unsupported(d)), + } +} + +/// A float operation of one lane, or None when `name` is not one. +pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> { + if !is_float(name) { + return Ok(None); + } + round_ok(d, mode)?; + let fs = float_srcs(name); + let mut x = [0f32; 3]; + for i in 0..3 { + x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) }; + } + let [a, b, c] = x; + let i = |v: f32| v.to_bits(); + let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b }; + let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 }; + let r = match name { + "V_ADD_F32" => i(a + b), + "V_SUB_F32" => i(a - b), + "V_SUBREV_F32" => i(b - a), + "V_MUL_F32" => i(a * b), + "V_MUL_LEGACY_F32" => i(legacy(a, b)), + "V_MIN_F32" => i(min(a, b)), + "V_MAX_F32" => i(max(a, b)), + "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)), + "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }), + // not fused: the product is rounded first + "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c), + "V_MIN3_F32" => i(min(min(a, b), c)), + "V_MAX3_F32" => i(max(max(a, b), c)), + "V_MED3_F32" => { + if a.is_nan() || b.is_nan() || c.is_nan() { + i(min(min(a, b), c)) + } else { + i(max(a, b).min(max(min(a, b), c))) + } + } + "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32), + "V_FLOOR_F32" => i(a.floor()), + "V_CEIL_F32" => i(a.ceil()), + "V_TRUNC_F32" => i(a.trunc()), + "V_RNDNE_F32" => i(a.round_ties_even()), + "V_FRACT_F32" => { + if a.is_infinite() { + i(f32::NAN) + } else { + i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF))) + } + } + "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32), + "V_RSQ_F32" => i((1.0 / f64::from(a).sqrt()) as f32), + "V_SQRT_F32" => i(f64::from(a).sqrt() as f32), + "V_EXP_F32" => i(f64::from(a).exp2() as f32), + "V_LOG_F32" => i(f64::from(a).log2() as f32), + "V_SIN_F32" => i((f64::from(a) * std::f64::consts::TAU).sin() as f32), + "V_COS_F32" => i((f64::from(a) * std::f64::consts::TAU).cos() as f32), + "V_CVT_F32_I32" => i(src[0] as i32 as f32), + "V_CVT_F32_U32" => i(src[0] as f32), + "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => { + let k = u32::from(name.as_bytes()[name.len() - 1] - b'0'); + i((src[0] >> (8 * k) & 0xFF) as f32) + } + "V_CVT_I32_F32" => to_i32(a.trunc()), + "V_CVT_FLR_I32_F32" => to_i32(a.floor()), + "V_CVT_RPI_I32_F32" => to_i32((a + 0.5).floor()), + "V_CVT_U32_F32" => if a.is_nan() { 0 } else { a.trunc().clamp(0.0, u32::MAX as f32) as u32 }, + "V_CVT_F16_F32" => { + if mode >> 2 & 3 != 0 { + return Err(unsupported(d)); + } + u32::from(f32_to_f16(a, false)) ~~~~ --- Question: this writes the f16 with bits 31:16 cleared. LLVM's GCNSubtarget::zeroesHigh16BitsOfDest lists V_CVT_F16_F32 as keeping the high half on gfx10, and XCL keeps it too. If LLVM is right, any program that packs two halves with it gets a false mismatch.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 90

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {

min and max return the second operand when both are zeros of opposite sign, so MIN(-0, +0) gives +0 and MAX(+0, -0) gives -0. The pseudocode in the ISA guide (12.7, V_MIN_F32 / V_MAX_F32) has explicit cases for this: min gives -0 and max gives +0 whatever the operand order. It also quiets and returns an sNaN operand when IEEE mode is set, where this helper drops it. Could you add bit-pattern tests for both operand orders? The same probably applies to the other min/max/med3 variants.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758764 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758764). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 90 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { ~~~~ --- min and max return the second operand when both are zeros of opposite sign, so MIN(-0, +0) gives +0 and MAX(+0, -0) gives -0. The pseudocode in the ISA guide (12.7, V_MIN_F32 / V_MAX_F32) has explicit cases for this: min gives -0 and max gives +0 whatever the operand order. It also quiets and returns an sNaN operand when IEEE mode is set, where this helper drops it. Could you add bit-pattern tests for both operand orders? The same probably applies to the other min/max/med3 variants.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 160

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a < b { a } else { b })
+}
+
+fn max(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a > b { a } else { b })
+}
+
+fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> {
+    if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) }
+}
+
+/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out.
+fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> {
+    match mode >> 4 & 3 {
+        3 => Ok(x),
+        0 if x.is_subnormal() => Ok(0.0f32.copysign(x)),
+        0 => Ok(x),
+        _ => Err(unsupported(d)),
+    }
+}
+
+/// A float operation of one lane, or None when `name` is not one.
+pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> {
+    if !is_float(name) {
+        return Ok(None);
+    }
+    round_ok(d, mode)?;
+    let fs = float_srcs(name);
+    let mut x = [0f32; 3];
+    for i in 0..3 {
+        x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) };
+    }
+    let [a, b, c] = x;
+    let i = |v: f32| v.to_bits();
+    let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b };
+    let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 };
+    let r = match name {
+        "V_ADD_F32" => i(a + b),
+        "V_SUB_F32" => i(a - b),
+        "V_SUBREV_F32" => i(b - a),
+        "V_MUL_F32" => i(a * b),
+        "V_MUL_LEGACY_F32" => i(legacy(a, b)),
+        "V_MIN_F32" => i(min(a, b)),
+        "V_MAX_F32" => i(max(a, b)),
+        "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)),
+        "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }),
+        // not fused: the product is rounded first
+        "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c),
+        "V_MIN3_F32" => i(min(min(a, b), c)),
+        "V_MAX3_F32" => i(max(max(a, b), c)),
+        "V_MED3_F32" => {
+            if a.is_nan() || b.is_nan() || c.is_nan() {
+                i(min(min(a, b), c))
+            } else {
+                i(max(a, b).min(max(min(a, b), c)))
+            }
+        }
+        "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32),
+        "V_FLOOR_F32" => i(a.floor()),
+        "V_CEIL_F32" => i(a.ceil()),
+        "V_TRUNC_F32" => i(a.trunc()),
+        "V_RNDNE_F32" => i(a.round_ties_even()),
+        "V_FRACT_F32" => {
+            if a.is_infinite() {
+                i(f32::NAN)
+            } else {
+                i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF)))
+            }
+        }
+        "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32),

The ISA guide's entries for V_RCP_F32, V_RSQ_F32 and V_SQRT_F32 (12.8, p. 141-142) say denormals are flushed, whatever MODE says. With MODE 0xF0, RCP(0x00400000) gives 2^127 here instead of +inf.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758778 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758778). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 160 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a < b { a } else { b }) +} + +fn max(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a > b { a } else { b }) +} + +fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> { + if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) } +} + +/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out. +fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> { + match mode >> 4 & 3 { + 3 => Ok(x), + 0 if x.is_subnormal() => Ok(0.0f32.copysign(x)), + 0 => Ok(x), + _ => Err(unsupported(d)), + } +} + +/// A float operation of one lane, or None when `name` is not one. +pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> { + if !is_float(name) { + return Ok(None); + } + round_ok(d, mode)?; + let fs = float_srcs(name); + let mut x = [0f32; 3]; + for i in 0..3 { + x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) }; + } + let [a, b, c] = x; + let i = |v: f32| v.to_bits(); + let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b }; + let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 }; + let r = match name { + "V_ADD_F32" => i(a + b), + "V_SUB_F32" => i(a - b), + "V_SUBREV_F32" => i(b - a), + "V_MUL_F32" => i(a * b), + "V_MUL_LEGACY_F32" => i(legacy(a, b)), + "V_MIN_F32" => i(min(a, b)), + "V_MAX_F32" => i(max(a, b)), + "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)), + "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }), + // not fused: the product is rounded first + "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c), + "V_MIN3_F32" => i(min(min(a, b), c)), + "V_MAX3_F32" => i(max(max(a, b), c)), + "V_MED3_F32" => { + if a.is_nan() || b.is_nan() || c.is_nan() { + i(min(min(a, b), c)) + } else { + i(max(a, b).min(max(min(a, b), c))) + } + } + "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32), + "V_FLOOR_F32" => i(a.floor()), + "V_CEIL_F32" => i(a.ceil()), + "V_TRUNC_F32" => i(a.trunc()), + "V_RNDNE_F32" => i(a.round_ties_even()), + "V_FRACT_F32" => { + if a.is_infinite() { + i(f32::NAN) + } else { + i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF))) + } + } + "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32), ~~~~ --- The ISA guide's entries for V_RCP_F32, V_RSQ_F32 and V_SQRT_F32 (12.8, p. 141-142) say denormals are flushed, whatever MODE says. With MODE 0xF0, RCP(0x00400000) gives 2^127 here instead of +inf.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 28

@@ -0,0 +1,458 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept.
+pub(crate) const MODE: u32 = 0xF0;

MODE starts at 0xF0: f32 denormals kept, DX10_CLAMP = 0, IEEE = 0. Per the ISA guide: output modifiers are ignored when output denormals are enabled or IEEE is set (6.2, p. 44), so in this mode the OMOD x2 that the "exact float rules" case checks should do nothing, yet the reference and XCL both apply it and the case passes on both sides. DX10_CLAMP clear means CLAMP passes NaN through (3.5, Table 4), while the reference turns it into 0. The round, denormal and dx10_clamp bits are initialized from the program's RSRC1 (3.12, p. 23). Could MODE come from RSRC1, and could the reference stop on the MODE bits it does not read (s_setreg of IEEE, DX10_CLAMP, the f16 bits)?

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758790 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758790). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 28 ~~~~diff @@ -0,0 +1,458 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept. +pub(crate) const MODE: u32 = 0xF0; ~~~~ --- MODE starts at 0xF0: f32 denormals kept, DX10_CLAMP = 0, IEEE = 0. Per the ISA guide: output modifiers are ignored when output denormals are enabled or IEEE is set (6.2, p. 44), so in this mode the OMOD x2 that the "exact float rules" case checks should do nothing, yet the reference and XCL both apply it and the case passes on both sides. DX10_CLAMP clear means CLAMP passes NaN through (3.5, Table 4), while the reference turns it into 0. The round, denormal and dx10_clamp bits are initialized from the program's RSRC1 (3.12, p. 23). Could MODE come from RSRC1, and could the reference stop on the MODE bits it does not read (s_setreg of IEEE, DX10_CLAMP, the f16 bits)?
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 164

@@ -0,0 +1,496 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None)
+    } else if name.starts_with("S_BUFFER_LOAD_DWORD") {
+        let v = [w.s[base], w.s[base + 1], w.s[base + 2]];
+        let stride = u64::from(v[1] >> 16 & 0x3FFF);
+        let records = u64::from(v[2]);
+        let limit = if stride == 0 { records } else { records * stride };
+        (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit)))
+    } else {
+        return Err(unsupported(d));
+    };
+    for k in 0..n {
+        let (x, t) = match limit {
+            Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0),
+            Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?,
+            None => load(d, cx, (addr & !3) + 4 * k as u64)?,
+        };
+        w.s[dst + k] = x;
+        w.st[dst + k] = t;
+    }
+    Ok(())
+}
+
+/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled.
+#[derive(Clone, Copy, PartialEq)]
+enum Kind {
+    Uint,
+    Sint,
+    Float,
+    Unorm,
+}
+
+fn format(code: u32) -> Option<(usize, u32, Kind)> {
+    Some(match code {
+        20 => (1, 32, Kind::Uint),
+        21 => (1, 32, Kind::Sint),
+        22 => (1, 32, Kind::Float),
+        56 => (4, 8, Kind::Unorm),
+        60 => (4, 8, Kind::Uint),
+        62 => (2, 32, Kind::Uint),
+        63 => (2, 32, Kind::Sint),
+        64 => (2, 32, Kind::Float),
+        72 => (3, 32, Kind::Uint),
+        73 => (3, 32, Kind::Sint),
+        74 => (3, 32, Kind::Float),
+        75 => (4, 32, Kind::Uint),
+        76 => (4, 32, Kind::Sint),
+        77 => (4, 32, Kind::Float),
+        _ => return None,
+    })
+}
+
+/// The 32-bit buffer and global atomics modelled.
+const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"];
+
+/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps).
+fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> {
+    Ok(match op {
+        "ADD" => old.wrapping_add(x),
+        "SUB" => old.wrapping_sub(x),
+        "RSUB" => x.wrapping_sub(old),
+        "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32,
+        "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32,
+        "UMIN" | "MIN_U32" => old.min(x),
+        "UMAX" | "MAX_U32" => old.max(x),
+        "AND" | "AND_B32" => old & x,
+        "OR" | "OR_B32" => old | x,
+        "XOR" | "XOR_B32" => old ^ x,
+        "SWAP" | "WRXCHG" => x,
+        "INC" => if old >= x { 0 } else { old + 1 },
+        "DEC" => if old == 0 || old > x { x } else { old - 1 },
+        "CMPSWAP" => if old == cmp { x } else { old },
+        _ => return Err(unsupported(d)),
+    })
+}
+
+/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw
+/// buffer (stride 0) is out of range past num_records bytes, a structured one past
+/// num_records elements; out of range reads 0 and writes nothing.
+pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let f = |x: &str| field(d, x);
+    if f("LDS") == 1 || f("TFE") == 1 {
+        return Err(unsupported(d));
+    }
+    let r = 4 * f("SRSRC") as usize;
+    let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]];
+    let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32;
+    let stride = u64::from(v[1] >> 16 & 0x3FFF);
+    let records = u64::from(v[2]);
+    if v[3] >> 23 & 1 == 1 {
+        return Err(unsupported(d));
+    }
+    let soff = u64::from(w.scalar(d, f("SOFFSET"))?);
+    let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1);
+    let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize);
+    let op = name.trim_start_matches("T").trim_start_matches("BUFFER_");
+    // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF)
+    let fmt = if op.contains("FORMAT") {
+        if op.contains("D16") {
+            return Err(unsupported(d));
+        }
+        let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F };
+        if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" {
+            // a dst_sel other than x, y, z, w
+            return Err(unsupported(d));
+        }
+        Some(format(code).ok_or_else(|| unsupported(d))?)
+    } else {
+        None
+    };
+    let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 };
+    let exec = w.exec();
+    for l in 0..w.lanes {
+        if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 };
+        let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 };
+        let off = voff + f("OFFSET") + soff;
+        let addr = base + index * stride + off;
+        let out = |size: u64| if stride == 0 { off + size > records } else { index >= records };

Bounds: the ISA guide (8.1, Range Checking, Table 35 and its notes, p. 61-62) has four OOB_SELECT modes; in mode 3 num_records is reduced by SOFFSET; DWORDX2/X3/X4 loads and stores are range-checked per component, while format loads/stores and atomics are all or nothing. The reference reads neither OOB_SELECT (word 3, bits 29:28) nor SWIZZLE_ENABLE, and checks a DWORDX2/X3/X4 access as a whole. XCL main has its own rule (no SOFFSET, per dword, emit.rs around 2172-2240), so both sides can be wrong together depending on the mode. Could the reference follow Table 35 for the modes it models and stop on the others, with a test per mode?

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758802 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758802). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 164 ~~~~diff @@ -0,0 +1,496 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None) + } else if name.starts_with("S_BUFFER_LOAD_DWORD") { + let v = [w.s[base], w.s[base + 1], w.s[base + 2]]; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + let limit = if stride == 0 { records } else { records * stride }; + (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit))) + } else { + return Err(unsupported(d)); + }; + for k in 0..n { + let (x, t) = match limit { + Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0), + Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?, + None => load(d, cx, (addr & !3) + 4 * k as u64)?, + }; + w.s[dst + k] = x; + w.st[dst + k] = t; + } + Ok(()) +} + +/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Uint, + Sint, + Float, + Unorm, +} + +fn format(code: u32) -> Option<(usize, u32, Kind)> { + Some(match code { + 20 => (1, 32, Kind::Uint), + 21 => (1, 32, Kind::Sint), + 22 => (1, 32, Kind::Float), + 56 => (4, 8, Kind::Unorm), + 60 => (4, 8, Kind::Uint), + 62 => (2, 32, Kind::Uint), + 63 => (2, 32, Kind::Sint), + 64 => (2, 32, Kind::Float), + 72 => (3, 32, Kind::Uint), + 73 => (3, 32, Kind::Sint), + 74 => (3, 32, Kind::Float), + 75 => (4, 32, Kind::Uint), + 76 => (4, 32, Kind::Sint), + 77 => (4, 32, Kind::Float), + _ => return None, + }) +} + +/// The 32-bit buffer and global atomics modelled. +const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"]; + +/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps). +fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> { + Ok(match op { + "ADD" => old.wrapping_add(x), + "SUB" => old.wrapping_sub(x), + "RSUB" => x.wrapping_sub(old), + "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32, + "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32, + "UMIN" | "MIN_U32" => old.min(x), + "UMAX" | "MAX_U32" => old.max(x), + "AND" | "AND_B32" => old & x, + "OR" | "OR_B32" => old | x, + "XOR" | "XOR_B32" => old ^ x, + "SWAP" | "WRXCHG" => x, + "INC" => if old >= x { 0 } else { old + 1 }, + "DEC" => if old == 0 || old > x { x } else { old - 1 }, + "CMPSWAP" => if old == cmp { x } else { old }, + _ => return Err(unsupported(d)), + }) +} + +/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw +/// buffer (stride 0) is out of range past num_records bytes, a structured one past +/// num_records elements; out of range reads 0 and writes nothing. +pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let f = |x: &str| field(d, x); + if f("LDS") == 1 || f("TFE") == 1 { + return Err(unsupported(d)); + } + let r = 4 * f("SRSRC") as usize; + let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]]; + let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + if v[3] >> 23 & 1 == 1 { + return Err(unsupported(d)); + } + let soff = u64::from(w.scalar(d, f("SOFFSET"))?); + let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1); + let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize); + let op = name.trim_start_matches("T").trim_start_matches("BUFFER_"); + // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF) + let fmt = if op.contains("FORMAT") { + if op.contains("D16") { + return Err(unsupported(d)); + } + let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F }; + if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" { + // a dst_sel other than x, y, z, w + return Err(unsupported(d)); + } + Some(format(code).ok_or_else(|| unsupported(d))?) + } else { + None + }; + let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 }; + let exec = w.exec(); + for l in 0..w.lanes { + if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored { + continue; + } + let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 }; + let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 }; + let off = voff + f("OFFSET") + soff; + let addr = base + index * stride + off; + let out = |size: u64| if stride == 0 { off + size > records } else { index >= records }; ~~~~ --- Bounds: the ISA guide (8.1, Range Checking, Table 35 and its notes, p. 61-62) has four OOB_SELECT modes; in mode 3 num_records is reduced by SOFFSET; DWORDX2/X3/X4 loads and stores are range-checked per component, while format loads/stores and atomics are all or nothing. The reference reads neither OOB_SELECT (word 3, bits 29:28) nor SWIZZLE_ENABLE, and checks a DWORDX2/X3/X4 access as a whole. XCL main has its own rule (no SOFFSET, per dword, emit.rs around 2172-2240), so both sides can be wrong together depending on the mode. Could the reference follow Table 35 for the modes it models and stop on the others, with a test per mode?
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 179

@@ -0,0 +1,496 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None)
+    } else if name.starts_with("S_BUFFER_LOAD_DWORD") {
+        let v = [w.s[base], w.s[base + 1], w.s[base + 2]];
+        let stride = u64::from(v[1] >> 16 & 0x3FFF);
+        let records = u64::from(v[2]);
+        let limit = if stride == 0 { records } else { records * stride };
+        (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit)))
+    } else {
+        return Err(unsupported(d));
+    };
+    for k in 0..n {
+        let (x, t) = match limit {
+            Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0),
+            Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?,
+            None => load(d, cx, (addr & !3) + 4 * k as u64)?,
+        };
+        w.s[dst + k] = x;
+        w.st[dst + k] = t;
+    }
+    Ok(())
+}
+
+/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled.
+#[derive(Clone, Copy, PartialEq)]
+enum Kind {
+    Uint,
+    Sint,
+    Float,
+    Unorm,
+}
+
+fn format(code: u32) -> Option<(usize, u32, Kind)> {
+    Some(match code {
+        20 => (1, 32, Kind::Uint),
+        21 => (1, 32, Kind::Sint),
+        22 => (1, 32, Kind::Float),
+        56 => (4, 8, Kind::Unorm),
+        60 => (4, 8, Kind::Uint),
+        62 => (2, 32, Kind::Uint),
+        63 => (2, 32, Kind::Sint),
+        64 => (2, 32, Kind::Float),
+        72 => (3, 32, Kind::Uint),
+        73 => (3, 32, Kind::Sint),
+        74 => (3, 32, Kind::Float),
+        75 => (4, 32, Kind::Uint),
+        76 => (4, 32, Kind::Sint),
+        77 => (4, 32, Kind::Float),
+        _ => return None,
+    })
+}
+
+/// The 32-bit buffer and global atomics modelled.
+const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"];
+
+/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps).
+fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> {
+    Ok(match op {
+        "ADD" => old.wrapping_add(x),
+        "SUB" => old.wrapping_sub(x),
+        "RSUB" => x.wrapping_sub(old),
+        "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32,
+        "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32,
+        "UMIN" | "MIN_U32" => old.min(x),
+        "UMAX" | "MAX_U32" => old.max(x),
+        "AND" | "AND_B32" => old & x,
+        "OR" | "OR_B32" => old | x,
+        "XOR" | "XOR_B32" => old ^ x,
+        "SWAP" | "WRXCHG" => x,
+        "INC" => if old >= x { 0 } else { old + 1 },
+        "DEC" => if old == 0 || old > x { x } else { old - 1 },
+        "CMPSWAP" => if old == cmp { x } else { old },
+        _ => return Err(unsupported(d)),
+    })
+}
+
+/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw
+/// buffer (stride 0) is out of range past num_records bytes, a structured one past
+/// num_records elements; out of range reads 0 and writes nothing.
+pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let f = |x: &str| field(d, x);
+    if f("LDS") == 1 || f("TFE") == 1 {
+        return Err(unsupported(d));
+    }
+    let r = 4 * f("SRSRC") as usize;
+    let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]];
+    let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32;
+    let stride = u64::from(v[1] >> 16 & 0x3FFF);
+    let records = u64::from(v[2]);
+    if v[3] >> 23 & 1 == 1 {
+        return Err(unsupported(d));
+    }
+    let soff = u64::from(w.scalar(d, f("SOFFSET"))?);
+    let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1);
+    let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize);
+    let op = name.trim_start_matches("T").trim_start_matches("BUFFER_");
+    // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF)
+    let fmt = if op.contains("FORMAT") {
+        if op.contains("D16") {
+            return Err(unsupported(d));
+        }
+        let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F };
+        if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" {
+            // a dst_sel other than x, y, z, w
+            return Err(unsupported(d));
+        }
+        Some(format(code).ok_or_else(|| unsupported(d))?)
+    } else {
+        None
+    };
+    let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 };
+    let exec = w.exec();
+    for l in 0..w.lanes {
+        if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 };
+        let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 };
+        let off = voff + f("OFFSET") + soff;
+        let addr = base + index * stride + off;
+        let out = |size: u64| if stride == 0 { off + size > records } else { index >= records };
+        let tin = w.vt[l][vdata..(vdata + 4).min(256)].iter().copied().max().unwrap_or(0);
+        if let Some((n, bits, kind)) = fmt {
+            let bytes = n as u64 * u64::from(bits) / 8;
+            if op.starts_with("LOAD") {
+                let mut c = [0u32, 0, 0, if kind == Kind::Float || kind == Kind::Unorm { 1.0f32.to_bits() } else { 1 }];
+                let mut t = 0;
+                if !out(bytes) {
+                    for k in 0..n {
+                        if bits == 32 {
+                            let (x, tt) = load(d, cx, addr + 4 * k as u64)?;
+                            (c[k], t) = (x, t.max(tt));
+                        } else {
+                            let (x, tt) = load(d, cx, addr & !3)?;
+                            t = t.max(tt);
+                            let byte = x >> (8 * (addr & 3) + 8 * k as u64) & 0xFF;

For an 8-bit format with 4 channels at an address that is not 4-aligned, the shift reaches 32 or more: a panic in debug, a wrong byte in release. The bytes can also cross into the next dword. Also, an out-of-range format load returns W = 1 here (line 169); the ISA guide (8.1, note 1 under Table 35) returns 0, and 1 only for components whose dst_sel is SEL_1.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758818 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758818). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 179 ~~~~diff @@ -0,0 +1,496 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None) + } else if name.starts_with("S_BUFFER_LOAD_DWORD") { + let v = [w.s[base], w.s[base + 1], w.s[base + 2]]; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + let limit = if stride == 0 { records } else { records * stride }; + (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit))) + } else { + return Err(unsupported(d)); + }; + for k in 0..n { + let (x, t) = match limit { + Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0), + Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?, + None => load(d, cx, (addr & !3) + 4 * k as u64)?, + }; + w.s[dst + k] = x; + w.st[dst + k] = t; + } + Ok(()) +} + +/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Uint, + Sint, + Float, + Unorm, +} + +fn format(code: u32) -> Option<(usize, u32, Kind)> { + Some(match code { + 20 => (1, 32, Kind::Uint), + 21 => (1, 32, Kind::Sint), + 22 => (1, 32, Kind::Float), + 56 => (4, 8, Kind::Unorm), + 60 => (4, 8, Kind::Uint), + 62 => (2, 32, Kind::Uint), + 63 => (2, 32, Kind::Sint), + 64 => (2, 32, Kind::Float), + 72 => (3, 32, Kind::Uint), + 73 => (3, 32, Kind::Sint), + 74 => (3, 32, Kind::Float), + 75 => (4, 32, Kind::Uint), + 76 => (4, 32, Kind::Sint), + 77 => (4, 32, Kind::Float), + _ => return None, + }) +} + +/// The 32-bit buffer and global atomics modelled. +const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"]; + +/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps). +fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> { + Ok(match op { + "ADD" => old.wrapping_add(x), + "SUB" => old.wrapping_sub(x), + "RSUB" => x.wrapping_sub(old), + "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32, + "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32, + "UMIN" | "MIN_U32" => old.min(x), + "UMAX" | "MAX_U32" => old.max(x), + "AND" | "AND_B32" => old & x, + "OR" | "OR_B32" => old | x, + "XOR" | "XOR_B32" => old ^ x, + "SWAP" | "WRXCHG" => x, + "INC" => if old >= x { 0 } else { old + 1 }, + "DEC" => if old == 0 || old > x { x } else { old - 1 }, + "CMPSWAP" => if old == cmp { x } else { old }, + _ => return Err(unsupported(d)), + }) +} + +/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw +/// buffer (stride 0) is out of range past num_records bytes, a structured one past +/// num_records elements; out of range reads 0 and writes nothing. +pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let f = |x: &str| field(d, x); + if f("LDS") == 1 || f("TFE") == 1 { + return Err(unsupported(d)); + } + let r = 4 * f("SRSRC") as usize; + let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]]; + let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + if v[3] >> 23 & 1 == 1 { + return Err(unsupported(d)); + } + let soff = u64::from(w.scalar(d, f("SOFFSET"))?); + let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1); + let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize); + let op = name.trim_start_matches("T").trim_start_matches("BUFFER_"); + // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF) + let fmt = if op.contains("FORMAT") { + if op.contains("D16") { + return Err(unsupported(d)); + } + let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F }; + if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" { + // a dst_sel other than x, y, z, w + return Err(unsupported(d)); + } + Some(format(code).ok_or_else(|| unsupported(d))?) + } else { + None + }; + let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 }; + let exec = w.exec(); + for l in 0..w.lanes { + if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored { + continue; + } + let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 }; + let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 }; + let off = voff + f("OFFSET") + soff; + let addr = base + index * stride + off; + let out = |size: u64| if stride == 0 { off + size > records } else { index >= records }; + let tin = w.vt[l][vdata..(vdata + 4).min(256)].iter().copied().max().unwrap_or(0); + if let Some((n, bits, kind)) = fmt { + let bytes = n as u64 * u64::from(bits) / 8; + if op.starts_with("LOAD") { + let mut c = [0u32, 0, 0, if kind == Kind::Float || kind == Kind::Unorm { 1.0f32.to_bits() } else { 1 }]; + let mut t = 0; + if !out(bytes) { + for k in 0..n { + if bits == 32 { + let (x, tt) = load(d, cx, addr + 4 * k as u64)?; + (c[k], t) = (x, t.max(tt)); + } else { + let (x, tt) = load(d, cx, addr & !3)?; + t = t.max(tt); + let byte = x >> (8 * (addr & 3) + 8 * k as u64) & 0xFF; ~~~~ --- For an 8-bit format with 4 channels at an address that is not 4-aligned, the shift reaches 32 or more: a panic in debug, a wrong byte in release. The bytes can also cross into the next dword. Also, an out-of-range format load returns W = 1 here (line 169); the ISA guide (8.1, note 1 under Table 35) returns 0, and 1 only for components whose dst_sel is SEL_1.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/tests.rs; line 452

@@ -0,0 +1,585 @@
+use super::asm::{asm, end, i, lit, I, TO, V};
+use super::*;
+use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture};
+
+const EXEC: u64 = 126;
+const VCC: u64 = 106;
+
+fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> {
+    let mut l = list.to_vec();
+    l.push(end());
+    run_kernel(&asm(&l), true, st, mem, &[], &[], flip)
+}
+
+/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes.
+fn lanes_state() -> KernelState {
+    let mut st = KernelState::default();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+    }
+    st
+}
+
+fn kernel(list: &[I]) -> Run {
+    kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn saveexec_families_save_the_old_exec_and_set_scc() {
+    // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]),
+        i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]),
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]),
+    ]);
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC");
+    assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves");
+    assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0");
+    // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC
+    assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000);
+    assert_eq!(pair(26), pair(24));
+    assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC");
+    assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on");
+}
+
+#[test]
+fn branches_see_the_whole_wave_masks() {
+    // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken
+    let r = kernel(&[
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8),
+        i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]),
+        i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]),
+        i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2));
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40));
+}
+
+#[test]
+fn salu_carries_overflows_and_fields() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF),
+        i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]),
+        i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF),
+        i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]),
+        lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]),
+        i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]),
+        i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]),
+        i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32");
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow");
+    assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX));
+    assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31));
+    assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed");
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE));
+}
+
+#[test]
+fn an_instruction_outside_the_model_stops_the_run() {
+    let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]);
+    match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) {
+        Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"),
+        other => panic!("{:?}", other.map(|_| ())),
+    }
+    let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand");
+    let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_))));
+}
+
+/// One encoding of every instruction the reference models.
+fn modelled_words() -> Vec<Vec<u8>> {
+    const ENCODINGS: [&str; 17] = [
+        "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS",
+        "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL",
+    ];
+    let mut words = Vec::new();
+    for inst in rdna2::all_instructions() {
+        for name in ENCODINGS {
+            let enc = rdna2::encoding(name).unwrap();
+            let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue };
+            if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) {
+                words.push(code);
+            }
+        }
+    }
+    words
+}
+
+/// The decoder is checked against LLVM's on every instruction the reference models:
+/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs
+/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names
+/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input).
+#[test]
+fn modelled_instructions_decode_as_llvm_disassembles_them() {
+    use std::io::Write;
+    let words = modelled_words();
+    let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect();
+    if let Ok(path) = std::env::var("XCL_LLVM_WORDS") {
+        std::fs::write(path, &input).unwrap();
+    }
+    let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") {
+        std::fs::read_to_string(path).unwrap()
+    } else {
+        let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into());
+        let child = std::process::Command::new(&mc)
+            .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"])
+            .stdin(std::process::Stdio::piped())
+            .stdout(std::process::Stdio::piped())
+            .stderr(std::process::Stdio::piped())
+            .spawn();
+        let Ok(mut child) = child else {
+            let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc");
+            return;
+        };
+        child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
+        String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned()
+    };
+    // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order
+    let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect();
+    assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word");
+    // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`)
+    let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy");
+    let mut bad = Vec::new();
+    for (code, t) in words.iter().zip(theirs) {
+        let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap());
+        // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have
+        let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal";
+        if norm(t) != norm(&ours) && !vop3_readfirstlane {
+            bad.push(format!("{ours} / {t}"));
+        }
+    }
+    assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len());
+    let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len());
+}
+
+/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled.
+fn modelled(code: &[u8]) -> bool {
+    let mut st = KernelState::default();
+    st.sgpr[124] = 0;
+    !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. }))
+}
+
+// ------------------------------------------------------------- vector ALU and lanes
+
+#[test]
+fn lane_reads_and_writes_use_all_64_lanes() {
+    let r = kernel(&[
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234),
+        i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]),
+    ]);
+    assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40");
+    assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33");
+    assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63");
+    assert_eq!(r.vgpr[31][2], 0, "and nowhere else");
+    assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half");
+    assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0");
+}
+
+#[test]
+fn mbcnt_counts_the_lanes_below_in_both_halves() {
+    let r = kernel(&[
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]),
+        i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]),
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]),
+    ]);
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][2], l as u32, "lane {l}");
+        assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone");
+    }
+}
+
+#[test]
+fn carries_and_compares_write_a_bit_per_lane_of_the_pair() {
+    let mut st = lanes_state();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[4] = if l % 3 == 0 { u32::MAX } else { 7 };
+    }
+    let r = kernel_with(
+        &[
+            i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]),
+            i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]),
+            lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]),
+            lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l);
+    assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword");
+    assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry");
+    assert_eq!(pair(24), !0u64 << 36);
+    assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC");
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0));
+        assert_eq!(r.vgpr[l][7], u32::from(l > 35));
+        assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value");
+    }
+}
+
+#[test]
+fn integer_valu_known_answers() {
+    let mut st = lanes_state();
+    st.vgpr[0][4] = 0x8000_0001;
+    st.vgpr[0][5] = 0x0000_0003;
+    let r = kernel_with(
+        &[
+            i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]),
+            i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]),
+            i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]),
+            i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]),
+            i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let v = &r.vgpr[0];
+    assert_eq!(v[10], 1);
+    assert_eq!(v[11], 0xFFFF_FFFE);
+    assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12");
+    assert_eq!(v[13], u32::MAX, "bit 31 sign-extended");
+    assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign");
+    assert_eq!(v[14], 0xC000_0000);
+    assert_eq!(v[15], 1);
+    assert_eq!((v[16], v[17]), (2, 7));
+    assert_eq!((v[18], v[19]), (4, 5));
+}
+
+#[test]
+fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98),
+        i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+        i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+    ]);
+    for l in 0..64u32 {
+        assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}");
+        assert_eq!(r.vgpr[l as usize][3], l, "lane {l}");
+    }
+}
+
+#[test]
+fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() {
+    let mut st = lanes_state();
+    for r in st.vgpr.iter_mut() {
+        r[5] = 0xAAAA;
+        r[6] = 0xBBBB;
+    }
+    // lanes 0..63 but lane 17: off
+    st.sgpr[126] = !(1 << 17);
+    let r = kernel_with(
+        &[
+            // row_mirror, bound_ctrl 1
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]),
+            // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]),
+            // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1
+            i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in 0..64usize {
+        let v = &r.vgpr[l];
+        if l == 17 {
+            assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off");
+            continue;
+        }
+        let m = (l & !15) + 15 - (l & 15);
+        assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror");
+        assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1");
+        let s = l ^ 1;
+        assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8");
+    }
+}
+
+// ------------------------------------------------------------- rules turned the wrong way
+
+/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must
+/// fail with the flipped one, or the check could not see the rule.
+fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> {
+    vec![
+        (Flip::Lane31, "v_readlane of lane 40", |flip| {
+            kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121)
+        }),
+        (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| {
+            kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip)
+                .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16))
+        }),
+        (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| {
+            let mut st = lanes_state();
+            st.sgpr[126] = 0;
+            kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 }))
+        }),
+        (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| {
+            kernel_with(
+                &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])],
+                &lanes_state(),
+                &[],
+                flip,
+            )
+            .map_or(false, |r| r.sgpr[10] == 1)
+        }),
+    ]
+}
+
+#[test]
+fn each_rule_check_fails_when_its_rule_is_flipped() {
+    for (flip, what, check) in rule_checks() {
+        assert!(check(Flip::None), "{what}: fails with the ISA's rule");
+        assert!(!check(flip), "{what}: still passes with {flip:?}");
+    }
+}
+
+// ------------------------------------------------------------- memory, LDS and groups
+
+#[test]
+fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() {
+    let mut st = lanes_state();
+    st.sgpr[126] = !(1 << 5);
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * (l as u32 + 7);
+    }
+    let r = kernel_with(
+        &[
+            // and 0x1F, xor 16
+            i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+            i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in (0..64usize).filter(|&l| l != 5) {
+        let s = l ^ 16;
+        assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle");
+        let b = (l & 32) | ((l + 7) & 31);
+        assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute");
+    }
+}
+
+#[test]
+fn memory_buffers_globals_and_lds() {
+    let mut st = lanes_state();
+    // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400
+    st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]);
+    st.sgpr[12] = 0x400;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * l as u32;
+    }
+    let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect();
+    let r = kernel_with(
+        &[
+            i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]),
+            i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]),
+            i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]),
+            i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]),
+            i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]),
+            i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]),
+            i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]),
+        ],
+        &st,
+        &mem,
+        Flip::None,
+    )
+    .unwrap();
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0");
+    for l in 0..64usize {
+        assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load");
+        assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add");
+        assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value");
+        // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l
+        assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword");
+        assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order");
+    }
+}
+
+#[test]
+fn groups_of_waves_meet_at_the_barrier_and_share_the_lds() {
+    // each thread writes LDS[t] = t + 1000, meets the group, reads LDS[t ^ 64] and stores it
+    let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+    let code = asm(&[
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]),
+        lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], 1000),
+        i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 2)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 1)], 256),
+        i("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3)]),

This DS_READ_B32 fills v4 and the global store uses v4 without an s_waitcnt lgkmcnt(0). The synchronous interpreter hides it, but on hardware the store needs the wait. Since these programs are meant to be compared with hardware later, it would be good to add it here and check the other memory tests for the same pattern.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758828 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758828). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/tests.rs`; line 452 ~~~~diff @@ -0,0 +1,585 @@ +use super::asm::{asm, end, i, lit, I, TO, V}; +use super::*; +use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture}; + +const EXEC: u64 = 126; +const VCC: u64 = 106; + +fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> { + let mut l = list.to_vec(); + l.push(end()); + run_kernel(&asm(&l), true, st, mem, &[], &[], flip) +} + +/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes. +fn lanes_state() -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + } + st +} + +fn kernel(list: &[I]) -> Run { + kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}")) +} + +#[test] +fn saveexec_families_save_the_old_exec_and_set_scc() { + // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39 + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]), + ]); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC"); + assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves"); + assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0"); + // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC + assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000); + assert_eq!(pair(26), pair(24)); + assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC"); + assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on"); +} + +#[test] +fn branches_see_the_whole_wave_masks() { + // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken + let r = kernel(&[ + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2)); + assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40)); +} + +#[test] +fn salu_carries_overflows_and_fields() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]), + i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF), + i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]), + lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]), + i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]), + i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]), + i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32"); + assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow"); + assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX)); + assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31)); + assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE)); +} + +#[test] +fn an_instruction_outside_the_model_stops_the_run() { + let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]); + match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) { + Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"), + other => panic!("{:?}", other.map(|_| ())), + } + let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand"); + let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_)))); +} + +/// One encoding of every instruction the reference models. +fn modelled_words() -> Vec<Vec<u8>> { + const ENCODINGS: [&str; 17] = [ + "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS", + "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL", + ]; + let mut words = Vec::new(); + for inst in rdna2::all_instructions() { + for name in ENCODINGS { + let enc = rdna2::encoding(name).unwrap(); + let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue }; + if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) { + words.push(code); + } + } + } + words +} + +/// The decoder is checked against LLVM's on every instruction the reference models: +/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs +/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names +/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input). +#[test] +fn modelled_instructions_decode_as_llvm_disassembles_them() { + use std::io::Write; + let words = modelled_words(); + let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect(); + if let Ok(path) = std::env::var("XCL_LLVM_WORDS") { + std::fs::write(path, &input).unwrap(); + } + let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") { + std::fs::read_to_string(path).unwrap() + } else { + let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into()); + let child = std::process::Command::new(&mc) + .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn(); + let Ok(mut child) = child else { + let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc"); + return; + }; + child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap(); + String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned() + }; + // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order + let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect(); + assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word"); + // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`) + let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy"); + let mut bad = Vec::new(); + for (code, t) in words.iter().zip(theirs) { + let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap()); + // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have + let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal"; + if norm(t) != norm(&ours) && !vop3_readfirstlane { + bad.push(format!("{ours} / {t}")); + } + } + assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len()); + let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len()); +} + +/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled. +fn modelled(code: &[u8]) -> bool { + let mut st = KernelState::default(); + st.sgpr[124] = 0; + !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. })) +} + +// ------------------------------------------------------------- vector ALU and lanes + +#[test] +fn lane_reads_and_writes_use_all_64_lanes() { + let r = kernel(&[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]), + ]); + assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40"); + assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33"); + assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63"); + assert_eq!(r.vgpr[31][2], 0, "and nowhere else"); + assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half"); + assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0"); +} + +#[test] +fn mbcnt_counts_the_lanes_below_in_both_halves() { + let r = kernel(&[ + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]), + ]); + for l in 0..64 { + assert_eq!(r.vgpr[l][2], l as u32, "lane {l}"); + assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone"); + } +} + +#[test] +fn carries_and_compares_write_a_bit_per_lane_of_the_pair() { + let mut st = lanes_state(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[4] = if l % 3 == 0 { u32::MAX } else { 7 }; + } + let r = kernel_with( + &[ + i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]), + i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]), + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]), + lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l); + assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword"); + assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry"); + assert_eq!(pair(24), !0u64 << 36); + assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC"); + for l in 0..64 { + assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0)); + assert_eq!(r.vgpr[l][7], u32::from(l > 35)); + assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value"); + } +} + +#[test] +fn integer_valu_known_answers() { + let mut st = lanes_state(); + st.vgpr[0][4] = 0x8000_0001; + st.vgpr[0][5] = 0x0000_0003; + let r = kernel_with( + &[ + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]), + i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]), + lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]), + i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]), + i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]), + i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let v = &r.vgpr[0]; + assert_eq!(v[10], 1); + assert_eq!(v[11], 0xFFFF_FFFE); + assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12"); + assert_eq!(v[13], u32::MAX, "bit 31 sign-extended"); + assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign"); + assert_eq!(v[14], 0xC000_0000); + assert_eq!(v[15], 1); + assert_eq!((v[16], v[17]), (2, 7)); + assert_eq!((v[18], v[19]), (4, 5)); +} + +#[test] +fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + ]); + for l in 0..64u32 { + assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}"); + assert_eq!(r.vgpr[l as usize][3], l, "lane {l}"); + } +} + +#[test] +fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() { + let mut st = lanes_state(); + for r in st.vgpr.iter_mut() { + r[5] = 0xAAAA; + r[6] = 0xBBBB; + } + // lanes 0..63 but lane 17: off + st.sgpr[126] = !(1 << 17); + let r = kernel_with( + &[ + // row_mirror, bound_ctrl 1 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]), + // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]), + // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1 + i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in 0..64usize { + let v = &r.vgpr[l]; + if l == 17 { + assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off"); + continue; + } + let m = (l & !15) + 15 - (l & 15); + assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror"); + assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1"); + let s = l ^ 1; + assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8"); + } +} + +// ------------------------------------------------------------- rules turned the wrong way + +/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must +/// fail with the flipped one, or the check could not see the rule. +fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> { + vec![ + (Flip::Lane31, "v_readlane of lane 40", |flip| { + kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121) + }), + (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| { + kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip) + .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16)) + }), + (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| { + let mut st = lanes_state(); + st.sgpr[126] = 0; + kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 })) + }), + (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| { + kernel_with( + &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])], + &lanes_state(), + &[], + flip, + ) + .map_or(false, |r| r.sgpr[10] == 1) + }), + ] +} + +#[test] +fn each_rule_check_fails_when_its_rule_is_flipped() { + for (flip, what, check) in rule_checks() { + assert!(check(Flip::None), "{what}: fails with the ISA's rule"); + assert!(!check(flip), "{what}: still passes with {flip:?}"); + } +} + +// ------------------------------------------------------------- memory, LDS and groups + +#[test] +fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() { + let mut st = lanes_state(); + st.sgpr[126] = !(1 << 5); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * (l as u32 + 7); + } + let r = kernel_with( + &[ + // and 0x1F, xor 16 + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in (0..64usize).filter(|&l| l != 5) { + let s = l ^ 16; + assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle"); + let b = (l & 32) | ((l + 7) & 31); + assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute"); + } +} + +#[test] +fn memory_buffers_globals_and_lds() { + let mut st = lanes_state(); + // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400 + st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]); + st.sgpr[12] = 0x400; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * l as u32; + } + let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect(); + let r = kernel_with( + &[ + i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]), + i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]), + i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]), + i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]), + i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]), + i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]), + ], + &st, + &mem, + Flip::None, + ) + .unwrap(); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0"); + for l in 0..64usize { + assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load"); + assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add"); + assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value"); + // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l + assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword"); + assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order"); + } +} + +#[test] +fn groups_of_waves_meet_at_the_barrier_and_share_the_lds() { + // each thread writes LDS[t] = t + 1000, meets the group, reads LDS[t ^ 64] and stores it + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let code = asm(&[ + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], 1000), + i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 2)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 1)], 256), + i("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3)]), ~~~~ --- This DS_READ_B32 fills v4 and the global store uses v4 without an s_waitcnt lgkmcnt(0). The synchronous interpreter hides it, but on hardware the store needs the wait. Since these programs are meant to be compared with hardware later, it would be good to add it here and check the other memory tests for the same pattern.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/tests.rs; line 437

@@ -0,0 +1,585 @@
+use super::asm::{asm, end, i, lit, I, TO, V};
+use super::*;
+use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture};
+
+const EXEC: u64 = 126;
+const VCC: u64 = 106;
+
+fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> {
+    let mut l = list.to_vec();
+    l.push(end());
+    run_kernel(&asm(&l), true, st, mem, &[], &[], flip)
+}
+
+/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes.
+fn lanes_state() -> KernelState {
+    let mut st = KernelState::default();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+    }
+    st
+}
+
+fn kernel(list: &[I]) -> Run {
+    kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn saveexec_families_save_the_old_exec_and_set_scc() {
+    // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]),
+        i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]),
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]),
+    ]);
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC");
+    assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves");
+    assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0");
+    // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC
+    assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000);
+    assert_eq!(pair(26), pair(24));
+    assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC");
+    assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on");
+}
+
+#[test]
+fn branches_see_the_whole_wave_masks() {
+    // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken
+    let r = kernel(&[
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8),
+        i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]),
+        i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]),
+        i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2));
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40));
+}
+
+#[test]
+fn salu_carries_overflows_and_fields() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF),
+        i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]),
+        i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF),
+        i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]),
+        lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]),
+        i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]),
+        i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]),
+        i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32");
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow");
+    assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX));
+    assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31));
+    assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed");
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE));
+}
+
+#[test]
+fn an_instruction_outside_the_model_stops_the_run() {
+    let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]);
+    match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) {
+        Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"),
+        other => panic!("{:?}", other.map(|_| ())),
+    }
+    let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand");
+    let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_))));
+}
+
+/// One encoding of every instruction the reference models.
+fn modelled_words() -> Vec<Vec<u8>> {
+    const ENCODINGS: [&str; 17] = [
+        "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS",
+        "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL",
+    ];
+    let mut words = Vec::new();
+    for inst in rdna2::all_instructions() {
+        for name in ENCODINGS {
+            let enc = rdna2::encoding(name).unwrap();
+            let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue };
+            if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) {
+                words.push(code);
+            }
+        }
+    }
+    words
+}
+
+/// The decoder is checked against LLVM's on every instruction the reference models:
+/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs
+/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names
+/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input).
+#[test]
+fn modelled_instructions_decode_as_llvm_disassembles_them() {
+    use std::io::Write;
+    let words = modelled_words();
+    let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect();
+    if let Ok(path) = std::env::var("XCL_LLVM_WORDS") {
+        std::fs::write(path, &input).unwrap();
+    }
+    let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") {
+        std::fs::read_to_string(path).unwrap()
+    } else {
+        let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into());
+        let child = std::process::Command::new(&mc)
+            .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"])
+            .stdin(std::process::Stdio::piped())
+            .stdout(std::process::Stdio::piped())
+            .stderr(std::process::Stdio::piped())
+            .spawn();
+        let Ok(mut child) = child else {
+            let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc");
+            return;
+        };
+        child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
+        String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned()
+    };
+    // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order
+    let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect();
+    assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word");
+    // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`)
+    let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy");
+    let mut bad = Vec::new();
+    for (code, t) in words.iter().zip(theirs) {
+        let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap());
+        // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have
+        let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal";
+        if norm(t) != norm(&ours) && !vop3_readfirstlane {
+            bad.push(format!("{ours} / {t}"));
+        }
+    }
+    assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len());
+    let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len());
+}
+
+/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled.
+fn modelled(code: &[u8]) -> bool {
+    let mut st = KernelState::default();
+    st.sgpr[124] = 0;
+    !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. }))
+}
+
+// ------------------------------------------------------------- vector ALU and lanes
+
+#[test]
+fn lane_reads_and_writes_use_all_64_lanes() {
+    let r = kernel(&[
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234),
+        i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]),
+    ]);
+    assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40");
+    assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33");
+    assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63");
+    assert_eq!(r.vgpr[31][2], 0, "and nowhere else");
+    assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half");
+    assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0");
+}
+
+#[test]
+fn mbcnt_counts_the_lanes_below_in_both_halves() {
+    let r = kernel(&[
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]),
+        i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]),
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]),
+    ]);
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][2], l as u32, "lane {l}");
+        assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone");
+    }
+}
+
+#[test]
+fn carries_and_compares_write_a_bit_per_lane_of_the_pair() {
+    let mut st = lanes_state();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[4] = if l % 3 == 0 { u32::MAX } else { 7 };
+    }
+    let r = kernel_with(
+        &[
+            i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]),
+            i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]),
+            lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]),
+            lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l);
+    assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword");
+    assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry");
+    assert_eq!(pair(24), !0u64 << 36);
+    assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC");
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0));
+        assert_eq!(r.vgpr[l][7], u32::from(l > 35));
+        assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value");
+    }
+}
+
+#[test]
+fn integer_valu_known_answers() {
+    let mut st = lanes_state();
+    st.vgpr[0][4] = 0x8000_0001;
+    st.vgpr[0][5] = 0x0000_0003;
+    let r = kernel_with(
+        &[
+            i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]),
+            i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]),
+            i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]),
+            i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]),
+            i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let v = &r.vgpr[0];
+    assert_eq!(v[10], 1);
+    assert_eq!(v[11], 0xFFFF_FFFE);
+    assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12");
+    assert_eq!(v[13], u32::MAX, "bit 31 sign-extended");
+    assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign");
+    assert_eq!(v[14], 0xC000_0000);
+    assert_eq!(v[15], 1);
+    assert_eq!((v[16], v[17]), (2, 7));
+    assert_eq!((v[18], v[19]), (4, 5));
+}
+
+#[test]
+fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98),
+        i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+        i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+    ]);
+    for l in 0..64u32 {
+        assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}");
+        assert_eq!(r.vgpr[l as usize][3], l, "lane {l}");
+    }
+}
+
+#[test]
+fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() {
+    let mut st = lanes_state();
+    for r in st.vgpr.iter_mut() {
+        r[5] = 0xAAAA;
+        r[6] = 0xBBBB;
+    }
+    // lanes 0..63 but lane 17: off
+    st.sgpr[126] = !(1 << 17);
+    let r = kernel_with(
+        &[
+            // row_mirror, bound_ctrl 1
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]),
+            // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]),
+            // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1
+            i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in 0..64usize {
+        let v = &r.vgpr[l];
+        if l == 17 {
+            assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off");
+            continue;
+        }
+        let m = (l & !15) + 15 - (l & 15);
+        assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror");
+        assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1");
+        let s = l ^ 1;
+        assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8");
+    }
+}
+
+// ------------------------------------------------------------- rules turned the wrong way
+
+/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must
+/// fail with the flipped one, or the check could not see the rule.
+fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> {
+    vec![
+        (Flip::Lane31, "v_readlane of lane 40", |flip| {
+            kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121)
+        }),
+        (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| {
+            kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip)
+                .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16))
+        }),
+        (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| {
+            let mut st = lanes_state();
+            st.sgpr[126] = 0;
+            kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 }))
+        }),
+        (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| {
+            kernel_with(
+                &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])],
+                &lanes_state(),
+                &[],
+                flip,
+            )
+            .map_or(false, |r| r.sgpr[10] == 1)
+        }),
+    ]
+}
+
+#[test]
+fn each_rule_check_fails_when_its_rule_is_flipped() {
+    for (flip, what, check) in rule_checks() {
+        assert!(check(Flip::None), "{what}: fails with the ISA's rule");
+        assert!(!check(flip), "{what}: still passes with {flip:?}");
+    }
+}
+
+// ------------------------------------------------------------- memory, LDS and groups
+
+#[test]
+fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() {
+    let mut st = lanes_state();
+    st.sgpr[126] = !(1 << 5);
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * (l as u32 + 7);
+    }
+    let r = kernel_with(
+        &[
+            // and 0x1F, xor 16
+            i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+            i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in (0..64usize).filter(|&l| l != 5) {
+        let s = l ^ 16;
+        assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle");
+        let b = (l & 32) | ((l + 7) & 31);
+        assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute");
+    }
+}
+
+#[test]
+fn memory_buffers_globals_and_lds() {
+    let mut st = lanes_state();
+    // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400
+    st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]);
+    st.sgpr[12] = 0x400;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * l as u32;
+    }
+    let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect();
+    let r = kernel_with(
+        &[
+            i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]),
+            i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]),
+            i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]),
+            i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]),
+            i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]),
+            i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]),
+            i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]),
+        ],
+        &st,
+        &mem,
+        Flip::None,
+    )
+    .unwrap();
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0");
+    for l in 0..64usize {
+        assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load");
+        assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add");
+        assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value");
+        // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l
+        assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword");
+        assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order");

Question: the returned values assume contending LDS atomics run in lane order. The final sum is fixed, but the old values each lane gets depend on an order I could not find stated in the ISA guide. Checking the sum, or one address per lane, would not depend on it. For DS_PERMUTE_B32 with several senders to one lane the guide is explicit: its pseudocode says the highest-numbered source wins, but the text under it says the final value is not predictable (12.13). A case should avoid that.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758837 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758837). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/tests.rs`; line 437 ~~~~diff @@ -0,0 +1,585 @@ +use super::asm::{asm, end, i, lit, I, TO, V}; +use super::*; +use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture}; + +const EXEC: u64 = 126; +const VCC: u64 = 106; + +fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> { + let mut l = list.to_vec(); + l.push(end()); + run_kernel(&asm(&l), true, st, mem, &[], &[], flip) +} + +/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes. +fn lanes_state() -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + } + st +} + +fn kernel(list: &[I]) -> Run { + kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}")) +} + +#[test] +fn saveexec_families_save_the_old_exec_and_set_scc() { + // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39 + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]), + ]); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC"); + assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves"); + assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0"); + // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC + assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000); + assert_eq!(pair(26), pair(24)); + assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC"); + assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on"); +} + +#[test] +fn branches_see_the_whole_wave_masks() { + // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken + let r = kernel(&[ + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2)); + assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40)); +} + +#[test] +fn salu_carries_overflows_and_fields() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]), + i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF), + i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]), + lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]), + i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]), + i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]), + i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32"); + assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow"); + assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX)); + assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31)); + assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE)); +} + +#[test] +fn an_instruction_outside_the_model_stops_the_run() { + let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]); + match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) { + Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"), + other => panic!("{:?}", other.map(|_| ())), + } + let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand"); + let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_)))); +} + +/// One encoding of every instruction the reference models. +fn modelled_words() -> Vec<Vec<u8>> { + const ENCODINGS: [&str; 17] = [ + "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS", + "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL", + ]; + let mut words = Vec::new(); + for inst in rdna2::all_instructions() { + for name in ENCODINGS { + let enc = rdna2::encoding(name).unwrap(); + let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue }; + if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) { + words.push(code); + } + } + } + words +} + +/// The decoder is checked against LLVM's on every instruction the reference models: +/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs +/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names +/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input). +#[test] +fn modelled_instructions_decode_as_llvm_disassembles_them() { + use std::io::Write; + let words = modelled_words(); + let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect(); + if let Ok(path) = std::env::var("XCL_LLVM_WORDS") { + std::fs::write(path, &input).unwrap(); + } + let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") { + std::fs::read_to_string(path).unwrap() + } else { + let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into()); + let child = std::process::Command::new(&mc) + .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn(); + let Ok(mut child) = child else { + let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc"); + return; + }; + child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap(); + String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned() + }; + // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order + let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect(); + assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word"); + // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`) + let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy"); + let mut bad = Vec::new(); + for (code, t) in words.iter().zip(theirs) { + let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap()); + // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have + let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal"; + if norm(t) != norm(&ours) && !vop3_readfirstlane { + bad.push(format!("{ours} / {t}")); + } + } + assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len()); + let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len()); +} + +/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled. +fn modelled(code: &[u8]) -> bool { + let mut st = KernelState::default(); + st.sgpr[124] = 0; + !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. })) +} + +// ------------------------------------------------------------- vector ALU and lanes + +#[test] +fn lane_reads_and_writes_use_all_64_lanes() { + let r = kernel(&[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]), + ]); + assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40"); + assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33"); + assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63"); + assert_eq!(r.vgpr[31][2], 0, "and nowhere else"); + assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half"); + assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0"); +} + +#[test] +fn mbcnt_counts_the_lanes_below_in_both_halves() { + let r = kernel(&[ + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]), + ]); + for l in 0..64 { + assert_eq!(r.vgpr[l][2], l as u32, "lane {l}"); + assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone"); + } +} + +#[test] +fn carries_and_compares_write_a_bit_per_lane_of_the_pair() { + let mut st = lanes_state(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[4] = if l % 3 == 0 { u32::MAX } else { 7 }; + } + let r = kernel_with( + &[ + i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]), + i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]), + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]), + lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l); + assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword"); + assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry"); + assert_eq!(pair(24), !0u64 << 36); + assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC"); + for l in 0..64 { + assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0)); + assert_eq!(r.vgpr[l][7], u32::from(l > 35)); + assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value"); + } +} + +#[test] +fn integer_valu_known_answers() { + let mut st = lanes_state(); + st.vgpr[0][4] = 0x8000_0001; + st.vgpr[0][5] = 0x0000_0003; + let r = kernel_with( + &[ + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]), + i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]), + lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]), + i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]), + i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]), + i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let v = &r.vgpr[0]; + assert_eq!(v[10], 1); + assert_eq!(v[11], 0xFFFF_FFFE); + assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12"); + assert_eq!(v[13], u32::MAX, "bit 31 sign-extended"); + assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign"); + assert_eq!(v[14], 0xC000_0000); + assert_eq!(v[15], 1); + assert_eq!((v[16], v[17]), (2, 7)); + assert_eq!((v[18], v[19]), (4, 5)); +} + +#[test] +fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + ]); + for l in 0..64u32 { + assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}"); + assert_eq!(r.vgpr[l as usize][3], l, "lane {l}"); + } +} + +#[test] +fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() { + let mut st = lanes_state(); + for r in st.vgpr.iter_mut() { + r[5] = 0xAAAA; + r[6] = 0xBBBB; + } + // lanes 0..63 but lane 17: off + st.sgpr[126] = !(1 << 17); + let r = kernel_with( + &[ + // row_mirror, bound_ctrl 1 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]), + // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]), + // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1 + i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in 0..64usize { + let v = &r.vgpr[l]; + if l == 17 { + assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off"); + continue; + } + let m = (l & !15) + 15 - (l & 15); + assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror"); + assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1"); + let s = l ^ 1; + assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8"); + } +} + +// ------------------------------------------------------------- rules turned the wrong way + +/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must +/// fail with the flipped one, or the check could not see the rule. +fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> { + vec![ + (Flip::Lane31, "v_readlane of lane 40", |flip| { + kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121) + }), + (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| { + kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip) + .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16)) + }), + (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| { + let mut st = lanes_state(); + st.sgpr[126] = 0; + kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 })) + }), + (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| { + kernel_with( + &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])], + &lanes_state(), + &[], + flip, + ) + .map_or(false, |r| r.sgpr[10] == 1) + }), + ] +} + +#[test] +fn each_rule_check_fails_when_its_rule_is_flipped() { + for (flip, what, check) in rule_checks() { + assert!(check(Flip::None), "{what}: fails with the ISA's rule"); + assert!(!check(flip), "{what}: still passes with {flip:?}"); + } +} + +// ------------------------------------------------------------- memory, LDS and groups + +#[test] +fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() { + let mut st = lanes_state(); + st.sgpr[126] = !(1 << 5); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * (l as u32 + 7); + } + let r = kernel_with( + &[ + // and 0x1F, xor 16 + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in (0..64usize).filter(|&l| l != 5) { + let s = l ^ 16; + assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle"); + let b = (l & 32) | ((l + 7) & 31); + assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute"); + } +} + +#[test] +fn memory_buffers_globals_and_lds() { + let mut st = lanes_state(); + // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400 + st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]); + st.sgpr[12] = 0x400; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * l as u32; + } + let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect(); + let r = kernel_with( + &[ + i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]), + i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]), + i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]), + i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]), + i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]), + i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]), + ], + &st, + &mem, + Flip::None, + ) + .unwrap(); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0"); + for l in 0..64usize { + assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load"); + assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add"); + assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value"); + // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l + assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword"); + assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order"); ~~~~ --- Question: the returned values assume contending LDS atomics run in lane order. The final sum is fixed, but the old values each lane gets depend on an order I could not find stated in the ISA guide. Checking the sum, or one address per lane, would not depend on it. For DS_PERMUTE_B32 with several senders to one lane the guide is explicit: its pseudocode says the highest-numbered source wins, but the text under it says the final value is not predictable (12.13). A case should avoid that.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/tests.rs; line 121

@@ -0,0 +1,585 @@
+use super::asm::{asm, end, i, lit, I, TO, V};
+use super::*;
+use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture};
+
+const EXEC: u64 = 126;
+const VCC: u64 = 106;
+
+fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> {
+    let mut l = list.to_vec();
+    l.push(end());
+    run_kernel(&asm(&l), true, st, mem, &[], &[], flip)
+}
+
+/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes.
+fn lanes_state() -> KernelState {
+    let mut st = KernelState::default();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+    }
+    st
+}
+
+fn kernel(list: &[I]) -> Run {
+    kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn saveexec_families_save_the_old_exec_and_set_scc() {
+    // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]),
+        i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]),
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]),
+    ]);
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC");
+    assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves");
+    assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0");
+    // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC
+    assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000);
+    assert_eq!(pair(26), pair(24));
+    assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC");
+    assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on");
+}
+
+#[test]
+fn branches_see_the_whole_wave_masks() {
+    // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken
+    let r = kernel(&[
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8),
+        i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]),
+        i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]),
+        i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2));
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40));
+}
+
+#[test]
+fn salu_carries_overflows_and_fields() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF),
+        i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]),
+        i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF),
+        i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]),
+        lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]),
+        i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]),
+        i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]),
+        i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32");
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow");
+    assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX));
+    assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31));
+    assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed");
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE));
+}
+
+#[test]
+fn an_instruction_outside_the_model_stops_the_run() {
+    let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]);
+    match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) {
+        Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"),
+        other => panic!("{:?}", other.map(|_| ())),
+    }
+    let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand");
+    let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_))));
+}
+
+/// One encoding of every instruction the reference models.
+fn modelled_words() -> Vec<Vec<u8>> {
+    const ENCODINGS: [&str; 17] = [
+        "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS",
+        "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL",
+    ];
+    let mut words = Vec::new();
+    for inst in rdna2::all_instructions() {
+        for name in ENCODINGS {
+            let enc = rdna2::encoding(name).unwrap();
+            let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue };

The check encodes each instruction with every field at 0 and compares the mnemonic only (line 160). Since encode and decode share one table, it proves the opcode-to-name table, not field positions, DPP/SDWA/literal variants or semantics. S_SETREG/S_GETREG are filtered out (hwreg 0). It is also always SKIPPED in CI (no llvm-mc there). The description's "826 modelled encodings agree" would read better as "826 opcode names agree".

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758845 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758845). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/tests.rs`; line 121 ~~~~diff @@ -0,0 +1,585 @@ +use super::asm::{asm, end, i, lit, I, TO, V}; +use super::*; +use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture}; + +const EXEC: u64 = 126; +const VCC: u64 = 106; + +fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> { + let mut l = list.to_vec(); + l.push(end()); + run_kernel(&asm(&l), true, st, mem, &[], &[], flip) +} + +/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes. +fn lanes_state() -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + } + st +} + +fn kernel(list: &[I]) -> Run { + kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}")) +} + +#[test] +fn saveexec_families_save_the_old_exec_and_set_scc() { + // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39 + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]), + ]); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC"); + assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves"); + assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0"); + // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC + assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000); + assert_eq!(pair(26), pair(24)); + assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC"); + assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on"); +} + +#[test] +fn branches_see_the_whole_wave_masks() { + // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken + let r = kernel(&[ + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2)); + assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40)); +} + +#[test] +fn salu_carries_overflows_and_fields() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]), + i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF), + i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]), + lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]), + i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]), + i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]), + i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32"); + assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow"); + assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX)); + assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31)); + assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE)); +} + +#[test] +fn an_instruction_outside_the_model_stops_the_run() { + let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]); + match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) { + Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"), + other => panic!("{:?}", other.map(|_| ())), + } + let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand"); + let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_)))); +} + +/// One encoding of every instruction the reference models. +fn modelled_words() -> Vec<Vec<u8>> { + const ENCODINGS: [&str; 17] = [ + "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS", + "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL", + ]; + let mut words = Vec::new(); + for inst in rdna2::all_instructions() { + for name in ENCODINGS { + let enc = rdna2::encoding(name).unwrap(); + let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue }; ~~~~ --- The check encodes each instruction with every field at 0 and compares the mnemonic only (line 160). Since encode and decode share one table, it proves the opcode-to-name table, not field positions, DPP/SDWA/literal variants or semantics. S_SETREG/S_GETREG are filtered out (hwreg 0). It is also always SKIPPED in CI (no llvm-mc there). The description's "826 modelled encodings agree" would read better as "826 opcode names agree".
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 706

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),
+    }
+}
+
+pub(crate) type Form = (&'static str, fn(&Case) -> Got);
+
+/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native
+/// ones on one with 64-lane waves.
+pub(crate) fn gpu_forms() -> Vec<Form> {
+    let mut forms: Vec<Form> = Vec::new();
+    if runner::wave32_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL split", |c| hlsl(c, true)));
+        }
+        forms.push(("direct split", |c| direct(c, true)));
+        forms.push(("per-lane split", |c| per_lane(c, true)));
+    }
+    if runner::wave64_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL wave64", |c| hlsl(c, false)));
+        }
+        forms.push(("direct wave64", |c| direct(c, false)));
+        forms.push(("per-lane wave64", |c| per_lane(c, false)));
+    }
+    forms
+}
+
+/// A dword as an integer ordered like the float it is, for ULP distances.
+fn ordered(x: u32) -> i64 {
+    if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) }
+}
+
+/// The verdict of one form on one case.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Verdict {
+    /// dwords compared exactly, dwords compared within their bound
+    Match(usize, usize),
+    /// first differing dword (where, reference, form) and how many differ
+    Mismatch(String, u32, u32, usize),
+    Refused(String),
+    Failed(String),
+}
+
+pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict {
+    let words = match got {
+        Got::Words(w) => w,
+        Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()),
+        Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()),
+    };
+    let (want, taint) = want;
+    if words.len() != want.len() {
+        return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len()));
+    }
+    let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0);
+    for k in 0..want.len() {
+        let (w, g, t) = (want[k], words[k], taint[k]);
+        let ok = if t == 0 {
+            exact += 1;
+            w == g
+        } else {
+            bounded += 1;
+            w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t)
+        };
+        if !ok {
+            n += 1;
+            first.get_or_insert(k);
+        }
+    }
+    match first {
+        None => Verdict::Match(exact, bounded),
+        Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n),
+    }
+}
+
+// ------------------------------------------------------------------------ the cases
+
+/// lanes_state of the tests, plus v2 = a value with both halves' patterns.
+fn kernel_state(exec: u64) -> KernelState {
+    let mut st = KernelState::default();
+    st.sgpr[126] = exec as u32;
+    st.sgpr[127] = (exec >> 32) as u32;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+        r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7;
+        r[3] = 4 * l as u32;
+        r[4] = ((l as f32) * 0.25 - 3.0).to_bits();
+    }
+    st
+}
+
+/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions.
+fn kernel_case(name: &str, list: &[I], exec: u64) -> Case {
+    let mut l = vec![
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32),
+    ];
+    l.extend_from_slice(list);
+    l.push(end());
+    Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62);
+
+fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I {
+    i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)])
+}
+
+/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8.
+pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I {
+    const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
+    let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)];
+    f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x)));
+    (name, "VOP2_VOP_DPP8", f, None)
+}
+
+pub(crate) fn kernel_cases() -> Vec<Case> {
+    let mut cases = vec![
+        kernel_case(
+            "lane reads across the halves",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "lane reads and ballots under a full EXEC",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]),
+                lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]),
+                i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "a scalar written while lanes are off reaches them",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "a scalar written in a branch reaches the lanes outside it",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "permlane16 and permlanex16",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]),
+                i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP16 rows with BOUND_CTRL and EXEC holes",
+            &[
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]),
+                dpp16("V_OR_B32", 6, 2, 1, 0x140, 1),
+                dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0),
+                dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1),
+                dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0),
+                dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1),
+                dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP8 xor steps with EXEC holes",
+            &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)],
+            HOLES,
+        ),
+        kernel_case(
+            "ds_swizzle, ds_bpermute and ds_permute",
+            &[
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]),
+                lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]),
+                i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]),
+                // index lane + 40: past the half, which wraps within it
+                lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "masks across the halves",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]),
+                i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]),
+                i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]),
+                i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]),
+                lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45),
+                i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]),
+                i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]),
+                i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "carries across the halves",
+            &[
+                lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000),
+                i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]),
+                i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]),
+                i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]),
+                i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "exact float rules",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]),
+                i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]),
+                i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]),
+                i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]),
+                i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]),
+                i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]),
+                i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]),
+                i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]),
+                i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]),
+                i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]),
+                i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]),
+                i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]),
+                i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]),
+                i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]),
+                i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "transcendentals",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]),
+                i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]),
+                i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]),
+                i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]),
+                i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]),
+            ],
+            !0,
+        ),
+    ];
+    // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into
+    let mut img = kernel_case(
+        "images",
+        &[
+            i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]),
+            i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()),
+            i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]),
+            i("S_WAITCNT", "ENC_SOPP", &[]),
+        ],
+        !0,
+    );
+    if let Abi::Kernel(st) = &mut img.abi {
+        // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D
+        st.sgpr[0] = 0;
+        st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+        st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+    }
+    img.tex = vec![
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false },
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true },
+    ];
+    img.samplers = vec![TestSampler {
+        filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT,
+        address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+        comparison: None,
+    }];
+    cases.push(img);
+    cases
+}
+
+const EXEC_PAIR: u64 = 126;
+
+/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material
+/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a
+/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS.
+/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs.
+pub(crate) fn classifier() -> Vec<u8> {
+    let mut l = vec![
+        i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]),
+        i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]),
+        i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]),
+        // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]),
+        i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]),
+        i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        // lanes of material 7 are off for the reductions
+        i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]),
+    ];
+    // (op, identity, result SGPR, LDS atomic)
+    for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] {
+        l.extend([
+            i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]),
+            dpp8_xor(op, 11, 11, 11, 1),
+            dpp8_xor(op, 11, 11, 11, 2),
+            dpp8_xor(op, 11, 11, 11, 4),
+            dpp16(op, 11, 11, 11, 0x140, 1),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+            i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+            i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]),
+            i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]),
+            i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]),
+            i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]),
+        ]);
+        if let Some((atomic, at)) = ds {
+            l.extend([
+                lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]),
+                i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]),
+            ]);
+        }
+    }
+    l.extend([
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        // five dwords a thread at s1 + 20 · thread
+        i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]),
+        end(),
+    ]);
+    asm(&l)
+}
+
+/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in
+/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in
+/// row 3.
+pub(crate) fn classifier_case() -> Case {
+    let groups = 6u32;
+    let mut mem = vec![0u32; groups as usize * 256 * 6];
+    for g in 0..groups as usize {
+        for t in 0..256usize {
+            let lane = t % 64;
+            mem[g * 256 + t] = match g {
+                0 => 3,
+                1 => if lane < 32 { 2 } else { 5 },
+                2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6],
+                3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 },
+                4 => if t == 20 { 1 } else { 6 },
+                _ => if t == 50 { 9 } else { 6 },
+            };
+        }
+    }
+    let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 };
+    Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has
+/// no threads, its lanes are turned on, given the identity and read by v_readlane 32.
+pub(crate) fn empty_half_case() -> Case {
+    let code = asm(&[
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]),
+        i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]),
+        end(),
+    ]);
+    let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 };
+    Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+pub(crate) fn cases() -> Vec<Case> {
+    let mut c = kernel_cases();
+    c.push(classifier_case());
+    c.push(empty_half_case());
+    c
+}
+
+/// Mismatches main has today, (case, form): each one is listed in the pull request that
+/// added the harness. A form that starts to agree turns the test red until its line goes.
+const KNOWN: &[(&str, &str)] = &[
+    ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "direct split"),
+    ("a whole-wave section in a wave with an empty upper half", "per-lane split"),
+];
+
+fn print(case: &str, form: &str, v: &Verdict) {
+    use std::io::Write;
+    let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}");
+}
+
+#[test]
+fn gpu_wave64_forms_agree_with_the_reference() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let forms = gpu_forms();
+    if forms.is_empty() {
+        return runner::skip_test("no wave64");
+    }
+    let mut unexpected = Vec::new();
+    let mut matched = 0;
+    for case in cases() {
+        let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name));
+        for (form, run) in &forms {
+            let v = judge(&case, &want, run(&case));
+            print(&case.name, form, &v);
+            let known = KNOWN.contains(&(case.name.as_str(), *form));
+            match (&v, known) {
+                (Verdict::Match(..), false) => matched += 1,
+                (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {}

A KNOWN entry accepts any Mismatch and also Failed, so a DXC or dispatch failure, or a different mismatch in the same case and form, stays green. Refused passes for every pair, so a case that stops translating, or a form that refuses the whole suite while another one matches (matched > 0 is a total), is not seen. Could KNOWN name the expected first differing word, Failed always count as unexpected, and each available form need at least one Match?

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758854 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758854). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 706 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), + } +} + +pub(crate) type Form = (&'static str, fn(&Case) -> Got); + +/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native +/// ones on one with 64-lane waves. +pub(crate) fn gpu_forms() -> Vec<Form> { + let mut forms: Vec<Form> = Vec::new(); + if runner::wave32_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL split", |c| hlsl(c, true))); + } + forms.push(("direct split", |c| direct(c, true))); + forms.push(("per-lane split", |c| per_lane(c, true))); + } + if runner::wave64_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL wave64", |c| hlsl(c, false))); + } + forms.push(("direct wave64", |c| direct(c, false))); + forms.push(("per-lane wave64", |c| per_lane(c, false))); + } + forms +} + +/// A dword as an integer ordered like the float it is, for ULP distances. +fn ordered(x: u32) -> i64 { + if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) } +} + +/// The verdict of one form on one case. +#[derive(Debug, PartialEq)] +pub(crate) enum Verdict { + /// dwords compared exactly, dwords compared within their bound + Match(usize, usize), + /// first differing dword (where, reference, form) and how many differ + Mismatch(String, u32, u32, usize), + Refused(String), + Failed(String), +} + +pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict { + let words = match got { + Got::Words(w) => w, + Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()), + Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()), + }; + let (want, taint) = want; + if words.len() != want.len() { + return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len())); + } + let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0); + for k in 0..want.len() { + let (w, g, t) = (want[k], words[k], taint[k]); + let ok = if t == 0 { + exact += 1; + w == g + } else { + bounded += 1; + w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t) + }; + if !ok { + n += 1; + first.get_or_insert(k); + } + } + match first { + None => Verdict::Match(exact, bounded), + Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n), + } +} + +// ------------------------------------------------------------------------ the cases + +/// lanes_state of the tests, plus v2 = a value with both halves' patterns. +fn kernel_state(exec: u64) -> KernelState { + let mut st = KernelState::default(); + st.sgpr[126] = exec as u32; + st.sgpr[127] = (exec >> 32) as u32; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7; + r[3] = 4 * l as u32; + r[4] = ((l as f32) * 0.25 - 3.0).to_bits(); + } + st +} + +/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions. +fn kernel_case(name: &str, list: &[I], exec: u64) -> Case { + let mut l = vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32), + ]; + l.extend_from_slice(list); + l.push(end()); + Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62); + +fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I { + i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)]) +} + +/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8. +pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I { + const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)]; + f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x))); + (name, "VOP2_VOP_DPP8", f, None) +} + +pub(crate) fn kernel_cases() -> Vec<Case> { + let mut cases = vec![ + kernel_case( + "lane reads across the halves", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]), + ], + !0, + ), + kernel_case( + "lane reads and ballots under a full EXEC", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]), + lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]), + i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]), + ], + !0, + ), + kernel_case( + "a scalar written while lanes are off reaches them", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "a scalar written in a branch reaches the lanes outside it", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "permlane16 and permlanex16", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]), + ], + HOLES, + ), + kernel_case( + "DPP16 rows with BOUND_CTRL and EXEC holes", + &[ + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]), + dpp16("V_OR_B32", 6, 2, 1, 0x140, 1), + dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0), + dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1), + dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0), + dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1), + dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1), + ], + HOLES, + ), + kernel_case( + "DPP8 xor steps with EXEC holes", + &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)], + HOLES, + ), + kernel_case( + "ds_swizzle, ds_bpermute and ds_permute", + &[ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]), + i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]), + // index lane + 40: past the half, which wraps within it + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + HOLES, + ), + kernel_case( + "masks across the halves", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]), + i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]), + lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]), + ], + HOLES, + ), + kernel_case( + "carries across the halves", + &[ + lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000), + i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]), + i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]), + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]), + ], + HOLES, + ), + kernel_case( + "exact float rules", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]), + i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]), + i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]), + i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]), + i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]), + i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]), + i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]), + i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]), + i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]), + i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]), + i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]), + i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]), + i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]), + i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]), + ], + HOLES, + ), + kernel_case( + "transcendentals", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]), + ], + !0, + ), + ]; + // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into + let mut img = kernel_case( + "images", + &[ + i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]), + i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()), + i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + !0, + ); + if let Abi::Kernel(st) = &mut img.abi { + // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D + st.sgpr[0] = 0; + st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]); + st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]); + } + img.tex = vec![ + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false }, + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true }, + ]; + img.samplers = vec![TestSampler { + filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT, + address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + comparison: None, + }]; + cases.push(img); + cases +} + +const EXEC_PAIR: u64 = 126; + +/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material +/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a +/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS. +/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs. +pub(crate) fn classifier() -> Vec<u8> { + let mut l = vec![ + i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]), + i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]), + i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]), + // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]), + i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + // lanes of material 7 are off for the reductions + i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]), + ]; + // (op, identity, result SGPR, LDS atomic) + for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] { + l.extend([ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]), + dpp8_xor(op, 11, 11, 11, 1), + dpp8_xor(op, 11, 11, 11, 2), + dpp8_xor(op, 11, 11, 11, 4), + dpp16(op, 11, 11, 11, 0x140, 1), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]), + i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]), + ]); + if let Some((atomic, at)) = ds { + l.extend([ + lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]), + i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]), + ]); + } + } + l.extend([ + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]), + // five dwords a thread at s1 + 20 · thread + i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]), + end(), + ]); + asm(&l) +} + +/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in +/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in +/// row 3. +pub(crate) fn classifier_case() -> Case { + let groups = 6u32; + let mut mem = vec![0u32; groups as usize * 256 * 6]; + for g in 0..groups as usize { + for t in 0..256usize { + let lane = t % 64; + mem[g * 256 + t] = match g { + 0 => 3, + 1 => if lane < 32 { 2 } else { 5 }, + 2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6], + 3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 }, + 4 => if t == 20 { 1 } else { 6 }, + _ => if t == 50 { 9 } else { 6 }, + }; + } + } + let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 }; + Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has +/// no threads, its lanes are turned on, given the identity and read by v_readlane 32. +pub(crate) fn empty_half_case() -> Case { + let code = asm(&[ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]), + end(), + ]); + let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +pub(crate) fn cases() -> Vec<Case> { + let mut c = kernel_cases(); + c.push(classifier_case()); + c.push(empty_half_case()); + c +} + +/// Mismatches main has today, (case, form): each one is listed in the pull request that +/// added the harness. A form that starts to agree turns the test red until its line goes. +const KNOWN: &[(&str, &str)] = &[ + ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "direct split"), + ("a whole-wave section in a wave with an empty upper half", "per-lane split"), +]; + +fn print(case: &str, form: &str, v: &Verdict) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}"); +} + +#[test] +fn gpu_wave64_forms_agree_with_the_reference() { + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + let forms = gpu_forms(); + if forms.is_empty() { + return runner::skip_test("no wave64"); + } + let mut unexpected = Vec::new(); + let mut matched = 0; + for case in cases() { + let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name)); + for (form, run) in &forms { + let v = judge(&case, &want, run(&case)); + print(&case.name, form, &v); + let known = KNOWN.contains(&(case.name.as_str(), *form)); + match (&v, known) { + (Verdict::Match(..), false) => matched += 1, + (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {} ~~~~ --- A KNOWN entry accepts any Mismatch and also Failed, so a DXC or dispatch failure, or a different mismatch in the same case and form, stays green. Refused passes for every pair, so a case that stops translating, or a form that refuses the whole suite while another one matches (matched > 0 is a total), is not seen. Could KNOWN name the expected first differing word, Failed always count as unexpected, and each available form need at least one Match?
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 221

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),

A panic in the lowering or in its interpreter is reported as Refused, so it never fails a test. The CPU fuzz (fuzz.rs:446) reports only mismatches and does not count refusals, so "40,000 seeds, 0 mismatches" does not say how many seeds were translated at all. Could panics be failures, and the fuzz print matched / refused per form?

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758862 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758862). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 221 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), ~~~~ --- A panic in the lowering or in its interpreter is reported as Refused, so it never fails a test. The CPU fuzz (fuzz.rs:446) reports only mismatches and does not count refusals, so "40,000 seeds, 0 mismatches" does not say how many seeds were translated at all. Could panics be failures, and the fuzz print matched / refused per form?
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 727

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),
+    }
+}
+
+pub(crate) type Form = (&'static str, fn(&Case) -> Got);
+
+/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native
+/// ones on one with 64-lane waves.
+pub(crate) fn gpu_forms() -> Vec<Form> {
+    let mut forms: Vec<Form> = Vec::new();
+    if runner::wave32_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL split", |c| hlsl(c, true)));
+        }
+        forms.push(("direct split", |c| direct(c, true)));
+        forms.push(("per-lane split", |c| per_lane(c, true)));
+    }
+    if runner::wave64_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL wave64", |c| hlsl(c, false)));
+        }
+        forms.push(("direct wave64", |c| direct(c, false)));
+        forms.push(("per-lane wave64", |c| per_lane(c, false)));
+    }
+    forms
+}
+
+/// A dword as an integer ordered like the float it is, for ULP distances.
+fn ordered(x: u32) -> i64 {
+    if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) }
+}
+
+/// The verdict of one form on one case.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Verdict {
+    /// dwords compared exactly, dwords compared within their bound
+    Match(usize, usize),
+    /// first differing dword (where, reference, form) and how many differ
+    Mismatch(String, u32, u32, usize),
+    Refused(String),
+    Failed(String),
+}
+
+pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict {
+    let words = match got {
+        Got::Words(w) => w,
+        Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()),
+        Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()),
+    };
+    let (want, taint) = want;
+    if words.len() != want.len() {
+        return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len()));
+    }
+    let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0);
+    for k in 0..want.len() {
+        let (w, g, t) = (want[k], words[k], taint[k]);
+        let ok = if t == 0 {
+            exact += 1;
+            w == g
+        } else {
+            bounded += 1;
+            w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t)
+        };
+        if !ok {
+            n += 1;
+            first.get_or_insert(k);
+        }
+    }
+    match first {
+        None => Verdict::Match(exact, bounded),
+        Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n),
+    }
+}
+
+// ------------------------------------------------------------------------ the cases
+
+/// lanes_state of the tests, plus v2 = a value with both halves' patterns.
+fn kernel_state(exec: u64) -> KernelState {
+    let mut st = KernelState::default();
+    st.sgpr[126] = exec as u32;
+    st.sgpr[127] = (exec >> 32) as u32;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+        r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7;
+        r[3] = 4 * l as u32;
+        r[4] = ((l as f32) * 0.25 - 3.0).to_bits();
+    }
+    st
+}
+
+/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions.
+fn kernel_case(name: &str, list: &[I], exec: u64) -> Case {
+    let mut l = vec![
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32),
+    ];
+    l.extend_from_slice(list);
+    l.push(end());
+    Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62);
+
+fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I {
+    i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)])
+}
+
+/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8.
+pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I {
+    const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
+    let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)];
+    f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x)));
+    (name, "VOP2_VOP_DPP8", f, None)
+}
+
+pub(crate) fn kernel_cases() -> Vec<Case> {
+    let mut cases = vec![
+        kernel_case(
+            "lane reads across the halves",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "lane reads and ballots under a full EXEC",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]),
+                lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]),
+                i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "a scalar written while lanes are off reaches them",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "a scalar written in a branch reaches the lanes outside it",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "permlane16 and permlanex16",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]),
+                i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP16 rows with BOUND_CTRL and EXEC holes",
+            &[
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]),
+                dpp16("V_OR_B32", 6, 2, 1, 0x140, 1),
+                dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0),
+                dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1),
+                dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0),
+                dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1),
+                dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP8 xor steps with EXEC holes",
+            &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)],
+            HOLES,
+        ),
+        kernel_case(
+            "ds_swizzle, ds_bpermute and ds_permute",
+            &[
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]),
+                lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]),
+                i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]),
+                // index lane + 40: past the half, which wraps within it
+                lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "masks across the halves",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]),
+                i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]),
+                i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]),
+                i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]),
+                lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45),
+                i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]),
+                i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]),
+                i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "carries across the halves",
+            &[
+                lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000),
+                i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]),
+                i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]),
+                i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]),
+                i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "exact float rules",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]),
+                i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]),
+                i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]),
+                i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]),
+                i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]),
+                i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]),
+                i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]),
+                i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]),
+                i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]),
+                i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]),
+                i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]),
+                i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]),
+                i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]),
+                i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]),
+                i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "transcendentals",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]),
+                i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]),
+                i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]),
+                i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]),
+                i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]),
+            ],
+            !0,
+        ),
+    ];
+    // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into
+    let mut img = kernel_case(
+        "images",
+        &[
+            i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]),
+            i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()),
+            i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]),
+            i("S_WAITCNT", "ENC_SOPP", &[]),
+        ],
+        !0,
+    );
+    if let Abi::Kernel(st) = &mut img.abi {
+        // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D
+        st.sgpr[0] = 0;
+        st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+        st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+    }
+    img.tex = vec![
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false },
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true },
+    ];
+    img.samplers = vec![TestSampler {
+        filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT,
+        address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+        comparison: None,
+    }];
+    cases.push(img);
+    cases
+}
+
+const EXEC_PAIR: u64 = 126;
+
+/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material
+/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a
+/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS.
+/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs.
+pub(crate) fn classifier() -> Vec<u8> {
+    let mut l = vec![
+        i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]),
+        i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]),
+        i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]),
+        // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]),
+        i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]),
+        i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        // lanes of material 7 are off for the reductions
+        i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]),
+    ];
+    // (op, identity, result SGPR, LDS atomic)
+    for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] {
+        l.extend([
+            i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]),
+            dpp8_xor(op, 11, 11, 11, 1),
+            dpp8_xor(op, 11, 11, 11, 2),
+            dpp8_xor(op, 11, 11, 11, 4),
+            dpp16(op, 11, 11, 11, 0x140, 1),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+            i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+            i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]),
+            i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]),
+            i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]),
+            i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]),
+        ]);
+        if let Some((atomic, at)) = ds {
+            l.extend([
+                lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]),
+                i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]),
+            ]);
+        }
+    }
+    l.extend([
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        // five dwords a thread at s1 + 20 · thread
+        i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]),
+        end(),
+    ]);
+    asm(&l)
+}
+
+/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in
+/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in
+/// row 3.
+pub(crate) fn classifier_case() -> Case {
+    let groups = 6u32;
+    let mut mem = vec![0u32; groups as usize * 256 * 6];
+    for g in 0..groups as usize {
+        for t in 0..256usize {
+            let lane = t % 64;
+            mem[g * 256 + t] = match g {
+                0 => 3,
+                1 => if lane < 32 { 2 } else { 5 },
+                2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6],
+                3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 },
+                4 => if t == 20 { 1 } else { 6 },
+                _ => if t == 50 { 9 } else { 6 },
+            };
+        }
+    }
+    let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 };
+    Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has
+/// no threads, its lanes are turned on, given the identity and read by v_readlane 32.
+pub(crate) fn empty_half_case() -> Case {
+    let code = asm(&[
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]),
+        i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]),
+        end(),
+    ]);
+    let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 };
+    Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+pub(crate) fn cases() -> Vec<Case> {
+    let mut c = kernel_cases();
+    c.push(classifier_case());
+    c.push(empty_half_case());
+    c
+}
+
+/// Mismatches main has today, (case, form): each one is listed in the pull request that
+/// added the harness. A form that starts to agree turns the test red until its line goes.
+const KNOWN: &[(&str, &str)] = &[
+    ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "direct split"),
+    ("a whole-wave section in a wave with an empty upper half", "per-lane split"),
+];
+
+fn print(case: &str, form: &str, v: &Verdict) {
+    use std::io::Write;
+    let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}");
+}
+
+#[test]
+fn gpu_wave64_forms_agree_with_the_reference() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let forms = gpu_forms();
+    if forms.is_empty() {
+        return runner::skip_test("no wave64");
+    }
+    let mut unexpected = Vec::new();
+    let mut matched = 0;
+    for case in cases() {
+        let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name));
+        for (form, run) in &forms {
+            let v = judge(&case, &want, run(&case));
+            print(&case.name, form, &v);
+            let known = KNOWN.contains(&(case.name.as_str(), *form));
+            match (&v, known) {
+                (Verdict::Match(..), false) => matched += 1,
+                (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {}
+                _ => unexpected.push(format!("{} / {form}: {v:?}", case.name)),
+            }
+        }
+    }
+    assert!(unexpected.is_empty(), "{} unexpected:\n{}", unexpected.len(), unexpected.join("\n"));
+    assert!(matched > 0, "no form translated any case");
+}
+
+/// The negative controls: a reference with a rule turned the wrong way must disagree with
+/// every form that agrees with the right one, on the cases that use the rule.
+#[test]
+fn gpu_a_flipped_rule_is_seen_by_every_form() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let forms = gpu_forms();
+    if forms.is_empty() {
+        return runner::skip_test("no wave64");
+    }
+    let mut blind = Vec::new();
+    for (flip, case) in [(Flip::Lane31, "lane reads across the halves"), (Flip::PermlaneOwnRow, "permlane16 and permlanex16"), (Flip::Lane31, "classifier-shaped reduction"), (Flip::PermlaneOwnRow, "classifier-shaped reduction")] {

This control does not depend on the forms: with taint 0, a form that matches right cannot match wrong as soon as right != wrong. So it shows that the flipped rule changes a compared word, which needs no GPU, and it is silent for a form that refuses or fails. It also uses 2 of the 4 flips (ExecIgnored and VccLow are only in tests.rs). Asserting right != wrong directly, for every flip, and reporting which forms were really checked, would say the same more honestly.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758866 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758866). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 727 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), + } +} + +pub(crate) type Form = (&'static str, fn(&Case) -> Got); + +/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native +/// ones on one with 64-lane waves. +pub(crate) fn gpu_forms() -> Vec<Form> { + let mut forms: Vec<Form> = Vec::new(); + if runner::wave32_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL split", |c| hlsl(c, true))); + } + forms.push(("direct split", |c| direct(c, true))); + forms.push(("per-lane split", |c| per_lane(c, true))); + } + if runner::wave64_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL wave64", |c| hlsl(c, false))); + } + forms.push(("direct wave64", |c| direct(c, false))); + forms.push(("per-lane wave64", |c| per_lane(c, false))); + } + forms +} + +/// A dword as an integer ordered like the float it is, for ULP distances. +fn ordered(x: u32) -> i64 { + if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) } +} + +/// The verdict of one form on one case. +#[derive(Debug, PartialEq)] +pub(crate) enum Verdict { + /// dwords compared exactly, dwords compared within their bound + Match(usize, usize), + /// first differing dword (where, reference, form) and how many differ + Mismatch(String, u32, u32, usize), + Refused(String), + Failed(String), +} + +pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict { + let words = match got { + Got::Words(w) => w, + Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()), + Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()), + }; + let (want, taint) = want; + if words.len() != want.len() { + return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len())); + } + let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0); + for k in 0..want.len() { + let (w, g, t) = (want[k], words[k], taint[k]); + let ok = if t == 0 { + exact += 1; + w == g + } else { + bounded += 1; + w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t) + }; + if !ok { + n += 1; + first.get_or_insert(k); + } + } + match first { + None => Verdict::Match(exact, bounded), + Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n), + } +} + +// ------------------------------------------------------------------------ the cases + +/// lanes_state of the tests, plus v2 = a value with both halves' patterns. +fn kernel_state(exec: u64) -> KernelState { + let mut st = KernelState::default(); + st.sgpr[126] = exec as u32; + st.sgpr[127] = (exec >> 32) as u32; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7; + r[3] = 4 * l as u32; + r[4] = ((l as f32) * 0.25 - 3.0).to_bits(); + } + st +} + +/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions. +fn kernel_case(name: &str, list: &[I], exec: u64) -> Case { + let mut l = vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32), + ]; + l.extend_from_slice(list); + l.push(end()); + Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62); + +fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I { + i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)]) +} + +/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8. +pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I { + const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)]; + f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x))); + (name, "VOP2_VOP_DPP8", f, None) +} + +pub(crate) fn kernel_cases() -> Vec<Case> { + let mut cases = vec![ + kernel_case( + "lane reads across the halves", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]), + ], + !0, + ), + kernel_case( + "lane reads and ballots under a full EXEC", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]), + lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]), + i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]), + ], + !0, + ), + kernel_case( + "a scalar written while lanes are off reaches them", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "a scalar written in a branch reaches the lanes outside it", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "permlane16 and permlanex16", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]), + ], + HOLES, + ), + kernel_case( + "DPP16 rows with BOUND_CTRL and EXEC holes", + &[ + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]), + dpp16("V_OR_B32", 6, 2, 1, 0x140, 1), + dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0), + dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1), + dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0), + dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1), + dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1), + ], + HOLES, + ), + kernel_case( + "DPP8 xor steps with EXEC holes", + &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)], + HOLES, + ), + kernel_case( + "ds_swizzle, ds_bpermute and ds_permute", + &[ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]), + i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]), + // index lane + 40: past the half, which wraps within it + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + HOLES, + ), + kernel_case( + "masks across the halves", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]), + i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]), + lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]), + ], + HOLES, + ), + kernel_case( + "carries across the halves", + &[ + lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000), + i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]), + i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]), + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]), + ], + HOLES, + ), + kernel_case( + "exact float rules", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]), + i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]), + i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]), + i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]), + i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]), + i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]), + i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]), + i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]), + i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]), + i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]), + i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]), + i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]), + i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]), + i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]), + ], + HOLES, + ), + kernel_case( + "transcendentals", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]), + ], + !0, + ), + ]; + // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into + let mut img = kernel_case( + "images", + &[ + i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]), + i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()), + i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + !0, + ); + if let Abi::Kernel(st) = &mut img.abi { + // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D + st.sgpr[0] = 0; + st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]); + st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]); + } + img.tex = vec![ + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false }, + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true }, + ]; + img.samplers = vec![TestSampler { + filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT, + address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + comparison: None, + }]; + cases.push(img); + cases +} + +const EXEC_PAIR: u64 = 126; + +/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material +/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a +/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS. +/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs. +pub(crate) fn classifier() -> Vec<u8> { + let mut l = vec![ + i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]), + i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]), + i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]), + // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]), + i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + // lanes of material 7 are off for the reductions + i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]), + ]; + // (op, identity, result SGPR, LDS atomic) + for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] { + l.extend([ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]), + dpp8_xor(op, 11, 11, 11, 1), + dpp8_xor(op, 11, 11, 11, 2), + dpp8_xor(op, 11, 11, 11, 4), + dpp16(op, 11, 11, 11, 0x140, 1), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]), + i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]), + ]); + if let Some((atomic, at)) = ds { + l.extend([ + lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]), + i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]), + ]); + } + } + l.extend([ + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]), + // five dwords a thread at s1 + 20 · thread + i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]), + end(), + ]); + asm(&l) +} + +/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in +/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in +/// row 3. +pub(crate) fn classifier_case() -> Case { + let groups = 6u32; + let mut mem = vec![0u32; groups as usize * 256 * 6]; + for g in 0..groups as usize { + for t in 0..256usize { + let lane = t % 64; + mem[g * 256 + t] = match g { + 0 => 3, + 1 => if lane < 32 { 2 } else { 5 }, + 2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6], + 3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 }, + 4 => if t == 20 { 1 } else { 6 }, + _ => if t == 50 { 9 } else { 6 }, + }; + } + } + let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 }; + Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has +/// no threads, its lanes are turned on, given the identity and read by v_readlane 32. +pub(crate) fn empty_half_case() -> Case { + let code = asm(&[ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]), + end(), + ]); + let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +pub(crate) fn cases() -> Vec<Case> { + let mut c = kernel_cases(); + c.push(classifier_case()); + c.push(empty_half_case()); + c +} + +/// Mismatches main has today, (case, form): each one is listed in the pull request that +/// added the harness. A form that starts to agree turns the test red until its line goes. +const KNOWN: &[(&str, &str)] = &[ + ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "direct split"), + ("a whole-wave section in a wave with an empty upper half", "per-lane split"), +]; + +fn print(case: &str, form: &str, v: &Verdict) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}"); +} + +#[test] +fn gpu_wave64_forms_agree_with_the_reference() { + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + let forms = gpu_forms(); + if forms.is_empty() { + return runner::skip_test("no wave64"); + } + let mut unexpected = Vec::new(); + let mut matched = 0; + for case in cases() { + let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name)); + for (form, run) in &forms { + let v = judge(&case, &want, run(&case)); + print(&case.name, form, &v); + let known = KNOWN.contains(&(case.name.as_str(), *form)); + match (&v, known) { + (Verdict::Match(..), false) => matched += 1, + (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {} + _ => unexpected.push(format!("{} / {form}: {v:?}", case.name)), + } + } + } + assert!(unexpected.is_empty(), "{} unexpected:\n{}", unexpected.len(), unexpected.join("\n")); + assert!(matched > 0, "no form translated any case"); +} + +/// The negative controls: a reference with a rule turned the wrong way must disagree with +/// every form that agrees with the right one, on the cases that use the rule. +#[test] +fn gpu_a_flipped_rule_is_seen_by_every_form() { + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + let forms = gpu_forms(); + if forms.is_empty() { + return runner::skip_test("no wave64"); + } + let mut blind = Vec::new(); + for (flip, case) in [(Flip::Lane31, "lane reads across the halves"), (Flip::PermlaneOwnRow, "permlane16 and permlanex16"), (Flip::Lane31, "classifier-shaped reduction"), (Flip::PermlaneOwnRow, "classifier-shaped reduction")] { ~~~~ --- This control does not depend on the forms: with taint 0, a form that matches `right` cannot match `wrong` as soon as `right != wrong`. So it shows that the flipped rule changes a compared word, which needs no GPU, and it is silent for a form that refuses or fails. It also uses 2 of the 4 flips (ExecIgnored and VccLow are only in tests.rs). Asserting `right != wrong` directly, for every flip, and reporting which forms were really checked, would say the same more honestly.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 282

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),
+    }
+}
+
+pub(crate) type Form = (&'static str, fn(&Case) -> Got);
+
+/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native
+/// ones on one with 64-lane waves.
+pub(crate) fn gpu_forms() -> Vec<Form> {
+    let mut forms: Vec<Form> = Vec::new();
+    if runner::wave32_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL split", |c| hlsl(c, true)));
+        }
+        forms.push(("direct split", |c| direct(c, true)));
+        forms.push(("per-lane split", |c| per_lane(c, true)));
+    }
+    if runner::wave64_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL wave64", |c| hlsl(c, false)));
+        }
+        forms.push(("direct wave64", |c| direct(c, false)));
+        forms.push(("per-lane wave64", |c| per_lane(c, false)));
+    }
+    forms
+}
+
+/// A dword as an integer ordered like the float it is, for ULP distances.
+fn ordered(x: u32) -> i64 {
+    if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) }
+}
+
+/// The verdict of one form on one case.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Verdict {
+    /// dwords compared exactly, dwords compared within their bound
+    Match(usize, usize),
+    /// first differing dword (where, reference, form) and how many differ
+    Mismatch(String, u32, u32, usize),
+    Refused(String),
+    Failed(String),
+}
+
+pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict {
+    let words = match got {
+        Got::Words(w) => w,
+        Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()),
+        Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()),
+    };
+    let (want, taint) = want;
+    if words.len() != want.len() {
+        return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len()));
+    }
+    let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0);
+    for k in 0..want.len() {
+        let (w, g, t) = (want[k], words[k], taint[k]);
+        let ok = if t == 0 {
+            exact += 1;
+            w == g
+        } else {
+            bounded += 1;
+            w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t)

The taint bound is applied the same way to every dword. After a cancellation (an approximate value minus 1.0, or a Newton step after V_RCP) a one-ULP input error is many ULPs at the output, which gives false mismatches; and an integer dword downstream (V_RCP then V_CVT_U32_F32) accepts 2 for 1. Also V_SIN_F32(0.5) is about 1.2e-16 in the reference and -8.7e-8 on the GPU: opposite signs, far apart in ULPs, while D3D allows an absolute error of 0.0008 for sincos. And NaNs without taint are compared bit for bit, but their bits come from the host FPU. Could tolerant checks be limited to direct float outputs with the D3D bounds (relative for rcp/rsq, absolute for sin/cos/log)?

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758879 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758879). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 282 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), + } +} + +pub(crate) type Form = (&'static str, fn(&Case) -> Got); + +/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native +/// ones on one with 64-lane waves. +pub(crate) fn gpu_forms() -> Vec<Form> { + let mut forms: Vec<Form> = Vec::new(); + if runner::wave32_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL split", |c| hlsl(c, true))); + } + forms.push(("direct split", |c| direct(c, true))); + forms.push(("per-lane split", |c| per_lane(c, true))); + } + if runner::wave64_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL wave64", |c| hlsl(c, false))); + } + forms.push(("direct wave64", |c| direct(c, false))); + forms.push(("per-lane wave64", |c| per_lane(c, false))); + } + forms +} + +/// A dword as an integer ordered like the float it is, for ULP distances. +fn ordered(x: u32) -> i64 { + if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) } +} + +/// The verdict of one form on one case. +#[derive(Debug, PartialEq)] +pub(crate) enum Verdict { + /// dwords compared exactly, dwords compared within their bound + Match(usize, usize), + /// first differing dword (where, reference, form) and how many differ + Mismatch(String, u32, u32, usize), + Refused(String), + Failed(String), +} + +pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict { + let words = match got { + Got::Words(w) => w, + Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()), + Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()), + }; + let (want, taint) = want; + if words.len() != want.len() { + return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len())); + } + let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0); + for k in 0..want.len() { + let (w, g, t) = (want[k], words[k], taint[k]); + let ok = if t == 0 { + exact += 1; + w == g + } else { + bounded += 1; + w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t) ~~~~ --- The taint bound is applied the same way to every dword. After a cancellation (an approximate value minus 1.0, or a Newton step after V_RCP) a one-ULP input error is many ULPs at the output, which gives false mismatches; and an integer dword downstream (V_RCP then V_CVT_U32_F32) accepts 2 for 1. Also V_SIN_F32(0.5) is about 1.2e-16 in the reference and -8.7e-8 on the GPU: opposite signs, far apart in ULPs, while D3D allows an absolute error of 0.0008 for sincos. And NaNs without taint are compared bit for bit, but their bits come from the host FPU. Could tolerant checks be limited to direct float outputs with the D3D bounds (relative for rcp/rsq, absolute for sin/cos/log)?
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 44

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));

The compared registers are the static destinations. V_MOVRELD_B32 v5 with M0 = 10 writes v15 (lanes.rs:96-108); if nothing else writes v15, a form that leaves it alone passes. VCC, EXEC and SCC are also only seen indirectly. Copying such results to a fixed output in the case would close it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758889 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758889). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 44 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); ~~~~ --- The compared registers are the static destinations. V_MOVRELD_B32 v5 with M0 = 10 writes v15 (lanes.rs:96-108); if nothing else writes v15, a form that leaves it alone passes. VCC, EXEC and SCC are also only seen indirectly. Copying such results to a fixed output in the case would close it.
CharlyRien commented 2026-12-02 20:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T20:43:06Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 58

@@ -0,0 +1,550 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, masks read as data, and (compute) LDS across two waves at a barrier. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines. Integers only, and floats that stay small integers, so every
+//! comparison is exact.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, lowering_on_the_cpu, reference, Abi, Case, Form, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[t ^ k], k below 32 (compute only, at the top)

LDS[t ^ k] with k below 32 never leaves the lane's own 32-lane half, nor its wave, so this block does not test "LDS across two waves" as the description says (the unit test at tests.rs:442 does). DPP, ds_swizzle and permlane are also only generated with every lane on, and the float values are small and exact: no NaN, inf, denormal or -0 reaches a form, and they are too small to tell a fused FMA from an unfused one.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775758900 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4775758900). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T20:43:06Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 58 ~~~~diff @@ -0,0 +1,550 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, masks read as data, and (compute) LDS across two waves at a barrier. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. Integers only, and floats that stay small integers, so every +//! comparison is exact. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, lowering_on_the_cpu, reference, Abi, Case, Form, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[t ^ k], k below 32 (compute only, at the top) ~~~~ --- LDS[t ^ k] with k below 32 never leaves the lane's own 32-lane half, nor its wave, so this block does not test "LDS across two waves" as the description says (the unit test at tests.rs:442 does). DPP, ds_swizzle and permlane are also only generated with every lane on, and the float values are small and exact: no NaN, inf, denormal or -0 reaches a form, and they are too small to tell a fused FMA from an unfused one.
Foniass commented 2026-12-02 20:47:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T20:47:21Z.


Review of d2293dcb (code reading only, not a merge-check; Build and test (Windows, no GPU) red, PR description red) · 2 high, 1 medium

In short: The PR adds a test-only CPU interpreter of RDNA2 wave64 code (gpu::rdna2_ref), a harness that compares every wave64 form with it, and a fuzzer. It is 4,414 hand-written lines, none of them generated or test data. The runtime is untouched apart from a test-module split in recomp/lower.rs. What blocks it is the size, plus known-mismatch lists that can turn the suite red on other GPUs.

High

  1. Too large to review as one PR; please split it into a stack. 4,414 lines is more than five times the ~800 lines at which CONTRIBUTING.md asks for a split. The description argues the interpreter is only shown right by the harness, but each commit already builds on its own, so a stack (Stacked on #N) works. The commits give a natural split:

    • the core, SALU and asm.rs, with the llvm-mc decoder check as its own part;
    • integer VALU and lanes (valu.rs, lanes.rs);
    • memory, LDS and groups of waves (mem.rs);
    • f32 and images (float.rs, image.rs);
    • the harness, with the run_insts split in recomp/lower.rs (forms.rs);
    • the fuzzer (fuzz.rs).

    Each commit is 550-930 lines, so the larger ones need halving again to get near ~400.

  2. The known-mismatch lists come from one NVIDIA card but fail elsewhere when a mismatch is absent.

    • KNOWN (forms.rs ~675) and KNOWN_SEEDS (fuzz.rs ~466) are keyed only by case or seed and form.
    • A listed mismatch that does not show up turns the test red (forms.rs ~707; "known to differ, now ..." in fuzz.rs ~505).
    • On a GPU with 64-lane waves, gpu_forms() (forms.rs ~229) also runs the native wave64 forms, which the description says have never run. The v_sub_f32 -0 case has no known cause, so it may be specific to NVIDIA.
    • On another vendor, including the maintainer's AMD batch GPU, the suite can go red without a regression.

    Fix: key the known entries by the adapter or wave size they were seen on, or report a known mismatch that went away instead of failing.

Medium

  1. Two CPU tests take about a minute each on every suite run.

    • an_instruction_outside_the_model_stops_the_run (tests.rs ~107) loops on S_BRANCH -1 up to the full STEPS = 4_000_000 (mod.rs ~345).
    • modelled_instructions_decode_as_llvm_disassembles_them builds modelled_words() (~112) before it checks for llvm-mc (~146-155), then only logs SKIPPED ...: no llvm-mc.
    • The PR's own CI log shows both "running for over 60 seconds".

    Fix: pass a small step limit for the endless branch, and look for llvm-mc before building the words.

Checked and fine
  • Outside rdna2_ref/, the only changes are the #[cfg(test)] module line in gpu/mod.rs and the run_insts split out of run_mem in the test module of recomp/lower.rs. run_mem still panics on a refusal, so the runtime path is untouched.
  • GPU tests call runner::skip_test when there is no adapter or no wave64 form. The pack census reads XCL_SAMPLE_RPF and is #[ignore].
  • Not a duplicate: #3562 is the wave64 fold in the translator, not a reference interpreter.
  • The red Build and test check fails in tests/frame_clock.rs, which this diff does not touch. Every rdna2_ref test passed or was skipped in that job.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7358317488 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7358317488). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T20:47:21Z. --- **Review** of `d2293dcb` (code reading only, not a merge-check; `Build and test (Windows, no GPU)` red, `PR description` red) · 2 high, 1 medium **In short:** The PR adds a test-only CPU interpreter of RDNA2 wave64 code (`gpu::rdna2_ref`), a harness that compares every wave64 form with it, and a fuzzer. It is 4,414 hand-written lines, none of them generated or test data. The runtime is untouched apart from a test-module split in `recomp/lower.rs`. What blocks it is the size, plus known-mismatch lists that can turn the suite red on other GPUs. #### High 1. **Too large to review as one PR; please split it into a stack.** 4,414 lines is more than five times the ~800 lines at which CONTRIBUTING.md asks for a split. The description argues the interpreter is only shown right by the harness, but each commit already builds on its own, so a stack (`Stacked on #N`) works. The commits give a natural split: - the core, SALU and `asm.rs`, with the llvm-mc decoder check as its own part; - integer VALU and lanes (`valu.rs`, `lanes.rs`); - memory, LDS and groups of waves (`mem.rs`); - f32 and images (`float.rs`, `image.rs`); - the harness, with the `run_insts` split in `recomp/lower.rs` (`forms.rs`); - the fuzzer (`fuzz.rs`). Each commit is 550-930 lines, so the larger ones need halving again to get near ~400. 2. **The known-mismatch lists come from one NVIDIA card but fail elsewhere when a mismatch is absent.** - `KNOWN` (`forms.rs` ~675) and `KNOWN_SEEDS` (`fuzz.rs` ~466) are keyed only by case or seed and form. - A listed mismatch that does not show up turns the test red (`forms.rs` ~707; "known to differ, now ..." in `fuzz.rs` ~505). - On a GPU with 64-lane waves, `gpu_forms()` (`forms.rs` ~229) also runs the native wave64 forms, which the description says have never run. The `v_sub_f32` -0 case has no known cause, so it may be specific to NVIDIA. - On another vendor, including the maintainer's AMD batch GPU, the suite can go red without a regression. Fix: key the known entries by the adapter or wave size they were seen on, or report a known mismatch that went away instead of failing. #### Medium 3. **Two CPU tests take about a minute each on every suite run.** - `an_instruction_outside_the_model_stops_the_run` (`tests.rs` ~107) loops on `S_BRANCH -1` up to the full `STEPS = 4_000_000` (`mod.rs` ~345). - `modelled_instructions_decode_as_llvm_disassembles_them` builds `modelled_words()` (~112) before it checks for llvm-mc (~146-155), then only logs `SKIPPED ...: no llvm-mc`. - The PR's own CI log shows both "running for over 60 seconds". Fix: pass a small step limit for the endless branch, and look for llvm-mc before building the words. <details><summary>Checked and fine</summary> - Outside `rdna2_ref/`, the only changes are the `#[cfg(test)]` module line in `gpu/mod.rs` and the `run_insts` split out of `run_mem` in the test module of `recomp/lower.rs`. `run_mem` still panics on a refusal, so the runtime path is untouched. - GPU tests call `runner::skip_test` when there is no adapter or no wave64 form. The pack census reads `XCL_SAMPLE_RPF` and is `#[ignore]`. - Not a duplicate: #3562 is the wave64 fold in the translator, not a reference interpreter. - The red `Build and test` check fails in `tests/frame_clock.rs`, which this diff does not touch. Every `rdna2_ref` test passed or was skipped in that job. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
CharlyRien commented 2026-12-02 21:08:22 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T21:08:22Z.


Follow-up: a longer fuzz run on a 32-lane GPU.

Stack: RTX 3090 (driver 616.56), Ryzen 9 5950X, Windows 11 22631, rustc 1.100.0, debug, PR head 9ceea007 with no local change.
Command: XCL_FUZZ_WAVE64_SEEDS=2000 cargo test -p xcl --lib rdna2_ref -- --nocapture
Result: 24 passed, 4 failed (gpu_fuzz_wave64_0 to _3), 1 ignored, 1687 s. The 8,000 seeds give 468 mismatches that are not in KNOWN_SEEDS, on 323 seeds. None of them is in the first 25 seeds of a base, so a 100-seed run cannot see them.

I sorted them from the shrunk programs. I found no case where the reference is wrong. One small group is a harness issue.

# group seeds HLSL split direct split per-lane split cause
1 whole-wave section in the 2nd wave of a 96-thread group 128 124 128 14 your mismatch 2 (known)
2 -0 instead of +0 94 94 0 0 your mismatch 3: DXC fast-math (found)
3 s_mul_i32 emitted as a signed multiply 15 15 0 0 mul nsw in the DXIL (new)
4 per-lane: whole-wave section after an if/else or a loop 19 0 0 19 same root as your mismatch 4
5 direct split, kernel, one half of EXEC empty at the start 58 0 58 0 not found (new)
6 direct split, compute, nested if/else with sections 11 0 11 0 probably the same as 5
7 fma(+0, -4, +0) gives -0 1 1 1 1 FMad; the driver may drop + 0
8 NaN bits, 0xFFC00000 / 0x7FFFFFFF 1 1 1 0 harness

1. All 128 are compute programs with 96 threads. The first wrong dword is always in threads 64-95. This is the hand-written case already in KNOWN. It shows up in about 6% of the seeds, so any larger XCL_FUZZ_WAVE64_SEEDS will fail until it is fixed, or known as a class rather than by seed.

2. The cause of mismatch 3 is DXC's default fast-math. Seed 833, shrunk: v13 = v16 - v15, where v16 = (16·tid + K) & 7 is always 0. DXC compiles it to fsub fast float -0.000000e+00, %v15, that is -v15, so -0 when v15 is +0. With -Gis it stays fsub float 0.000000e+00, %v15. DXC needs to see a 0 - x or (x - y) - x shape, which is why the hand-written subtraction gives +0. Smallest seed: 1242 (kernel), v13 = v15 + v16; v13 = v15 - v13 with v16 = +0.

3. New. recomp/emit.rs:1703 emits s_mul_i32 as (uint)((int)a * (int)b). DXC turns it into mul nsw i32, so a product that wraps is poison. Seed 2001922: s8 = s0 * 0x2F5E5358 with s0 = 0x40000000 wraps to 0, and s_flbit_i32_b32 s5, s8 should give -1. DXC replaces the s8 == 0 test with s0 == 0, and the form gives 32. With an unsigned s0 * 0x2F5E5358u the DXIL keeps the test on the product. The other seeds are s_max_i32, s_cmp_gt_i32 or s_cmp_lg_u32 on wrapped products (wrong SCC). A plain a * b on uint gives the same low 32 bits. v_mul_i32_i24 (emit.rs:4077) has the same shape; the fuzzer does not generate it.

4. Same root as mismatch 4, but a plain if/else is enough: s_or_saveexec_b64 turns on only the running lane's bit (recomp/lower.rs:681-690). Seed 3000238: lane 0 takes the else side, so it never runs the section in the then side, and v8 of lane 0 keeps 1 instead of the identity 0. 7 of the 19 seeds use a loop instead.

5. New, direct split only. All 58 programs start with one half of EXEC empty (0x3FFFFFFF, 0x7, 0xFFFFFFFF00000000, …). Only half of the kernel programs do (3,004 of 6,026), so this is not chance. HLSL split and per-lane split agree with the reference on these seeds. I did not find the cause. Smallest, seed 2000282 (EXEC = 0x3FFFFFFF): in the else side's section, lane 0 gets the identity, as if bit 0 of the saved EXEC (s46) were 0. v17 of lane 0: reference 0x9B3E8BCD (its v4), direct split 0xFFFFFFFF.

("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], Some(1073741823)),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], Some(0)),
("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 40), ("SRC0", 263), ("SRC1", 263)], None),
("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 42), ("SSRC0", 40)], None),
("S_CBRANCH_EXECZ", "ENC_SOPP", &[("TO", 6)], None),
("V_BFE_I32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 262), ("SRC1", 258), ("SRC2", 259)], None),
("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 42), ("SSRC1", 40)], None),
("S_CBRANCH_EXECZ", "ENC_SOPP", &[("TO", 12)], None),
("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 46), ("SSRC0", 193)], None),
("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", 193), ("SRC1", 260), ("SRC2", 46)], None),
("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", 273), ("SRC1", 128)], None),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 46)], None),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 42)], None),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", 4)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 27), ("SRC0", 5)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 28), ("SRC0", 6)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 29), ("SRC0", 7)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 30), ("SRC0", 8)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 9)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 32), ("SRC0", 10)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 33), ("SRC0", 11)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 34), ("SRC0", 12)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 35), ("SRC0", 13)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 36), ("SRC0", 14)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 37), ("SRC0", 15)], None),
("S_ENDPGM", "ENC_SOPP", &[], None),

My guess is the per-half branches or the lazy mask exchange (the local vote in dxil/idioms.rs, skip_is_local in dxil/mask_exchange.rs). A run of this seed with XCL_WAVE64_IDIOMS=0 would tell them apart. I have not run it.

6. Compute programs with nested if/else and sections; the first wrong dword is mostly in thread 0. Smallest: seed 1000823. I think a half with no lane in EXEC at a branch is the trigger here too, but I did not check it.

7. Seed 1501: fma(+0, -4, +0) is +0 in IEEE and in the reference. All three forms give -0. They emit FMad, and DisableMathRefactoring is dropped when FMad is used (dxil/prelude.rs:849-858), so the driver may drop the + 0. Not checked further.

8. Seed 1000650: a loop squares v16 until it is infinite, then computes inf - inf. The reference gives 0xFFC00000 (the x86 default NaN, which is also the NaN in AMD's ISA examples); the GPU gives 0x7FFFFFFF. D3D does not fix the bits of a NaN. The generator says floats stay small integers (fuzz.rs:5-6), but a loop of v_mul_f32 overflows, and judge takes two NaNs as equal only for tainted words (forms.rs:277-282). Taking any two NaNs as equal would fix it.

Also seen: two seeds of group 2 shrank into a group 1 program (2001255, 1000761), because the shrinker accepts any mismatch (fuzz.rs:402-404).

Not tested: AMD and the native wave64 forms; the rebased head d2293dcb; the exact causes of groups 5, 6 and 7.

AI use: Claude Code (Claude Opus 5.5) ran the fuzz and sorted the mismatches; checked and posted by me.

<!-- greyfinch-sync:ivall/xcl:comment:7358845851 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7358845851). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T21:08:22Z. --- Follow-up: a longer fuzz run on a 32-lane GPU. Stack: RTX 3090 (driver 616.56), Ryzen 9 5950X, Windows 11 22631, rustc 1.100.0, debug, PR head 9ceea007 with no local change. Command: `XCL_FUZZ_WAVE64_SEEDS=2000 cargo test -p xcl --lib rdna2_ref -- --nocapture` Result: 24 passed, 4 failed (`gpu_fuzz_wave64_0` to `_3`), 1 ignored, 1687 s. The 8,000 seeds give 468 mismatches that are not in `KNOWN_SEEDS`, on 323 seeds. None of them is in the first 25 seeds of a base, so a 100-seed run cannot see them. I sorted them from the shrunk programs. I found no case where the reference is wrong. One small group is a harness issue. | # | group | seeds | HLSL split | direct split | per-lane split | cause | |---|---|---|---|---|---|---| | 1 | whole-wave section in the 2nd wave of a 96-thread group | 128 | 124 | 128 | 14 | your mismatch 2 (known) | | 2 | -0 instead of +0 | 94 | 94 | 0 | 0 | your mismatch 3: DXC fast-math (found) | | 3 | `s_mul_i32` emitted as a signed multiply | 15 | 15 | 0 | 0 | `mul nsw` in the DXIL (new) | | 4 | per-lane: whole-wave section after an if/else or a loop | 19 | 0 | 0 | 19 | same root as your mismatch 4 | | 5 | direct split, kernel, one half of EXEC empty at the start | 58 | 0 | 58 | 0 | not found (new) | | 6 | direct split, compute, nested if/else with sections | 11 | 0 | 11 | 0 | probably the same as 5 | | 7 | `fma(+0, -4, +0)` gives -0 | 1 | 1 | 1 | 1 | FMad; the driver may drop `+ 0` | | 8 | NaN bits, 0xFFC00000 / 0x7FFFFFFF | 1 | 1 | 1 | 0 | harness | **1.** All 128 are compute programs with 96 threads. The first wrong dword is always in threads 64-95. This is the hand-written case already in `KNOWN`. It shows up in about 6% of the seeds, so any larger `XCL_FUZZ_WAVE64_SEEDS` will fail until it is fixed, or known as a class rather than by seed. **2.** The cause of mismatch 3 is DXC's default fast-math. Seed 833, shrunk: `v13 = v16 - v15`, where v16 = (16·tid + K) & 7 is always 0. DXC compiles it to `fsub fast float -0.000000e+00, %v15`, that is `-v15`, so -0 when v15 is +0. With `-Gis` it stays `fsub float 0.000000e+00, %v15`. DXC needs to see a `0 - x` or `(x - y) - x` shape, which is why the hand-written subtraction gives +0. Smallest seed: 1242 (kernel), `v13 = v15 + v16; v13 = v15 - v13` with v16 = +0. **3.** New. `recomp/emit.rs:1703` emits `s_mul_i32` as `(uint)((int)a * (int)b)`. DXC turns it into `mul nsw i32`, so a product that wraps is poison. Seed 2001922: s8 = s0 * 0x2F5E5358 with s0 = 0x40000000 wraps to 0, and `s_flbit_i32_b32 s5, s8` should give -1. DXC replaces the `s8 == 0` test with `s0 == 0`, and the form gives 32. With an unsigned `s0 * 0x2F5E5358u` the DXIL keeps the test on the product. The other seeds are `s_max_i32`, `s_cmp_gt_i32` or `s_cmp_lg_u32` on wrapped products (wrong SCC). A plain `a * b` on uint gives the same low 32 bits. `v_mul_i32_i24` (emit.rs:4077) has the same shape; the fuzzer does not generate it. **4.** Same root as mismatch 4, but a plain if/else is enough: `s_or_saveexec_b64` turns on only the running lane's bit (recomp/lower.rs:681-690). Seed 3000238: lane 0 takes the else side, so it never runs the section in the then side, and v8 of lane 0 keeps 1 instead of the identity 0. 7 of the 19 seeds use a loop instead. **5.** New, direct split only. All 58 programs start with one half of EXEC empty (0x3FFFFFFF, 0x7, 0xFFFFFFFF00000000, …). Only half of the kernel programs do (3,004 of 6,026), so this is not chance. HLSL split and per-lane split agree with the reference on these seeds. I did not find the cause. Smallest, seed 2000282 (EXEC = 0x3FFFFFFF): in the else side's section, lane 0 gets the identity, as if bit 0 of the saved EXEC (s46) were 0. v17 of lane 0: reference 0x9B3E8BCD (its v4), direct split 0xFFFFFFFF. ```rust ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], Some(1073741823)), ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], Some(0)), ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 40), ("SRC0", 263), ("SRC1", 263)], None), ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 42), ("SSRC0", 40)], None), ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("TO", 6)], None), ("V_BFE_I32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 262), ("SRC1", 258), ("SRC2", 259)], None), ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 42), ("SSRC1", 40)], None), ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("TO", 12)], None), ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 46), ("SSRC0", 193)], None), ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", 193), ("SRC1", 260), ("SRC2", 46)], None), ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", 273), ("SRC1", 128)], None), ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 46)], None), ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 42)], None), ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", 4)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 27), ("SRC0", 5)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 28), ("SRC0", 6)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 29), ("SRC0", 7)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 30), ("SRC0", 8)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 9)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 32), ("SRC0", 10)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 33), ("SRC0", 11)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 34), ("SRC0", 12)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 35), ("SRC0", 13)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 36), ("SRC0", 14)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 37), ("SRC0", 15)], None), ("S_ENDPGM", "ENC_SOPP", &[], None), ``` My guess is the per-half branches or the lazy mask exchange (the local vote in dxil/idioms.rs, `skip_is_local` in dxil/mask_exchange.rs). A run of this seed with `XCL_WAVE64_IDIOMS=0` would tell them apart. I have not run it. **6.** Compute programs with nested if/else and sections; the first wrong dword is mostly in thread 0. Smallest: seed 1000823. I think a half with no lane in EXEC at a branch is the trigger here too, but I did not check it. **7.** Seed 1501: `fma(+0, -4, +0)` is +0 in IEEE and in the reference. All three forms give -0. They emit FMad, and `DisableMathRefactoring` is dropped when FMad is used (dxil/prelude.rs:849-858), so the driver may drop the `+ 0`. Not checked further. **8.** Seed 1000650: a loop squares v16 until it is infinite, then computes inf - inf. The reference gives 0xFFC00000 (the x86 default NaN, which is also the NaN in AMD's ISA examples); the GPU gives 0x7FFFFFFF. D3D does not fix the bits of a NaN. The generator says floats stay small integers (fuzz.rs:5-6), but a loop of `v_mul_f32` overflows, and `judge` takes two NaNs as equal only for tainted words (forms.rs:277-282). Taking any two NaNs as equal would fix it. Also seen: two seeds of group 2 shrank into a group 1 program (2001255, 1000761), because the shrinker accepts any mismatch (fuzz.rs:402-404). Not tested: AMD and the native wave64 forms; the rebased head d2293dcb; the exact causes of groups 5, 6 and 7. AI use: Claude Code (Claude Opus 5.5) ran the fuzz and sorted the mismatches; checked and posted by me.
Royalflamejlh commented 2026-12-02 22:01:23 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:23Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/salu.rs; line 299

@@ -0,0 +1,328 @@
+//! Scalar ALU and program control (ISA chapters 4 and 5): SOPP, SOPK, SOP1, SOP2, SOPC.
+
+use super::{fault, field, unsupported, Ctx, Program, State, Stop, Wave};
+use crate::gpu::rdna2::{self, Decoded};
+
+pub(super) fn sopp(w: &mut Wave, d: &Decoded, p: &Program, cx: &mut Ctx) -> Result<(), Stop> {
+    let simm = field(d, "SIMM16") as u32;
+    let taken = match d.inst.name {
+        "S_NOP" | "S_WAITCNT" | "S_WAITCNT_DEPCTR" | "S_INST_PREFETCH" | "S_SETPRIO" | "S_CLAUSE" | "S_SLEEP" | "S_ICACHE_INV" | "S_TTRACEDATA" | "S_TTRACEDATA_IMM" => false,
+        "S_ENDPGM" => {
+            w.state = State::Done;
+            return Ok(());
+        }
+        "S_BARRIER" => {
+            w.state = State::Barrier;
+            return Ok(());
+        }
+        // MODE: FP_ROUND [3:0], FP_DENORM [7:4]
+        "S_ROUND_MODE" => {
+            w.mode = w.mode & !0xF | simm & 0xF;
+            false
+        }
+        "S_DENORM_MODE" => {
+            w.mode = w.mode & !0xF0 | (simm & 0xF) << 4;
+            false
+        }
+        "S_BRANCH" => true,
+        "S_CBRANCH_SCC0" => !w.scc,
+        "S_CBRANCH_SCC1" => w.scc,
+        "S_CBRANCH_VCCZ" => w.vcc(cx.flip) == 0,
+        "S_CBRANCH_VCCNZ" => w.vcc(cx.flip) != 0,
+        "S_CBRANCH_EXECZ" => w.exec() == 0,
+        "S_CBRANCH_EXECNZ" => w.exec() != 0,
+        _ => return Err(unsupported(d)),
+    };
+    if taken {
+        let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no branch target"))?;
+        w.jump_to(d, p, t)?;
+    }
+    Ok(())
+}
+
+fn bits(x: u32, off: u32, width: u32) -> u32 {
+    if width == 0 { 0 } else { (x >> (off & 31)) & (((1u64 << width.min(32)) - 1) as u32) }
+}
+
+/// The MODE bits `simm16` (hwreg id, offset, size) names: MODE is the only register modelled
+/// (None: FLAT_SCR_LO / HI, which only scratch access reads, and that is not modelled).
+fn hwreg(d: &Decoded, simm: u32) -> Result<Option<u32>, Stop> {
+    let (id, off, size) = (simm & 63, simm >> 6 & 31, (simm >> 11 & 31) + 1);
+    match id {
+        1 => Ok(Some((((1u64 << size) - 1) as u32) << off)),
+        20 | 21 => Ok(None),
+        _ => Err(unsupported(d)),
+    }
+}
+
+pub(super) fn run(w: &mut Wave, d: &Decoded, p: &Program) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let f = |n: &str| field(d, n);
+    let wide = w.lanes == 64;
+    if d.enc.name == "ENC_SOPK" {
+        let simm = f("SIMM16") as u16;
+        let (k, ku) = (simm as i16 as i32, u32::from(simm));
+        let dst = f("SDST");
+        let cur = w.scalar(d, dst).unwrap_or(0);
+        match name {
+            "S_MOVK_I32" => w.set_s(d, dst, k as u32)?,
+            "S_CMOVK_I32" if w.scc => w.set_s(d, dst, k as u32)?,
+            "S_CMOVK_I32" => {}
+            "S_ADDK_I32" => {
+                let (r, o) = (cur as i32).overflowing_add(k);
+                w.set_s(d, dst, r as u32)?;
+                w.scc = o;
+            }
+            "S_MULK_I32" => w.set_s(d, dst, (cur as i32).wrapping_mul(k) as u32)?,
+            "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_EXPCNT" | "S_WAITCNT_LGKMCNT" => {}
+            "S_SETREG_IMM32_B32" | "S_SETREG_B32" => {
+                let Some(m) = hwreg(d, ku)? else { return Ok(()) };
+                let x = if name == "S_SETREG_B32" { cur } else { d.literal.ok_or_else(|| fault(d, "no literal"))? };
+                w.mode = w.mode & !m | (x << (ku >> 6 & 31)) & m;
+            }
+            "S_GETREG_B32" => {
+                let m = hwreg(d, ku)?.ok_or_else(|| unsupported(d))?;
+                w.set_s(d, dst, (w.mode & m) >> (ku >> 6 & 31))?;
+            }
+            "S_CALL_B64" => {
+                w.set_pair(dst as usize, d.pc + 4);
+                let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no call target"))?;
+                w.jump_to(d, p, t)?;
+            }
+            _ if name.starts_with("S_CMPK_") => {
+                let signed = name.ends_with("_I32");
+                let (a, b) = if signed { (i64::from(cur as i32), i64::from(k)) } else { (i64::from(cur), i64::from(ku)) };
+                w.scc = compare(d, &name[7..9], a, b)?;
+            }
+            _ => return Err(unsupported(d)),
+        }
+        return Ok(());
+    }
+    if d.enc.name == "ENC_SOPC" {
+        let (c0, c1) = (f("SSRC0"), f("SSRC1"));
+        w.scc = match name {
+            "S_BITCMP0_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 0,
+            "S_BITCMP1_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 1,
+            "S_BITCMP0_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 0,
+            "S_BITCMP1_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 1,
+            "S_CMP_EQ_U64" => w.scalar64(d, c0, false)? == w.scalar64(d, c1, false)?,
+            "S_CMP_LG_U64" => w.scalar64(d, c0, false)? != w.scalar64(d, c1, false)?,
+            _ if name.starts_with("S_CMP_") => {
+                let (a, b) = (w.scalar(d, c0)?, w.scalar(d, c1)?);
+                let (a, b) = if name.ends_with("_I32") { (i64::from(a as i32), i64::from(b as i32)) } else { (i64::from(a), i64::from(b)) };
+                compare(d, &name[6..8], a, b)?
+            }
+            _ => return Err(unsupported(d)),
+        };
+        return Ok(());
+    }
+    let dst = f("SDST");
+    let (c0, c1) = (f("SSRC0"), if d.enc.name == "ENC_SOP2" { f("SSRC1") } else { 0 });
+    let s32 = |w: &Wave, c| w.scalar(d, c);
+    let s64 = |w: &Wave, c| w.scalar64(d, c, false);
+    // exec-mask families: D = EXEC, EXEC = S0 op EXEC (WREXEC: D = the new EXEC), SCC = EXEC != 0
+    if name.contains("SAVEEXEC") || name.contains("WREXEC") {
+        let b64 = name.ends_with("_B64");
+        if b64 != wide {
+            return Err(fault(d, "a mask instruction of the other wave size"));
+        }
+        let (s, e) = (if b64 { s64(w, c0)? } else { u64::from(s32(w, c0)?) }, w.exec());
+        let op = name.trim_start_matches("S_").split("_SAVEEXEC").next().unwrap().split("_WREXEC").next().unwrap();
+        let mut new = match op {
+            "AND" => s & e,
+            "OR" => s | e,
+            "XOR" => s ^ e,
+            "ANDN2" => s & !e,
+            "ORN2" => s | !e,
+            "NAND" => !(s & e),
+            "NOR" => !(s | e),
+            "XNOR" => !(s ^ e),
+            "ANDN1" => !s & e,
+            "ORN1" => !s | e,
+            _ => return Err(unsupported(d)),
+        };
+        if !wide {
+            new &= 0xFFFF_FFFF;
+        }
+        let saved = if name.contains("WREXEC") { new } else { e };
+        if b64 { w.set_pair(dst as usize, saved) } else { w.set_s(d, dst, saved as u32)? }
+        w.set_mask(126, new);
+        w.scc = new != 0;
+        return Ok(());
+    }
+    let b64 = matches!(name.rsplit('_').next(), Some("B64" | "I64" | "U64")) && !name.contains("_I32_");
+    if b64 {
+        let (a, b) = (s64(w, c0)?, s64(w, c1).unwrap_or(0));
+        let sh = s32(w, c1).unwrap_or(0) & 63;
+        let (r, scc) = match name {
+            "S_MOV_B64" => (a, None),
+            "S_CMOV_B64" => (if w.scc { a } else { s64(w, dst)? }, None),
+            "S_NOT_B64" => (!a, Some(!a != 0)),
+            "S_WQM_B64" => {
+                let r = (0..16).fold(0u64, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m });
+                (r, Some(r != 0))
+            }
+            "S_BREV_B64" => (a.reverse_bits(), None),
+            "S_QUADMASK_B64" => {
+                let r = (0..16).fold(0u64, |m, q| m | u64::from(a >> (4 * q) & 15 != 0) << q);
+                (r, Some(r != 0))
+            }
+            "S_BITREPLICATE_B64_B32" => ((0..32).fold(0u64, |m, i| m | (a >> i & 1) * 3 << (2 * i)), None),
+            "S_GETPC_B64" => (d.pc + 4, None),
+            "S_SETPC_B64" => return w.jump_to(d, p, a),
+            "S_SWAPPC_B64" => {
+                w.set_pair(dst as usize, d.pc + 4);
+                return w.jump_to(d, p, a);
+            }
+            "S_AND_B64" => (a & b, Some(a & b != 0)),
+            "S_OR_B64" => (a | b, Some(a | b != 0)),
+            "S_XOR_B64" => (a ^ b, Some(a ^ b != 0)),
+            "S_ANDN2_B64" => (a & !b, Some(a & !b != 0)),
+            "S_ORN2_B64" => (a | !b, Some(a | !b != 0)),
+            "S_NAND_B64" => (!(a & b), Some(!(a & b) != 0)),
+            "S_NOR_B64" => (!(a | b), Some(!(a | b) != 0)),
+            "S_XNOR_B64" => (!(a ^ b), Some(!(a ^ b) != 0)),
+            "S_CSELECT_B64" => (if w.scc { a } else { b }, None),
+            "S_LSHL_B64" => (a << sh, Some(a << sh != 0)),
+            "S_LSHR_B64" => (a >> sh, Some(a >> sh != 0)),
+            "S_ASHR_I64" => (((a as i64) >> sh) as u64, Some((a as i64) >> sh != 0)),
+            "S_BFM_B64" => {
+                let (n, o) = (s32(w, c0)? & 63, s32(w, c1)? & 63);
+                ((if n == 0 { 0 } else { u64::MAX >> (64 - n) }) << o, None)
+            }
+            "S_BFE_U64" | "S_BFE_I64" => {
+                let x = s32(w, c1)?;
+                let (o, n) = (x & 63, (x >> 16) & 127);
+                let n = n.min(64);
+                let x = if name == "S_BFE_I64" { ((a as i64) >> o) as u64 } else { a >> o };
+                let mut r = if n == 0 { 0 } else { x & (u64::MAX >> (64 - n)) };
+                if name == "S_BFE_I64" && n > 0 && n < 64 && r >> (n - 1) & 1 == 1 {
+                    r |= u64::MAX << n;
+                }
+                (r, Some(r != 0))
+            }
+            "S_BITSET0_B64" | "S_BITSET1_B64" => {
+                let bit = s32(w, c0)? & 63;
+                let cur = w.pair(dst as usize);
+                (if name.contains("SET1") { cur | 1 << bit } else { cur & !(1 << bit) }, None)
+            }
+            "S_MOVRELS_B64" => (w.pair((c0 as usize + w.s[124] as usize).min(126)), None),
+            _ => return Err(unsupported(d)),
+        };
+        if name == "S_MOVRELD_B64" {
+            return Err(unsupported(d));
+        }
+        w.set_pair(dst as usize, r);
+        if let Some(c) = scc {
+            w.scc = c;
+        }
+        return Ok(());
+    }
+    let a = s32(w, c0)?;
+    let b = if d.enc.name == "ENC_SOP2" { s32(w, c1)? } else { 0 };
+    let (sa, sb) = (a as i32, b as i32);
+    let src64 = || s64(w, c0);
+    let nz = |r: u32| (r, Some(r != 0));
+    let (r, scc): (u32, Option<bool>) = match name {
+        "S_MOV_B32" => (a, None),
+        "S_CMOV_B32" => (if w.scc { a } else { s32(w, dst)? }, None),
+        "S_NOT_B32" => nz(!a),
+        "S_WQM_B32" => nz((0..8).fold(0u32, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m })),
+        "S_BREV_B32" => (a.reverse_bits(), None),
+        "S_BCNT0_I32_B32" => nz(a.count_zeros()),
+        "S_BCNT0_I32_B64" => nz(src64()?.count_zeros()),
+        "S_BCNT1_I32_B32" => nz(a.count_ones()),
+        "S_BCNT1_I32_B64" => nz(src64()?.count_ones()),
+        "S_FF0_I32_B32" => (if a == u32::MAX { u32::MAX } else { a.trailing_ones() }, None),
+        "S_FF0_I32_B64" => (match src64()? { u64::MAX => u32::MAX, x => x.trailing_ones() }, None),
+        "S_FF1_I32_B32" => (if a == 0 { u32::MAX } else { a.trailing_zeros() }, None),
+        "S_FF1_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.trailing_zeros() }, None),
+        "S_FLBIT_I32_B32" => (if a == 0 { u32::MAX } else { a.leading_zeros() }, None),
+        "S_FLBIT_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.leading_zeros() }, None),
+        "S_FLBIT_I32" => (if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }, None),
+        "S_FLBIT_I32_I64" => {
+            let x = src64()?;
+            (if x == 0 || x == u64::MAX { u32::MAX } else { (if (x as i64) < 0 { !x } else { x }).leading_zeros() }, None)
+        }
+        "S_SEXT_I32_I8" => (a as i8 as i32 as u32, None),
+        "S_SEXT_I32_I16" => (a as i16 as i32 as u32, None),
+        "S_BITSET0_B32" => (s32(w, dst)? & !(1 << (a & 31)), None),
+        "S_BITSET1_B32" => (s32(w, dst)? | 1 << (a & 31), None),
+        "S_ABS_I32" => nz(sa.unsigned_abs()),
+        "S_QUADMASK_B32" => nz((0..8).fold(0u32, |m, q| m | u32::from(a >> (4 * q) & 15 != 0) << q)),
+        "S_MOVRELS_B32" => {
+            let r = c0 as usize + w.s[124] as usize;
+            (*w.s.get(r).ok_or_else(|| fault(d, "s_movrels past s127"))?, None)
+        }
+        "S_MOVRELD_B32" => {
+            let r = dst + u64::from(w.s[124]);
+            return w.set_s(d, r, a);
+        }
+        "S_ADD_U32" => (a.wrapping_add(b), Some(a.checked_add(b).is_none())),
+        "S_SUB_U32" => (a.wrapping_sub(b), Some(b > a)),
+        "S_ADD_I32" => (sa.wrapping_add(sb) as u32, Some(sa.checked_add(sb).is_none())),
+        "S_SUB_I32" => (sa.wrapping_sub(sb) as u32, Some(sa.checked_sub(sb).is_none())),
+        "S_ADDC_U32" => {
+            let r = u64::from(a) + u64::from(b) + u64::from(w.scc);
+            (r as u32, Some(r >> 32 != 0))
+        }
+        "S_SUBB_U32" => {
+            let r = i64::from(a) - i64::from(b) - i64::from(w.scc);
+            (r as u32, Some(r < 0))
+        }
+        "S_MIN_I32" => (sa.min(sb) as u32, Some(sa < sb)),
+        "S_MIN_U32" => (a.min(b), Some(a < b)),
+        "S_MAX_I32" => (sa.max(sb) as u32, Some(sa > sb)),
+        "S_MAX_U32" => (a.max(b), Some(a > b)),
+        "S_CSELECT_B32" => (if w.scc { a } else { b }, None),
+        "S_AND_B32" => nz(a & b),
+        "S_OR_B32" => nz(a | b),
+        "S_XOR_B32" => nz(a ^ b),
+        "S_ANDN2_B32" => nz(a & !b),
+        "S_ORN2_B32" => nz(a | !b),
+        "S_NAND_B32" => nz(!(a & b)),
+        "S_NOR_B32" => nz(!(a | b)),
+        "S_XNOR_B32" => nz(!(a ^ b)),
+        "S_LSHL_B32" => nz(a << (b & 31)),
+        "S_LSHR_B32" => nz(a >> (b & 31)),
+        "S_ASHR_I32" => nz((sa >> (b & 31)) as u32),
+        "S_BFM_B32" => ((((1u64 << (a & 31)) - 1) as u32) << (b & 31), None),
+        "S_MUL_I32" => (sa.wrapping_mul(sb) as u32, None),
+        "S_MUL_HI_U32" => ((u64::from(a) * u64::from(b) >> 32) as u32, None),
+        "S_MUL_HI_I32" => ((i64::from(sa) * i64::from(sb) >> 32) as u32, None),
+        "S_BFE_U32" => nz(bits(a, b, (b >> 16) & 127)),
+        "S_BFE_I32" => {
+            let n = ((b >> 16) & 127).min(32);
+            let r = bits((sa >> (b & 31)) as u32, 0, n);
+            nz(if n > 0 && n < 32 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r })
+        }
+        "S_ABSDIFF_I32" => nz((i64::from(sa) - i64::from(sb)).unsigned_abs() as u32),

Fixed in salu.rs: S_ABSDIFF_I32 now subtracts in 32 bits and wraps (sa.wrapping_sub(sb).unsigned_abs()). salu_absdiff_pack_borrow_and_64_bit_fields checks the guide's example, (0x80000000, 1) gives 0x7fffffff with SCC = 1; with the old i64 subtraction it fails with 0x80000001. The same test covers s_pack_, s_subb_u32, s_cmp_u64, s_bfe64 across the dwords and s_bitset_b64.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776705962 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776705962). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:23Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/salu.rs`; line 299 ~~~~diff @@ -0,0 +1,328 @@ +//! Scalar ALU and program control (ISA chapters 4 and 5): SOPP, SOPK, SOP1, SOP2, SOPC. + +use super::{fault, field, unsupported, Ctx, Program, State, Stop, Wave}; +use crate::gpu::rdna2::{self, Decoded}; + +pub(super) fn sopp(w: &mut Wave, d: &Decoded, p: &Program, cx: &mut Ctx) -> Result<(), Stop> { + let simm = field(d, "SIMM16") as u32; + let taken = match d.inst.name { + "S_NOP" | "S_WAITCNT" | "S_WAITCNT_DEPCTR" | "S_INST_PREFETCH" | "S_SETPRIO" | "S_CLAUSE" | "S_SLEEP" | "S_ICACHE_INV" | "S_TTRACEDATA" | "S_TTRACEDATA_IMM" => false, + "S_ENDPGM" => { + w.state = State::Done; + return Ok(()); + } + "S_BARRIER" => { + w.state = State::Barrier; + return Ok(()); + } + // MODE: FP_ROUND [3:0], FP_DENORM [7:4] + "S_ROUND_MODE" => { + w.mode = w.mode & !0xF | simm & 0xF; + false + } + "S_DENORM_MODE" => { + w.mode = w.mode & !0xF0 | (simm & 0xF) << 4; + false + } + "S_BRANCH" => true, + "S_CBRANCH_SCC0" => !w.scc, + "S_CBRANCH_SCC1" => w.scc, + "S_CBRANCH_VCCZ" => w.vcc(cx.flip) == 0, + "S_CBRANCH_VCCNZ" => w.vcc(cx.flip) != 0, + "S_CBRANCH_EXECZ" => w.exec() == 0, + "S_CBRANCH_EXECNZ" => w.exec() != 0, + _ => return Err(unsupported(d)), + }; + if taken { + let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no branch target"))?; + w.jump_to(d, p, t)?; + } + Ok(()) +} + +fn bits(x: u32, off: u32, width: u32) -> u32 { + if width == 0 { 0 } else { (x >> (off & 31)) & (((1u64 << width.min(32)) - 1) as u32) } +} + +/// The MODE bits `simm16` (hwreg id, offset, size) names: MODE is the only register modelled +/// (None: FLAT_SCR_LO / HI, which only scratch access reads, and that is not modelled). +fn hwreg(d: &Decoded, simm: u32) -> Result<Option<u32>, Stop> { + let (id, off, size) = (simm & 63, simm >> 6 & 31, (simm >> 11 & 31) + 1); + match id { + 1 => Ok(Some((((1u64 << size) - 1) as u32) << off)), + 20 | 21 => Ok(None), + _ => Err(unsupported(d)), + } +} + +pub(super) fn run(w: &mut Wave, d: &Decoded, p: &Program) -> Result<(), Stop> { + let name = d.inst.name; + let f = |n: &str| field(d, n); + let wide = w.lanes == 64; + if d.enc.name == "ENC_SOPK" { + let simm = f("SIMM16") as u16; + let (k, ku) = (simm as i16 as i32, u32::from(simm)); + let dst = f("SDST"); + let cur = w.scalar(d, dst).unwrap_or(0); + match name { + "S_MOVK_I32" => w.set_s(d, dst, k as u32)?, + "S_CMOVK_I32" if w.scc => w.set_s(d, dst, k as u32)?, + "S_CMOVK_I32" => {} + "S_ADDK_I32" => { + let (r, o) = (cur as i32).overflowing_add(k); + w.set_s(d, dst, r as u32)?; + w.scc = o; + } + "S_MULK_I32" => w.set_s(d, dst, (cur as i32).wrapping_mul(k) as u32)?, + "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_EXPCNT" | "S_WAITCNT_LGKMCNT" => {} + "S_SETREG_IMM32_B32" | "S_SETREG_B32" => { + let Some(m) = hwreg(d, ku)? else { return Ok(()) }; + let x = if name == "S_SETREG_B32" { cur } else { d.literal.ok_or_else(|| fault(d, "no literal"))? }; + w.mode = w.mode & !m | (x << (ku >> 6 & 31)) & m; + } + "S_GETREG_B32" => { + let m = hwreg(d, ku)?.ok_or_else(|| unsupported(d))?; + w.set_s(d, dst, (w.mode & m) >> (ku >> 6 & 31))?; + } + "S_CALL_B64" => { + w.set_pair(dst as usize, d.pc + 4); + let t = rdna2::branch_target(d).ok_or_else(|| fault(d, "no call target"))?; + w.jump_to(d, p, t)?; + } + _ if name.starts_with("S_CMPK_") => { + let signed = name.ends_with("_I32"); + let (a, b) = if signed { (i64::from(cur as i32), i64::from(k)) } else { (i64::from(cur), i64::from(ku)) }; + w.scc = compare(d, &name[7..9], a, b)?; + } + _ => return Err(unsupported(d)), + } + return Ok(()); + } + if d.enc.name == "ENC_SOPC" { + let (c0, c1) = (f("SSRC0"), f("SSRC1")); + w.scc = match name { + "S_BITCMP0_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 0, + "S_BITCMP1_B32" => w.scalar(d, c0)? >> (w.scalar(d, c1)? & 31) & 1 == 1, + "S_BITCMP0_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 0, + "S_BITCMP1_B64" => w.scalar64(d, c0, false)? >> (w.scalar(d, c1)? & 63) & 1 == 1, + "S_CMP_EQ_U64" => w.scalar64(d, c0, false)? == w.scalar64(d, c1, false)?, + "S_CMP_LG_U64" => w.scalar64(d, c0, false)? != w.scalar64(d, c1, false)?, + _ if name.starts_with("S_CMP_") => { + let (a, b) = (w.scalar(d, c0)?, w.scalar(d, c1)?); + let (a, b) = if name.ends_with("_I32") { (i64::from(a as i32), i64::from(b as i32)) } else { (i64::from(a), i64::from(b)) }; + compare(d, &name[6..8], a, b)? + } + _ => return Err(unsupported(d)), + }; + return Ok(()); + } + let dst = f("SDST"); + let (c0, c1) = (f("SSRC0"), if d.enc.name == "ENC_SOP2" { f("SSRC1") } else { 0 }); + let s32 = |w: &Wave, c| w.scalar(d, c); + let s64 = |w: &Wave, c| w.scalar64(d, c, false); + // exec-mask families: D = EXEC, EXEC = S0 op EXEC (WREXEC: D = the new EXEC), SCC = EXEC != 0 + if name.contains("SAVEEXEC") || name.contains("WREXEC") { + let b64 = name.ends_with("_B64"); + if b64 != wide { + return Err(fault(d, "a mask instruction of the other wave size")); + } + let (s, e) = (if b64 { s64(w, c0)? } else { u64::from(s32(w, c0)?) }, w.exec()); + let op = name.trim_start_matches("S_").split("_SAVEEXEC").next().unwrap().split("_WREXEC").next().unwrap(); + let mut new = match op { + "AND" => s & e, + "OR" => s | e, + "XOR" => s ^ e, + "ANDN2" => s & !e, + "ORN2" => s | !e, + "NAND" => !(s & e), + "NOR" => !(s | e), + "XNOR" => !(s ^ e), + "ANDN1" => !s & e, + "ORN1" => !s | e, + _ => return Err(unsupported(d)), + }; + if !wide { + new &= 0xFFFF_FFFF; + } + let saved = if name.contains("WREXEC") { new } else { e }; + if b64 { w.set_pair(dst as usize, saved) } else { w.set_s(d, dst, saved as u32)? } + w.set_mask(126, new); + w.scc = new != 0; + return Ok(()); + } + let b64 = matches!(name.rsplit('_').next(), Some("B64" | "I64" | "U64")) && !name.contains("_I32_"); + if b64 { + let (a, b) = (s64(w, c0)?, s64(w, c1).unwrap_or(0)); + let sh = s32(w, c1).unwrap_or(0) & 63; + let (r, scc) = match name { + "S_MOV_B64" => (a, None), + "S_CMOV_B64" => (if w.scc { a } else { s64(w, dst)? }, None), + "S_NOT_B64" => (!a, Some(!a != 0)), + "S_WQM_B64" => { + let r = (0..16).fold(0u64, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m }); + (r, Some(r != 0)) + } + "S_BREV_B64" => (a.reverse_bits(), None), + "S_QUADMASK_B64" => { + let r = (0..16).fold(0u64, |m, q| m | u64::from(a >> (4 * q) & 15 != 0) << q); + (r, Some(r != 0)) + } + "S_BITREPLICATE_B64_B32" => ((0..32).fold(0u64, |m, i| m | (a >> i & 1) * 3 << (2 * i)), None), + "S_GETPC_B64" => (d.pc + 4, None), + "S_SETPC_B64" => return w.jump_to(d, p, a), + "S_SWAPPC_B64" => { + w.set_pair(dst as usize, d.pc + 4); + return w.jump_to(d, p, a); + } + "S_AND_B64" => (a & b, Some(a & b != 0)), + "S_OR_B64" => (a | b, Some(a | b != 0)), + "S_XOR_B64" => (a ^ b, Some(a ^ b != 0)), + "S_ANDN2_B64" => (a & !b, Some(a & !b != 0)), + "S_ORN2_B64" => (a | !b, Some(a | !b != 0)), + "S_NAND_B64" => (!(a & b), Some(!(a & b) != 0)), + "S_NOR_B64" => (!(a | b), Some(!(a | b) != 0)), + "S_XNOR_B64" => (!(a ^ b), Some(!(a ^ b) != 0)), + "S_CSELECT_B64" => (if w.scc { a } else { b }, None), + "S_LSHL_B64" => (a << sh, Some(a << sh != 0)), + "S_LSHR_B64" => (a >> sh, Some(a >> sh != 0)), + "S_ASHR_I64" => (((a as i64) >> sh) as u64, Some((a as i64) >> sh != 0)), + "S_BFM_B64" => { + let (n, o) = (s32(w, c0)? & 63, s32(w, c1)? & 63); + ((if n == 0 { 0 } else { u64::MAX >> (64 - n) }) << o, None) + } + "S_BFE_U64" | "S_BFE_I64" => { + let x = s32(w, c1)?; + let (o, n) = (x & 63, (x >> 16) & 127); + let n = n.min(64); + let x = if name == "S_BFE_I64" { ((a as i64) >> o) as u64 } else { a >> o }; + let mut r = if n == 0 { 0 } else { x & (u64::MAX >> (64 - n)) }; + if name == "S_BFE_I64" && n > 0 && n < 64 && r >> (n - 1) & 1 == 1 { + r |= u64::MAX << n; + } + (r, Some(r != 0)) + } + "S_BITSET0_B64" | "S_BITSET1_B64" => { + let bit = s32(w, c0)? & 63; + let cur = w.pair(dst as usize); + (if name.contains("SET1") { cur | 1 << bit } else { cur & !(1 << bit) }, None) + } + "S_MOVRELS_B64" => (w.pair((c0 as usize + w.s[124] as usize).min(126)), None), + _ => return Err(unsupported(d)), + }; + if name == "S_MOVRELD_B64" { + return Err(unsupported(d)); + } + w.set_pair(dst as usize, r); + if let Some(c) = scc { + w.scc = c; + } + return Ok(()); + } + let a = s32(w, c0)?; + let b = if d.enc.name == "ENC_SOP2" { s32(w, c1)? } else { 0 }; + let (sa, sb) = (a as i32, b as i32); + let src64 = || s64(w, c0); + let nz = |r: u32| (r, Some(r != 0)); + let (r, scc): (u32, Option<bool>) = match name { + "S_MOV_B32" => (a, None), + "S_CMOV_B32" => (if w.scc { a } else { s32(w, dst)? }, None), + "S_NOT_B32" => nz(!a), + "S_WQM_B32" => nz((0..8).fold(0u32, |m, q| if a >> (4 * q) & 15 != 0 { m | 15 << (4 * q) } else { m })), + "S_BREV_B32" => (a.reverse_bits(), None), + "S_BCNT0_I32_B32" => nz(a.count_zeros()), + "S_BCNT0_I32_B64" => nz(src64()?.count_zeros()), + "S_BCNT1_I32_B32" => nz(a.count_ones()), + "S_BCNT1_I32_B64" => nz(src64()?.count_ones()), + "S_FF0_I32_B32" => (if a == u32::MAX { u32::MAX } else { a.trailing_ones() }, None), + "S_FF0_I32_B64" => (match src64()? { u64::MAX => u32::MAX, x => x.trailing_ones() }, None), + "S_FF1_I32_B32" => (if a == 0 { u32::MAX } else { a.trailing_zeros() }, None), + "S_FF1_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.trailing_zeros() }, None), + "S_FLBIT_I32_B32" => (if a == 0 { u32::MAX } else { a.leading_zeros() }, None), + "S_FLBIT_I32_B64" => (match src64()? { 0 => u32::MAX, x => x.leading_zeros() }, None), + "S_FLBIT_I32" => (if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }, None), + "S_FLBIT_I32_I64" => { + let x = src64()?; + (if x == 0 || x == u64::MAX { u32::MAX } else { (if (x as i64) < 0 { !x } else { x }).leading_zeros() }, None) + } + "S_SEXT_I32_I8" => (a as i8 as i32 as u32, None), + "S_SEXT_I32_I16" => (a as i16 as i32 as u32, None), + "S_BITSET0_B32" => (s32(w, dst)? & !(1 << (a & 31)), None), + "S_BITSET1_B32" => (s32(w, dst)? | 1 << (a & 31), None), + "S_ABS_I32" => nz(sa.unsigned_abs()), + "S_QUADMASK_B32" => nz((0..8).fold(0u32, |m, q| m | u32::from(a >> (4 * q) & 15 != 0) << q)), + "S_MOVRELS_B32" => { + let r = c0 as usize + w.s[124] as usize; + (*w.s.get(r).ok_or_else(|| fault(d, "s_movrels past s127"))?, None) + } + "S_MOVRELD_B32" => { + let r = dst + u64::from(w.s[124]); + return w.set_s(d, r, a); + } + "S_ADD_U32" => (a.wrapping_add(b), Some(a.checked_add(b).is_none())), + "S_SUB_U32" => (a.wrapping_sub(b), Some(b > a)), + "S_ADD_I32" => (sa.wrapping_add(sb) as u32, Some(sa.checked_add(sb).is_none())), + "S_SUB_I32" => (sa.wrapping_sub(sb) as u32, Some(sa.checked_sub(sb).is_none())), + "S_ADDC_U32" => { + let r = u64::from(a) + u64::from(b) + u64::from(w.scc); + (r as u32, Some(r >> 32 != 0)) + } + "S_SUBB_U32" => { + let r = i64::from(a) - i64::from(b) - i64::from(w.scc); + (r as u32, Some(r < 0)) + } + "S_MIN_I32" => (sa.min(sb) as u32, Some(sa < sb)), + "S_MIN_U32" => (a.min(b), Some(a < b)), + "S_MAX_I32" => (sa.max(sb) as u32, Some(sa > sb)), + "S_MAX_U32" => (a.max(b), Some(a > b)), + "S_CSELECT_B32" => (if w.scc { a } else { b }, None), + "S_AND_B32" => nz(a & b), + "S_OR_B32" => nz(a | b), + "S_XOR_B32" => nz(a ^ b), + "S_ANDN2_B32" => nz(a & !b), + "S_ORN2_B32" => nz(a | !b), + "S_NAND_B32" => nz(!(a & b)), + "S_NOR_B32" => nz(!(a | b)), + "S_XNOR_B32" => nz(!(a ^ b)), + "S_LSHL_B32" => nz(a << (b & 31)), + "S_LSHR_B32" => nz(a >> (b & 31)), + "S_ASHR_I32" => nz((sa >> (b & 31)) as u32), + "S_BFM_B32" => ((((1u64 << (a & 31)) - 1) as u32) << (b & 31), None), + "S_MUL_I32" => (sa.wrapping_mul(sb) as u32, None), + "S_MUL_HI_U32" => ((u64::from(a) * u64::from(b) >> 32) as u32, None), + "S_MUL_HI_I32" => ((i64::from(sa) * i64::from(sb) >> 32) as u32, None), + "S_BFE_U32" => nz(bits(a, b, (b >> 16) & 127)), + "S_BFE_I32" => { + let n = ((b >> 16) & 127).min(32); + let r = bits((sa >> (b & 31)) as u32, 0, n); + nz(if n > 0 && n < 32 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r }) + } + "S_ABSDIFF_I32" => nz((i64::from(sa) - i64::from(sb)).unsigned_abs() as u32), ~~~~ --- Fixed in `salu.rs`: S_ABSDIFF_I32 now subtracts in 32 bits and wraps (`sa.wrapping_sub(sb).unsigned_abs()`). `salu_absdiff_pack_borrow_and_64_bit_fields` checks the guide's example, (0x80000000, 1) gives 0x7fffffff with SCC = 1; with the old i64 subtraction it fails with 0x80000001. The same test covers s_pack_*, s_subb_u32, s_cmp_*_u64, s_bfe_*64 across the dwords and s_bitset*_b64. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:25Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 44

@@ -0,0 +1,496 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None)

Fixed in mem.rs: S_LOAD now clears the two low bits of the base, the immediate and SOFFSET before adding them (7.2.1). For S_BUFFER_LOAD the guide's pseudocode under "Reads using Buffer Constant" adds first, addr = (m_base + offset) & ~0x3, and the reference keeps that. s_load_drops_the_low_bits_of_each_address_component_and_s_buffer_load_of_the_sum loads base 0x1002 with offsets 1 and 2 through both; it failed before the change.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776706443 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776706443). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:25Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 44 ~~~~diff @@ -0,0 +1,496 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None) ~~~~ --- Fixed in `mem.rs`: S_LOAD now clears the two low bits of the base, the immediate and SOFFSET before adding them (7.2.1). For S_BUFFER_LOAD the guide's pseudocode under "Reads using Buffer Constant" adds first, `addr = (m_base + offset) & ~0x3`, and the reference keeps that. `s_load_drops_the_low_bits_of_each_address_component_and_s_buffer_load_of_the_sum` loads base 0x1002 with offsets 1 and 2 through both; it failed before the change. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:27Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 95

@@ -0,0 +1,458 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept.
+pub(crate) const MODE: u32 = 0xF0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stop {
+    /// an instruction (or an operand or modifier of one) outside the modelled set
+    Unsupported { pc: u64, name: String },
+    /// the program did something the console would not survive: a branch into nothing, an
+    /// access outside `mem`, an unaligned LDS dword
+    Fault { pc: u64, why: String },
+    /// the step limit
+    Steps(u64),
+}
+
+impl std::fmt::Display for Stop {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"),
+            Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"),
+            Stop::Steps(n) => write!(f, "no end after {n} steps"),
+        }
+    }
+}
+
+/// A rule of the ISA turned the wrong way, for tests that prove a check sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub(crate) enum Flip {
+    #[default]
+    None,
+    /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would
+    Lane31,
+    /// v_permlanex16 reads its own row instead of the other row of its half
+    PermlaneOwnRow,
+    /// vector instructions write the lanes EXEC has off
+    ExecIgnored,
+    /// VCC reads and branches see only its low half
+    VccLow,
+}
+
+pub(crate) fn unsupported(d: &Decoded) -> Stop {
+    Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) }
+}
+
+pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop {
+    Stop::Fault { pc: d.pc, why: why.into() }
+}
+
+pub(crate) fn field(d: &Decoded, name: &str) -> u64 {
+    field_value(d.enc, &d.words, name).unwrap_or(0)
+}
+
+/// A program decoded once: its instructions and where each starts.
+pub(crate) struct Program {
+    pub list: Vec<Decoded>,
+    pub index: HashMap<u64, usize>,
+}
+
+impl Program {
+    /// Words that do not decode (constants after the code) are left out; reaching one faults.
+    pub fn new(code: &[u8]) -> Program {
+        let mut list = Vec::new();
+        let mut off = 0;
+        while off + 4 <= code.len() {
+            match rdna2::decode(&code[off..], off as u64) {
+                Ok(d) => {
+                    off += d.len;
+                    list.push(d);
+                }
+                Err(_) => off += 4,

Fixed in mod.rs: an undecodable word stays in the program as a gap, and a run that falls through into one stops with a fault. A branch over the gap still works. execution_stops_at_a_word_that_does_not_decode puts 0xFFFFFFFF between two moves; it failed before the change.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776706752 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776706752). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:27Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 95 ~~~~diff @@ -0,0 +1,458 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept. +pub(crate) const MODE: u32 = 0xF0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stop { + /// an instruction (or an operand or modifier of one) outside the modelled set + Unsupported { pc: u64, name: String }, + /// the program did something the console would not survive: a branch into nothing, an + /// access outside `mem`, an unaligned LDS dword + Fault { pc: u64, why: String }, + /// the step limit + Steps(u64), +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"), + Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"), + Stop::Steps(n) => write!(f, "no end after {n} steps"), + } + } +} + +/// A rule of the ISA turned the wrong way, for tests that prove a check sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub(crate) enum Flip { + #[default] + None, + /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would + Lane31, + /// v_permlanex16 reads its own row instead of the other row of its half + PermlaneOwnRow, + /// vector instructions write the lanes EXEC has off + ExecIgnored, + /// VCC reads and branches see only its low half + VccLow, +} + +pub(crate) fn unsupported(d: &Decoded) -> Stop { + Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) } +} + +pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop { + Stop::Fault { pc: d.pc, why: why.into() } +} + +pub(crate) fn field(d: &Decoded, name: &str) -> u64 { + field_value(d.enc, &d.words, name).unwrap_or(0) +} + +/// A program decoded once: its instructions and where each starts. +pub(crate) struct Program { + pub list: Vec<Decoded>, + pub index: HashMap<u64, usize>, +} + +impl Program { + /// Words that do not decode (constants after the code) are left out; reaching one faults. + pub fn new(code: &[u8]) -> Program { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + list.push(d); + } + Err(_) => off += 4, ~~~~ --- Fixed in `mod.rs`: an undecodable word stays in the program as a gap, and a run that falls through into one stops with a fault. A branch over the gap still works. `execution_stops_at_a_word_that_does_not_decode` puts 0xFFFFFFFF between two moves; it failed before the change. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:29Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/valu.rs; line 413

@@ -0,0 +1,446 @@
+//! Vector ALU (ISA chapter 6): VOP1, VOP2, VOP3, VOPC and their DPP and SDWA forms. Integer
+//! operations live here, float operations in `float`, lane reads and DPP in `lanes`.
+
+use super::{fault, field, float, lanes, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::{self, Decoded, Variant};
+
+/// One lane's result: `v` (64 bits when `wide`) and its carry-out.
+pub(super) struct Out {
+    pub v: u64,
+    pub wide: bool,
+    pub carry: bool,
+}
+
+fn out(v: u32) -> Option<Out> {
+    Some(Out { v: u64::from(v), wide: false, carry: false })
+}
+
+fn sext24(x: u32) -> i64 {
+    i64::from((x << 8) as i32 >> 8)
+}
+
+fn bfe(x: u32, off: u32, width: u32) -> u32 {
+    let (o, n) = (off & 31, width & 31);
+    if n == 0 { 0 } else { (x >> o) & ((1u32 << n) - 1).max(if n == 32 { u32::MAX } else { 0 }) }
+}
+
+fn med3<T: Ord + Copy>(a: T, b: T, c: T) -> T {
+    a.max(b).min(a.min(b).max(c))
+}
+
+/// v_perm_b32: each selector byte of `s` picks a byte of {a, b} (b the low dword), a sign
+/// replicated from it, 0x00 or 0xff.
+fn perm(a: u32, b: u32, s: u32) -> u32 {
+    let x = u64::from(a) << 32 | u64::from(b);
+    (0..4).fold(0, |r, i| {
+        let sel = s >> (8 * i) & 0xFF;
+        let byte = match sel {
+            0..=7 => (x >> (8 * sel)) as u8,
+            8 => 0xFF * (x >> 15 & 1) as u8,
+            9 => 0xFF * (x >> 31 & 1) as u8,
+            10 => 0xFF * (x >> 47 & 1) as u8,
+            11 => 0xFF * (x >> 63 & 1) as u8,
+            12 => 0,
+            _ => 0xFF,
+        };
+        r | u32::from(byte) << (8 * i)
+    })
+}
+
+/// An integer operation of one lane; `sel` is the lane's bit of the select or carry-in mask.
+fn int(name: &str, [a, b, c]: [u32; 3], [_, b64, c64]: [u64; 3], lane: usize, sel: bool) -> Option<Out> {
+    let (sa, sb, sc) = (a as i32, b as i32, c as i32);
+    let before = (1u64 << lane) - 1;
+    let wide = |v: u64| Some(Out { v, wide: true, carry: false });
+    let carry = |r: i64| Some(Out { v: u64::from(r as u32), wide: false, carry: !(0..=u32::MAX as i64).contains(&r) });
+    match name {
+        "V_MOV_B32" => out(a),
+        "V_NOT_B32" => out(!a),
+        "V_BFREV_B32" => out(a.reverse_bits()),
+        "V_FFBH_U32" => out(if a == 0 { u32::MAX } else { a.leading_zeros() }),
+        "V_FFBL_B32" => out(if a == 0 { u32::MAX } else { a.trailing_zeros() }),
+        "V_FFBH_I32" => out(if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }),
+        "V_CNDMASK_B32" => out(if sel { b } else { a }),
+        "V_ADD_NC_U32" => out(a.wrapping_add(b)),
+        "V_SUB_NC_U32" => out(a.wrapping_sub(b)),
+        "V_SUBREV_NC_U32" => out(b.wrapping_sub(a)),
+        "V_ADD_NC_I32" => out(sa.wrapping_add(sb) as u32),
+        "V_SUB_NC_I32" => out(sa.wrapping_sub(sb) as u32),
+        "V_ADD_CO_U32" => carry(i64::from(a) + i64::from(b)),
+        "V_SUB_CO_U32" => carry(i64::from(a) - i64::from(b)),
+        "V_SUBREV_CO_U32" => carry(i64::from(b) - i64::from(a)),
+        "V_ADD_CO_CI_U32" => carry(i64::from(a) + i64::from(b) + i64::from(sel)),
+        "V_SUB_CO_CI_U32" => carry(i64::from(a) - i64::from(b) - i64::from(sel)),
+        "V_SUBREV_CO_CI_U32" => carry(i64::from(b) - i64::from(a) - i64::from(sel)),
+        "V_MUL_I32_I24" => out((sext24(a) * sext24(b)) as u32),
+        "V_MUL_HI_I32_I24" => out(((sext24(a) * sext24(b)) >> 32) as u32),
+        "V_MUL_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF)),
+        "V_MUL_HI_U32_U24" => out((u64::from(a & 0xFF_FFFF) * u64::from(b & 0xFF_FFFF) >> 32) as u32),
+        "V_MAD_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF).wrapping_add(c)),
+        "V_MAD_I32_I24" => out((sext24(a) * sext24(b) + i64::from(sc)) as u32),
+        "V_MUL_LO_U32" => out(a.wrapping_mul(b)),
+        "V_MUL_HI_U32" => out((u64::from(a) * u64::from(b) >> 32) as u32),
+        "V_MUL_HI_I32" => out((i64::from(sa) * i64::from(sb) >> 32) as u32),
+        "V_MIN_I32" => out(sa.min(sb) as u32),
+        "V_MAX_I32" => out(sa.max(sb) as u32),
+        "V_MIN_U32" => out(a.min(b)),
+        "V_MAX_U32" => out(a.max(b)),
+        "V_MIN3_I32" => out(sa.min(sb).min(sc) as u32),
+        "V_MAX3_I32" => out(sa.max(sb).max(sc) as u32),
+        "V_MED3_I32" => out(med3(sa, sb, sc) as u32),
+        "V_MIN3_U32" => out(a.min(b).min(c)),
+        "V_MAX3_U32" => out(a.max(b).max(c)),
+        "V_MED3_U32" => out(med3(a, b, c)),
+        "V_LSHRREV_B32" => out(b >> (a & 31)),
+        "V_ASHRREV_I32" => out((sb >> (a & 31)) as u32),
+        "V_LSHLREV_B32" => out(b << (a & 31)),
+        "V_AND_B32" => out(a & b),
+        "V_OR_B32" => out(a | b),
+        "V_XOR_B32" => out(a ^ b),
+        "V_XNOR_B32" => out(!(a ^ b)),
+        "V_BFE_U32" => out(bfe(a, b, c)),
+        // the shift is arithmetic: a field past bit 31 holds copies of the sign
+        "V_BFE_I32" => {
+            let n = c & 31;
+            let r = bfe((sa >> (b & 31)) as u32, 0, n);
+            out(if n > 0 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r })
+        }
+        "V_BFI_B32" => out((a & b) | (!a & c)),
+        "V_BFM_B32" => out((((1u64 << (a & 31)) - 1) as u32) << (b & 31)),
+        "V_ALIGNBIT_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (c & 31)) as u32),
+        "V_ALIGNBYTE_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (8 * (c & 3))) as u32),
+        "V_LSHL_ADD_U32" => out((a << (b & 31)).wrapping_add(c)),
+        "V_ADD_LSHL_U32" => out(a.wrapping_add(b) << (c & 31)),
+        "V_ADD3_U32" => out(a.wrapping_add(b).wrapping_add(c)),
+        "V_LSHL_OR_B32" => out((a << (b & 31)) | c),
+        "V_AND_OR_B32" => out((a & b) | c),
+        "V_OR3_B32" => out(a | b | c),
+        "V_XOR3_B32" => out(a ^ b ^ c),
+        "V_XAD_U32" => out((a ^ b).wrapping_add(c)),
+        "V_PERM_B32" => out(perm(a, b, c)),
+        "V_BCNT_U32_B32" => out(a.count_ones().wrapping_add(b)),
+        "V_MBCNT_LO_U32_B32" => out((a & before as u32).count_ones().wrapping_add(b)),
+        "V_MBCNT_HI_U32_B32" => out((a & (before >> 32) as u32).count_ones().wrapping_add(b)),
+        "V_SAD_U32" => out((i64::from(a) - i64::from(b)).unsigned_abs() as u32 + c),
+        "V_LSHLREV_B64" => wide(b64 << (a & 63)),
+        "V_LSHRREV_B64" => wide(b64 >> (a & 63)),
+        "V_ASHRREV_I64" => wide(((b64 as i64) >> (a & 63)) as u64),
+        "V_MAD_U64_U32" => {
+            let r = u128::from(a) * u128::from(b) + u128::from(c64);
+            Some(Out { v: r as u64, wide: true, carry: r >> 64 != 0 })
+        }
+        "V_MAD_I64_I32" => {
+            let r = i128::from(sa) * i128::from(sb) + i128::from(c64 as i64);
+            Some(Out { v: r as u64, wide: true, carry: r != i128::from(r as i64) })
+        }
+        _ => None,
+    }
+}
+
+/// Instructions whose sources are 64 bits wide: (src0, src1, src2).
+fn wide_srcs(name: &str) -> [bool; 3] {
+    match name {
+        "V_LSHLREV_B64" | "V_LSHRREV_B64" | "V_ASHRREV_I64" => [false, true, false],
+        "V_MAD_U64_U32" | "V_MAD_I64_I32" => [false, false, true],
+        _ => [false; 3],
+    }
+}
+
+/// An SDWA operand select: BYTE_0..3, WORD_0..1, DWORD.
+fn select(d: &Decoded, x: u32, sel: u64, sext: bool) -> Result<u32, Stop> {
+    let (off, width) = match sel {
+        0..=3 => (8 * sel as u32, 8),
+        4 | 5 => (16 * (sel as u32 - 4), 16),
+        6 => (0, 32),
+        _ => return Err(unsupported(d)),
+    };
+    let v = if width == 32 { x } else { x >> off & ((1 << width) - 1) };
+    Ok(if sext && width < 32 && v >> (width - 1) & 1 == 1 { v | u32::MAX << width } else { v })
+}
+
+pub(super) fn run(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    if let Some(r) = lanes::run(w, d, cx) {
+        return r;
+    }
+    if name.starts_with("V_CMP") {
+        return compare(w, d, cx);
+    }
+    if d.enc.name == "ENC_VOP3P" {
+        return float::vop3p(w, d, cx);
+    }
+    if matches!(name, "V_NOP" | "V_PIPEFLUSH") {
+        return Ok(());
+    }
+    let f = |n: &str| field(d, n);
+    let vop3 = matches!(d.enc.name, "ENC_VOP3" | "VOP3_SDST_ENC");
+    let sdst = d.enc.name == "VOP3_SDST_ENC";
+    let is_float = float::is_float(name);
+    let fsrc = float::float_srcs(name);
+    // the extension dword's layout for DPP / SDWA
+    let base = d.enc.name.trim_start_matches("ENC_");
+    let ext = |kind: &str| rdna2::encoding(&format!("{base}_VOP_{kind}")).ok_or_else(|| unsupported(d));
+    let xf = |e: &'static rdna2::Encoding, n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0);
+    let (mut abs, mut neg, mut omod, mut clamp) = (0u64, 0u64, 0u64, false);
+    let mut codes = if vop3 { [f("SRC0"), f("SRC1"), f("SRC2")] } else { [f("SRC0"), if d.enc.name == "ENC_VOP2" { 256 + f("VSRC1") } else { 0 }, 0] };
+    if vop3 {
+        abs = if sdst { 0 } else { f("ABS") };
+        neg = f("NEG");
+        omod = f("OMOD");
+        clamp = f("CLAMP") == 1;
+        if !sdst && f("OP_SEL") != 0 {
+            return Err(unsupported(d));
+        }
+    }
+    let mut sdwa = None;
+    let mut dpp16 = None;
+    let mut dpp8 = None;
+    match d.variant {
+        Variant::Plain => {}
+        Variant::Sdwa => {
+            let e = ext("SDWA")?;
+            codes[0] = xf(e, "VSRC0") + if xf(e, "S0") == 1 { 0 } else { 256 };
+            if d.enc.name == "ENC_VOP2" && xf(e, "S1") == 1 {
+                codes[1] -= 256;
+            }
+            abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1;
+            neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1;
+            omod = xf(e, "OMOD");
+            clamp = xf(e, "CLAMP") == 1;
+            sdwa = Some((xf(e, "SRC0_SEL"), xf(e, "SRC0_SEXT") == 1, xf(e, "SRC1_SEL"), xf(e, "SRC1_SEXT") == 1, xf(e, "DST_SEL"), xf(e, "DST_UNUSED")));
+        }
+        Variant::Dpp16 => {
+            let e = ext("DPP16")?;
+            codes[0] = 256 + xf(e, "VSRC0");
+            abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1;
+            neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1;
+            dpp16 = Some((xf(e, "DPP_CTRL"), xf(e, "ROW_MASK"), xf(e, "BANK_MASK"), xf(e, "BOUND_CTRL") == 1, xf(e, "FI") == 1));
+        }
+        Variant::Dpp8 => {
+            let e = ext("DPP8")?;
+            codes[0] = 256 + xf(e, "VSRC0");
+            let sel: Vec<u64> = (0..8).map(|k| xf(e, &format!("LANE_SEL_{k}"))).collect();
+            dpp8 = Some((sel, f("SRC0") == 0xEA));
+        }
+    }
+    if (abs | neg) & !(fsrc as u64) != 0 || ((omod != 0 || clamp) && !(is_float && float::float_dst(name))) {
+        return Err(unsupported(d));
+    }
+    let literal = d.literal;
+    // the second / third operand of the VOP2 forms that read the literal or the destination
+    let k = || literal.ok_or_else(|| fault(d, "no literal"));
+    let vdst = f("VDST");
+    let wsrc = wide_srcs(name);
+    let exec = w.exec();
+    let vcc = w.vcc(cx.flip);
+    let select_mask = if vop3 && matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") {
+        if codes[2] > 127 {
+            return Err(unsupported(d));
+        }
+        w.mask(codes[2] as usize)
+    } else {
+        vcc
+    };
+    let mut carry = 0u64;
+    let mut writes: Vec<(usize, Out)> = Vec::new();
+    for l in 0..w.lanes {
+        let on = exec >> l & 1 == 1;
+        if !on && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        // the DPP source of src0: None leaves the lane unwritten (masked by its row or bank,
+        // or an invalid source with BOUND_CTRL 0); an invalid source reads 0 otherwise
+        let mut dpp_src = None;
+        if let Some((ctrl, row, bank, bound, fi)) = &dpp16 {
+            let masked = row >> (l / 16) & 1 == 0 || bank >> ((l >> 2) & 3) & 1 == 0;
+            let s = lanes::dpp16_source(d, *ctrl, l, w.lanes)?.filter(|&s| exec >> s & 1 == 1 || *fi);
+            if masked || (s.is_none() && !bound) {
+                continue;
+            }
+            dpp_src = Some(s.map_or(0, |s| w.v[s][codes[0] as usize - 256]));
+        }
+        if let Some((sel, fi)) = &dpp8 {
+            let s = (l & !7) + sel[l & 7] as usize;
+            dpp_src = Some(if exec >> s & 1 == 1 || *fi { w.v[s][codes[0] as usize - 256] } else { 0 });
+        }
+        let mut src = [0u32; 3];
+        let mut src64 = [0u64; 3];
+        for i in 0..3 {
+            let present = i == 0 || (i == 1 && (vop3 || d.enc.name == "ENC_VOP2")) || (i == 2 && vop3);
+            if !present {
+                continue;
+            }
+            if wsrc[i] {
+                src64[i] = w.vsrc64(d, codes[i], l)?;
+            } else if i == 0 && dpp_src.is_some() {
+                src[0] = dpp_src.unwrap();
+            } else {
+                src[i] = w.vsrc(d, codes[i], l)?;
+            }
+        }
+        if let Some((s0, x0, s1, x1, ..)) = sdwa {
+            src[0] = select(d, src[0], s0, x0)?;
+            if d.enc.name == "ENC_VOP2" {
+                src[1] = select(d, src[1], s1, x1)?;
+            }
+        }
+        match name {
+            "V_FMAC_F32" | "V_MAC_F32" | "V_FMAC_LEGACY_F32" => src[2] = w.v[l][vdst as usize],
+            "V_FMAAK_F32" | "V_MADAK_F32" => src[2] = k()?,
+            "V_FMAMK_F32" | "V_MADMK_F32" => src = [src[0], k()?, src[1]],
+            _ => {}
+        }
+        let half = float::f16_srcs(name);
+        for i in 0..3 {
+            let sign = if half { 0x8000 } else { 0x8000_0000 };
+            if abs >> i & 1 == 1 {
+                src[i] &= !sign;
+            }
+            if neg >> i & 1 == 1 {
+                src[i] ^= sign;
+            }
+        }
+        let sel = select_mask >> l & 1 == 1;
+        let mut r = match float::eval(d, name, src, w.mode, l)? {
+            Some(v) => Out { v: u64::from(v), wide: false, carry: false },
+            None => int(name, src, src64, l, sel).ok_or_else(|| unsupported(d))?,
+        };
+        if is_float && float::float_dst(name) {
+            r.v = u64::from(float::output(d, r.v as u32, omod, clamp, w.mode)?);
+        }
+        if r.carry && on {
+            carry |= 1 << l;
+        }
+        if let Some((.., dsel, unused)) = sdwa {
+            let old = w.v[l][vdst as usize];
+            let (off, width) = match dsel {
+                0..=3 => (8 * dsel as u32, 8u32),
+                4 | 5 => (16 * (dsel as u32 - 4), 16),
+                6 => (0, 32),
+                _ => return Err(unsupported(d)),
+            };
+            if width < 32 {
+                let m = ((1u32 << width) - 1) << off;
+                let v = (r.v as u32) << off & m;
+                r.v = u64::from(match unused {
+                    0 => v,
+                    1 if off + width < 32 && (v >> (off + width - 1)) & 1 == 1 => v | (u32::MAX << (off + width)),
+                    1 => v,
+                    2 => old & !m | v,
+                    _ => return Err(unsupported(d)),
+                });
+            }
+        }
+        writes.push((l, r));
+    }
+    for (l, r) in writes {
+        let reg = vdst as usize;
+        w.v[l][reg] = r.v as u32;
+        if r.wide {
+            if reg == 255 {
+                return Err(fault(d, "a pair past v255"));
+            }
+            w.v[l][reg + 1] = (r.v >> 32) as u32;
+        }
+    }
+    let carries = matches!(name, "V_ADD_CO_U32" | "V_SUB_CO_U32" | "V_SUBREV_CO_U32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32" | "V_MAD_U64_U32" | "V_MAD_I64_I32");
+    if carries {
+        if sdst {
+            w.set_mask(f("SDST") as usize, carry);
+        } else if vop3 {
+            return Err(unsupported(d));
+        } else {
+            w.set_mask(106, carry);
+        }
+    }
+    Ok(())
+}
+
+/// V_CMP / V_CMPX: a bit for each active lane, 0 for the others, to VCC (VOPC),
+/// to the SGPRs VDST names (VOP3), or to EXEC alone (V_CMPX).
+fn compare(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    if d.variant != Variant::Plain {
+        return Err(unsupported(d));
+    }
+    let name = d.inst.name;
+    let vop3 = d.enc.name == "ENC_VOP3";
+    let f = |n: &str| field(d, n);
+    let codes = if vop3 { [f("SRC0"), f("SRC1")] } else { [f("SRC0"), 256 + f("VSRC1")] };
+    let (abs, neg) = if vop3 { (f("ABS"), f("NEG")) } else { (0, 0) };
+    if vop3 && (f("OP_SEL") != 0 || f("OMOD") != 0 || f("CLAMP") != 0) {
+        return Err(unsupported(d));
+    }
+    let x = name.starts_with("V_CMPX_");
+    let rest = name.trim_start_matches(if x { "V_CMPX_" } else { "V_CMP_" });
+    let (rel, ty) = rest.rsplit_once('_').ok_or_else(|| unsupported(d))?;
+    let float = ty.starts_with('F');
+    if (abs | neg) != 0 && (!float || (rel == "CLASS" && (abs | neg) & 2 != 0)) {
+        return Err(unsupported(d));
+    }
+    let exec = w.exec();
+    let mut m = 0u64;
+    for l in 0..w.lanes {
+        if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        let c = match ty {
+            "I32" | "U32" => {
+                let (a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?);
+                if ty == "I32" { int_rel(d, rel, i64::from(a as i32), i64::from(b as i32))? } else { int_rel(d, rel, i64::from(a), i64::from(b))? }
+            }
+            "I64" | "U64" => {
+                let (a, b) = (w.vsrc64(d, codes[0], l)?, w.vsrc64(d, codes[1], l)?);
+                if ty == "I64" { int_rel(d, rel, i128::from(a as i64), i128::from(b as i64))? } else { int_rel(d, rel, i128::from(a), i128::from(b))? }
+            }
+            "I16" | "U16" => {
+                let (a, b) = (w.vsrc(d, codes[0], l)? as u16, w.vsrc(d, codes[1], l)? as u16);
+                if ty == "I16" { int_rel(d, rel, a as i16, b as i16)? } else { int_rel(d, rel, a, b)? }
+            }
+            "F32" | "F16" => {
+                let (mut a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?);
+                let get = |x: u32, i: u64| -> f32 {
+                    let mut v = if ty == "F16" { float::f16_to_f32(x as u16) } else { f32::from_bits(x) };
+                    if abs >> i & 1 == 1 {
+                        v = v.abs();
+                    }
+                    if neg >> i & 1 == 1 {
+                        v = -v;
+                    }
+                    v
+                };
+                if rel == "CLASS" {
+                    if ty == "F16" {
+                        a = float::f16_to_f32(a as u16).to_bits();

Fixed in valu.rs: V_CMP_CLASS_F16 takes the class from the f16 bits (ABS and NEG on bit 15, then the exponent and mantissa fields), with no conversion. cmp_class_f16_classifies_the_f16_bits checks +1.0, the denormal 0x0001, the sNaN 0x7C01, -0 and NEG +1.0.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776707032 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776707032). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:29Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/valu.rs`; line 413 ~~~~diff @@ -0,0 +1,446 @@ +//! Vector ALU (ISA chapter 6): VOP1, VOP2, VOP3, VOPC and their DPP and SDWA forms. Integer +//! operations live here, float operations in `float`, lane reads and DPP in `lanes`. + +use super::{fault, field, float, lanes, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +/// One lane's result: `v` (64 bits when `wide`) and its carry-out. +pub(super) struct Out { + pub v: u64, + pub wide: bool, + pub carry: bool, +} + +fn out(v: u32) -> Option<Out> { + Some(Out { v: u64::from(v), wide: false, carry: false }) +} + +fn sext24(x: u32) -> i64 { + i64::from((x << 8) as i32 >> 8) +} + +fn bfe(x: u32, off: u32, width: u32) -> u32 { + let (o, n) = (off & 31, width & 31); + if n == 0 { 0 } else { (x >> o) & ((1u32 << n) - 1).max(if n == 32 { u32::MAX } else { 0 }) } +} + +fn med3<T: Ord + Copy>(a: T, b: T, c: T) -> T { + a.max(b).min(a.min(b).max(c)) +} + +/// v_perm_b32: each selector byte of `s` picks a byte of {a, b} (b the low dword), a sign +/// replicated from it, 0x00 or 0xff. +fn perm(a: u32, b: u32, s: u32) -> u32 { + let x = u64::from(a) << 32 | u64::from(b); + (0..4).fold(0, |r, i| { + let sel = s >> (8 * i) & 0xFF; + let byte = match sel { + 0..=7 => (x >> (8 * sel)) as u8, + 8 => 0xFF * (x >> 15 & 1) as u8, + 9 => 0xFF * (x >> 31 & 1) as u8, + 10 => 0xFF * (x >> 47 & 1) as u8, + 11 => 0xFF * (x >> 63 & 1) as u8, + 12 => 0, + _ => 0xFF, + }; + r | u32::from(byte) << (8 * i) + }) +} + +/// An integer operation of one lane; `sel` is the lane's bit of the select or carry-in mask. +fn int(name: &str, [a, b, c]: [u32; 3], [_, b64, c64]: [u64; 3], lane: usize, sel: bool) -> Option<Out> { + let (sa, sb, sc) = (a as i32, b as i32, c as i32); + let before = (1u64 << lane) - 1; + let wide = |v: u64| Some(Out { v, wide: true, carry: false }); + let carry = |r: i64| Some(Out { v: u64::from(r as u32), wide: false, carry: !(0..=u32::MAX as i64).contains(&r) }); + match name { + "V_MOV_B32" => out(a), + "V_NOT_B32" => out(!a), + "V_BFREV_B32" => out(a.reverse_bits()), + "V_FFBH_U32" => out(if a == 0 { u32::MAX } else { a.leading_zeros() }), + "V_FFBL_B32" => out(if a == 0 { u32::MAX } else { a.trailing_zeros() }), + "V_FFBH_I32" => out(if a == 0 || a == u32::MAX { u32::MAX } else { (if sa < 0 { !a } else { a }).leading_zeros() }), + "V_CNDMASK_B32" => out(if sel { b } else { a }), + "V_ADD_NC_U32" => out(a.wrapping_add(b)), + "V_SUB_NC_U32" => out(a.wrapping_sub(b)), + "V_SUBREV_NC_U32" => out(b.wrapping_sub(a)), + "V_ADD_NC_I32" => out(sa.wrapping_add(sb) as u32), + "V_SUB_NC_I32" => out(sa.wrapping_sub(sb) as u32), + "V_ADD_CO_U32" => carry(i64::from(a) + i64::from(b)), + "V_SUB_CO_U32" => carry(i64::from(a) - i64::from(b)), + "V_SUBREV_CO_U32" => carry(i64::from(b) - i64::from(a)), + "V_ADD_CO_CI_U32" => carry(i64::from(a) + i64::from(b) + i64::from(sel)), + "V_SUB_CO_CI_U32" => carry(i64::from(a) - i64::from(b) - i64::from(sel)), + "V_SUBREV_CO_CI_U32" => carry(i64::from(b) - i64::from(a) - i64::from(sel)), + "V_MUL_I32_I24" => out((sext24(a) * sext24(b)) as u32), + "V_MUL_HI_I32_I24" => out(((sext24(a) * sext24(b)) >> 32) as u32), + "V_MUL_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF)), + "V_MUL_HI_U32_U24" => out((u64::from(a & 0xFF_FFFF) * u64::from(b & 0xFF_FFFF) >> 32) as u32), + "V_MAD_U32_U24" => out((a & 0xFF_FFFF).wrapping_mul(b & 0xFF_FFFF).wrapping_add(c)), + "V_MAD_I32_I24" => out((sext24(a) * sext24(b) + i64::from(sc)) as u32), + "V_MUL_LO_U32" => out(a.wrapping_mul(b)), + "V_MUL_HI_U32" => out((u64::from(a) * u64::from(b) >> 32) as u32), + "V_MUL_HI_I32" => out((i64::from(sa) * i64::from(sb) >> 32) as u32), + "V_MIN_I32" => out(sa.min(sb) as u32), + "V_MAX_I32" => out(sa.max(sb) as u32), + "V_MIN_U32" => out(a.min(b)), + "V_MAX_U32" => out(a.max(b)), + "V_MIN3_I32" => out(sa.min(sb).min(sc) as u32), + "V_MAX3_I32" => out(sa.max(sb).max(sc) as u32), + "V_MED3_I32" => out(med3(sa, sb, sc) as u32), + "V_MIN3_U32" => out(a.min(b).min(c)), + "V_MAX3_U32" => out(a.max(b).max(c)), + "V_MED3_U32" => out(med3(a, b, c)), + "V_LSHRREV_B32" => out(b >> (a & 31)), + "V_ASHRREV_I32" => out((sb >> (a & 31)) as u32), + "V_LSHLREV_B32" => out(b << (a & 31)), + "V_AND_B32" => out(a & b), + "V_OR_B32" => out(a | b), + "V_XOR_B32" => out(a ^ b), + "V_XNOR_B32" => out(!(a ^ b)), + "V_BFE_U32" => out(bfe(a, b, c)), + // the shift is arithmetic: a field past bit 31 holds copies of the sign + "V_BFE_I32" => { + let n = c & 31; + let r = bfe((sa >> (b & 31)) as u32, 0, n); + out(if n > 0 && r >> (n - 1) & 1 == 1 { r | u32::MAX << n } else { r }) + } + "V_BFI_B32" => out((a & b) | (!a & c)), + "V_BFM_B32" => out((((1u64 << (a & 31)) - 1) as u32) << (b & 31)), + "V_ALIGNBIT_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (c & 31)) as u32), + "V_ALIGNBYTE_B32" => out(((u64::from(a) << 32 | u64::from(b)) >> (8 * (c & 3))) as u32), + "V_LSHL_ADD_U32" => out((a << (b & 31)).wrapping_add(c)), + "V_ADD_LSHL_U32" => out(a.wrapping_add(b) << (c & 31)), + "V_ADD3_U32" => out(a.wrapping_add(b).wrapping_add(c)), + "V_LSHL_OR_B32" => out((a << (b & 31)) | c), + "V_AND_OR_B32" => out((a & b) | c), + "V_OR3_B32" => out(a | b | c), + "V_XOR3_B32" => out(a ^ b ^ c), + "V_XAD_U32" => out((a ^ b).wrapping_add(c)), + "V_PERM_B32" => out(perm(a, b, c)), + "V_BCNT_U32_B32" => out(a.count_ones().wrapping_add(b)), + "V_MBCNT_LO_U32_B32" => out((a & before as u32).count_ones().wrapping_add(b)), + "V_MBCNT_HI_U32_B32" => out((a & (before >> 32) as u32).count_ones().wrapping_add(b)), + "V_SAD_U32" => out((i64::from(a) - i64::from(b)).unsigned_abs() as u32 + c), + "V_LSHLREV_B64" => wide(b64 << (a & 63)), + "V_LSHRREV_B64" => wide(b64 >> (a & 63)), + "V_ASHRREV_I64" => wide(((b64 as i64) >> (a & 63)) as u64), + "V_MAD_U64_U32" => { + let r = u128::from(a) * u128::from(b) + u128::from(c64); + Some(Out { v: r as u64, wide: true, carry: r >> 64 != 0 }) + } + "V_MAD_I64_I32" => { + let r = i128::from(sa) * i128::from(sb) + i128::from(c64 as i64); + Some(Out { v: r as u64, wide: true, carry: r != i128::from(r as i64) }) + } + _ => None, + } +} + +/// Instructions whose sources are 64 bits wide: (src0, src1, src2). +fn wide_srcs(name: &str) -> [bool; 3] { + match name { + "V_LSHLREV_B64" | "V_LSHRREV_B64" | "V_ASHRREV_I64" => [false, true, false], + "V_MAD_U64_U32" | "V_MAD_I64_I32" => [false, false, true], + _ => [false; 3], + } +} + +/// An SDWA operand select: BYTE_0..3, WORD_0..1, DWORD. +fn select(d: &Decoded, x: u32, sel: u64, sext: bool) -> Result<u32, Stop> { + let (off, width) = match sel { + 0..=3 => (8 * sel as u32, 8), + 4 | 5 => (16 * (sel as u32 - 4), 16), + 6 => (0, 32), + _ => return Err(unsupported(d)), + }; + let v = if width == 32 { x } else { x >> off & ((1 << width) - 1) }; + Ok(if sext && width < 32 && v >> (width - 1) & 1 == 1 { v | u32::MAX << width } else { v }) +} + +pub(super) fn run(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + if let Some(r) = lanes::run(w, d, cx) { + return r; + } + if name.starts_with("V_CMP") { + return compare(w, d, cx); + } + if d.enc.name == "ENC_VOP3P" { + return float::vop3p(w, d, cx); + } + if matches!(name, "V_NOP" | "V_PIPEFLUSH") { + return Ok(()); + } + let f = |n: &str| field(d, n); + let vop3 = matches!(d.enc.name, "ENC_VOP3" | "VOP3_SDST_ENC"); + let sdst = d.enc.name == "VOP3_SDST_ENC"; + let is_float = float::is_float(name); + let fsrc = float::float_srcs(name); + // the extension dword's layout for DPP / SDWA + let base = d.enc.name.trim_start_matches("ENC_"); + let ext = |kind: &str| rdna2::encoding(&format!("{base}_VOP_{kind}")).ok_or_else(|| unsupported(d)); + let xf = |e: &'static rdna2::Encoding, n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + let (mut abs, mut neg, mut omod, mut clamp) = (0u64, 0u64, 0u64, false); + let mut codes = if vop3 { [f("SRC0"), f("SRC1"), f("SRC2")] } else { [f("SRC0"), if d.enc.name == "ENC_VOP2" { 256 + f("VSRC1") } else { 0 }, 0] }; + if vop3 { + abs = if sdst { 0 } else { f("ABS") }; + neg = f("NEG"); + omod = f("OMOD"); + clamp = f("CLAMP") == 1; + if !sdst && f("OP_SEL") != 0 { + return Err(unsupported(d)); + } + } + let mut sdwa = None; + let mut dpp16 = None; + let mut dpp8 = None; + match d.variant { + Variant::Plain => {} + Variant::Sdwa => { + let e = ext("SDWA")?; + codes[0] = xf(e, "VSRC0") + if xf(e, "S0") == 1 { 0 } else { 256 }; + if d.enc.name == "ENC_VOP2" && xf(e, "S1") == 1 { + codes[1] -= 256; + } + abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1; + neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1; + omod = xf(e, "OMOD"); + clamp = xf(e, "CLAMP") == 1; + sdwa = Some((xf(e, "SRC0_SEL"), xf(e, "SRC0_SEXT") == 1, xf(e, "SRC1_SEL"), xf(e, "SRC1_SEXT") == 1, xf(e, "DST_SEL"), xf(e, "DST_UNUSED"))); + } + Variant::Dpp16 => { + let e = ext("DPP16")?; + codes[0] = 256 + xf(e, "VSRC0"); + abs = xf(e, "SRC0_ABS") | xf(e, "SRC1_ABS") << 1; + neg = xf(e, "SRC0_NEG") | xf(e, "SRC1_NEG") << 1; + dpp16 = Some((xf(e, "DPP_CTRL"), xf(e, "ROW_MASK"), xf(e, "BANK_MASK"), xf(e, "BOUND_CTRL") == 1, xf(e, "FI") == 1)); + } + Variant::Dpp8 => { + let e = ext("DPP8")?; + codes[0] = 256 + xf(e, "VSRC0"); + let sel: Vec<u64> = (0..8).map(|k| xf(e, &format!("LANE_SEL_{k}"))).collect(); + dpp8 = Some((sel, f("SRC0") == 0xEA)); + } + } + if (abs | neg) & !(fsrc as u64) != 0 || ((omod != 0 || clamp) && !(is_float && float::float_dst(name))) { + return Err(unsupported(d)); + } + let literal = d.literal; + // the second / third operand of the VOP2 forms that read the literal or the destination + let k = || literal.ok_or_else(|| fault(d, "no literal")); + let vdst = f("VDST"); + let wsrc = wide_srcs(name); + let exec = w.exec(); + let vcc = w.vcc(cx.flip); + let select_mask = if vop3 && matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + if codes[2] > 127 { + return Err(unsupported(d)); + } + w.mask(codes[2] as usize) + } else { + vcc + }; + let mut carry = 0u64; + let mut writes: Vec<(usize, Out)> = Vec::new(); + for l in 0..w.lanes { + let on = exec >> l & 1 == 1; + if !on && cx.flip != Flip::ExecIgnored { + continue; + } + // the DPP source of src0: None leaves the lane unwritten (masked by its row or bank, + // or an invalid source with BOUND_CTRL 0); an invalid source reads 0 otherwise + let mut dpp_src = None; + if let Some((ctrl, row, bank, bound, fi)) = &dpp16 { + let masked = row >> (l / 16) & 1 == 0 || bank >> ((l >> 2) & 3) & 1 == 0; + let s = lanes::dpp16_source(d, *ctrl, l, w.lanes)?.filter(|&s| exec >> s & 1 == 1 || *fi); + if masked || (s.is_none() && !bound) { + continue; + } + dpp_src = Some(s.map_or(0, |s| w.v[s][codes[0] as usize - 256])); + } + if let Some((sel, fi)) = &dpp8 { + let s = (l & !7) + sel[l & 7] as usize; + dpp_src = Some(if exec >> s & 1 == 1 || *fi { w.v[s][codes[0] as usize - 256] } else { 0 }); + } + let mut src = [0u32; 3]; + let mut src64 = [0u64; 3]; + for i in 0..3 { + let present = i == 0 || (i == 1 && (vop3 || d.enc.name == "ENC_VOP2")) || (i == 2 && vop3); + if !present { + continue; + } + if wsrc[i] { + src64[i] = w.vsrc64(d, codes[i], l)?; + } else if i == 0 && dpp_src.is_some() { + src[0] = dpp_src.unwrap(); + } else { + src[i] = w.vsrc(d, codes[i], l)?; + } + } + if let Some((s0, x0, s1, x1, ..)) = sdwa { + src[0] = select(d, src[0], s0, x0)?; + if d.enc.name == "ENC_VOP2" { + src[1] = select(d, src[1], s1, x1)?; + } + } + match name { + "V_FMAC_F32" | "V_MAC_F32" | "V_FMAC_LEGACY_F32" => src[2] = w.v[l][vdst as usize], + "V_FMAAK_F32" | "V_MADAK_F32" => src[2] = k()?, + "V_FMAMK_F32" | "V_MADMK_F32" => src = [src[0], k()?, src[1]], + _ => {} + } + let half = float::f16_srcs(name); + for i in 0..3 { + let sign = if half { 0x8000 } else { 0x8000_0000 }; + if abs >> i & 1 == 1 { + src[i] &= !sign; + } + if neg >> i & 1 == 1 { + src[i] ^= sign; + } + } + let sel = select_mask >> l & 1 == 1; + let mut r = match float::eval(d, name, src, w.mode, l)? { + Some(v) => Out { v: u64::from(v), wide: false, carry: false }, + None => int(name, src, src64, l, sel).ok_or_else(|| unsupported(d))?, + }; + if is_float && float::float_dst(name) { + r.v = u64::from(float::output(d, r.v as u32, omod, clamp, w.mode)?); + } + if r.carry && on { + carry |= 1 << l; + } + if let Some((.., dsel, unused)) = sdwa { + let old = w.v[l][vdst as usize]; + let (off, width) = match dsel { + 0..=3 => (8 * dsel as u32, 8u32), + 4 | 5 => (16 * (dsel as u32 - 4), 16), + 6 => (0, 32), + _ => return Err(unsupported(d)), + }; + if width < 32 { + let m = ((1u32 << width) - 1) << off; + let v = (r.v as u32) << off & m; + r.v = u64::from(match unused { + 0 => v, + 1 if off + width < 32 && (v >> (off + width - 1)) & 1 == 1 => v | (u32::MAX << (off + width)), + 1 => v, + 2 => old & !m | v, + _ => return Err(unsupported(d)), + }); + } + } + writes.push((l, r)); + } + for (l, r) in writes { + let reg = vdst as usize; + w.v[l][reg] = r.v as u32; + if r.wide { + if reg == 255 { + return Err(fault(d, "a pair past v255")); + } + w.v[l][reg + 1] = (r.v >> 32) as u32; + } + } + let carries = matches!(name, "V_ADD_CO_U32" | "V_SUB_CO_U32" | "V_SUBREV_CO_U32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32" | "V_MAD_U64_U32" | "V_MAD_I64_I32"); + if carries { + if sdst { + w.set_mask(f("SDST") as usize, carry); + } else if vop3 { + return Err(unsupported(d)); + } else { + w.set_mask(106, carry); + } + } + Ok(()) +} + +/// V_CMP / V_CMPX: a bit for each active lane, 0 for the others, to VCC (VOPC), +/// to the SGPRs VDST names (VOP3), or to EXEC alone (V_CMPX). +fn compare(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + if d.variant != Variant::Plain { + return Err(unsupported(d)); + } + let name = d.inst.name; + let vop3 = d.enc.name == "ENC_VOP3"; + let f = |n: &str| field(d, n); + let codes = if vop3 { [f("SRC0"), f("SRC1")] } else { [f("SRC0"), 256 + f("VSRC1")] }; + let (abs, neg) = if vop3 { (f("ABS"), f("NEG")) } else { (0, 0) }; + if vop3 && (f("OP_SEL") != 0 || f("OMOD") != 0 || f("CLAMP") != 0) { + return Err(unsupported(d)); + } + let x = name.starts_with("V_CMPX_"); + let rest = name.trim_start_matches(if x { "V_CMPX_" } else { "V_CMP_" }); + let (rel, ty) = rest.rsplit_once('_').ok_or_else(|| unsupported(d))?; + let float = ty.starts_with('F'); + if (abs | neg) != 0 && (!float || (rel == "CLASS" && (abs | neg) & 2 != 0)) { + return Err(unsupported(d)); + } + let exec = w.exec(); + let mut m = 0u64; + for l in 0..w.lanes { + if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored { + continue; + } + let c = match ty { + "I32" | "U32" => { + let (a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?); + if ty == "I32" { int_rel(d, rel, i64::from(a as i32), i64::from(b as i32))? } else { int_rel(d, rel, i64::from(a), i64::from(b))? } + } + "I64" | "U64" => { + let (a, b) = (w.vsrc64(d, codes[0], l)?, w.vsrc64(d, codes[1], l)?); + if ty == "I64" { int_rel(d, rel, i128::from(a as i64), i128::from(b as i64))? } else { int_rel(d, rel, i128::from(a), i128::from(b))? } + } + "I16" | "U16" => { + let (a, b) = (w.vsrc(d, codes[0], l)? as u16, w.vsrc(d, codes[1], l)? as u16); + if ty == "I16" { int_rel(d, rel, a as i16, b as i16)? } else { int_rel(d, rel, a, b)? } + } + "F32" | "F16" => { + let (mut a, b) = (w.vsrc(d, codes[0], l)?, w.vsrc(d, codes[1], l)?); + let get = |x: u32, i: u64| -> f32 { + let mut v = if ty == "F16" { float::f16_to_f32(x as u16) } else { f32::from_bits(x) }; + if abs >> i & 1 == 1 { + v = v.abs(); + } + if neg >> i & 1 == 1 { + v = -v; + } + v + }; + if rel == "CLASS" { + if ty == "F16" { + a = float::f16_to_f32(a as u16).to_bits(); ~~~~ --- Fixed in `valu.rs`: V_CMP_CLASS_F16 takes the class from the f16 bits (ABS and NEG on bit 15, then the exponent and mantissa fields), with no conversion. `cmp_class_f16_classifies_the_f16_bits` checks +1.0, the denormal 0x0001, the sNaN 0x7C01, -0 and NEG +1.0. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:31 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:31Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 157

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a < b { a } else { b })
+}
+
+fn max(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a > b { a } else { b })
+}
+
+fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> {
+    if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) }
+}
+
+/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out.
+fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> {
+    match mode >> 4 & 3 {
+        3 => Ok(x),
+        0 if x.is_subnormal() => Ok(0.0f32.copysign(x)),
+        0 => Ok(x),
+        _ => Err(unsupported(d)),
+    }
+}
+
+/// A float operation of one lane, or None when `name` is not one.
+pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> {
+    if !is_float(name) {
+        return Ok(None);
+    }
+    round_ok(d, mode)?;
+    let fs = float_srcs(name);
+    let mut x = [0f32; 3];
+    for i in 0..3 {
+        x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) };
+    }
+    let [a, b, c] = x;
+    let i = |v: f32| v.to_bits();
+    let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b };
+    let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 };
+    let r = match name {
+        "V_ADD_F32" => i(a + b),
+        "V_SUB_F32" => i(a - b),
+        "V_SUBREV_F32" => i(b - a),
+        "V_MUL_F32" => i(a * b),
+        "V_MUL_LEGACY_F32" => i(legacy(a, b)),
+        "V_MIN_F32" => i(min(a, b)),
+        "V_MAX_F32" => i(max(a, b)),
+        "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)),
+        "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }),
+        // not fused: the product is rounded first
+        "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c),
+        "V_MIN3_F32" => i(min(min(a, b), c)),
+        "V_MAX3_F32" => i(max(max(a, b), c)),
+        "V_MED3_F32" => {
+            if a.is_nan() || b.is_nan() || c.is_nan() {
+                i(min(min(a, b), c))
+            } else {
+                i(max(a, b).min(max(min(a, b), c)))
+            }
+        }
+        "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32),
+        "V_FLOOR_F32" => i(a.floor()),
+        "V_CEIL_F32" => i(a.ceil()),
+        "V_TRUNC_F32" => i(a.trunc()),
+        "V_RNDNE_F32" => i(a.round_ties_even()),
+        "V_FRACT_F32" => {
+            if a.is_infinite() {
+                i(f32::NAN)
+            } else {
+                i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF)))

Fixed in float.rs: V_FRACT_F32 of a NaN is now a NaN, as an infinity already was. fract_of_nan_is_nan checks it.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776707461 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776707461). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:31Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 157 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a < b { a } else { b }) +} + +fn max(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a > b { a } else { b }) +} + +fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> { + if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) } +} + +/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out. +fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> { + match mode >> 4 & 3 { + 3 => Ok(x), + 0 if x.is_subnormal() => Ok(0.0f32.copysign(x)), + 0 => Ok(x), + _ => Err(unsupported(d)), + } +} + +/// A float operation of one lane, or None when `name` is not one. +pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> { + if !is_float(name) { + return Ok(None); + } + round_ok(d, mode)?; + let fs = float_srcs(name); + let mut x = [0f32; 3]; + for i in 0..3 { + x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) }; + } + let [a, b, c] = x; + let i = |v: f32| v.to_bits(); + let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b }; + let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 }; + let r = match name { + "V_ADD_F32" => i(a + b), + "V_SUB_F32" => i(a - b), + "V_SUBREV_F32" => i(b - a), + "V_MUL_F32" => i(a * b), + "V_MUL_LEGACY_F32" => i(legacy(a, b)), + "V_MIN_F32" => i(min(a, b)), + "V_MAX_F32" => i(max(a, b)), + "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)), + "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }), + // not fused: the product is rounded first + "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c), + "V_MIN3_F32" => i(min(min(a, b), c)), + "V_MAX3_F32" => i(max(max(a, b), c)), + "V_MED3_F32" => { + if a.is_nan() || b.is_nan() || c.is_nan() { + i(min(min(a, b), c)) + } else { + i(max(a, b).min(max(min(a, b), c))) + } + } + "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32), + "V_FLOOR_F32" => i(a.floor()), + "V_CEIL_F32" => i(a.ceil()), + "V_TRUNC_F32" => i(a.trunc()), + "V_RNDNE_F32" => i(a.round_ties_even()), + "V_FRACT_F32" => { + if a.is_infinite() { + i(f32::NAN) + } else { + i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF))) ~~~~ --- Fixed in `float.rs`: V_FRACT_F32 of a NaN is now a NaN, as an infinity already was. `fract_of_nan_is_nan` checks it. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:33 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:33Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 181

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a < b { a } else { b })
+}
+
+fn max(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a > b { a } else { b })
+}
+
+fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> {
+    if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) }
+}
+
+/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out.
+fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> {
+    match mode >> 4 & 3 {
+        3 => Ok(x),
+        0 if x.is_subnormal() => Ok(0.0f32.copysign(x)),
+        0 => Ok(x),
+        _ => Err(unsupported(d)),
+    }
+}
+
+/// A float operation of one lane, or None when `name` is not one.
+pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> {
+    if !is_float(name) {
+        return Ok(None);
+    }
+    round_ok(d, mode)?;
+    let fs = float_srcs(name);
+    let mut x = [0f32; 3];
+    for i in 0..3 {
+        x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) };
+    }
+    let [a, b, c] = x;
+    let i = |v: f32| v.to_bits();
+    let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b };
+    let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 };
+    let r = match name {
+        "V_ADD_F32" => i(a + b),
+        "V_SUB_F32" => i(a - b),
+        "V_SUBREV_F32" => i(b - a),
+        "V_MUL_F32" => i(a * b),
+        "V_MUL_LEGACY_F32" => i(legacy(a, b)),
+        "V_MIN_F32" => i(min(a, b)),
+        "V_MAX_F32" => i(max(a, b)),
+        "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)),
+        "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }),
+        // not fused: the product is rounded first
+        "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c),
+        "V_MIN3_F32" => i(min(min(a, b), c)),
+        "V_MAX3_F32" => i(max(max(a, b), c)),
+        "V_MED3_F32" => {
+            if a.is_nan() || b.is_nan() || c.is_nan() {
+                i(min(min(a, b), c))
+            } else {
+                i(max(a, b).min(max(min(a, b), c)))
+            }
+        }
+        "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32),
+        "V_FLOOR_F32" => i(a.floor()),
+        "V_CEIL_F32" => i(a.ceil()),
+        "V_TRUNC_F32" => i(a.trunc()),
+        "V_RNDNE_F32" => i(a.round_ties_even()),
+        "V_FRACT_F32" => {
+            if a.is_infinite() {
+                i(f32::NAN)
+            } else {
+                i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF)))
+            }
+        }
+        "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32),
+        "V_RSQ_F32" => i((1.0 / f64::from(a).sqrt()) as f32),
+        "V_SQRT_F32" => i(f64::from(a).sqrt() as f32),
+        "V_EXP_F32" => i(f64::from(a).exp2() as f32),
+        "V_LOG_F32" => i(f64::from(a).log2() as f32),
+        "V_SIN_F32" => i((f64::from(a) * std::f64::consts::TAU).sin() as f32),
+        "V_COS_F32" => i((f64::from(a) * std::f64::consts::TAU).cos() as f32),
+        "V_CVT_F32_I32" => i(src[0] as i32 as f32),
+        "V_CVT_F32_U32" => i(src[0] as f32),
+        "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => {
+            let k = u32::from(name.as_bytes()[name.len() - 1] - b'0');
+            i((src[0] >> (8 * k) & 0xFF) as f32)
+        }
+        "V_CVT_I32_F32" => to_i32(a.trunc()),
+        "V_CVT_FLR_I32_F32" => to_i32(a.floor()),
+        "V_CVT_RPI_I32_F32" => to_i32((a + 0.5).floor()),
+        "V_CVT_U32_F32" => if a.is_nan() { 0 } else { a.trunc().clamp(0.0, u32::MAX as f32) as u32 },
+        "V_CVT_F16_F32" => {
+            if mode >> 2 & 3 != 0 {
+                return Err(unsupported(d));
+            }
+            u32::from(f32_to_f16(a, false))

Decided by LLVM: GCNSubtarget::zeroesHigh16BitsOfDest has gfx10 keep the high half, and Mesa ACO's instr_is_16bit counts v_cvt_f16_f32 as a 16-bit write on GFX10+. The guide does not say. valu.rs now keeps bits 31:16 of the destination (under SDWA, DST_SEL decides). cvt_f16_f32_keeps_the_high_half checks 0xABCD0000 becoming 0xABCD3C00.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776707821 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776707821). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:33Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 181 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a < b { a } else { b }) +} + +fn max(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a > b { a } else { b }) +} + +fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> { + if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) } +} + +/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out. +fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> { + match mode >> 4 & 3 { + 3 => Ok(x), + 0 if x.is_subnormal() => Ok(0.0f32.copysign(x)), + 0 => Ok(x), + _ => Err(unsupported(d)), + } +} + +/// A float operation of one lane, or None when `name` is not one. +pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> { + if !is_float(name) { + return Ok(None); + } + round_ok(d, mode)?; + let fs = float_srcs(name); + let mut x = [0f32; 3]; + for i in 0..3 { + x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) }; + } + let [a, b, c] = x; + let i = |v: f32| v.to_bits(); + let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b }; + let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 }; + let r = match name { + "V_ADD_F32" => i(a + b), + "V_SUB_F32" => i(a - b), + "V_SUBREV_F32" => i(b - a), + "V_MUL_F32" => i(a * b), + "V_MUL_LEGACY_F32" => i(legacy(a, b)), + "V_MIN_F32" => i(min(a, b)), + "V_MAX_F32" => i(max(a, b)), + "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)), + "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }), + // not fused: the product is rounded first + "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c), + "V_MIN3_F32" => i(min(min(a, b), c)), + "V_MAX3_F32" => i(max(max(a, b), c)), + "V_MED3_F32" => { + if a.is_nan() || b.is_nan() || c.is_nan() { + i(min(min(a, b), c)) + } else { + i(max(a, b).min(max(min(a, b), c))) + } + } + "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32), + "V_FLOOR_F32" => i(a.floor()), + "V_CEIL_F32" => i(a.ceil()), + "V_TRUNC_F32" => i(a.trunc()), + "V_RNDNE_F32" => i(a.round_ties_even()), + "V_FRACT_F32" => { + if a.is_infinite() { + i(f32::NAN) + } else { + i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF))) + } + } + "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32), + "V_RSQ_F32" => i((1.0 / f64::from(a).sqrt()) as f32), + "V_SQRT_F32" => i(f64::from(a).sqrt() as f32), + "V_EXP_F32" => i(f64::from(a).exp2() as f32), + "V_LOG_F32" => i(f64::from(a).log2() as f32), + "V_SIN_F32" => i((f64::from(a) * std::f64::consts::TAU).sin() as f32), + "V_COS_F32" => i((f64::from(a) * std::f64::consts::TAU).cos() as f32), + "V_CVT_F32_I32" => i(src[0] as i32 as f32), + "V_CVT_F32_U32" => i(src[0] as f32), + "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => { + let k = u32::from(name.as_bytes()[name.len() - 1] - b'0'); + i((src[0] >> (8 * k) & 0xFF) as f32) + } + "V_CVT_I32_F32" => to_i32(a.trunc()), + "V_CVT_FLR_I32_F32" => to_i32(a.floor()), + "V_CVT_RPI_I32_F32" => to_i32((a + 0.5).floor()), + "V_CVT_U32_F32" => if a.is_nan() { 0 } else { a.trunc().clamp(0.0, u32::MAX as f32) as u32 }, + "V_CVT_F16_F32" => { + if mode >> 2 & 3 != 0 { + return Err(unsupported(d)); + } + u32::from(f32_to_f16(a, false)) ~~~~ --- Decided by LLVM: GCNSubtarget::zeroesHigh16BitsOfDest has gfx10 keep the high half, and Mesa ACO's instr_is_16bit counts v_cvt_f16_f32 as a 16-bit write on GFX10+. The guide does not say. `valu.rs` now keeps bits 31:16 of the destination (under SDWA, DST_SEL decides). `cvt_f16_f32_keeps_the_high_half` checks 0xABCD0000 becoming 0xABCD3C00. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:35 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:35Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 90

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {

Fixed in float.rs, following 12.7: of two zeros V_MIN_F32 gives -0 and V_MAX_F32 +0 in either order, and with IEEE set an sNaN operand is quieted and returned. MIN3/MAX3 are built from these, and V_MED3_F32 follows its pseudocode. min_max_and_med3_order_zeros_by_sign_and_return_an_snan_in_ieee_mode checks the bit patterns in both orders, with IEEE set by s_setreg.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776708162 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776708162). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:35Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 90 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { ~~~~ --- Fixed in `float.rs`, following 12.7: of two zeros V_MIN_F32 gives -0 and V_MAX_F32 +0 in either order, and with IEEE set an sNaN operand is quieted and returned. MIN3/MAX3 are built from these, and V_MED3_F32 follows its pseudocode. `min_max_and_med3_order_zeros_by_sign_and_return_an_snan_in_ieee_mode` checks the bit patterns in both orders, with IEEE set by s_setreg. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:37 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:37Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/float.rs; line 160

@@ -0,0 +1,289 @@
+//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix.
+//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are
+//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and
+//! `Wave::step` taints it with the bound the D3D rules allow.
+
+use super::{field, unsupported, Ctx, Flip, Stop, Wave};
+use crate::gpu::rdna2::Decoded;
+
+pub(super) fn is_float(name: &str) -> bool {
+    FLOAT.contains(&name)
+}
+
+const FLOAT: &[&str] = &[
+    "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32",
+    "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32",
+    "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32",
+    "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32",
+    "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1",
+    "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32",
+];
+
+/// Which sources are floats (and so take ABS and NEG).
+pub(super) fn float_srcs(name: &str) -> u8 {
+    match name {
+        // its VOP3 form takes ABS and NEG on the two values it selects from
+        "V_CNDMASK_B32" => 3,
+        _ if !is_float(name) => 0,
+        "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0,
+        "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1,
+        "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3,
+        _ => 7,
+    }
+}
+
+/// Whether the result is an f32 (and so takes OMOD and CLAMP).
+pub(super) fn float_dst(name: &str) -> bool {
+    !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16")
+}
+
+/// Whether the sources are f16 (ABS and NEG act on bit 15).
+pub(super) fn f16_srcs(name: &str) -> bool {
+    matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16")
+}
+
+pub(crate) fn f16_to_f32(h: u16) -> f32 {
+    let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF));
+    let mag = match e {
+        0 => m as f32 * (2f32).powi(-24),
+        31 => if m == 0 { f32::INFINITY } else { f32::NAN },
+        _ => f32::from_bits((e + 112) << 23 | m << 13),
+    };
+    if s == 1 { -mag } else { mag }
+}
+
+/// f32 to f16, rounded to nearest even (`rtz`: toward zero).
+pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 {
+    let b = x.to_bits();
+    let s = ((b >> 16) & 0x8000) as u16;
+    let a = x.abs();
+    if a.is_nan() {
+        return s | 0x7E00;
+    }
+    if a.is_infinite() {
+        return s | 0x7C00;
+    }
+    // the value in units of the f16 grid at its exponent, exactly in f64
+    let a = f64::from(a);
+    let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 };
+    let q = a / 2f64.powi(e);
+    let mut n = if rtz { q.trunc() } else { q.round_ties_even() };
+    let mut e = e;
+    if n >= 2048.0 {
+        n /= 2.0;
+        e += 1;
+    }
+    if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 {
+        return if rtz { s | 0x7BFF } else { s | 0x7C00 };
+    }
+    let n = n as u32;
+    if n < 1024 {
+        return s | n as u16;
+    }
+    s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16
+}
+
+fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 {
+    if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) }
+}
+
+fn min(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a < b { a } else { b })
+}
+
+fn max(a: f32, b: f32) -> f32 {
+    nan_or(a, b, |a, b| if a > b { a } else { b })
+}
+
+fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> {
+    if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) }
+}
+
+/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out.
+fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> {
+    match mode >> 4 & 3 {
+        3 => Ok(x),
+        0 if x.is_subnormal() => Ok(0.0f32.copysign(x)),
+        0 => Ok(x),
+        _ => Err(unsupported(d)),
+    }
+}
+
+/// A float operation of one lane, or None when `name` is not one.
+pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> {
+    if !is_float(name) {
+        return Ok(None);
+    }
+    round_ok(d, mode)?;
+    let fs = float_srcs(name);
+    let mut x = [0f32; 3];
+    for i in 0..3 {
+        x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) };
+    }
+    let [a, b, c] = x;
+    let i = |v: f32| v.to_bits();
+    let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b };
+    let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 };
+    let r = match name {
+        "V_ADD_F32" => i(a + b),
+        "V_SUB_F32" => i(a - b),
+        "V_SUBREV_F32" => i(b - a),
+        "V_MUL_F32" => i(a * b),
+        "V_MUL_LEGACY_F32" => i(legacy(a, b)),
+        "V_MIN_F32" => i(min(a, b)),
+        "V_MAX_F32" => i(max(a, b)),
+        "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)),
+        "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }),
+        // not fused: the product is rounded first
+        "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c),
+        "V_MIN3_F32" => i(min(min(a, b), c)),
+        "V_MAX3_F32" => i(max(max(a, b), c)),
+        "V_MED3_F32" => {
+            if a.is_nan() || b.is_nan() || c.is_nan() {
+                i(min(min(a, b), c))
+            } else {
+                i(max(a, b).min(max(min(a, b), c)))
+            }
+        }
+        "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32),
+        "V_FLOOR_F32" => i(a.floor()),
+        "V_CEIL_F32" => i(a.ceil()),
+        "V_TRUNC_F32" => i(a.trunc()),
+        "V_RNDNE_F32" => i(a.round_ties_even()),
+        "V_FRACT_F32" => {
+            if a.is_infinite() {
+                i(f32::NAN)
+            } else {
+                i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF)))
+            }
+        }
+        "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32),

Fixed in float.rs: V_RCP_F32, V_RSQ_F32 and V_SQRT_F32 flush denormal inputs and results whatever MODE says (12.8). In rcp_rsq_and_sqrt_flush_denormals_whatever_the_mode, RCP(0x00400000) gives +inf, RCP(2^127) 0, SQRT of a denormal 0 and RSQ of a negative denormal -inf.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776708457 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776708457). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:37Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/float.rs`; line 160 ~~~~diff @@ -0,0 +1,289 @@ +//! f32 arithmetic (ISA chapter 6 and its opcode pages), the f16 conversions, and v_fma_mix. +//! Rounding is to nearest even (MODE.FP_ROUND 0; another mode stops the run); denormals are +//! kept or flushed by MODE.FP_DENORM. The transcendentals give the correctly rounded value and +//! `Wave::step` taints it with the bound the D3D rules allow. + +use super::{field, unsupported, Ctx, Flip, Stop, Wave}; +use crate::gpu::rdna2::Decoded; + +pub(super) fn is_float(name: &str) -> bool { + FLOAT.contains(&name) +} + +const FLOAT: &[&str] = &[ + "V_ADD_F32", "V_SUB_F32", "V_SUBREV_F32", "V_MUL_F32", "V_MUL_LEGACY_F32", "V_MIN_F32", "V_MAX_F32", "V_FMA_F32", "V_FMAC_F32", + "V_FMA_LEGACY_F32", "V_FMAC_LEGACY_F32", "V_MAD_F32", "V_MAC_F32", "V_MADAK_F32", "V_MADMK_F32", "V_FMAAK_F32", "V_FMAMK_F32", + "V_MIN3_F32", "V_MAX3_F32", "V_MED3_F32", "V_LDEXP_F32", "V_FLOOR_F32", "V_CEIL_F32", "V_TRUNC_F32", "V_RNDNE_F32", "V_FRACT_F32", + "V_RCP_F32", "V_RCP_IFLAG_F32", "V_RSQ_F32", "V_SQRT_F32", "V_EXP_F32", "V_LOG_F32", "V_SIN_F32", "V_COS_F32", "V_CVT_F32_I32", + "V_CVT_F32_U32", "V_CVT_I32_F32", "V_CVT_U32_F32", "V_CVT_FLR_I32_F32", "V_CVT_RPI_I32_F32", "V_CVT_F32_UBYTE0", "V_CVT_F32_UBYTE1", + "V_CVT_F32_UBYTE2", "V_CVT_F32_UBYTE3", "V_CVT_F16_F32", "V_CVT_F32_F16", "V_CVT_PKRTZ_F16_F32", "V_PACK_B32_F16", "V_CVT_PK_U8_F32", +]; + +/// Which sources are floats (and so take ABS and NEG). +pub(super) fn float_srcs(name: &str) -> u8 { + match name { + // its VOP3 form takes ABS and NEG on the two values it selects from + "V_CNDMASK_B32" => 3, + _ if !is_float(name) => 0, + "V_CVT_F32_I32" | "V_CVT_F32_U32" | "V_CVT_F32_UBYTE0" | "V_CVT_F32_UBYTE1" | "V_CVT_F32_UBYTE2" | "V_CVT_F32_UBYTE3" => 0, + "V_LDEXP_F32" | "V_CVT_PK_U8_F32" => 1, + "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16" => 3, + _ => 7, + } +} + +/// Whether the result is an f32 (and so takes OMOD and CLAMP). +pub(super) fn float_dst(name: &str) -> bool { + !matches!(name, "V_CVT_I32_F32" | "V_CVT_U32_F32" | "V_CVT_FLR_I32_F32" | "V_CVT_RPI_I32_F32" | "V_CVT_PK_U8_F32" | "V_CVT_F16_F32" | "V_CVT_PKRTZ_F16_F32" | "V_PACK_B32_F16") +} + +/// Whether the sources are f16 (ABS and NEG act on bit 15). +pub(super) fn f16_srcs(name: &str) -> bool { + matches!(name, "V_CVT_F32_F16" | "V_PACK_B32_F16") +} + +pub(crate) fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = (u32::from(h >> 15), u32::from(h >> 10 & 31), u32::from(h & 0x3FF)); + let mag = match e { + 0 => m as f32 * (2f32).powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 to f16, rounded to nearest even (`rtz`: toward zero). +pub(crate) fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let b = x.to_bits(); + let s = ((b >> 16) & 0x8000) as u16; + let a = x.abs(); + if a.is_nan() { + return s | 0x7E00; + } + if a.is_infinite() { + return s | 0x7C00; + } + // the value in units of the f16 grid at its exponent, exactly in f64 + let a = f64::from(a); + let e = if a == 0.0 { -24 } else { (a.log2().floor() as i32).max(-14) - 10 }; + let q = a / 2f64.powi(e); + let mut n = if rtz { q.trunc() } else { q.round_ties_even() }; + let mut e = e; + if n >= 2048.0 { + n /= 2.0; + e += 1; + } + if e + 10 > 15 || (n * 2f64.powi(e)) >= 65536.0 { + return if rtz { s | 0x7BFF } else { s | 0x7C00 }; + } + let n = n as u32; + if n < 1024 { + return s | n as u16; + } + s | (((e + 10 + 15) as u32) << 10 | (n & 0x3FF)) as u16 +} + +fn nan_or(a: f32, b: f32, f: impl Fn(f32, f32) -> f32) -> f32 { + if a.is_nan() { b } else if b.is_nan() { a } else { f(a, b) } +} + +fn min(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a < b { a } else { b }) +} + +fn max(a: f32, b: f32) -> f32 { + nan_or(a, b, |a, b| if a > b { a } else { b }) +} + +fn round_ok(d: &Decoded, mode: u32) -> Result<(), Stop> { + if mode & 3 != 0 { Err(unsupported(d)) } else { Ok(()) } +} + +/// MODE.FP_DENORM for f32: 3 keeps denormals, 0 flushes them in and out. +fn flush(d: &Decoded, mode: u32, x: f32) -> Result<f32, Stop> { + match mode >> 4 & 3 { + 3 => Ok(x), + 0 if x.is_subnormal() => Ok(0.0f32.copysign(x)), + 0 => Ok(x), + _ => Err(unsupported(d)), + } +} + +/// A float operation of one lane, or None when `name` is not one. +pub(super) fn eval(d: &Decoded, name: &str, src: [u32; 3], mode: u32, _lane: usize) -> Result<Option<u32>, Stop> { + if !is_float(name) { + return Ok(None); + } + round_ok(d, mode)?; + let fs = float_srcs(name); + let mut x = [0f32; 3]; + for i in 0..3 { + x[i] = if fs >> i & 1 == 1 && !f16_srcs(name) { flush(d, mode, f32::from_bits(src[i]))? } else { f32::from_bits(src[i]) }; + } + let [a, b, c] = x; + let i = |v: f32| v.to_bits(); + let legacy = |a: f32, b: f32| if a == 0.0 || b == 0.0 { 0.0 } else { a * b }; + let to_i32 = |v: f32| if v.is_nan() { 0 } else { v.clamp(i32::MIN as f32, i32::MAX as f32) as i32 as u32 }; + let r = match name { + "V_ADD_F32" => i(a + b), + "V_SUB_F32" => i(a - b), + "V_SUBREV_F32" => i(b - a), + "V_MUL_F32" => i(a * b), + "V_MUL_LEGACY_F32" => i(legacy(a, b)), + "V_MIN_F32" => i(min(a, b)), + "V_MAX_F32" => i(max(a, b)), + "V_FMA_F32" | "V_FMAC_F32" | "V_FMAAK_F32" | "V_FMAMK_F32" => i(a.mul_add(b, c)), + "V_FMA_LEGACY_F32" | "V_FMAC_LEGACY_F32" => i(if a == 0.0 || b == 0.0 { 0.0 + c } else { a.mul_add(b, c) }), + // not fused: the product is rounded first + "V_MAD_F32" | "V_MAC_F32" | "V_MADAK_F32" | "V_MADMK_F32" => i(flush(d, mode, a * b)? + c), + "V_MIN3_F32" => i(min(min(a, b), c)), + "V_MAX3_F32" => i(max(max(a, b), c)), + "V_MED3_F32" => { + if a.is_nan() || b.is_nan() || c.is_nan() { + i(min(min(a, b), c)) + } else { + i(max(a, b).min(max(min(a, b), c))) + } + } + "V_LDEXP_F32" => i((f64::from(a) * 2f64.powi((src[1] as i32).clamp(-400, 400))) as f32), + "V_FLOOR_F32" => i(a.floor()), + "V_CEIL_F32" => i(a.ceil()), + "V_TRUNC_F32" => i(a.trunc()), + "V_RNDNE_F32" => i(a.round_ties_even()), + "V_FRACT_F32" => { + if a.is_infinite() { + i(f32::NAN) + } else { + i((a - a.floor()).min(f32::from_bits(0x3F7F_FFFF))) + } + } + "V_RCP_F32" | "V_RCP_IFLAG_F32" => i((1.0 / f64::from(a)) as f32), ~~~~ --- Fixed in `float.rs`: V_RCP_F32, V_RSQ_F32 and V_SQRT_F32 flush denormal inputs and results whatever MODE says (12.8). In `rcp_rsq_and_sqrt_flush_denormals_whatever_the_mode`, RCP(0x00400000) gives +inf, RCP(2^127) 0, SQRT of a denormal 0 and RSQ of a negative denormal -inf. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:38Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 28

@@ -0,0 +1,458 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept.
+pub(crate) const MODE: u32 = 0xF0;

Changed in float.rs and mod.rs: OMOD is ignored when f32 output denormals are on or IEEE is set (6.2), and CLAMP gives 0 for a NaN only with DX10_CLAMP set (3.5, Table 4). MODE starts at 0x1F0 (f32 and f16 denormals kept, DX10_CLAMP set, IEEE clear). It stays a constant because neither the kernel ABI nor CsInterface carries an RSRC1, and XCL's forms assume one fixed mode. A float instruction stops on MODE bits above IEEE and on an f32 rounding other than to nearest, and an f16 one on a non-default f16 rounding or flushed f16 denormals. "exact float rules" now starts with s_denorm_mode 0xC (f32 denormals flushed), so its OMOD is still checked where it applies. Tests: omod_is_off_with_output_denormals_or_ieee_and_clamp_keeps_nan_without_dx10_clamp, a_float_instruction_stops_on_mode_bits_the_reference_does_not_model.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776708806 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776708806). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:38Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 28 ~~~~diff @@ -0,0 +1,458 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start: round to nearest even, f32 and f16/f64 denormals kept. +pub(crate) const MODE: u32 = 0xF0; ~~~~ --- Changed in `float.rs` and `mod.rs`: OMOD is ignored when f32 output denormals are on or IEEE is set (6.2), and CLAMP gives 0 for a NaN only with DX10_CLAMP set (3.5, Table 4). MODE starts at 0x1F0 (f32 and f16 denormals kept, DX10_CLAMP set, IEEE clear). It stays a constant because neither the kernel ABI nor CsInterface carries an RSRC1, and XCL's forms assume one fixed mode. A float instruction stops on MODE bits above IEEE and on an f32 rounding other than to nearest, and an f16 one on a non-default f16 rounding or flushed f16 denormals. "exact float rules" now starts with `s_denorm_mode 0xC` (f32 denormals flushed), so its OMOD is still checked where it applies. Tests: `omod_is_off_with_output_denormals_or_ieee_and_clamp_keeps_nan_without_dx10_clamp`, `a_float_instruction_stops_on_mode_bits_the_reference_does_not_model`. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:40Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 164

@@ -0,0 +1,496 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None)
+    } else if name.starts_with("S_BUFFER_LOAD_DWORD") {
+        let v = [w.s[base], w.s[base + 1], w.s[base + 2]];
+        let stride = u64::from(v[1] >> 16 & 0x3FFF);
+        let records = u64::from(v[2]);
+        let limit = if stride == 0 { records } else { records * stride };
+        (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit)))
+    } else {
+        return Err(unsupported(d));
+    };
+    for k in 0..n {
+        let (x, t) = match limit {
+            Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0),
+            Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?,
+            None => load(d, cx, (addr & !3) + 4 * k as u64)?,
+        };
+        w.s[dst + k] = x;
+        w.st[dst + k] = t;
+    }
+    Ok(())
+}
+
+/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled.
+#[derive(Clone, Copy, PartialEq)]
+enum Kind {
+    Uint,
+    Sint,
+    Float,
+    Unorm,
+}
+
+fn format(code: u32) -> Option<(usize, u32, Kind)> {
+    Some(match code {
+        20 => (1, 32, Kind::Uint),
+        21 => (1, 32, Kind::Sint),
+        22 => (1, 32, Kind::Float),
+        56 => (4, 8, Kind::Unorm),
+        60 => (4, 8, Kind::Uint),
+        62 => (2, 32, Kind::Uint),
+        63 => (2, 32, Kind::Sint),
+        64 => (2, 32, Kind::Float),
+        72 => (3, 32, Kind::Uint),
+        73 => (3, 32, Kind::Sint),
+        74 => (3, 32, Kind::Float),
+        75 => (4, 32, Kind::Uint),
+        76 => (4, 32, Kind::Sint),
+        77 => (4, 32, Kind::Float),
+        _ => return None,
+    })
+}
+
+/// The 32-bit buffer and global atomics modelled.
+const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"];
+
+/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps).
+fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> {
+    Ok(match op {
+        "ADD" => old.wrapping_add(x),
+        "SUB" => old.wrapping_sub(x),
+        "RSUB" => x.wrapping_sub(old),
+        "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32,
+        "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32,
+        "UMIN" | "MIN_U32" => old.min(x),
+        "UMAX" | "MAX_U32" => old.max(x),
+        "AND" | "AND_B32" => old & x,
+        "OR" | "OR_B32" => old | x,
+        "XOR" | "XOR_B32" => old ^ x,
+        "SWAP" | "WRXCHG" => x,
+        "INC" => if old >= x { 0 } else { old + 1 },
+        "DEC" => if old == 0 || old > x { x } else { old - 1 },
+        "CMPSWAP" => if old == cmp { x } else { old },
+        _ => return Err(unsupported(d)),
+    })
+}
+
+/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw
+/// buffer (stride 0) is out of range past num_records bytes, a structured one past
+/// num_records elements; out of range reads 0 and writes nothing.
+pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let f = |x: &str| field(d, x);
+    if f("LDS") == 1 || f("TFE") == 1 {
+        return Err(unsupported(d));
+    }
+    let r = 4 * f("SRSRC") as usize;
+    let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]];
+    let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32;
+    let stride = u64::from(v[1] >> 16 & 0x3FFF);
+    let records = u64::from(v[2]);
+    if v[3] >> 23 & 1 == 1 {
+        return Err(unsupported(d));
+    }
+    let soff = u64::from(w.scalar(d, f("SOFFSET"))?);
+    let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1);
+    let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize);
+    let op = name.trim_start_matches("T").trim_start_matches("BUFFER_");
+    // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF)
+    let fmt = if op.contains("FORMAT") {
+        if op.contains("D16") {
+            return Err(unsupported(d));
+        }
+        let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F };
+        if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" {
+            // a dst_sel other than x, y, z, w
+            return Err(unsupported(d));
+        }
+        Some(format(code).ok_or_else(|| unsupported(d))?)
+    } else {
+        None
+    };
+    let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 };
+    let exec = w.exec();
+    for l in 0..w.lanes {
+        if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 };
+        let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 };
+        let off = voff + f("OFFSET") + soff;
+        let addr = base + index * stride + off;
+        let out = |size: u64| if stride == 0 { off + size > records } else { index >= records };

Changed in mem.rs: the reference reads OOB_SELECT (word 3, bits 29:28) and follows 8.1 Table 35 and its notes. Mode 3 counts SOFFSET against num_records; dword x2/x3/x4 accesses are checked per dword; format elements and atomics are all or nothing. Mode 0 uses offset + payload > stride, which agrees with the table for aligned dwords. SWIZZLE_ENABLE stops the run. buffer_range_checks_follow_each_oob_select has one case per mode. XCL ignores OOB_SELECT and checks stride-0 buffers without SOFFSET, so it agrees with the reference in modes 1 and 3 only when SOFFSET is 0; that is for a separate pull request.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776709200 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776709200). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:40Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 164 ~~~~diff @@ -0,0 +1,496 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None) + } else if name.starts_with("S_BUFFER_LOAD_DWORD") { + let v = [w.s[base], w.s[base + 1], w.s[base + 2]]; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + let limit = if stride == 0 { records } else { records * stride }; + (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit))) + } else { + return Err(unsupported(d)); + }; + for k in 0..n { + let (x, t) = match limit { + Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0), + Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?, + None => load(d, cx, (addr & !3) + 4 * k as u64)?, + }; + w.s[dst + k] = x; + w.st[dst + k] = t; + } + Ok(()) +} + +/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Uint, + Sint, + Float, + Unorm, +} + +fn format(code: u32) -> Option<(usize, u32, Kind)> { + Some(match code { + 20 => (1, 32, Kind::Uint), + 21 => (1, 32, Kind::Sint), + 22 => (1, 32, Kind::Float), + 56 => (4, 8, Kind::Unorm), + 60 => (4, 8, Kind::Uint), + 62 => (2, 32, Kind::Uint), + 63 => (2, 32, Kind::Sint), + 64 => (2, 32, Kind::Float), + 72 => (3, 32, Kind::Uint), + 73 => (3, 32, Kind::Sint), + 74 => (3, 32, Kind::Float), + 75 => (4, 32, Kind::Uint), + 76 => (4, 32, Kind::Sint), + 77 => (4, 32, Kind::Float), + _ => return None, + }) +} + +/// The 32-bit buffer and global atomics modelled. +const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"]; + +/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps). +fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> { + Ok(match op { + "ADD" => old.wrapping_add(x), + "SUB" => old.wrapping_sub(x), + "RSUB" => x.wrapping_sub(old), + "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32, + "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32, + "UMIN" | "MIN_U32" => old.min(x), + "UMAX" | "MAX_U32" => old.max(x), + "AND" | "AND_B32" => old & x, + "OR" | "OR_B32" => old | x, + "XOR" | "XOR_B32" => old ^ x, + "SWAP" | "WRXCHG" => x, + "INC" => if old >= x { 0 } else { old + 1 }, + "DEC" => if old == 0 || old > x { x } else { old - 1 }, + "CMPSWAP" => if old == cmp { x } else { old }, + _ => return Err(unsupported(d)), + }) +} + +/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw +/// buffer (stride 0) is out of range past num_records bytes, a structured one past +/// num_records elements; out of range reads 0 and writes nothing. +pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let f = |x: &str| field(d, x); + if f("LDS") == 1 || f("TFE") == 1 { + return Err(unsupported(d)); + } + let r = 4 * f("SRSRC") as usize; + let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]]; + let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + if v[3] >> 23 & 1 == 1 { + return Err(unsupported(d)); + } + let soff = u64::from(w.scalar(d, f("SOFFSET"))?); + let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1); + let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize); + let op = name.trim_start_matches("T").trim_start_matches("BUFFER_"); + // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF) + let fmt = if op.contains("FORMAT") { + if op.contains("D16") { + return Err(unsupported(d)); + } + let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F }; + if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" { + // a dst_sel other than x, y, z, w + return Err(unsupported(d)); + } + Some(format(code).ok_or_else(|| unsupported(d))?) + } else { + None + }; + let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 }; + let exec = w.exec(); + for l in 0..w.lanes { + if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored { + continue; + } + let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 }; + let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 }; + let off = voff + f("OFFSET") + soff; + let addr = base + index * stride + off; + let out = |size: u64| if stride == 0 { off + size > records } else { index >= records }; ~~~~ --- Changed in `mem.rs`: the reference reads OOB_SELECT (word 3, bits 29:28) and follows 8.1 Table 35 and its notes. Mode 3 counts SOFFSET against num_records; dword x2/x3/x4 accesses are checked per dword; format elements and atomics are all or nothing. Mode 0 uses offset + payload > stride, which agrees with the table for aligned dwords. SWIZZLE_ENABLE stops the run. `buffer_range_checks_follow_each_oob_select` has one case per mode. XCL ignores OOB_SELECT and checks stride-0 buffers without SOFFSET, so it agrees with the reference in modes 1 and 3 only when SOFFSET is 0; that is for a separate pull request. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:42 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:42Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 179

@@ -0,0 +1,496 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None)
+    } else if name.starts_with("S_BUFFER_LOAD_DWORD") {
+        let v = [w.s[base], w.s[base + 1], w.s[base + 2]];
+        let stride = u64::from(v[1] >> 16 & 0x3FFF);
+        let records = u64::from(v[2]);
+        let limit = if stride == 0 { records } else { records * stride };
+        (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit)))
+    } else {
+        return Err(unsupported(d));
+    };
+    for k in 0..n {
+        let (x, t) = match limit {
+            Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0),
+            Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?,
+            None => load(d, cx, (addr & !3) + 4 * k as u64)?,
+        };
+        w.s[dst + k] = x;
+        w.st[dst + k] = t;
+    }
+    Ok(())
+}
+
+/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled.
+#[derive(Clone, Copy, PartialEq)]
+enum Kind {
+    Uint,
+    Sint,
+    Float,
+    Unorm,
+}
+
+fn format(code: u32) -> Option<(usize, u32, Kind)> {
+    Some(match code {
+        20 => (1, 32, Kind::Uint),
+        21 => (1, 32, Kind::Sint),
+        22 => (1, 32, Kind::Float),
+        56 => (4, 8, Kind::Unorm),
+        60 => (4, 8, Kind::Uint),
+        62 => (2, 32, Kind::Uint),
+        63 => (2, 32, Kind::Sint),
+        64 => (2, 32, Kind::Float),
+        72 => (3, 32, Kind::Uint),
+        73 => (3, 32, Kind::Sint),
+        74 => (3, 32, Kind::Float),
+        75 => (4, 32, Kind::Uint),
+        76 => (4, 32, Kind::Sint),
+        77 => (4, 32, Kind::Float),
+        _ => return None,
+    })
+}
+
+/// The 32-bit buffer and global atomics modelled.
+const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"];
+
+/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps).
+fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> {
+    Ok(match op {
+        "ADD" => old.wrapping_add(x),
+        "SUB" => old.wrapping_sub(x),
+        "RSUB" => x.wrapping_sub(old),
+        "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32,
+        "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32,
+        "UMIN" | "MIN_U32" => old.min(x),
+        "UMAX" | "MAX_U32" => old.max(x),
+        "AND" | "AND_B32" => old & x,
+        "OR" | "OR_B32" => old | x,
+        "XOR" | "XOR_B32" => old ^ x,
+        "SWAP" | "WRXCHG" => x,
+        "INC" => if old >= x { 0 } else { old + 1 },
+        "DEC" => if old == 0 || old > x { x } else { old - 1 },
+        "CMPSWAP" => if old == cmp { x } else { old },
+        _ => return Err(unsupported(d)),
+    })
+}
+
+/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw
+/// buffer (stride 0) is out of range past num_records bytes, a structured one past
+/// num_records elements; out of range reads 0 and writes nothing.
+pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let f = |x: &str| field(d, x);
+    if f("LDS") == 1 || f("TFE") == 1 {
+        return Err(unsupported(d));
+    }
+    let r = 4 * f("SRSRC") as usize;
+    let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]];
+    let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32;
+    let stride = u64::from(v[1] >> 16 & 0x3FFF);
+    let records = u64::from(v[2]);
+    if v[3] >> 23 & 1 == 1 {
+        return Err(unsupported(d));
+    }
+    let soff = u64::from(w.scalar(d, f("SOFFSET"))?);
+    let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1);
+    let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize);
+    let op = name.trim_start_matches("T").trim_start_matches("BUFFER_");
+    // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF)
+    let fmt = if op.contains("FORMAT") {
+        if op.contains("D16") {
+            return Err(unsupported(d));
+        }
+        let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F };
+        if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" {
+            // a dst_sel other than x, y, z, w
+            return Err(unsupported(d));
+        }
+        Some(format(code).ok_or_else(|| unsupported(d))?)
+    } else {
+        None
+    };
+    let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 };
+    let exec = w.exec();
+    for l in 0..w.lanes {
+        if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored {
+            continue;
+        }
+        let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 };
+        let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 };
+        let off = voff + f("OFFSET") + soff;
+        let addr = base + index * stride + off;
+        let out = |size: u64| if stride == 0 { off + size > records } else { index >= records };
+        let tin = w.vt[l][vdata..(vdata + 4).min(256)].iter().copied().max().unwrap_or(0);
+        if let Some((n, bits, kind)) = fmt {
+            let bytes = n as u64 * u64::from(bits) / 8;
+            if op.starts_with("LOAD") {
+                let mut c = [0u32, 0, 0, if kind == Kind::Float || kind == Kind::Unorm { 1.0f32.to_bits() } else { 1 }];
+                let mut t = 0;
+                if !out(bytes) {
+                    for k in 0..n {
+                        if bits == 32 {
+                            let (x, tt) = load(d, cx, addr + 4 * k as u64)?;
+                            (c[k], t) = (x, t.max(tt));
+                        } else {
+                            let (x, tt) = load(d, cx, addr & !3)?;
+                            t = t.max(tt);
+                            let byte = x >> (8 * (addr & 3) + 8 * k as u64) & 0xFF;

Fixed in mem.rs: each byte of an 8-bit element is read from its own address, across dwords, and an out-of-range format load returns 0 in W (8.1, note 1). A dst_sel other than x, y, z, w still stops the run, so SEL_1 does not arise. an_8_bit_format_element_reads_its_bytes_across_dwords loads at offset 2 (it panicked in debug before), and the OOB test checks W = 0.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776709551 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776709551). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:42Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 179 ~~~~diff @@ -0,0 +1,496 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + (w.pair(base).wrapping_add(imm).wrapping_add(soff) & 0xFFFF_FFFF_FFFF, None) + } else if name.starts_with("S_BUFFER_LOAD_DWORD") { + let v = [w.s[base], w.s[base + 1], w.s[base + 2]]; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + let limit = if stride == 0 { records } else { records * stride }; + (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit))) + } else { + return Err(unsupported(d)); + }; + for k in 0..n { + let (x, t) = match limit { + Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0), + Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?, + None => load(d, cx, (addr & !3) + 4 * k as u64)?, + }; + w.s[dst + k] = x; + w.st[dst + k] = t; + } + Ok(()) +} + +/// A buffer format: (channels, bits a channel, kind) for the gfx10 unified formats modelled. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Uint, + Sint, + Float, + Unorm, +} + +fn format(code: u32) -> Option<(usize, u32, Kind)> { + Some(match code { + 20 => (1, 32, Kind::Uint), + 21 => (1, 32, Kind::Sint), + 22 => (1, 32, Kind::Float), + 56 => (4, 8, Kind::Unorm), + 60 => (4, 8, Kind::Uint), + 62 => (2, 32, Kind::Uint), + 63 => (2, 32, Kind::Sint), + 64 => (2, 32, Kind::Float), + 72 => (3, 32, Kind::Uint), + 73 => (3, 32, Kind::Sint), + 74 => (3, 32, Kind::Float), + 75 => (4, 32, Kind::Uint), + 76 => (4, 32, Kind::Sint), + 77 => (4, 32, Kind::Float), + _ => return None, + }) +} + +/// The 32-bit buffer and global atomics modelled. +const ATOMICS: [&str; 13] = ["ADD", "SUB", "SMIN", "SMAX", "UMIN", "UMAX", "AND", "OR", "XOR", "SWAP", "CMPSWAP", "INC", "DEC"]; + +/// The 32-bit result of an atomic on `old` with `x` (and `cmp` for the compare-swaps). +fn atomic(d: &Decoded, op: &str, old: u32, x: u32, cmp: u32) -> Result<u32, Stop> { + Ok(match op { + "ADD" => old.wrapping_add(x), + "SUB" => old.wrapping_sub(x), + "RSUB" => x.wrapping_sub(old), + "SMIN" | "MIN_I32" => (old as i32).min(x as i32) as u32, + "SMAX" | "MAX_I32" => (old as i32).max(x as i32) as u32, + "UMIN" | "MIN_U32" => old.min(x), + "UMAX" | "MAX_U32" => old.max(x), + "AND" | "AND_B32" => old & x, + "OR" | "OR_B32" => old | x, + "XOR" | "XOR_B32" => old ^ x, + "SWAP" | "WRXCHG" => x, + "INC" => if old >= x { 0 } else { old + 1 }, + "DEC" => if old == 0 || old > x { x } else { old - 1 }, + "CMPSWAP" => if old == cmp { x } else { old }, + _ => return Err(unsupported(d)), + }) +} + +/// buffer_* and tbuffer_* (MUBUF, MTBUF): address = base + index · stride + offset. A raw +/// buffer (stride 0) is out of range past num_records bytes, a structured one past +/// num_records elements; out of range reads 0 and writes nothing. +pub(super) fn buffer(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let f = |x: &str| field(d, x); + if f("LDS") == 1 || f("TFE") == 1 { + return Err(unsupported(d)); + } + let r = 4 * f("SRSRC") as usize; + let v = [w.s[r], w.s[r + 1], w.s[r + 2], w.s[r + 3]]; + let base = u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + if v[3] >> 23 & 1 == 1 { + return Err(unsupported(d)); + } + let soff = u64::from(w.scalar(d, f("SOFFSET"))?); + let (idxen, offen) = (f("IDXEN") == 1, f("OFFEN") == 1); + let (vaddr, vdata) = (f("VADDR") as usize, f("VDATA") as usize); + let op = name.trim_start_matches("T").trim_start_matches("BUFFER_"); + // the format of a FORMAT access: the V#'s, or the instruction's (MTBUF) + let fmt = if op.contains("FORMAT") { + if op.contains("D16") { + return Err(unsupported(d)); + } + let code = if d.enc.name == "ENC_MTBUF" { f("FORMAT") as u32 } else { v[3] >> 12 & 0x7F }; + if v[3] & 0xFFF != 0xFAC && d.enc.name == "ENC_MUBUF" { + // a dst_sel other than x, y, z, w + return Err(unsupported(d)); + } + Some(format(code).ok_or_else(|| unsupported(d))?) + } else { + None + }; + let comps = if fmt.is_some() { ["_XYZW", "_XYZ", "_XY", "_X"].iter().find(|s| op.ends_with(*s)).map_or(0, |s| s.len() - 1) } else { 0 }; + let exec = w.exec(); + for l in 0..w.lanes { + if exec >> l & 1 == 0 && cx.flip != Flip::ExecIgnored { + continue; + } + let index = if idxen { u64::from(w.v[l][vaddr]) } else { 0 }; + let voff = if offen { u64::from(w.v[l][vaddr + usize::from(idxen)]) } else { 0 }; + let off = voff + f("OFFSET") + soff; + let addr = base + index * stride + off; + let out = |size: u64| if stride == 0 { off + size > records } else { index >= records }; + let tin = w.vt[l][vdata..(vdata + 4).min(256)].iter().copied().max().unwrap_or(0); + if let Some((n, bits, kind)) = fmt { + let bytes = n as u64 * u64::from(bits) / 8; + if op.starts_with("LOAD") { + let mut c = [0u32, 0, 0, if kind == Kind::Float || kind == Kind::Unorm { 1.0f32.to_bits() } else { 1 }]; + let mut t = 0; + if !out(bytes) { + for k in 0..n { + if bits == 32 { + let (x, tt) = load(d, cx, addr + 4 * k as u64)?; + (c[k], t) = (x, t.max(tt)); + } else { + let (x, tt) = load(d, cx, addr & !3)?; + t = t.max(tt); + let byte = x >> (8 * (addr & 3) + 8 * k as u64) & 0xFF; ~~~~ --- Fixed in `mem.rs`: each byte of an 8-bit element is read from its own address, across dwords, and an out-of-range format load returns 0 in W (8.1, note 1). A dst_sel other than x, y, z, w still stops the run, so SEL_1 does not arise. `an_8_bit_format_element_reads_its_bytes_across_dwords` loads at offset 2 (it panicked in debug before), and the OOB test checks W = 0. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:44Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/tests.rs; line 452

@@ -0,0 +1,585 @@
+use super::asm::{asm, end, i, lit, I, TO, V};
+use super::*;
+use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture};
+
+const EXEC: u64 = 126;
+const VCC: u64 = 106;
+
+fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> {
+    let mut l = list.to_vec();
+    l.push(end());
+    run_kernel(&asm(&l), true, st, mem, &[], &[], flip)
+}
+
+/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes.
+fn lanes_state() -> KernelState {
+    let mut st = KernelState::default();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+    }
+    st
+}
+
+fn kernel(list: &[I]) -> Run {
+    kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn saveexec_families_save_the_old_exec_and_set_scc() {
+    // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]),
+        i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]),
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]),
+    ]);
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC");
+    assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves");
+    assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0");
+    // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC
+    assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000);
+    assert_eq!(pair(26), pair(24));
+    assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC");
+    assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on");
+}
+
+#[test]
+fn branches_see_the_whole_wave_masks() {
+    // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken
+    let r = kernel(&[
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8),
+        i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]),
+        i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]),
+        i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2));
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40));
+}
+
+#[test]
+fn salu_carries_overflows_and_fields() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF),
+        i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]),
+        i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF),
+        i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]),
+        lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]),
+        i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]),
+        i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]),
+        i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32");
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow");
+    assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX));
+    assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31));
+    assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed");
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE));
+}
+
+#[test]
+fn an_instruction_outside_the_model_stops_the_run() {
+    let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]);
+    match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) {
+        Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"),
+        other => panic!("{:?}", other.map(|_| ())),
+    }
+    let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand");
+    let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_))));
+}
+
+/// One encoding of every instruction the reference models.
+fn modelled_words() -> Vec<Vec<u8>> {
+    const ENCODINGS: [&str; 17] = [
+        "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS",
+        "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL",
+    ];
+    let mut words = Vec::new();
+    for inst in rdna2::all_instructions() {
+        for name in ENCODINGS {
+            let enc = rdna2::encoding(name).unwrap();
+            let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue };
+            if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) {
+                words.push(code);
+            }
+        }
+    }
+    words
+}
+
+/// The decoder is checked against LLVM's on every instruction the reference models:
+/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs
+/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names
+/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input).
+#[test]
+fn modelled_instructions_decode_as_llvm_disassembles_them() {
+    use std::io::Write;
+    let words = modelled_words();
+    let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect();
+    if let Ok(path) = std::env::var("XCL_LLVM_WORDS") {
+        std::fs::write(path, &input).unwrap();
+    }
+    let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") {
+        std::fs::read_to_string(path).unwrap()
+    } else {
+        let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into());
+        let child = std::process::Command::new(&mc)
+            .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"])
+            .stdin(std::process::Stdio::piped())
+            .stdout(std::process::Stdio::piped())
+            .stderr(std::process::Stdio::piped())
+            .spawn();
+        let Ok(mut child) = child else {
+            let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc");
+            return;
+        };
+        child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
+        String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned()
+    };
+    // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order
+    let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect();
+    assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word");
+    // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`)
+    let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy");
+    let mut bad = Vec::new();
+    for (code, t) in words.iter().zip(theirs) {
+        let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap());
+        // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have
+        let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal";
+        if norm(t) != norm(&ours) && !vop3_readfirstlane {
+            bad.push(format!("{ours} / {t}"));
+        }
+    }
+    assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len());
+    let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len());
+}
+
+/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled.
+fn modelled(code: &[u8]) -> bool {
+    let mut st = KernelState::default();
+    st.sgpr[124] = 0;
+    !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. }))
+}
+
+// ------------------------------------------------------------- vector ALU and lanes
+
+#[test]
+fn lane_reads_and_writes_use_all_64_lanes() {
+    let r = kernel(&[
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234),
+        i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]),
+    ]);
+    assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40");
+    assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33");
+    assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63");
+    assert_eq!(r.vgpr[31][2], 0, "and nowhere else");
+    assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half");
+    assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0");
+}
+
+#[test]
+fn mbcnt_counts_the_lanes_below_in_both_halves() {
+    let r = kernel(&[
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]),
+        i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]),
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]),
+    ]);
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][2], l as u32, "lane {l}");
+        assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone");
+    }
+}
+
+#[test]
+fn carries_and_compares_write_a_bit_per_lane_of_the_pair() {
+    let mut st = lanes_state();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[4] = if l % 3 == 0 { u32::MAX } else { 7 };
+    }
+    let r = kernel_with(
+        &[
+            i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]),
+            i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]),
+            lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]),
+            lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l);
+    assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword");
+    assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry");
+    assert_eq!(pair(24), !0u64 << 36);
+    assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC");
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0));
+        assert_eq!(r.vgpr[l][7], u32::from(l > 35));
+        assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value");
+    }
+}
+
+#[test]
+fn integer_valu_known_answers() {
+    let mut st = lanes_state();
+    st.vgpr[0][4] = 0x8000_0001;
+    st.vgpr[0][5] = 0x0000_0003;
+    let r = kernel_with(
+        &[
+            i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]),
+            i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]),
+            i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]),
+            i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]),
+            i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let v = &r.vgpr[0];
+    assert_eq!(v[10], 1);
+    assert_eq!(v[11], 0xFFFF_FFFE);
+    assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12");
+    assert_eq!(v[13], u32::MAX, "bit 31 sign-extended");
+    assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign");
+    assert_eq!(v[14], 0xC000_0000);
+    assert_eq!(v[15], 1);
+    assert_eq!((v[16], v[17]), (2, 7));
+    assert_eq!((v[18], v[19]), (4, 5));
+}
+
+#[test]
+fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98),
+        i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+        i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+    ]);
+    for l in 0..64u32 {
+        assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}");
+        assert_eq!(r.vgpr[l as usize][3], l, "lane {l}");
+    }
+}
+
+#[test]
+fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() {
+    let mut st = lanes_state();
+    for r in st.vgpr.iter_mut() {
+        r[5] = 0xAAAA;
+        r[6] = 0xBBBB;
+    }
+    // lanes 0..63 but lane 17: off
+    st.sgpr[126] = !(1 << 17);
+    let r = kernel_with(
+        &[
+            // row_mirror, bound_ctrl 1
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]),
+            // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]),
+            // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1
+            i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in 0..64usize {
+        let v = &r.vgpr[l];
+        if l == 17 {
+            assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off");
+            continue;
+        }
+        let m = (l & !15) + 15 - (l & 15);
+        assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror");
+        assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1");
+        let s = l ^ 1;
+        assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8");
+    }
+}
+
+// ------------------------------------------------------------- rules turned the wrong way
+
+/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must
+/// fail with the flipped one, or the check could not see the rule.
+fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> {
+    vec![
+        (Flip::Lane31, "v_readlane of lane 40", |flip| {
+            kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121)
+        }),
+        (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| {
+            kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip)
+                .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16))
+        }),
+        (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| {
+            let mut st = lanes_state();
+            st.sgpr[126] = 0;
+            kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 }))
+        }),
+        (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| {
+            kernel_with(
+                &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])],
+                &lanes_state(),
+                &[],
+                flip,
+            )
+            .map_or(false, |r| r.sgpr[10] == 1)
+        }),
+    ]
+}
+
+#[test]
+fn each_rule_check_fails_when_its_rule_is_flipped() {
+    for (flip, what, check) in rule_checks() {
+        assert!(check(Flip::None), "{what}: fails with the ISA's rule");
+        assert!(!check(flip), "{what}: still passes with {flip:?}");
+    }
+}
+
+// ------------------------------------------------------------- memory, LDS and groups
+
+#[test]
+fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() {
+    let mut st = lanes_state();
+    st.sgpr[126] = !(1 << 5);
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * (l as u32 + 7);
+    }
+    let r = kernel_with(
+        &[
+            // and 0x1F, xor 16
+            i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+            i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in (0..64usize).filter(|&l| l != 5) {
+        let s = l ^ 16;
+        assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle");
+        let b = (l & 32) | ((l + 7) & 31);
+        assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute");
+    }
+}
+
+#[test]
+fn memory_buffers_globals_and_lds() {
+    let mut st = lanes_state();
+    // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400
+    st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]);
+    st.sgpr[12] = 0x400;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * l as u32;
+    }
+    let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect();
+    let r = kernel_with(
+        &[
+            i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]),
+            i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]),
+            i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]),
+            i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]),
+            i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]),
+            i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]),
+            i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]),
+        ],
+        &st,
+        &mem,
+        Flip::None,
+    )
+    .unwrap();
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0");
+    for l in 0..64usize {
+        assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load");
+        assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add");
+        assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value");
+        // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l
+        assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword");
+        assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order");
+    }
+}
+
+#[test]
+fn groups_of_waves_meet_at_the_barrier_and_share_the_lds() {
+    // each thread writes LDS[t] = t + 1000, meets the group, reads LDS[t ^ 64] and stores it
+    let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+    let code = asm(&[
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]),
+        lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], 1000),
+        i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 2)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 1)], 256),
+        i("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3)]),

Added in tests.rs: s_waitcnt before the global store in the groups test, s_waitcnt_vscnt between the global store and the atomic on the same address, and a final s_waitcnt in the memory, swizzle, image and new tests.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776709865 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776709865). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:44Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/tests.rs`; line 452 ~~~~diff @@ -0,0 +1,585 @@ +use super::asm::{asm, end, i, lit, I, TO, V}; +use super::*; +use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture}; + +const EXEC: u64 = 126; +const VCC: u64 = 106; + +fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> { + let mut l = list.to_vec(); + l.push(end()); + run_kernel(&asm(&l), true, st, mem, &[], &[], flip) +} + +/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes. +fn lanes_state() -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + } + st +} + +fn kernel(list: &[I]) -> Run { + kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}")) +} + +#[test] +fn saveexec_families_save_the_old_exec_and_set_scc() { + // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39 + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]), + ]); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC"); + assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves"); + assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0"); + // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC + assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000); + assert_eq!(pair(26), pair(24)); + assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC"); + assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on"); +} + +#[test] +fn branches_see_the_whole_wave_masks() { + // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken + let r = kernel(&[ + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2)); + assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40)); +} + +#[test] +fn salu_carries_overflows_and_fields() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]), + i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF), + i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]), + lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]), + i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]), + i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]), + i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32"); + assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow"); + assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX)); + assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31)); + assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE)); +} + +#[test] +fn an_instruction_outside_the_model_stops_the_run() { + let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]); + match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) { + Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"), + other => panic!("{:?}", other.map(|_| ())), + } + let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand"); + let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_)))); +} + +/// One encoding of every instruction the reference models. +fn modelled_words() -> Vec<Vec<u8>> { + const ENCODINGS: [&str; 17] = [ + "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS", + "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL", + ]; + let mut words = Vec::new(); + for inst in rdna2::all_instructions() { + for name in ENCODINGS { + let enc = rdna2::encoding(name).unwrap(); + let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue }; + if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) { + words.push(code); + } + } + } + words +} + +/// The decoder is checked against LLVM's on every instruction the reference models: +/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs +/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names +/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input). +#[test] +fn modelled_instructions_decode_as_llvm_disassembles_them() { + use std::io::Write; + let words = modelled_words(); + let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect(); + if let Ok(path) = std::env::var("XCL_LLVM_WORDS") { + std::fs::write(path, &input).unwrap(); + } + let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") { + std::fs::read_to_string(path).unwrap() + } else { + let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into()); + let child = std::process::Command::new(&mc) + .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn(); + let Ok(mut child) = child else { + let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc"); + return; + }; + child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap(); + String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned() + }; + // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order + let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect(); + assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word"); + // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`) + let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy"); + let mut bad = Vec::new(); + for (code, t) in words.iter().zip(theirs) { + let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap()); + // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have + let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal"; + if norm(t) != norm(&ours) && !vop3_readfirstlane { + bad.push(format!("{ours} / {t}")); + } + } + assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len()); + let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len()); +} + +/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled. +fn modelled(code: &[u8]) -> bool { + let mut st = KernelState::default(); + st.sgpr[124] = 0; + !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. })) +} + +// ------------------------------------------------------------- vector ALU and lanes + +#[test] +fn lane_reads_and_writes_use_all_64_lanes() { + let r = kernel(&[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]), + ]); + assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40"); + assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33"); + assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63"); + assert_eq!(r.vgpr[31][2], 0, "and nowhere else"); + assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half"); + assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0"); +} + +#[test] +fn mbcnt_counts_the_lanes_below_in_both_halves() { + let r = kernel(&[ + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]), + ]); + for l in 0..64 { + assert_eq!(r.vgpr[l][2], l as u32, "lane {l}"); + assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone"); + } +} + +#[test] +fn carries_and_compares_write_a_bit_per_lane_of_the_pair() { + let mut st = lanes_state(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[4] = if l % 3 == 0 { u32::MAX } else { 7 }; + } + let r = kernel_with( + &[ + i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]), + i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]), + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]), + lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l); + assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword"); + assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry"); + assert_eq!(pair(24), !0u64 << 36); + assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC"); + for l in 0..64 { + assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0)); + assert_eq!(r.vgpr[l][7], u32::from(l > 35)); + assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value"); + } +} + +#[test] +fn integer_valu_known_answers() { + let mut st = lanes_state(); + st.vgpr[0][4] = 0x8000_0001; + st.vgpr[0][5] = 0x0000_0003; + let r = kernel_with( + &[ + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]), + i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]), + lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]), + i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]), + i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]), + i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let v = &r.vgpr[0]; + assert_eq!(v[10], 1); + assert_eq!(v[11], 0xFFFF_FFFE); + assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12"); + assert_eq!(v[13], u32::MAX, "bit 31 sign-extended"); + assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign"); + assert_eq!(v[14], 0xC000_0000); + assert_eq!(v[15], 1); + assert_eq!((v[16], v[17]), (2, 7)); + assert_eq!((v[18], v[19]), (4, 5)); +} + +#[test] +fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + ]); + for l in 0..64u32 { + assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}"); + assert_eq!(r.vgpr[l as usize][3], l, "lane {l}"); + } +} + +#[test] +fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() { + let mut st = lanes_state(); + for r in st.vgpr.iter_mut() { + r[5] = 0xAAAA; + r[6] = 0xBBBB; + } + // lanes 0..63 but lane 17: off + st.sgpr[126] = !(1 << 17); + let r = kernel_with( + &[ + // row_mirror, bound_ctrl 1 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]), + // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]), + // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1 + i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in 0..64usize { + let v = &r.vgpr[l]; + if l == 17 { + assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off"); + continue; + } + let m = (l & !15) + 15 - (l & 15); + assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror"); + assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1"); + let s = l ^ 1; + assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8"); + } +} + +// ------------------------------------------------------------- rules turned the wrong way + +/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must +/// fail with the flipped one, or the check could not see the rule. +fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> { + vec![ + (Flip::Lane31, "v_readlane of lane 40", |flip| { + kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121) + }), + (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| { + kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip) + .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16)) + }), + (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| { + let mut st = lanes_state(); + st.sgpr[126] = 0; + kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 })) + }), + (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| { + kernel_with( + &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])], + &lanes_state(), + &[], + flip, + ) + .map_or(false, |r| r.sgpr[10] == 1) + }), + ] +} + +#[test] +fn each_rule_check_fails_when_its_rule_is_flipped() { + for (flip, what, check) in rule_checks() { + assert!(check(Flip::None), "{what}: fails with the ISA's rule"); + assert!(!check(flip), "{what}: still passes with {flip:?}"); + } +} + +// ------------------------------------------------------------- memory, LDS and groups + +#[test] +fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() { + let mut st = lanes_state(); + st.sgpr[126] = !(1 << 5); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * (l as u32 + 7); + } + let r = kernel_with( + &[ + // and 0x1F, xor 16 + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in (0..64usize).filter(|&l| l != 5) { + let s = l ^ 16; + assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle"); + let b = (l & 32) | ((l + 7) & 31); + assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute"); + } +} + +#[test] +fn memory_buffers_globals_and_lds() { + let mut st = lanes_state(); + // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400 + st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]); + st.sgpr[12] = 0x400; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * l as u32; + } + let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect(); + let r = kernel_with( + &[ + i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]), + i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]), + i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]), + i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]), + i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]), + i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]), + ], + &st, + &mem, + Flip::None, + ) + .unwrap(); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0"); + for l in 0..64usize { + assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load"); + assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add"); + assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value"); + // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l + assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword"); + assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order"); + } +} + +#[test] +fn groups_of_waves_meet_at_the_barrier_and_share_the_lds() { + // each thread writes LDS[t] = t + 1000, meets the group, reads LDS[t ^ 64] and stores it + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let code = asm(&[ + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], 1000), + i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 2)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 1)], 256), + i("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3)]), ~~~~ --- Added in `tests.rs`: `s_waitcnt` before the global store in the groups test, `s_waitcnt_vscnt` between the global store and the atomic on the same address, and a final `s_waitcnt` in the memory, swizzle, image and new tests. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:46 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:46Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/tests.rs; line 437

@@ -0,0 +1,585 @@
+use super::asm::{asm, end, i, lit, I, TO, V};
+use super::*;
+use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture};
+
+const EXEC: u64 = 126;
+const VCC: u64 = 106;
+
+fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> {
+    let mut l = list.to_vec();
+    l.push(end());
+    run_kernel(&asm(&l), true, st, mem, &[], &[], flip)
+}
+
+/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes.
+fn lanes_state() -> KernelState {
+    let mut st = KernelState::default();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+    }
+    st
+}
+
+fn kernel(list: &[I]) -> Run {
+    kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn saveexec_families_save_the_old_exec_and_set_scc() {
+    // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]),
+        i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]),
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]),
+    ]);
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC");
+    assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves");
+    assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0");
+    // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC
+    assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000);
+    assert_eq!(pair(26), pair(24));
+    assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC");
+    assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on");
+}
+
+#[test]
+fn branches_see_the_whole_wave_masks() {
+    // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken
+    let r = kernel(&[
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8),
+        i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]),
+        i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]),
+        i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2));
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40));
+}
+
+#[test]
+fn salu_carries_overflows_and_fields() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF),
+        i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]),
+        i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF),
+        i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]),
+        lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]),
+        i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]),
+        i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]),
+        i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32");
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow");
+    assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX));
+    assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31));
+    assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed");
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE));
+}
+
+#[test]
+fn an_instruction_outside_the_model_stops_the_run() {
+    let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]);
+    match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) {
+        Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"),
+        other => panic!("{:?}", other.map(|_| ())),
+    }
+    let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand");
+    let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_))));
+}
+
+/// One encoding of every instruction the reference models.
+fn modelled_words() -> Vec<Vec<u8>> {
+    const ENCODINGS: [&str; 17] = [
+        "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS",
+        "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL",
+    ];
+    let mut words = Vec::new();
+    for inst in rdna2::all_instructions() {
+        for name in ENCODINGS {
+            let enc = rdna2::encoding(name).unwrap();
+            let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue };
+            if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) {
+                words.push(code);
+            }
+        }
+    }
+    words
+}
+
+/// The decoder is checked against LLVM's on every instruction the reference models:
+/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs
+/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names
+/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input).
+#[test]
+fn modelled_instructions_decode_as_llvm_disassembles_them() {
+    use std::io::Write;
+    let words = modelled_words();
+    let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect();
+    if let Ok(path) = std::env::var("XCL_LLVM_WORDS") {
+        std::fs::write(path, &input).unwrap();
+    }
+    let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") {
+        std::fs::read_to_string(path).unwrap()
+    } else {
+        let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into());
+        let child = std::process::Command::new(&mc)
+            .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"])
+            .stdin(std::process::Stdio::piped())
+            .stdout(std::process::Stdio::piped())
+            .stderr(std::process::Stdio::piped())
+            .spawn();
+        let Ok(mut child) = child else {
+            let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc");
+            return;
+        };
+        child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
+        String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned()
+    };
+    // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order
+    let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect();
+    assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word");
+    // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`)
+    let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy");
+    let mut bad = Vec::new();
+    for (code, t) in words.iter().zip(theirs) {
+        let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap());
+        // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have
+        let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal";
+        if norm(t) != norm(&ours) && !vop3_readfirstlane {
+            bad.push(format!("{ours} / {t}"));
+        }
+    }
+    assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len());
+    let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len());
+}
+
+/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled.
+fn modelled(code: &[u8]) -> bool {
+    let mut st = KernelState::default();
+    st.sgpr[124] = 0;
+    !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. }))
+}
+
+// ------------------------------------------------------------- vector ALU and lanes
+
+#[test]
+fn lane_reads_and_writes_use_all_64_lanes() {
+    let r = kernel(&[
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234),
+        i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+        i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]),
+    ]);
+    assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40");
+    assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33");
+    assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63");
+    assert_eq!(r.vgpr[31][2], 0, "and nowhere else");
+    assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half");
+    assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0");
+}
+
+#[test]
+fn mbcnt_counts_the_lanes_below_in_both_halves() {
+    let r = kernel(&[
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]),
+        i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]),
+        i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]),
+    ]);
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][2], l as u32, "lane {l}");
+        assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone");
+    }
+}
+
+#[test]
+fn carries_and_compares_write_a_bit_per_lane_of_the_pair() {
+    let mut st = lanes_state();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[4] = if l % 3 == 0 { u32::MAX } else { 7 };
+    }
+    let r = kernel_with(
+        &[
+            i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]),
+            i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]),
+            lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]),
+            lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l);
+    assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword");
+    assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry");
+    assert_eq!(pair(24), !0u64 << 36);
+    assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC");
+    for l in 0..64 {
+        assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0));
+        assert_eq!(r.vgpr[l][7], u32::from(l > 35));
+        assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value");
+    }
+}
+
+#[test]
+fn integer_valu_known_answers() {
+    let mut st = lanes_state();
+    st.vgpr[0][4] = 0x8000_0001;
+    st.vgpr[0][5] = 0x0000_0003;
+    let r = kernel_with(
+        &[
+            i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]),
+            lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]),
+            i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]),
+            i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]),
+            i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]),
+            i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]),
+            i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    let v = &r.vgpr[0];
+    assert_eq!(v[10], 1);
+    assert_eq!(v[11], 0xFFFF_FFFE);
+    assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12");
+    assert_eq!(v[13], u32::MAX, "bit 31 sign-extended");
+    assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign");
+    assert_eq!(v[14], 0xC000_0000);
+    assert_eq!(v[15], 1);
+    assert_eq!((v[16], v[17]), (2, 7));
+    assert_eq!((v[18], v[19]), (4, 5));
+}
+
+#[test]
+fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98),
+        i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+        i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]),
+    ]);
+    for l in 0..64u32 {
+        assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}");
+        assert_eq!(r.vgpr[l as usize][3], l, "lane {l}");
+    }
+}
+
+#[test]
+fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() {
+    let mut st = lanes_state();
+    for r in st.vgpr.iter_mut() {
+        r[5] = 0xAAAA;
+        r[6] = 0xBBBB;
+    }
+    // lanes 0..63 but lane 17: off
+    st.sgpr[126] = !(1 << 17);
+    let r = kernel_with(
+        &[
+            // row_mirror, bound_ctrl 1
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]),
+            // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5
+            i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]),
+            // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1
+            i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in 0..64usize {
+        let v = &r.vgpr[l];
+        if l == 17 {
+            assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off");
+            continue;
+        }
+        let m = (l & !15) + 15 - (l & 15);
+        assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror");
+        assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1");
+        let s = l ^ 1;
+        assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8");
+    }
+}
+
+// ------------------------------------------------------------- rules turned the wrong way
+
+/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must
+/// fail with the flipped one, or the check could not see the rule.
+fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> {
+    vec![
+        (Flip::Lane31, "v_readlane of lane 40", |flip| {
+            kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121)
+        }),
+        (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| {
+            kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip)
+                .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16))
+        }),
+        (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| {
+            let mut st = lanes_state();
+            st.sgpr[126] = 0;
+            kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 }))
+        }),
+        (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| {
+            kernel_with(
+                &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])],
+                &lanes_state(),
+                &[],
+                flip,
+            )
+            .map_or(false, |r| r.sgpr[10] == 1)
+        }),
+    ]
+}
+
+#[test]
+fn each_rule_check_fails_when_its_rule_is_flipped() {
+    for (flip, what, check) in rule_checks() {
+        assert!(check(Flip::None), "{what}: fails with the ISA's rule");
+        assert!(!check(flip), "{what}: still passes with {flip:?}");
+    }
+}
+
+// ------------------------------------------------------------- memory, LDS and groups
+
+#[test]
+fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() {
+    let mut st = lanes_state();
+    st.sgpr[126] = !(1 << 5);
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * (l as u32 + 7);
+    }
+    let r = kernel_with(
+        &[
+            // and 0x1F, xor 16
+            i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+            i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]),
+        ],
+        &st,
+        &[],
+        Flip::None,
+    )
+    .unwrap();
+    for l in (0..64usize).filter(|&l| l != 5) {
+        let s = l ^ 16;
+        assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle");
+        let b = (l & 32) | ((l + 7) & 31);
+        assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute");
+    }
+}
+
+#[test]
+fn memory_buffers_globals_and_lds() {
+    let mut st = lanes_state();
+    // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400
+    st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]);
+    st.sgpr[12] = 0x400;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[3] = 4 * l as u32;
+    }
+    let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect();
+    let r = kernel_with(
+        &[
+            i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]),
+            i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]),
+            i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]),
+            i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]),
+            i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]),
+            i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]),
+            i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]),
+        ],
+        &st,
+        &mem,
+        Flip::None,
+    )
+    .unwrap();
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0");
+    for l in 0..64usize {
+        assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load");
+        assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add");
+        assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value");
+        // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l
+        assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword");
+        assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order");

Changed in tests.rs: DS_ADD_RTN_U32 now works on each lane's own dword, and the test checks the old value and the value read back, so lane order no longer matters. The DS_PERMUTE_B32 case in forms.rs uses address 4·lane ^ 0x54, lane ^ 21 within each half: one sender per lane, so the unpredictable case in 12.13 does not arise.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776710177 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776710177). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:46Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/tests.rs`; line 437 ~~~~diff @@ -0,0 +1,585 @@ +use super::asm::{asm, end, i, lit, I, TO, V}; +use super::*; +use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture}; + +const EXEC: u64 = 126; +const VCC: u64 = 106; + +fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> { + let mut l = list.to_vec(); + l.push(end()); + run_kernel(&asm(&l), true, st, mem, &[], &[], flip) +} + +/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes. +fn lanes_state() -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + } + st +} + +fn kernel(list: &[I]) -> Run { + kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}")) +} + +#[test] +fn saveexec_families_save_the_old_exec_and_set_scc() { + // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39 + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]), + ]); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC"); + assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves"); + assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0"); + // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC + assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000); + assert_eq!(pair(26), pair(24)); + assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC"); + assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on"); +} + +#[test] +fn branches_see_the_whole_wave_masks() { + // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken + let r = kernel(&[ + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2)); + assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40)); +} + +#[test] +fn salu_carries_overflows_and_fields() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]), + i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF), + i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]), + lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]), + i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]), + i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]), + i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32"); + assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow"); + assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX)); + assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31)); + assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE)); +} + +#[test] +fn an_instruction_outside_the_model_stops_the_run() { + let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]); + match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) { + Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"), + other => panic!("{:?}", other.map(|_| ())), + } + let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand"); + let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_)))); +} + +/// One encoding of every instruction the reference models. +fn modelled_words() -> Vec<Vec<u8>> { + const ENCODINGS: [&str; 17] = [ + "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS", + "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL", + ]; + let mut words = Vec::new(); + for inst in rdna2::all_instructions() { + for name in ENCODINGS { + let enc = rdna2::encoding(name).unwrap(); + let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue }; + if modelled(&[code.clone(), vec![0, 0, 0x81, 0xBF]].concat()) { + words.push(code); + } + } + } + words +} + +/// The decoder is checked against LLVM's on every instruction the reference models: +/// `llvm-mc --disassemble -show-encoding` of `modelled_words`, run here when `llvm-mc` runs +/// (`XCL_LLVM_MC`, or on the PATH), or read from the listing `XCL_LLVM_DISASM` names +/// (`XCL_LLVM_WORDS` writes the words to give it, as llvm-mc's input). +#[test] +fn modelled_instructions_decode_as_llvm_disassembles_them() { + use std::io::Write; + let words = modelled_words(); + let input: String = words.iter().map(|c| c.iter().map(|b| format!("{b:#04x} ")).collect::<String>() + "\n").collect(); + if let Ok(path) = std::env::var("XCL_LLVM_WORDS") { + std::fs::write(path, &input).unwrap(); + } + let listing = if let Ok(path) = std::env::var("XCL_LLVM_DISASM") { + std::fs::read_to_string(path).unwrap() + } else { + let mc = std::env::var("XCL_LLVM_MC").unwrap_or_else(|_| "llvm-mc".into()); + let child = std::process::Command::new(&mc) + .args(["--disassemble", "-show-encoding", "-triple=amdgcn", "-mcpu=gfx1013", "-mattr=+wavefrontsize64,-wavefrontsize32"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn(); + let Ok(mut child) = child else { + let _ = writeln!(std::io::stderr(), "SKIPPED modelled_instructions_decode_as_llvm_disassembles_them: no llvm-mc"); + return; + }; + child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap(); + String::from_utf8_lossy(&child.wait_with_output().unwrap().stdout).into_owned() + }; + // LLVM writes one line a word, in order; it re-encodes some fields, so lines are paired by order + let theirs: Vec<&str> = listing.lines().filter(|l| l.contains("; encoding: [")).map(|l| l.split_whitespace().next().unwrap()).collect(); + assert_eq!(theirs.len(), words.len(), "llvm-mc did not disassemble every word"); + // gfx10.1's names of the opcodes gfx10.3 made fused (`rdna2_xbox`) + let norm = |s: &str| s.trim_end_matches("_e32").trim_end_matches("_e64").replace("v_mac_legacy", "v_fmac_legacy").replace("v_mad_legacy", "v_fma_legacy"); + let mut bad = Vec::new(); + for (code, t) in words.iter().zip(theirs) { + let ours = rdna2::mnemonic(&rdna2::decode(code, 0).unwrap()); + // AMD's tables give v_readfirstlane_b32 a VOP3 form, which LLVM's gfx10 does not have + let vop3_readfirstlane = ours == "v_readfirstlane_b32" && t == "v_illegal"; + if norm(t) != norm(&ours) && !vop3_readfirstlane { + bad.push(format!("{ours} / {t}")); + } + } + assert!(bad.is_empty(), "{} of {} differ: {bad:?}", bad.len(), words.len()); + let _ = writeln!(std::io::stderr(), "{} modelled encodings agree with LLVM's disassembler", words.len()); +} + +/// Whether the reference runs `code` (one instruction and s_endpgm) or stops at it as unmodelled. +fn modelled(code: &[u8]) -> bool { + let mut st = KernelState::default(); + st.sgpr[124] = 0; + !matches!(run_kernel(code, true, &st, &[0; 4096], &[], &[], Flip::None), Err(Stop::Unsupported { .. })) +} + +// ------------------------------------------------------------- vector ALU and lanes + +#[test] +fn lane_reads_and_writes_use_all_64_lanes() { + let r = kernel(&[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 97), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 4)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x1234), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 5), ("SRC1", 128 + 63)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], 0xFFFF_FF00), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 1)]), + ]); + assert_eq!(r.sgpr[10], 121, "v_readlane of lane 40"); + assert_eq!(r.sgpr[11], 100, "a lane select of 97 is lane 33"); + assert_eq!(r.vgpr[63][2], 0x1234, "v_writelane into lane 63"); + assert_eq!(r.vgpr[31][2], 0, "and nowhere else"); + assert_eq!(r.sgpr[12], 3 * 40 + 1, "v_readfirstlane with the first lane in the upper half"); + assert_eq!(r.sgpr[13], 1, "v_readfirstlane with EXEC 0 reads lane 0"); +} + +#[test] +fn mbcnt_counts_the_lanes_below_in_both_halves() { + let r = kernel(&[ + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 193), ("SRC1", V + 2)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 193), ("SRC1", 128)]), + ]); + for l in 0..64 { + assert_eq!(r.vgpr[l][2], l as u32, "lane {l}"); + assert_eq!(r.vgpr[l][3], l.min(32) as u32, "lane {l}: mbcnt_lo alone"); + } +} + +#[test] +fn carries_and_compares_write_a_bit_per_lane_of_the_pair() { + let mut st = lanes_state(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[4] = if l % 3 == 0 { u32::MAX } else { 7 }; + } + let r = kernel_with( + &[ + i("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 5), ("SDST", 20), ("SRC0", V + 4), ("SRC1", 129)]), + i("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 22), ("SRC0", 128), ("SRC1", 128), ("SRC2", 20)]), + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], 35), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 128), ("SRC1", 129), ("SRC2", 24)]), + lit("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 50), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 129)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + let thirds = (0..64).filter(|l| l % 3 == 0).fold(0u64, |m, l| m | 1 << l); + assert_eq!(pair(20), thirds, "the carry-out of every lane, lanes 32..63 in the high dword"); + assert_eq!(pair(22), 0, "0 + 0 + carry-in has no carry"); + assert_eq!(pair(24), !0u64 << 36); + assert_eq!(pair(126), !0u64 << 51, "v_cmpx writes EXEC"); + for l in 0..64 { + assert_eq!(r.vgpr[l][6], u32::from(l % 3 == 0)); + assert_eq!(r.vgpr[l][7], u32::from(l > 35)); + assert_eq!(r.vgpr[l][8], u32::from(l > 50), "lane {l}: lanes off in EXEC keep their value"); + } +} + +#[test] +fn integer_valu_known_answers() { + let mut st = lanes_state(); + st.vgpr[0][4] = 0x8000_0001; + st.vgpr[0][5] = 0x0000_0003; + let r = kernel_with( + &[ + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 4), ("SRC1", V + 5)]), + i("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 4), ("SRC1", V + 5)]), + lit("V_PERM_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", 255)], 0x0C07_0009), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", 128 + 31), ("SRC2", 129)]), + i("V_BFE_I32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 30), ("SRC2", 131)]), + i("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 5), ("SRC1", V + 4), ("SRC2", 129)]), + i("V_FFBH_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 4)]), + i("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 16), ("SRC0", 129), ("SRC1", V + 4)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 18), ("SDST", 30), ("SRC0", V + 4), ("SRC1", V + 5), ("SRC2", V + 4)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + let v = &r.vgpr[0]; + assert_eq!(v[10], 1); + assert_eq!(v[11], 0xFFFF_FFFE); + assert_eq!(v[12], 0x0080_0300, "selectors 9 (the sign of bit 31 of src1), 0, 7, 12"); + assert_eq!(v[13], u32::MAX, "bit 31 sign-extended"); + assert_eq!(v[20], -2i32 as u32, "the field past bit 31 is the shifted-in sign"); + assert_eq!(v[14], 0xC000_0000); + assert_eq!(v[15], 1); + assert_eq!((v[16], v[17]), (2, 7)); + assert_eq!((v[18], v[19]), (4, 5)); +} + +#[test] +fn permlanex16_swaps_the_rows_of_each_half_and_permlane16_keeps_them() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V), ("SRC1", 4), ("SRC2", 5)]), + ]); + for l in 0..64u32 { + assert_eq!(r.vgpr[l as usize][2], (l / 16 ^ 1) * 16 + l % 16, "lane {l}"); + assert_eq!(r.vgpr[l as usize][3], l, "lane {l}"); + } +} + +#[test] +fn dpp_rows_mirror_shift_and_respect_bound_ctrl_and_exec() { + let mut st = lanes_state(); + for r in st.vgpr.iter_mut() { + r[5] = 0xAAAA; + r[6] = 0xBBBB; + } + // lanes 0..63 but lane 17: off + st.sgpr[126] = !(1 << 17); + let r = kernel_with( + &[ + // row_mirror, bound_ctrl 1 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 2), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)]), + // row_shr:1, bound_ctrl 0: lane 0 of each row and lane 18 (source 17 off) keep v5 + i("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 5), ("SRC0", 0xFA), ("VSRC0", 0), ("DPP_CTRL", 0x111), ("ROW_MASK", 15), ("BANK_MASK", 15)]), + // dpp8 xor 1 (selects 1, 0, 3, 2, 5, 4, 7, 6), added to v1 + i("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 1), ("LANE_SEL_0", 1), ("LANE_SEL_1", 0), ("LANE_SEL_2", 3), ("LANE_SEL_3", 2), ("LANE_SEL_4", 5), ("LANE_SEL_5", 4), ("LANE_SEL_6", 7), ("LANE_SEL_7", 6)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in 0..64usize { + let v = &r.vgpr[l]; + if l == 17 { + assert_eq!((v[2], v[5], v[6]), (0, 0xAAAA, 0xBBBB), "lane 17 is off"); + continue; + } + let m = (l & !15) + 15 - (l & 15); + assert_eq!(v[2], if m == 17 { 0 } else { m as u32 }, "lane {l}: row_mirror"); + assert_eq!(v[5], if l % 16 == 0 || l == 18 { 0xAAAA } else { l as u32 - 1 }, "lane {l}: row_shr:1"); + let s = l ^ 1; + assert_eq!(v[6], if s == 17 { 0 } else { s as u32 } + 3 * l as u32 + 1, "lane {l}: dpp8"); + } +} + +// ------------------------------------------------------------- rules turned the wrong way + +/// The programs and checks whose rules `Flip` turns: each passes with the ISA's rule and must +/// fail with the flipped one, or the check could not see the rule. +fn rule_checks() -> Vec<(Flip, &'static str, fn(Flip) -> bool)> { + vec![ + (Flip::Lane31, "v_readlane of lane 40", |flip| { + kernel_with(&[i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", 128 + 40)])], &lanes_state(), &[], flip).map_or(false, |r| r.sgpr[10] == 121) + }), + (Flip::PermlaneOwnRow, "v_permlanex16 of the identity", |flip| { + kernel_with(&[i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)])], &lanes_state(), &[], flip) + .map_or(false, |r| (0..64).all(|l| r.vgpr[l][2] == ((l as u32 / 16) ^ 1) * 16)) + }), + (Flip::ExecIgnored, "a v_mov under an EXEC of the upper half", |flip| { + let mut st = lanes_state(); + st.sgpr[126] = 0; + kernel_with(&[i("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])], &st, &[], flip).map_or(false, |r| (0..64).all(|l| r.vgpr[l][1] == if l < 32 { 3 * l as u32 + 1 } else { 0 })) + }), + (Flip::VccLow, "s_cbranch_vccz with VCC in the upper half", |flip| { + kernel_with( + &[lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 40), i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 3)]), i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)])], + &lanes_state(), + &[], + flip, + ) + .map_or(false, |r| r.sgpr[10] == 1) + }), + ] +} + +#[test] +fn each_rule_check_fails_when_its_rule_is_flipped() { + for (flip, what, check) in rule_checks() { + assert!(check(Flip::None), "{what}: fails with the ISA's rule"); + assert!(!check(flip), "{what}: still passes with {flip:?}"); + } +} + +// ------------------------------------------------------------- memory, LDS and groups + +#[test] +fn ds_swizzle_and_bpermute_stay_in_their_half_and_read_0_from_lanes_off() { + let mut st = lanes_state(); + st.sgpr[126] = !(1 << 5); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * (l as u32 + 7); + } + let r = kernel_with( + &[ + // and 0x1F, xor 16 + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 3), ("DATA0", 1)]), + ], + &st, + &[], + Flip::None, + ) + .unwrap(); + for l in (0..64usize).filter(|&l| l != 5) { + let s = l ^ 16; + assert_eq!(r.vgpr[l][2], if s == 5 { 0 } else { s as u32 }, "lane {l}: swizzle"); + let b = (l & 32) | ((l + 7) & 31); + assert_eq!(r.vgpr[l][4], if b == 5 { 0 } else { 3 * b as u32 + 1 }, "lane {l}: bpermute"); + } +} + +#[test] +fn memory_buffers_globals_and_lds() { + let mut st = lanes_state(); + // V# at s[8:11]: base 0x100, raw, 0x80 bytes; s[12:13] the global base 0x400 + st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x80, 0]); + st.sgpr[12] = 0x400; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[3] = 4 * l as u32; + } + let mem: Vec<u32> = (0..1024).map(|k| 0x1000 + k).collect(); + let r = kernel_with( + &[ + i("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 4), ("OFFSET", 0x7C), ("SOFFSET", 125)]), + i("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 3), ("SRSRC", 2), ("SOFFSET", 128), ("OFFEN", 1)]), + i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 1), ("SADDR", 12)]), + i("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 0), ("SADDR", 12), ("VDST", 5), ("GLC", 1)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 0), ("DATA1", 1), ("OFFSET0", 0), ("OFFSET1", 64)]), + i("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 3), ("OFFSET1", 1)]), + i("DS_ADD_RTN_U32", "ENC_DS", &[("VDST", 7), ("ADDR", 128), ("DATA0", 0)]), + ], + &st, + &mem, + Flip::None, + ) + .unwrap(); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0x1000 + (0x100 + 0x7C) / 4, 0), "the dword past num_records reads 0"); + for l in 0..64usize { + assert_eq!(r.vgpr[l][4], if l < 32 { 0x1040 + l as u32 } else { 0 }, "lane {l}: buffer load"); + assert_eq!(r.mem[0x100 + l], 3 * l as u32 + 1 + l as u32, "lane {l}: global store then atomic add"); + assert_eq!(r.vgpr[l][5], 3 * l as u32 + 1, "lane {l}: the atomic's old value"); + // dword l + 64 (offset 256 = 64 dwords · 4) holds v1 of lane l + assert_eq!(r.vgpr[l][6], 3 * l as u32 + 1, "lane {l}: ds_read of ds_write2's second dword"); + assert_eq!(r.vgpr[l][7], (0..l as u32).sum::<u32>(), "lane {l}: ds_add_rtn in lane order"); ~~~~ --- Changed in `tests.rs`: DS_ADD_RTN_U32 now works on each lane's own dword, and the test checks the old value and the value read back, so lane order no longer matters. The DS_PERMUTE_B32 case in `forms.rs` uses address 4·lane ^ 0x54, lane ^ 21 within each half: one sender per lane, so the unpredictable case in 12.13 does not arise. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/tests.rs; line 121

@@ -0,0 +1,585 @@
+use super::asm::{asm, end, i, lit, I, TO, V};
+use super::*;
+use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture};
+
+const EXEC: u64 = 126;
+const VCC: u64 = 106;
+
+fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> {
+    let mut l = list.to_vec();
+    l.push(end());
+    run_kernel(&asm(&l), true, st, mem, &[], &[], flip)
+}
+
+/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes.
+fn lanes_state() -> KernelState {
+    let mut st = KernelState::default();
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+    }
+    st
+}
+
+fn kernel(list: &[I]) -> Run {
+    kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}"))
+}
+
+#[test]
+fn saveexec_families_save_the_old_exec_and_set_scc() {
+    // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]),
+        i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]),
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]),
+    ]);
+    let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32;
+    assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC");
+    assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves");
+    assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0");
+    // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC
+    assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000);
+    assert_eq!(pair(26), pair(24));
+    assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC");
+    assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on");
+}
+
+#[test]
+fn branches_see_the_whole_wave_masks() {
+    // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken
+    let r = kernel(&[
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8),
+        i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+        i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]),
+        i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]),
+        i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]),
+        i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2));
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40));
+}
+
+#[test]
+fn salu_carries_overflows_and_fields() {
+    let r = kernel(&[
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF),
+        i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]),
+        i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF),
+        i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]),
+        lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16),
+        i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]),
+        i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]),
+        i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]),
+        i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]),
+        i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]),
+        i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]),
+    ]);
+    assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32");
+    assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow");
+    assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX));
+    assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31));
+    assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed");
+    assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE));
+}
+
+#[test]
+fn an_instruction_outside_the_model_stops_the_run() {
+    let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]);
+    match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) {
+        Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"),
+        other => panic!("{:?}", other.map(|_| ())),
+    }
+    let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand");
+    let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]);
+    assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_))));
+}
+
+/// One encoding of every instruction the reference models.
+fn modelled_words() -> Vec<Vec<u8>> {
+    const ENCODINGS: [&str; 17] = [
+        "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS",
+        "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL",
+    ];
+    let mut words = Vec::new();
+    for inst in rdna2::all_instructions() {
+        for name in ENCODINGS {
+            let enc = rdna2::encoding(name).unwrap();
+            let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue };

Agreed: it proves the opcode-to-name table and nothing about field positions, variants or semantics. The description now says "823 opcode names agree with llvm-mc" (run through XCL_LLVM_DISASM after this round's changes; V_FMAC/FMA_LEGACY are no longer modelled) and that CI skips the check. It also looks for llvm-mc before it builds the words now.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776710573 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776710573). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/tests.rs`; line 121 ~~~~diff @@ -0,0 +1,585 @@ +use super::asm::{asm, end, i, lit, I, TO, V}; +use super::*; +use crate::gpu::recomp::runner::{TexDim, TestSampler, TestTexture}; + +const EXEC: u64 = 126; +const VCC: u64 = 106; + +fn kernel_with(list: &[I], st: &KernelState, mem: &[u32], flip: Flip) -> Result<Run, Stop> { + let mut l = list.to_vec(); + l.push(end()); + run_kernel(&asm(&l), true, st, mem, &[], &[], flip) +} + +/// One wave of 64 with v0 = the lane, v1 = 3 · lane + 1, EXEC all lanes. +fn lanes_state() -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + } + st +} + +fn kernel(list: &[I]) -> Run { + kernel_with(list, &lanes_state(), &[], Flip::None).unwrap_or_else(|e| panic!("{e}")) +} + +#[test] +fn saveexec_families_save_the_old_exec_and_set_scc() { + // EXEC = lanes 32..63 only; s[10:11] = lanes 0..39 + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 255)], u32::MAX), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 255)], 0xFF), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", EXEC)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 10)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", EXEC)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 193)]), + ]); + let pair = |k: usize| u64::from(r.sgpr[k]) | u64::from(r.sgpr[k + 1]) << 32; + assert_eq!(pair(20), 0xFFFF_FFFF_0000_0000, "s_and_saveexec saves the old EXEC"); + assert_eq!(pair(22), 0xFF_0000_0000, "EXEC = S0 & EXEC, across the halves"); + assert_eq!(r.sgpr[30], 1, "SCC = EXEC != 0"); + // andn2_wrexec: EXEC = S0 & ~EXEC, and D gets the new EXEC + assert_eq!(pair(24), 0xFF_FFFF_FFFF & !0xFF_0000_0000); + assert_eq!(pair(26), pair(24)); + assert_eq!(pair(28), pair(24), "s_or_saveexec saves EXEC"); + assert_eq!((r.sgpr[126], r.sgpr[127]), (u32::MAX, u32::MAX), "s_or_saveexec -1 turns every lane on"); +} + +#[test] +fn branches_see_the_whole_wave_masks() { + // VCC has lane 40 only: vccz is not taken, execz with only the upper half on is not taken + let r = kernel(&[ + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 107), ("SSRC0", 255)], 1 << 8), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(TO, 4)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 7)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 130)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", VCC)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", VCC)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 2)); + assert_eq!((r.sgpr[12], r.sgpr[13]), (1, 40)); +} + +#[test] +fn salu_carries_overflows_and_fields() { + let r = kernel(&[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0xFFFF_FFFF), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 4), ("SSRC1", 130)]), + i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 128), ("SSRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x7FFF_FFFF), + i("S_ADD_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 129)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 129), ("SSRC1", 130)]), + lit("S_BFE_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + lit("S_BFE_I32", "ENC_SOP2", &[("SDST", 15), ("SSRC0", 4), ("SSRC1", 255)], 4 | 8 << 16), + i("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 128)]), + i("S_FLBIT_I32_B32", "ENC_SOP1", &[("SDST", 17), ("SSRC0", 129)]), + i("S_MOVK_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0xFFFE)]), + i("S_CMPK_LT_I32", "ENC_SOPK", &[("SDST", 18), ("SIMM16", 0)]), + i("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 19), ("SSRC0", 129), ("SSRC1", 130)]), + i("S_LSHL_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 4), ("SSRC1", 128 + 33)]), + ]); + assert_eq!((r.sgpr[10], r.sgpr[11]), (1, 1), "s_add_u32's carry into s_addc_u32"); + assert_eq!((r.sgpr[12], r.sgpr[13]), (0x8000_0000, 1), "s_add_i32 sets SCC on a signed overflow"); + assert_eq!((r.sgpr[14], r.sgpr[15]), (0xFF, u32::MAX)); + assert_eq!((r.sgpr[16], r.sgpr[17]), (u32::MAX, 31)); + assert_eq!((r.sgpr[18], r.sgpr[19]), (0xFFFF_FFFE, 1), "s_movk sign-extends, s_cmpk_lt_i32 compares signed"); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0, 0xFFFF_FFFE)); +} + +#[test] +fn an_instruction_outside_the_model_stops_the_run() { + let code = asm(&[i("V_SIN_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), i("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]), end()]); + match run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None) { + Err(Stop::Unsupported { pc: 0, name }) => assert!(name.starts_with("v_sin_f16"), "{name}"), + other => panic!("{:?}", other.map(|_| ())), + } + let code = asm(&[i("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("NEG", 1)]), end()]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Unsupported { .. })), "NEG on an integer operand"); + let code = asm(&[i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFF)])]); + assert!(matches!(run_kernel(&code, true, &KernelState::default(), &[], &[], &[], Flip::None), Err(Stop::Steps(_)))); +} + +/// One encoding of every instruction the reference models. +fn modelled_words() -> Vec<Vec<u8>> { + const ENCODINGS: [&str; 17] = [ + "ENC_SOP1", "ENC_SOPC", "ENC_SOPP", "ENC_SOPK", "ENC_SOP2", "ENC_SMEM", "ENC_VOP1", "ENC_VOPC", "ENC_VOP2", "ENC_VOP3", "VOP3_SDST_ENC", "ENC_VOP3P", "ENC_DS", + "ENC_MUBUF", "ENC_MTBUF", "ENC_MIMG", "ENC_FLAT_GLBL", + ]; + let mut words = Vec::new(); + for inst in rdna2::all_instructions() { + for name in ENCODINGS { + let enc = rdna2::encoding(name).unwrap(); + let Ok(code) = rdna2::encode(inst.name, enc.name, &[], inst.always_literal.then_some(0)) else { continue }; ~~~~ --- Agreed: it proves the opcode-to-name table and nothing about field positions, variants or semantics. The description now says "823 opcode names agree with llvm-mc" (run through `XCL_LLVM_DISASM` after this round's changes; V_FMAC/FMA_LEGACY are no longer modelled) and that CI skips the check. It also looks for llvm-mc before it builds the words now. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:50Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 706

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),
+    }
+}
+
+pub(crate) type Form = (&'static str, fn(&Case) -> Got);
+
+/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native
+/// ones on one with 64-lane waves.
+pub(crate) fn gpu_forms() -> Vec<Form> {
+    let mut forms: Vec<Form> = Vec::new();
+    if runner::wave32_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL split", |c| hlsl(c, true)));
+        }
+        forms.push(("direct split", |c| direct(c, true)));
+        forms.push(("per-lane split", |c| per_lane(c, true)));
+    }
+    if runner::wave64_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL wave64", |c| hlsl(c, false)));
+        }
+        forms.push(("direct wave64", |c| direct(c, false)));
+        forms.push(("per-lane wave64", |c| per_lane(c, false)));
+    }
+    forms
+}
+
+/// A dword as an integer ordered like the float it is, for ULP distances.
+fn ordered(x: u32) -> i64 {
+    if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) }
+}
+
+/// The verdict of one form on one case.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Verdict {
+    /// dwords compared exactly, dwords compared within their bound
+    Match(usize, usize),
+    /// first differing dword (where, reference, form) and how many differ
+    Mismatch(String, u32, u32, usize),
+    Refused(String),
+    Failed(String),
+}
+
+pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict {
+    let words = match got {
+        Got::Words(w) => w,
+        Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()),
+        Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()),
+    };
+    let (want, taint) = want;
+    if words.len() != want.len() {
+        return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len()));
+    }
+    let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0);
+    for k in 0..want.len() {
+        let (w, g, t) = (want[k], words[k], taint[k]);
+        let ok = if t == 0 {
+            exact += 1;
+            w == g
+        } else {
+            bounded += 1;
+            w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t)
+        };
+        if !ok {
+            n += 1;
+            first.get_or_insert(k);
+        }
+    }
+    match first {
+        None => Verdict::Match(exact, bounded),
+        Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n),
+    }
+}
+
+// ------------------------------------------------------------------------ the cases
+
+/// lanes_state of the tests, plus v2 = a value with both halves' patterns.
+fn kernel_state(exec: u64) -> KernelState {
+    let mut st = KernelState::default();
+    st.sgpr[126] = exec as u32;
+    st.sgpr[127] = (exec >> 32) as u32;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+        r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7;
+        r[3] = 4 * l as u32;
+        r[4] = ((l as f32) * 0.25 - 3.0).to_bits();
+    }
+    st
+}
+
+/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions.
+fn kernel_case(name: &str, list: &[I], exec: u64) -> Case {
+    let mut l = vec![
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32),
+    ];
+    l.extend_from_slice(list);
+    l.push(end());
+    Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62);
+
+fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I {
+    i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)])
+}
+
+/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8.
+pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I {
+    const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
+    let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)];
+    f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x)));
+    (name, "VOP2_VOP_DPP8", f, None)
+}
+
+pub(crate) fn kernel_cases() -> Vec<Case> {
+    let mut cases = vec![
+        kernel_case(
+            "lane reads across the halves",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "lane reads and ballots under a full EXEC",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]),
+                lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]),
+                i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "a scalar written while lanes are off reaches them",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "a scalar written in a branch reaches the lanes outside it",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "permlane16 and permlanex16",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]),
+                i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP16 rows with BOUND_CTRL and EXEC holes",
+            &[
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]),
+                dpp16("V_OR_B32", 6, 2, 1, 0x140, 1),
+                dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0),
+                dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1),
+                dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0),
+                dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1),
+                dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP8 xor steps with EXEC holes",
+            &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)],
+            HOLES,
+        ),
+        kernel_case(
+            "ds_swizzle, ds_bpermute and ds_permute",
+            &[
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]),
+                lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]),
+                i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]),
+                // index lane + 40: past the half, which wraps within it
+                lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "masks across the halves",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]),
+                i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]),
+                i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]),
+                i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]),
+                lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45),
+                i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]),
+                i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]),
+                i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "carries across the halves",
+            &[
+                lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000),
+                i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]),
+                i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]),
+                i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]),
+                i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "exact float rules",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]),
+                i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]),
+                i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]),
+                i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]),
+                i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]),
+                i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]),
+                i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]),
+                i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]),
+                i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]),
+                i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]),
+                i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]),
+                i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]),
+                i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]),
+                i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]),
+                i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "transcendentals",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]),
+                i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]),
+                i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]),
+                i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]),
+                i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]),
+            ],
+            !0,
+        ),
+    ];
+    // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into
+    let mut img = kernel_case(
+        "images",
+        &[
+            i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]),
+            i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()),
+            i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]),
+            i("S_WAITCNT", "ENC_SOPP", &[]),
+        ],
+        !0,
+    );
+    if let Abi::Kernel(st) = &mut img.abi {
+        // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D
+        st.sgpr[0] = 0;
+        st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+        st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+    }
+    img.tex = vec![
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false },
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true },
+    ];
+    img.samplers = vec![TestSampler {
+        filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT,
+        address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+        comparison: None,
+    }];
+    cases.push(img);
+    cases
+}
+
+const EXEC_PAIR: u64 = 126;
+
+/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material
+/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a
+/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS.
+/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs.
+pub(crate) fn classifier() -> Vec<u8> {
+    let mut l = vec![
+        i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]),
+        i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]),
+        i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]),
+        // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]),
+        i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]),
+        i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        // lanes of material 7 are off for the reductions
+        i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]),
+    ];
+    // (op, identity, result SGPR, LDS atomic)
+    for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] {
+        l.extend([
+            i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]),
+            dpp8_xor(op, 11, 11, 11, 1),
+            dpp8_xor(op, 11, 11, 11, 2),
+            dpp8_xor(op, 11, 11, 11, 4),
+            dpp16(op, 11, 11, 11, 0x140, 1),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+            i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+            i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]),
+            i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]),
+            i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]),
+            i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]),
+        ]);
+        if let Some((atomic, at)) = ds {
+            l.extend([
+                lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]),
+                i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]),
+            ]);
+        }
+    }
+    l.extend([
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        // five dwords a thread at s1 + 20 · thread
+        i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]),
+        end(),
+    ]);
+    asm(&l)
+}
+
+/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in
+/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in
+/// row 3.
+pub(crate) fn classifier_case() -> Case {
+    let groups = 6u32;
+    let mut mem = vec![0u32; groups as usize * 256 * 6];
+    for g in 0..groups as usize {
+        for t in 0..256usize {
+            let lane = t % 64;
+            mem[g * 256 + t] = match g {
+                0 => 3,
+                1 => if lane < 32 { 2 } else { 5 },
+                2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6],
+                3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 },
+                4 => if t == 20 { 1 } else { 6 },
+                _ => if t == 50 { 9 } else { 6 },
+            };
+        }
+    }
+    let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 };
+    Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has
+/// no threads, its lanes are turned on, given the identity and read by v_readlane 32.
+pub(crate) fn empty_half_case() -> Case {
+    let code = asm(&[
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]),
+        i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]),
+        end(),
+    ]);
+    let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 };
+    Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+pub(crate) fn cases() -> Vec<Case> {
+    let mut c = kernel_cases();
+    c.push(classifier_case());
+    c.push(empty_half_case());
+    c
+}
+
+/// Mismatches main has today, (case, form): each one is listed in the pull request that
+/// added the harness. A form that starts to agree turns the test red until its line goes.
+const KNOWN: &[(&str, &str)] = &[
+    ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "direct split"),
+    ("a whole-wave section in a wave with an empty upper half", "per-lane split"),
+];
+
+fn print(case: &str, form: &str, v: &Verdict) {
+    use std::io::Write;
+    let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}");
+}
+
+#[test]
+fn gpu_wave64_forms_agree_with_the_reference() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let forms = gpu_forms();
+    if forms.is_empty() {
+        return runner::skip_test("no wave64");
+    }
+    let mut unexpected = Vec::new();
+    let mut matched = 0;
+    for case in cases() {
+        let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name));
+        for (form, run) in &forms {
+            let v = judge(&case, &want, run(&case));
+            print(&case.name, form, &v);
+            let known = KNOWN.contains(&(case.name.as_str(), *form));
+            match (&v, known) {
+                (Verdict::Match(..), false) => matched += 1,
+                (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {}

Changed in forms.rs: KNOWN is gone. EXPECTED pins the outcome of every (case, form) pair per adapter: Match, KnownMismatch(first differing dword) or Refused(part of the reason). Failed is never expected. A different first dword, a new refusal, a refusal that now translates, or a pair with no line fails with the line it would need. Every pair that ran here has a line, so every form needs its matches. On an adapter with no lines (AMD, and so the native wave64 forms) the test prints the lines and skips.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776710921 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776710921). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:50Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 706 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), + } +} + +pub(crate) type Form = (&'static str, fn(&Case) -> Got); + +/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native +/// ones on one with 64-lane waves. +pub(crate) fn gpu_forms() -> Vec<Form> { + let mut forms: Vec<Form> = Vec::new(); + if runner::wave32_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL split", |c| hlsl(c, true))); + } + forms.push(("direct split", |c| direct(c, true))); + forms.push(("per-lane split", |c| per_lane(c, true))); + } + if runner::wave64_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL wave64", |c| hlsl(c, false))); + } + forms.push(("direct wave64", |c| direct(c, false))); + forms.push(("per-lane wave64", |c| per_lane(c, false))); + } + forms +} + +/// A dword as an integer ordered like the float it is, for ULP distances. +fn ordered(x: u32) -> i64 { + if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) } +} + +/// The verdict of one form on one case. +#[derive(Debug, PartialEq)] +pub(crate) enum Verdict { + /// dwords compared exactly, dwords compared within their bound + Match(usize, usize), + /// first differing dword (where, reference, form) and how many differ + Mismatch(String, u32, u32, usize), + Refused(String), + Failed(String), +} + +pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict { + let words = match got { + Got::Words(w) => w, + Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()), + Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()), + }; + let (want, taint) = want; + if words.len() != want.len() { + return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len())); + } + let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0); + for k in 0..want.len() { + let (w, g, t) = (want[k], words[k], taint[k]); + let ok = if t == 0 { + exact += 1; + w == g + } else { + bounded += 1; + w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t) + }; + if !ok { + n += 1; + first.get_or_insert(k); + } + } + match first { + None => Verdict::Match(exact, bounded), + Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n), + } +} + +// ------------------------------------------------------------------------ the cases + +/// lanes_state of the tests, plus v2 = a value with both halves' patterns. +fn kernel_state(exec: u64) -> KernelState { + let mut st = KernelState::default(); + st.sgpr[126] = exec as u32; + st.sgpr[127] = (exec >> 32) as u32; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7; + r[3] = 4 * l as u32; + r[4] = ((l as f32) * 0.25 - 3.0).to_bits(); + } + st +} + +/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions. +fn kernel_case(name: &str, list: &[I], exec: u64) -> Case { + let mut l = vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32), + ]; + l.extend_from_slice(list); + l.push(end()); + Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62); + +fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I { + i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)]) +} + +/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8. +pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I { + const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)]; + f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x))); + (name, "VOP2_VOP_DPP8", f, None) +} + +pub(crate) fn kernel_cases() -> Vec<Case> { + let mut cases = vec![ + kernel_case( + "lane reads across the halves", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]), + ], + !0, + ), + kernel_case( + "lane reads and ballots under a full EXEC", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]), + lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]), + i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]), + ], + !0, + ), + kernel_case( + "a scalar written while lanes are off reaches them", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "a scalar written in a branch reaches the lanes outside it", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "permlane16 and permlanex16", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]), + ], + HOLES, + ), + kernel_case( + "DPP16 rows with BOUND_CTRL and EXEC holes", + &[ + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]), + dpp16("V_OR_B32", 6, 2, 1, 0x140, 1), + dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0), + dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1), + dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0), + dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1), + dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1), + ], + HOLES, + ), + kernel_case( + "DPP8 xor steps with EXEC holes", + &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)], + HOLES, + ), + kernel_case( + "ds_swizzle, ds_bpermute and ds_permute", + &[ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]), + i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]), + // index lane + 40: past the half, which wraps within it + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + HOLES, + ), + kernel_case( + "masks across the halves", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]), + i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]), + lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]), + ], + HOLES, + ), + kernel_case( + "carries across the halves", + &[ + lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000), + i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]), + i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]), + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]), + ], + HOLES, + ), + kernel_case( + "exact float rules", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]), + i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]), + i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]), + i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]), + i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]), + i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]), + i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]), + i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]), + i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]), + i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]), + i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]), + i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]), + i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]), + i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]), + ], + HOLES, + ), + kernel_case( + "transcendentals", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]), + ], + !0, + ), + ]; + // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into + let mut img = kernel_case( + "images", + &[ + i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]), + i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()), + i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + !0, + ); + if let Abi::Kernel(st) = &mut img.abi { + // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D + st.sgpr[0] = 0; + st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]); + st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]); + } + img.tex = vec![ + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false }, + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true }, + ]; + img.samplers = vec![TestSampler { + filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT, + address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + comparison: None, + }]; + cases.push(img); + cases +} + +const EXEC_PAIR: u64 = 126; + +/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material +/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a +/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS. +/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs. +pub(crate) fn classifier() -> Vec<u8> { + let mut l = vec![ + i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]), + i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]), + i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]), + // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]), + i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + // lanes of material 7 are off for the reductions + i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]), + ]; + // (op, identity, result SGPR, LDS atomic) + for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] { + l.extend([ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]), + dpp8_xor(op, 11, 11, 11, 1), + dpp8_xor(op, 11, 11, 11, 2), + dpp8_xor(op, 11, 11, 11, 4), + dpp16(op, 11, 11, 11, 0x140, 1), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]), + i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]), + ]); + if let Some((atomic, at)) = ds { + l.extend([ + lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]), + i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]), + ]); + } + } + l.extend([ + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]), + // five dwords a thread at s1 + 20 · thread + i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]), + end(), + ]); + asm(&l) +} + +/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in +/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in +/// row 3. +pub(crate) fn classifier_case() -> Case { + let groups = 6u32; + let mut mem = vec![0u32; groups as usize * 256 * 6]; + for g in 0..groups as usize { + for t in 0..256usize { + let lane = t % 64; + mem[g * 256 + t] = match g { + 0 => 3, + 1 => if lane < 32 { 2 } else { 5 }, + 2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6], + 3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 }, + 4 => if t == 20 { 1 } else { 6 }, + _ => if t == 50 { 9 } else { 6 }, + }; + } + } + let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 }; + Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has +/// no threads, its lanes are turned on, given the identity and read by v_readlane 32. +pub(crate) fn empty_half_case() -> Case { + let code = asm(&[ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]), + end(), + ]); + let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +pub(crate) fn cases() -> Vec<Case> { + let mut c = kernel_cases(); + c.push(classifier_case()); + c.push(empty_half_case()); + c +} + +/// Mismatches main has today, (case, form): each one is listed in the pull request that +/// added the harness. A form that starts to agree turns the test red until its line goes. +const KNOWN: &[(&str, &str)] = &[ + ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "direct split"), + ("a whole-wave section in a wave with an empty upper half", "per-lane split"), +]; + +fn print(case: &str, form: &str, v: &Verdict) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}"); +} + +#[test] +fn gpu_wave64_forms_agree_with_the_reference() { + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + let forms = gpu_forms(); + if forms.is_empty() { + return runner::skip_test("no wave64"); + } + let mut unexpected = Vec::new(); + let mut matched = 0; + for case in cases() { + let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name)); + for (form, run) in &forms { + let v = judge(&case, &want, run(&case)); + print(&case.name, form, &v); + let known = KNOWN.contains(&(case.name.as_str(), *form)); + match (&v, known) { + (Verdict::Match(..), false) => matched += 1, + (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {} ~~~~ --- Changed in `forms.rs`: `KNOWN` is gone. `EXPECTED` pins the outcome of every (case, form) pair per adapter: `Match`, `KnownMismatch(first differing dword)` or `Refused(part of the reason)`. Failed is never expected. A different first dword, a new refusal, a refusal that now translates, or a pair with no line fails with the line it would need. Every pair that ran here has a line, so every form needs its matches. On an adapter with no lines (AMD, and so the native wave64 forms) the test prints the lines and skips. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:52Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 221

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),

Changed: a panic in the lowering or its interpreter is Got::Failed now, which fails the test. The fuzz prints, per form, the seeds compared, refused (by reason) and mismatched (by known class), fails on a refusal not in REFUSALS, and fails when a form compares fewer seeds than its floor in MIN_COMPARED_PERCENT. You were right about the number: at d2293dcb the lowering compared 1 of the 1,000 CPU seeds (264 compute, the rest used instructions it does not translate). The CPU part now generates programs of what the lowering translates: 149 of 1,000 compared, 0 mismatches. At 5,000 seeds a base, 1,535 of 10,000 compared and 12 mismatched, all a whole-wave section while lanes are elsewhere (mismatch 4's class).

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776711308 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776711308). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:52Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 221 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), ~~~~ --- Changed: a panic in the lowering or its interpreter is `Got::Failed` now, which fails the test. The fuzz prints, per form, the seeds compared, refused (by reason) and mismatched (by known class), fails on a refusal not in `REFUSALS`, and fails when a form compares fewer seeds than its floor in `MIN_COMPARED_PERCENT`. You were right about the number: at d2293dcb the lowering compared 1 of the 1,000 CPU seeds (264 compute, the rest used instructions it does not translate). The CPU part now generates programs of what the lowering translates: 149 of 1,000 compared, 0 mismatches. At 5,000 seeds a base, 1,535 of 10,000 compared and 12 mismatched, all a whole-wave section while lanes are elsewhere (mismatch 4's class). In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:53Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 727

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),
+    }
+}
+
+pub(crate) type Form = (&'static str, fn(&Case) -> Got);
+
+/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native
+/// ones on one with 64-lane waves.
+pub(crate) fn gpu_forms() -> Vec<Form> {
+    let mut forms: Vec<Form> = Vec::new();
+    if runner::wave32_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL split", |c| hlsl(c, true)));
+        }
+        forms.push(("direct split", |c| direct(c, true)));
+        forms.push(("per-lane split", |c| per_lane(c, true)));
+    }
+    if runner::wave64_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL wave64", |c| hlsl(c, false)));
+        }
+        forms.push(("direct wave64", |c| direct(c, false)));
+        forms.push(("per-lane wave64", |c| per_lane(c, false)));
+    }
+    forms
+}
+
+/// A dword as an integer ordered like the float it is, for ULP distances.
+fn ordered(x: u32) -> i64 {
+    if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) }
+}
+
+/// The verdict of one form on one case.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Verdict {
+    /// dwords compared exactly, dwords compared within their bound
+    Match(usize, usize),
+    /// first differing dword (where, reference, form) and how many differ
+    Mismatch(String, u32, u32, usize),
+    Refused(String),
+    Failed(String),
+}
+
+pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict {
+    let words = match got {
+        Got::Words(w) => w,
+        Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()),
+        Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()),
+    };
+    let (want, taint) = want;
+    if words.len() != want.len() {
+        return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len()));
+    }
+    let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0);
+    for k in 0..want.len() {
+        let (w, g, t) = (want[k], words[k], taint[k]);
+        let ok = if t == 0 {
+            exact += 1;
+            w == g
+        } else {
+            bounded += 1;
+            w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t)
+        };
+        if !ok {
+            n += 1;
+            first.get_or_insert(k);
+        }
+    }
+    match first {
+        None => Verdict::Match(exact, bounded),
+        Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n),
+    }
+}
+
+// ------------------------------------------------------------------------ the cases
+
+/// lanes_state of the tests, plus v2 = a value with both halves' patterns.
+fn kernel_state(exec: u64) -> KernelState {
+    let mut st = KernelState::default();
+    st.sgpr[126] = exec as u32;
+    st.sgpr[127] = (exec >> 32) as u32;
+    for (l, r) in st.vgpr.iter_mut().enumerate() {
+        r[0] = l as u32;
+        r[1] = 3 * l as u32 + 1;
+        r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7;
+        r[3] = 4 * l as u32;
+        r[4] = ((l as f32) * 0.25 - 3.0).to_bits();
+    }
+    st
+}
+
+/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions.
+fn kernel_case(name: &str, list: &[I], exec: u64) -> Case {
+    let mut l = vec![
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32),
+        lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32),
+    ];
+    l.extend_from_slice(list);
+    l.push(end());
+    Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62);
+
+fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I {
+    i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)])
+}
+
+/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8.
+pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I {
+    const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
+    let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)];
+    f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x)));
+    (name, "VOP2_VOP_DPP8", f, None)
+}
+
+pub(crate) fn kernel_cases() -> Vec<Case> {
+    let mut cases = vec![
+        kernel_case(
+            "lane reads across the halves",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "lane reads and ballots under a full EXEC",
+            &[
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]),
+                i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]),
+                lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]),
+                i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]),
+                i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]),
+            ],
+            !0,
+        ),
+        kernel_case(
+            "a scalar written while lanes are off reaches them",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "a scalar written in a branch reaches the lanes outside it",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]),
+            ],
+            0xFFFF_FFFF << 32,
+        ),
+        kernel_case(
+            "permlane16 and permlanex16",
+            &[
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]),
+                i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP16 rows with BOUND_CTRL and EXEC holes",
+            &[
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]),
+                dpp16("V_OR_B32", 6, 2, 1, 0x140, 1),
+                dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0),
+                dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1),
+                dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0),
+                dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1),
+                dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "DPP8 xor steps with EXEC holes",
+            &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)],
+            HOLES,
+        ),
+        kernel_case(
+            "ds_swizzle, ds_bpermute and ds_permute",
+            &[
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]),
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]),
+                lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]),
+                i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]),
+                // index lane + 40: past the half, which wraps within it
+                lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160),
+                i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "masks across the halves",
+            &[
+                lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000),
+                i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]),
+                i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]),
+                i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]),
+                i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]),
+                i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]),
+                i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]),
+                i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]),
+                i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]),
+                lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45),
+                i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]),
+                i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]),
+                i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]),
+                i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "carries across the halves",
+            &[
+                lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000),
+                i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]),
+                i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]),
+                i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]),
+                i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "exact float rules",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]),
+                i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]),
+                i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]),
+                i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]),
+                i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]),
+                i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]),
+                i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]),
+                i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]),
+                i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]),
+                i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]),
+                i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]),
+                i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]),
+                i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]),
+                i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]),
+                i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]),
+            ],
+            HOLES,
+        ),
+        kernel_case(
+            "transcendentals",
+            &[
+                i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]),
+                i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]),
+                i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]),
+                i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]),
+                i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]),
+            ],
+            !0,
+        ),
+    ];
+    // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into
+    let mut img = kernel_case(
+        "images",
+        &[
+            i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]),
+            i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]),
+            i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]),
+            i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()),
+            lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()),
+            i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]),
+            i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]),
+            i("S_WAITCNT", "ENC_SOPP", &[]),
+        ],
+        !0,
+    );
+    if let Abi::Kernel(st) = &mut img.abi {
+        // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D
+        st.sgpr[0] = 0;
+        st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+        st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]);
+    }
+    img.tex = vec![
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false },
+        TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true },
+    ];
+    img.samplers = vec![TestSampler {
+        filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT,
+        address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
+        comparison: None,
+    }];
+    cases.push(img);
+    cases
+}
+
+const EXEC_PAIR: u64 = 126;
+
+/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material
+/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a
+/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS.
+/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs.
+pub(crate) fn classifier() -> Vec<u8> {
+    let mut l = vec![
+        i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]),
+        i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]),
+        i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]),
+        // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]),
+        i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]),
+        i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]),
+        i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]),
+        i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        // lanes of material 7 are off for the reductions
+        i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]),
+    ];
+    // (op, identity, result SGPR, LDS atomic)
+    for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] {
+        l.extend([
+            i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]),
+            i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]),
+            dpp8_xor(op, 11, 11, 11, 1),
+            dpp8_xor(op, 11, 11, 11, 2),
+            dpp8_xor(op, 11, 11, 11, 4),
+            dpp16(op, 11, 11, 11, 0x140, 1),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+            lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+            i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+            i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]),
+            i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]),
+            i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]),
+            i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]),
+            i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]),
+            i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]),
+        ]);
+        if let Some((atomic, at)) = ds {
+            l.extend([
+                lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]),
+                i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]),
+            ]);
+        }
+    }
+    l.extend([
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("S_BARRIER", "ENC_SOPP", &[]),
+        i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]),
+        // five dwords a thread at s1 + 20 · thread
+        i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]),
+        i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]),
+        i("S_WAITCNT", "ENC_SOPP", &[]),
+        i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]),
+        end(),
+    ]);
+    asm(&l)
+}
+
+/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in
+/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in
+/// row 3.
+pub(crate) fn classifier_case() -> Case {
+    let groups = 6u32;
+    let mut mem = vec![0u32; groups as usize * 256 * 6];
+    for g in 0..groups as usize {
+        for t in 0..256usize {
+            let lane = t % 64;
+            mem[g * 256 + t] = match g {
+                0 => 3,
+                1 => if lane < 32 { 2 } else { 5 },
+                2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6],
+                3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 },
+                4 => if t == 20 { 1 } else { 6 },
+                _ => if t == 50 { 9 } else { 6 },
+            };
+        }
+    }
+    let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 };
+    Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has
+/// no threads, its lanes are turned on, given the identity and read by v_readlane 32.
+pub(crate) fn empty_half_case() -> Case {
+    let code = asm(&[
+        i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]),
+        i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]),
+        i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]),
+        i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]),
+        i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]),
+        i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]),
+        i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]),
+        end(),
+    ]);
+    let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 };
+    Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true }
+}
+
+pub(crate) fn cases() -> Vec<Case> {
+    let mut c = kernel_cases();
+    c.push(classifier_case());
+    c.push(empty_half_case());
+    c
+}
+
+/// Mismatches main has today, (case, form): each one is listed in the pull request that
+/// added the harness. A form that starts to agree turns the test red until its line goes.
+const KNOWN: &[(&str, &str)] = &[
+    ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "HLSL split"),
+    ("a whole-wave section in a wave with an empty upper half", "direct split"),
+    ("a whole-wave section in a wave with an empty upper half", "per-lane split"),
+];
+
+fn print(case: &str, form: &str, v: &Verdict) {
+    use std::io::Write;
+    let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}");
+}
+
+#[test]
+fn gpu_wave64_forms_agree_with_the_reference() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let forms = gpu_forms();
+    if forms.is_empty() {
+        return runner::skip_test("no wave64");
+    }
+    let mut unexpected = Vec::new();
+    let mut matched = 0;
+    for case in cases() {
+        let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name));
+        for (form, run) in &forms {
+            let v = judge(&case, &want, run(&case));
+            print(&case.name, form, &v);
+            let known = KNOWN.contains(&(case.name.as_str(), *form));
+            match (&v, known) {
+                (Verdict::Match(..), false) => matched += 1,
+                (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {}
+                _ => unexpected.push(format!("{} / {form}: {v:?}", case.name)),
+            }
+        }
+    }
+    assert!(unexpected.is_empty(), "{} unexpected:\n{}", unexpected.len(), unexpected.join("\n"));
+    assert!(matched > 0, "no form translated any case");
+}
+
+/// The negative controls: a reference with a rule turned the wrong way must disagree with
+/// every form that agrees with the right one, on the cases that use the rule.
+#[test]
+fn gpu_a_flipped_rule_is_seen_by_every_form() {
+    if runner::adapter().is_err() {
+        return runner::skip_test("no GPU");
+    }
+    let forms = gpu_forms();
+    if forms.is_empty() {
+        return runner::skip_test("no wave64");
+    }
+    let mut blind = Vec::new();
+    for (flip, case) in [(Flip::Lane31, "lane reads across the halves"), (Flip::PermlaneOwnRow, "permlane16 and permlanex16"), (Flip::Lane31, "classifier-shaped reduction"), (Flip::PermlaneOwnRow, "classifier-shaped reduction")] {

Changed in forms.rs: a_flipped_rule_changes_a_compared_word_of_its_cases asserts right != wrong on the CPU for all four flips (Lane31, PermlaneOwnRow, ExecIgnored, VccLow). gpu_every_form_is_checked_against_every_flip requires each form to match the reference on a case of every flip, prints which forms were checked, and fails for a form that matched none of them. On the RTX 2070 SUPER all four flips were checked by all three split forms.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776711659 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776711659). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:53Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 727 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), + } +} + +pub(crate) type Form = (&'static str, fn(&Case) -> Got); + +/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native +/// ones on one with 64-lane waves. +pub(crate) fn gpu_forms() -> Vec<Form> { + let mut forms: Vec<Form> = Vec::new(); + if runner::wave32_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL split", |c| hlsl(c, true))); + } + forms.push(("direct split", |c| direct(c, true))); + forms.push(("per-lane split", |c| per_lane(c, true))); + } + if runner::wave64_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL wave64", |c| hlsl(c, false))); + } + forms.push(("direct wave64", |c| direct(c, false))); + forms.push(("per-lane wave64", |c| per_lane(c, false))); + } + forms +} + +/// A dword as an integer ordered like the float it is, for ULP distances. +fn ordered(x: u32) -> i64 { + if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) } +} + +/// The verdict of one form on one case. +#[derive(Debug, PartialEq)] +pub(crate) enum Verdict { + /// dwords compared exactly, dwords compared within their bound + Match(usize, usize), + /// first differing dword (where, reference, form) and how many differ + Mismatch(String, u32, u32, usize), + Refused(String), + Failed(String), +} + +pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict { + let words = match got { + Got::Words(w) => w, + Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()), + Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()), + }; + let (want, taint) = want; + if words.len() != want.len() { + return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len())); + } + let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0); + for k in 0..want.len() { + let (w, g, t) = (want[k], words[k], taint[k]); + let ok = if t == 0 { + exact += 1; + w == g + } else { + bounded += 1; + w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t) + }; + if !ok { + n += 1; + first.get_or_insert(k); + } + } + match first { + None => Verdict::Match(exact, bounded), + Some(k) => Verdict::Mismatch(label(case, k), want[k], words[k], n), + } +} + +// ------------------------------------------------------------------------ the cases + +/// lanes_state of the tests, plus v2 = a value with both halves' patterns. +fn kernel_state(exec: u64) -> KernelState { + let mut st = KernelState::default(); + st.sgpr[126] = exec as u32; + st.sgpr[127] = (exec >> 32) as u32; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 3 * l as u32 + 1; + r[2] = (l as u32).wrapping_mul(0x9E37_79B9) >> 7; + r[3] = 4 * l as u32; + r[4] = ((l as f32) * 0.25 - 3.0).to_bits(); + } + st +} + +/// A case of `list` run by one wave of 64, EXEC set to `exec` by its first instructions. +fn kernel_case(name: &str, list: &[I], exec: u64) -> Case { + let mut l = vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], exec as u32), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (exec >> 32) as u32), + ]; + l.extend_from_slice(list); + l.push(end()); + Case { name: name.into(), code: asm(&l), abi: Abi::Kernel(kernel_state(!0)), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +const HOLES: u64 = !(1 << 5 | 1 << 17 | 1 << 33 | 1 << 47 | 1 << 62); + +fn dpp16(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, ctrl: u64, bound: u64) -> I { + i(name, "VOP2_VOP_DPP16", &[("VDST", vdst), ("SRC0", 0xFA), ("VSRC0", vsrc0), ("VSRC1", vsrc1), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", bound)]) +} + +/// `name` in its DPP8 form, each lane reading lane ^ `x` of its group of 8. +pub(crate) fn dpp8_xor(name: &'static str, vdst: u64, vsrc0: u64, vsrc1: u64, x: u64) -> I { + const SEL: [&str; 8] = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + let mut f = vec![("VDST", vdst), ("SRC0", 0xE9), ("VSRC0", vsrc0), ("VSRC1", vsrc1)]; + f.extend(SEL.iter().enumerate().map(|(k, &n)| (n, k as u64 ^ x))); + (name, "VOP2_VOP_DPP8", f, None) +} + +pub(crate) fn kernel_cases() -> Vec<Case> { + let mut cases = vec![ + kernel_case( + "lane reads across the halves", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 100), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 4)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 10), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 5), ("SRC1", 128 + 50)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 2)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 2)]), + ], + !0, + ), + kernel_case( + "lane reads and ballots under a full EXEC", + &[ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("SRC1", 128 + 63)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)]), + lit("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 2)], 0x80_0000), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 106)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 106), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 107), ("SRC1", V + 6)]), + i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 10), ("VSRC1", 1)]), + i("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 11), ("SRC1", 128 + 50)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 8), ("SRC1", 128 + 50)]), + ], + !0, + ), + kernel_case( + "a scalar written while lanes are off reaches them", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 129)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 5)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "a scalar written in a branch reaches the lanes outside it", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 255)], 40), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(super::asm::TO, 6)]), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x600D), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 4)]), + ], + 0xFFFF_FFFF << 32, + ), + kernel_case( + "permlane16 and permlanex16", + &[ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 255)], 0x0123_4567), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 255)], 0x89AB_CDEF), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 7)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 7)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 4), ("SRC2", 5)]), + i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 5), ("SRC2", 4)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 1), ("SRC1", 5), ("SRC2", 4), ("OP_SEL", 1)]), + ], + HOLES, + ), + kernel_case( + "DPP16 rows with BOUND_CTRL and EXEC holes", + &[ + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 9)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128 + 9)]), + dpp16("V_OR_B32", 6, 2, 1, 0x140, 1), + dpp16("V_ADD_NC_U32", 7, 2, 1, 0x111, 0), + dpp16("V_MAX_U32", 8, 2, 1, 0x1B, 1), + dpp16("V_MIN_U32", 9, 2, 1, 0x161, 0), + dpp16("V_ADD_NC_U32", 10, 2, 1, 0x153, 1), + dpp16("V_ADD_F32", 11, 4, 4, 0x101, 1), + ], + HOLES, + ), + kernel_case( + "DPP8 xor steps with EXEC holes", + &[dpp8_xor("V_OR_B32", 6, 2, 2, 1), dpp8_xor("V_MIN_U32", 7, 2, 6, 2), dpp8_xor("V_MAX_F32", 8, 4, 4, 4), dpp8_xor("V_ADD_NC_U32", 9, 2, 1, 7)], + HOLES, + ), + kernel_case( + "ds_swizzle, ds_bpermute and ds_permute", + &[ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x40)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + lit("V_XOR_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 0x54), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 9), ("ADDR", 5), ("DATA0", 2)]), + i("DS_PERMUTE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 5), ("DATA0", 2)]), + // index lane + 40: past the half, which wraps within it + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 3)], 160), + i("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 5), ("DATA0", 2)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + HOLES, + ), + kernel_case( + "masks across the halves", + &[ + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0x80_0000), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 10)]), + i("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", EXEC_PAIR)]), + i("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 15), ("SSRC0", EXEC_PAIR)]), + i("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 126), ("SRC1", 128)]), + i("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 127), ("SRC1", V + 6)]), + i("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 12)]), + i("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 12), ("SSRC1", 10)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128 + 3)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 12)]), + lit("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], 45), + i("S_CBRANCH_VCCZ", "ENC_SOPP", &[(super::asm::TO, 15)]), + i("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]), + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 128 + 9), ("SRC1", V + 2), ("SRC2", 22)]), + ], + HOLES, + ), + kernel_case( + "carries across the halves", + &[ + lit("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 6), ("SDST", 10), ("SRC0", V + 2), ("SRC1", 255)], 0xFF80_0000), + i("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128), ("VSRC1", 0)]), + i("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 12), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 10)]), + i("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 16), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 1)]), + i("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", V + 1)]), + ], + HOLES, + ), + kernel_case( + "exact float rules", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 0)]), + i("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + i("V_FMA_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 242)]), + i("V_MED3_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 241), ("SRC2", 244)]), + i("V_FRACT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 4)]), + i("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 4)]), + i("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 4)]), + i("V_FMA_MIX_F32", "ENC_VOP3P", &[("VDST", 13), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", V + 4), ("OP_SEL_HI", 0)]), + i("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V + 4)]), + i("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 14)]), + i("V_MAX3_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", V + 6), ("SRC2", 247)]), + i("V_SUBREV_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", V + 6), ("NEG", 1), ("OMOD", 1)]), + i("V_CMP_CLASS_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 128 + 0x30)]), + i("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 18), ("SRC0", V + 4)]), + i("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 4)]), + ], + HOLES, + ), + kernel_case( + "transcendentals", + &[ + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + i("V_RCP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + i("V_RSQ_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + i("V_SQRT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + i("V_MUL_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 7), ("VSRC1", 6)]), + ], + !0, + ), + ]; + // images: a 4 x 4 float texture read, sampled and gathered, a uint UAV stored and ORed into + let mut img = kernel_case( + "images", + &[ + i("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 128 + 3), ("VSRC1", 0)]), + i("V_BFE_U32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V), ("SRC1", 130), ("SRC2", 130)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 10)]), + i("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 240), ("VSRC1", 12)]), + i("V_ADD_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 240), ("VSRC1", 13)]), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12)], 0.25f32.to_bits()), + lit("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 13)], 0.25f32.to_bits()), + i("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 20), ("VADDR", 10), ("SRSRC", 4), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 21), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_GATHER4_LZ", "ENC_MIMG", &[("VDATA", 22), ("VADDR", 12), ("SRSRC", 4), ("SSAMP", 0), ("DMASK", 1), ("DIM", 1)]), + i("IMAGE_ATOMIC_OR", "ENC_MIMG", &[("VDATA", 0), ("VADDR", 10), ("SRSRC", 6), ("DMASK", 1), ("DIM", 1)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + ], + !0, + ); + if let Abi::Kernel(st) = &mut img.abi { + // T#s as `recomp::tests` builds them: heap index, format (32_FLOAT, 32_UINT), 2D + st.sgpr[0] = 0; + st.sgpr[16..24].copy_from_slice(&[0, 22 << 20, 0, 9 << 28, 0, 0, 0, 0]); + st.sgpr[24..32].copy_from_slice(&[2, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]); + } + img.tex = vec![ + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: (0..16).flat_map(|k| (k as f32 * 1.5).to_le_bytes()).collect(), uav: false }, + TestTexture { dim: TexDim::D2, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0; 64], uav: true }, + ]; + img.samplers = vec![TestSampler { + filter: windows::Win32::Graphics::Direct3D12::D3D12_FILTER_MIN_MAG_MIP_POINT, + address: windows::Win32::Graphics::Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + comparison: None, + }]; + cases.push(img); + cases +} + +const EXEC_PAIR: u64 = 126; + +/// A 64-lane OR, AND and MIN in the shape of a tile classifier: lanes off in EXEC (material +/// 7) take the identity from the saved EXEC, three DPP8 xor steps, a row mirror, a +/// permlanex16, then v_readlane 32 and 0; a wave's results go to the group through LDS. +/// v0, v1 = the thread's x, y in a 16 x 16 group; s0 = the materials, s1 = the outputs. +pub(crate) fn classifier() -> Vec<u8> { + let mut l = vec![ + i("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 128 + 4), ("SRC2", V)]), + i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 128 + 8)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 2)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 0), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)]), + i("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 10), ("ADDR", 4), ("SADDR", 0x7D)]), + // LDS[0] = 0 (OR), LDS[1] = !0 (MIN), by thread 0, before anyone adds to them + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 193)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 128), ("SRC1", V + 0)]), + i("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 128), ("SRC1", V + 1)]), + i("S_AND_B64", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 32)]), + i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 34), ("SSRC0", 30)]), + i("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 5), ("DATA0", 6), ("DATA1", 7), ("OFFSET0", 0), ("OFFSET1", 1)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 34)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + // lanes of material 7 are off for the reductions + i("V_CMPX_NE_U32", "ENC_VOPC", &[("SRC0", 128 + 7), ("VSRC1", 10)]), + ]; + // (op, identity, result SGPR, LDS atomic) + for (op, id, s, ds) in [("V_OR_B32", 128u64, 40u64, Some(("DS_OR_B32", 0u64))), ("V_AND_B32", 193, 42, None), ("V_MIN_U32", 193, 44, Some(("DS_MIN_U32", 4)))] { + l.extend([ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 36), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", id), ("SRC1", V + 10), ("SRC2", 36)]), + dpp8_xor(op, 11, 11, 11, 1), + dpp8_xor(op, 11, 11, 11, 2), + dpp8_xor(op, 11, 11, 11, 4), + dpp16(op, 11, 11, 11, 0x140, 1), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 12), ("VSRC1", 11)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s), ("SRC0", V + 11), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", s + 1), ("SRC0", V + 11), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", s)]), + i(op, "ENC_VOP2", &[("VDST", 13), ("SRC0", s + 1), ("VSRC1", 13)]), + i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", s), ("SRC0", V + 13)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 36)]), + ]); + if let Some((atomic, at)) = ds { + l.extend([ + lit("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 255)], at as u32), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", s)]), + i(atomic, "ENC_DS", &[("ADDR", 14), ("DATA0", 15)]), + ]); + } + } + l.extend([ + i("S_MOV_B64", "ENC_SOP1", &[("SDST", EXEC_PAIR), ("SSRC0", 193)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("S_BARRIER", "ENC_SOPP", &[]), + i("DS_READ2_B32", "ENC_DS", &[("VDST", 16), ("ADDR", 5), ("OFFSET0", 0), ("OFFSET1", 1)]), + // five dwords a thread at s1 + 20 · thread + i("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128 + 20), ("VSRC1", 2)]), + i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 1), ("VSRC1", 3)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 18), ("SRC0", 40)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 19), ("SRC0", 42)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 44)]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i("GLOBAL_STORE_DWORDX3", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 18), ("SADDR", 0x7D)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 16), ("SADDR", 0x7D), ("OFFSET", 12)]), + end(), + ]); + asm(&l) +} + +/// The classifier on 6 groups: one surface everywhere; one per half of each wave; a mix in +/// both halves; odd lanes at 31, 32 and 63 of the first wave; one odd lane in row 1, one in +/// row 3. +pub(crate) fn classifier_case() -> Case { + let groups = 6u32; + let mut mem = vec![0u32; groups as usize * 256 * 6]; + for g in 0..groups as usize { + for t in 0..256usize { + let lane = t % 64; + mem[g * 256 + t] = match g { + 0 => 3, + 1 => if lane < 32 { 2 } else { 5 }, + 2 => [1u32, 4, 7, 9, 7, 3][(t * 7 + t / 5) % 6], + 3 => if t < 64 && [31, 32, 63].contains(&lane) { 8 } else { 6 }, + 4 => if t == 20 { 1 } else { 6 }, + _ => if t == 50 { 9 } else { 6 }, + }; + } + } + let cs = CsInterface { threads: [16, 16, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2 }; + Case { name: "classifier-shaped reduction".into(), code: classifier(), abi: Abi::Compute(cs, [groups, 1, 1], vec![0, groups * 256 * 4]), mem, tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +/// A whole-wave section in each wave of a 96-thread group: the second wave's upper half has +/// no threads, its lanes are turned on, given the identity and read by v_readlane 32. +pub(crate) fn empty_half_case() -> Case { + let code = asm(&[ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 193)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128 + 7), ("SRC1", V), ("SRC2", 10)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128 + 63)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 13)]), + i("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)]), + end(), + ]); + let cs = CsInterface { threads: [96, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + Case { name: "a whole-wave section in a wave with an empty upper half".into(), code, abi: Abi::Compute(cs, [1, 1, 1], Vec::new()), mem: vec![0; 192], tex: Vec::new(), samplers: Vec::new(), scalars: true } +} + +pub(crate) fn cases() -> Vec<Case> { + let mut c = kernel_cases(); + c.push(classifier_case()); + c.push(empty_half_case()); + c +} + +/// Mismatches main has today, (case, form): each one is listed in the pull request that +/// added the harness. A form that starts to agree turns the test red until its line goes. +const KNOWN: &[(&str, &str)] = &[ + ("ds_swizzle, ds_bpermute and ds_permute", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "HLSL split"), + ("a whole-wave section in a wave with an empty upper half", "direct split"), + ("a whole-wave section in a wave with an empty upper half", "per-lane split"), +]; + +fn print(case: &str, form: &str, v: &Verdict) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{case:42} {form:16} {v:?}"); +} + +#[test] +fn gpu_wave64_forms_agree_with_the_reference() { + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + let forms = gpu_forms(); + if forms.is_empty() { + return runner::skip_test("no wave64"); + } + let mut unexpected = Vec::new(); + let mut matched = 0; + for case in cases() { + let want = reference(&case, Flip::None).unwrap_or_else(|e| panic!("{}: {e}", case.name)); + for (form, run) in &forms { + let v = judge(&case, &want, run(&case)); + print(&case.name, form, &v); + let known = KNOWN.contains(&(case.name.as_str(), *form)); + match (&v, known) { + (Verdict::Match(..), false) => matched += 1, + (Verdict::Mismatch(..) | Verdict::Failed(_), true) | (Verdict::Refused(_), _) => {} + _ => unexpected.push(format!("{} / {form}: {v:?}", case.name)), + } + } + } + assert!(unexpected.is_empty(), "{} unexpected:\n{}", unexpected.len(), unexpected.join("\n")); + assert!(matched > 0, "no form translated any case"); +} + +/// The negative controls: a reference with a rule turned the wrong way must disagree with +/// every form that agrees with the right one, on the cases that use the rule. +#[test] +fn gpu_a_flipped_rule_is_seen_by_every_form() { + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + let forms = gpu_forms(); + if forms.is_empty() { + return runner::skip_test("no wave64"); + } + let mut blind = Vec::new(); + for (flip, case) in [(Flip::Lane31, "lane reads across the halves"), (Flip::PermlaneOwnRow, "permlane16 and permlanex16"), (Flip::Lane31, "classifier-shaped reduction"), (Flip::PermlaneOwnRow, "classifier-shaped reduction")] { ~~~~ --- Changed in `forms.rs`: `a_flipped_rule_changes_a_compared_word_of_its_cases` asserts right != wrong on the CPU for all four flips (Lane31, PermlaneOwnRow, ExecIgnored, VccLow). `gpu_every_form_is_checked_against_every_flip` requires each form to match the reference on a case of every flip, prints which forms were checked, and fails for a form that matched none of them. On the RTX 2070 SUPER all four flips were checked by all three split forms. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:55 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:55Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 282

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));
+    }
+    (s.into_iter().collect(), v.into_iter().collect())
+}
+
+/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no
+/// per-lane form, and a compute wave has no such lane).
+fn launched(case: &Case) -> u64 {
+    match &case.abi {
+        Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32,
+        Abi::Compute(..) => !0,
+    }
+}
+
+/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched
+/// (0 for the others), memory, and the UAV textures' bytes.
+fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> {
+    let (mut s, v) = written(&case.code);
+    if !case.scalars {
+        s.clear();
+    }
+    let on = launched(case);
+    let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect();
+    for &r in &v {
+        out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 }));
+    }
+    out.extend_from_slice(&mem[..case.mem.len()]);
+    for t in tex {
+        out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b))));
+    }
+    out
+}
+
+/// Where dword `k` of `kernel_words` comes from.
+fn label(case: &Case, k: usize) -> String {
+    if let Abi::Kernel(_) = case.abi {
+        let (mut s, v) = written(&case.code);
+        if !case.scalars {
+            s.clear();
+        }
+        if k < s.len() {
+            return format!("s{}", s[k]);
+        }
+        let k = k - s.len();
+        if k < 64 * v.len() {
+            return format!("v{} of lane {}", v[k / 64], k % 64);
+        }
+        let k = k - 64 * v.len();
+        if k < case.mem.len() {
+            return format!("memory dword {k}");
+        }
+        return format!("texture dword {}", k - case.mem.len());
+    }
+    format!("memory dword {k}")
+}
+
+/// The reference's output and the taint of each dword.
+pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> {
+    match &case.abi {
+        Abi::Kernel(st) => {
+            let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?;
+            let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect();
+            let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav);
+            let (s, v) = written(&case.code);
+            let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect();
+            for &reg in &v {
+                taint.extend((0..64).map(|l| r.vtaint[l][reg]));
+            }
+            taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)));
+            for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) {
+                taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4)));
+            }
+            Ok((words, taint))
+        }
+        Abi::Compute(cs, groups, io) => {
+            let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?;
+            let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect();
+            Ok((r.mem, taint))
+        }
+    }
+}
+
+fn io128(io: &[u32]) -> Vec<u32> {
+    let mut v = io.to_vec();
+    v.resize(128, 0);
+    v
+}
+
+fn hlsl(case: &Case, split: bool) -> Got {
+    let mode = match &case.abi {
+        Abi::Kernel(_) => Mode::Kernel,
+        Abi::Compute(cs, ..) => Mode::Compute(cs.clone()),
+    };
+    let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) {
+        Ok(t) if t.complete() => t,
+        Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)),
+        Err(e) => return Got::Refused(e),
+    };
+    let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) {
+        Ok(d) => d,
+        Err(e) => return Got::Failed(format!("DXC: {e}")),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+fn direct(case: &Case, split: bool) -> Got {
+    let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 };
+    let k = match &case.abi {
+        Abi::Kernel(_) => kernel::translate_full(&case.code, o),
+        Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs),
+    };
+    let k = match k {
+        Ok(k) => k,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => {
+            let r = match &k.dispatch_chain {
+                Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0),
+                None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem),
+            };
+            match r {
+                Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+                Err(e) => Got::Failed(e),
+            }
+        }
+    }
+}
+
+fn per_lane(case: &Case, split: bool) -> Got {
+    let insts = decoded(&case.code);
+    let dxil = match &case.abi {
+        Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0),
+        Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0),
+        Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs),
+        Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true),
+    };
+    let dxil = match dxil {
+        Ok(d) => d,
+        Err(e) => return Got::Refused(e),
+    };
+    match &case.abi {
+        Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) {
+            Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)),
+            Err(e) => Got::Failed(e),
+        },
+        Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) {
+            Ok(m) => Got::Words(m[..case.mem.len()].to_vec()),
+            Err(e) => Got::Failed(e),
+        },
+    }
+}
+
+/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode.
+pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got {
+    let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) };
+    if !case.tex.is_empty() {
+        return Got::Refused("textures".into());
+    }
+    let insts = decoded(&case.code);
+    let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem));
+    match run {
+        Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])),
+        Ok(Err(e)) => Got::Refused(e),
+        Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))),
+    }
+}
+
+pub(crate) type Form = (&'static str, fn(&Case) -> Got);
+
+/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native
+/// ones on one with 64-lane waves.
+pub(crate) fn gpu_forms() -> Vec<Form> {
+    let mut forms: Vec<Form> = Vec::new();
+    if runner::wave32_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL split", |c| hlsl(c, true)));
+        }
+        forms.push(("direct split", |c| direct(c, true)));
+        forms.push(("per-lane split", |c| per_lane(c, true)));
+    }
+    if runner::wave64_supported() == Ok(true) {
+        if dxc::location().is_ok() {
+            forms.push(("HLSL wave64", |c| hlsl(c, false)));
+        }
+        forms.push(("direct wave64", |c| direct(c, false)));
+        forms.push(("per-lane wave64", |c| per_lane(c, false)));
+    }
+    forms
+}
+
+/// A dword as an integer ordered like the float it is, for ULP distances.
+fn ordered(x: u32) -> i64 {
+    if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) }
+}
+
+/// The verdict of one form on one case.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Verdict {
+    /// dwords compared exactly, dwords compared within their bound
+    Match(usize, usize),
+    /// first differing dword (where, reference, form) and how many differ
+    Mismatch(String, u32, u32, usize),
+    Refused(String),
+    Failed(String),
+}
+
+pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict {
+    let words = match got {
+        Got::Words(w) => w,
+        Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()),
+        Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()),
+    };
+    let (want, taint) = want;
+    if words.len() != want.len() {
+        return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len()));
+    }
+    let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0);
+    for k in 0..want.len() {
+        let (w, g, t) = (want[k], words[k], taint[k]);
+        let ok = if t == 0 {
+            exact += 1;
+            w == g
+        } else {
+            bounded += 1;
+            w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t)

Changed in mod.rs and forms.rs: a bound now holds only for the approximate op's own result and for bit copies of it (moves, lane reads, selects). Anything computed from it is UNBOUNDED and not compared (counted in Match), so an integer downstream such as V_CVT_U32_F32 after V_RCP is not compared loosely. RCP/RSQ/SQRT keep their ULP bounds; V_SIN/V_COS use D3D's absolute 0.0008; V_EXP/V_LOG are not compared. A NaN made by float arithmetic agrees with any NaN. a_cancellation_after_an_approximate_rcp_is_not_compared gives v_rcp a 1-ULP error and checks that rcp(x)·x - 1 moves by over 2^20 ULPs and is not compared.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776712017 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776712017). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:55Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 282 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); + } + (s.into_iter().collect(), v.into_iter().collect()) +} + +/// The lanes on at launch: those that exist as threads (a lane off at launch runs in no +/// per-lane form, and a compute wave has no such lane). +fn launched(case: &Case) -> u64 { + match &case.abi { + Abi::Kernel(st) => u64::from(st.sgpr[126]) | u64::from(st.sgpr[127]) << 32, + Abi::Compute(..) => !0, + } +} + +/// The compared dwords of a kernel run: written SGPRs, written VGPRs of every lane launched +/// (0 for the others), memory, and the UAV textures' bytes. +fn kernel_words(case: &Case, sgpr: &[u32], vgpr: &[Vec<u32>], mem: &[u32], tex: &[Vec<u8>]) -> Vec<u32> { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + let on = launched(case); + let mut out: Vec<u32> = s.iter().map(|&r| sgpr[r]).collect(); + for &r in &v { + out.extend((0..64).map(|l| if on >> l & 1 == 1 { vgpr[l][r] } else { 0 })); + } + out.extend_from_slice(&mem[..case.mem.len()]); + for t in tex { + out.extend(t.chunks(4).map(|c| c.iter().rev().fold(0, |x, &b| x << 8 | u32::from(b)))); + } + out +} + +/// Where dword `k` of `kernel_words` comes from. +fn label(case: &Case, k: usize) -> String { + if let Abi::Kernel(_) = case.abi { + let (mut s, v) = written(&case.code); + if !case.scalars { + s.clear(); + } + if k < s.len() { + return format!("s{}", s[k]); + } + let k = k - s.len(); + if k < 64 * v.len() { + return format!("v{} of lane {}", v[k / 64], k % 64); + } + let k = k - 64 * v.len(); + if k < case.mem.len() { + return format!("memory dword {k}"); + } + return format!("texture dword {}", k - case.mem.len()); + } + format!("memory dword {k}") +} + +/// The reference's output and the taint of each dword. +pub(crate) fn reference(case: &Case, flip: Flip) -> Result<(Vec<u32>, Vec<u8>), Stop> { + match &case.abi { + Abi::Kernel(st) => { + let r = run_kernel(&case.code, true, st, &case.mem, &case.tex, &case.samplers, flip)?; + let uav: Vec<Vec<u8>> = r.textures.iter().zip(&case.tex).filter(|x| x.1.uav).map(|x| x.0.clone()).collect(); + let words = kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &uav); + let (s, v) = written(&case.code); + let mut taint: Vec<u8> = s.iter().filter(|_| case.scalars).map(|_| 0).collect(); + for &reg in &v { + taint.extend((0..64).map(|l| r.vtaint[l][reg])); + } + taint.extend((0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0))); + for ((t, &tt), _) in r.textures.iter().zip(&r.tex_taint).zip(&case.tex).filter(|x| x.1.uav) { + taint.extend(std::iter::repeat(u8::from(tt) * 4).take(t.len().div_ceil(4))); + } + Ok((words, taint)) + } + Abi::Compute(cs, groups, io) => { + let r = run_compute(&case.code, cs, true, *groups, io, &case.mem, flip)?; + let taint = (0..case.mem.len()).map(|k| r.mem_taint.get(&k).copied().unwrap_or(0)).collect(); + Ok((r.mem, taint)) + } + } +} + +fn io128(io: &[u32]) -> Vec<u32> { + let mut v = io.to_vec(); + v.resize(128, 0); + v +} + +fn hlsl(case: &Case, split: bool) -> Got { + let mode = match &case.abi { + Abi::Kernel(_) => Mode::Kernel, + Abi::Compute(cs, ..) => Mode::Compute(cs.clone()), + }; + let t = match recomp::translate(&case.code, &Options { mode, wave64: true, split_wave64: split, ..Default::default() }) { + Ok(t) if t.complete() => t, + Ok(t) => return Got::Refused(format!("{:?}", t.unsupported)), + Err(e) => return Got::Refused(e), + }; + let dxil = match dxc::compile(&t.hlsl, "main", "cs_6_6", &[]) { + Ok(d) => d, + Err(e) => return Got::Failed(format!("DXC: {e}")), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&dxil, st, &case.mem, &case.tex, &case.samplers, &t.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch_remapped(&dxil, *groups, t.dispatch_remap, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +fn direct(case: &Case, split: bool) -> Got { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let k = match &case.abi { + Abi::Kernel(_) => kernel::translate_full(&case.code, o), + Abi::Compute(cs, ..) => kernel::translate_compute(&case.code, o, cs), + }; + let k = match k { + Ok(k) => k, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with_statics(&k.dxil, st, &case.mem, &case.tex, &case.samplers, &k.static_samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => { + let r = match &k.dispatch_chain { + Some(chain) => runner::dispatch_split_samples(chain, *groups, &io128(io), &case.mem, u64::MAX, 1, false).map(|x| x.0), + None => runner::dispatch(&k.dxil, *groups, &io128(io), &case.mem), + }; + match r { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + } + } + } +} + +fn per_lane(case: &Case, split: bool) -> Got { + let insts = decoded(&case.code); + let dxil = match &case.abi { + Abi::Kernel(_) if split => lower_dxil::kernel_split(&insts).map(|x| x.0), + Abi::Kernel(_) => lower_dxil::kernel(&insts, true).map(|x| x.0), + Abi::Compute(cs, ..) if split => lower_dxil::compute_split(&insts, cs), + Abi::Compute(cs, ..) => lower_dxil::compute(&insts, cs, true), + }; + let dxil = match dxil { + Ok(d) => d, + Err(e) => return Got::Refused(e), + }; + match &case.abi { + Abi::Kernel(st) => match runner::run_with(&dxil, st, &case.mem, &case.tex, &case.samplers) { + Ok(r) => Got::Words(kernel_words(case, &r.sgpr, &r.vgpr, &r.mem, &r.textures)), + Err(e) => Got::Failed(e), + }, + Abi::Compute(_, groups, io) => match runner::dispatch(&dxil, *groups, &io128(io), &case.mem) { + Ok(m) => Got::Words(m[..case.mem.len()].to_vec()), + Err(e) => Got::Failed(e), + }, + } +} + +/// The lowering run on the CPU by its own interpreter (`lower::tests`): no GPU, kernel mode. +pub(crate) fn lowering_on_the_cpu(case: &Case) -> Got { + let Abi::Kernel(st) = &case.abi else { return Got::Refused("compute".into()) }; + if !case.tex.is_empty() { + return Got::Refused("textures".into()); + } + let insts = decoded(&case.code); + let run = std::panic::catch_unwind(|| lower::tests::run_insts(&insts, true, &st.sgpr, &st.vgpr, &case.mem)); + match run { + Ok(Ok((s, v, m))) => Got::Words(kernel_words(case, &s, &v, &m, &[])), + Ok(Err(e)) => Got::Refused(e), + Err(e) => Got::Refused(format!("its interpreter cannot run it: {}", e.downcast_ref::<String>().map_or("?", |s| s.as_str()))), + } +} + +pub(crate) type Form = (&'static str, fn(&Case) -> Got); + +/// The GPU forms this adapter runs: the split forms on one with 32-lane waves, the native +/// ones on one with 64-lane waves. +pub(crate) fn gpu_forms() -> Vec<Form> { + let mut forms: Vec<Form> = Vec::new(); + if runner::wave32_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL split", |c| hlsl(c, true))); + } + forms.push(("direct split", |c| direct(c, true))); + forms.push(("per-lane split", |c| per_lane(c, true))); + } + if runner::wave64_supported() == Ok(true) { + if dxc::location().is_ok() { + forms.push(("HLSL wave64", |c| hlsl(c, false))); + } + forms.push(("direct wave64", |c| direct(c, false))); + forms.push(("per-lane wave64", |c| per_lane(c, false))); + } + forms +} + +/// A dword as an integer ordered like the float it is, for ULP distances. +fn ordered(x: u32) -> i64 { + if x >> 31 == 1 { -i64::from(x & 0x7FFF_FFFF) } else { i64::from(x) } +} + +/// The verdict of one form on one case. +#[derive(Debug, PartialEq)] +pub(crate) enum Verdict { + /// dwords compared exactly, dwords compared within their bound + Match(usize, usize), + /// first differing dword (where, reference, form) and how many differ + Mismatch(String, u32, u32, usize), + Refused(String), + Failed(String), +} + +pub(crate) fn judge(case: &Case, want: &(Vec<u32>, Vec<u8>), got: Got) -> Verdict { + let words = match got { + Got::Words(w) => w, + Got::Refused(e) => return Verdict::Refused(e.lines().next().unwrap_or("").chars().take(160).collect()), + Got::Failed(e) => return Verdict::Failed(e.lines().next().unwrap_or("").chars().take(160).collect()), + }; + let (want, taint) = want; + if words.len() != want.len() { + return Verdict::Failed(format!("{} dwords, the reference {}", words.len(), want.len())); + } + let (mut exact, mut bounded, mut first, mut n) = (0, 0, None, 0); + for k in 0..want.len() { + let (w, g, t) = (want[k], words[k], taint[k]); + let ok = if t == 0 { + exact += 1; + w == g + } else { + bounded += 1; + w == g || (f32::from_bits(w).is_nan() && f32::from_bits(g).is_nan()) || (ordered(w) - ordered(g)).abs() <= i64::from(t) ~~~~ --- Changed in `mod.rs` and `forms.rs`: a bound now holds only for the approximate op's own result and for bit copies of it (moves, lane reads, selects). Anything computed from it is `UNBOUNDED` and not compared (counted in `Match`), so an integer downstream such as V_CVT_U32_F32 after V_RCP is not compared loosely. RCP/RSQ/SQRT keep their ULP bounds; V_SIN/V_COS use D3D's absolute 0.0008; V_EXP/V_LOG are not compared. A NaN made by float arithmetic agrees with any NaN. `a_cancellation_after_an_approximate_rcp_is_not_compared` gives v_rcp a 1-ULP error and checks that rcp(x)·x - 1 moves by over 2^20 ULPs and is not compared. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:01:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:01:57Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/forms.rs; line 44

@@ -0,0 +1,823 @@
+//! Every wave64 form XCL has against the reference: the same program and inputs through the
+//! reference and through each form, outputs compared dword by dword (bit for bit, or within the
+//! taint's ULP bound). A form that refuses a program is counted, not failed.
+
+use super::asm::{asm, end, i, lit, I, V};
+use super::*;
+use crate::gpu::dxil::kernel::{self, KernelOptions};
+use crate::gpu::recomp::runner::TexDim;
+use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options};
+
+pub(crate) enum Abi {
+    Kernel(KernelState),
+    /// interface, groups, io (user SGPRs)
+    Compute(CsInterface, [u32; 3], Vec<u32>),
+}
+
+pub(crate) struct Case {
+    pub name: String,
+    pub code: Vec<u8>,
+    pub abi: Abi,
+    pub mem: Vec<u32>,
+    pub tex: Vec<TestTexture>,
+    pub samplers: Vec<TestSampler>,
+    /// the SGPRs at the end are compared (kernel mode)
+    pub scalars: bool,
+}
+
+/// What a form gave: its output dwords, a refusal to translate, or a failure to run.
+pub(crate) enum Got {
+    Words(Vec<u32>),
+    Refused(String),
+    Failed(String),
+}
+
+fn decoded(code: &[u8]) -> Vec<Decoded> {
+    Program::new(code).list
+}
+
+/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode.
+fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) {
+    let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
+    for d in decoded(code) {
+        s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize));
+        v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize));

Changed in forms.rs: every kernel case now copies EXEC, VCC and SCC to s[100:105] at its end, so they are compared as SGPRs. No case or fuzz program uses V_MOVRELD; its rule is tested in the reference's own tests (sdwa_selects_relative_moves_and_swap). A case that uses it would copy the destination to a fixed register.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776712336 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776712336). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:01:57Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/forms.rs`; line 44 ~~~~diff @@ -0,0 +1,823 @@ +//! Every wave64 form XCL has against the reference: the same program and inputs through the +//! reference and through each form, outputs compared dword by dword (bit for bit, or within the +//! taint's ULP bound). A form that refuses a program is counted, not failed. + +use super::asm::{asm, end, i, lit, I, V}; +use super::*; +use crate::gpu::dxil::kernel::{self, KernelOptions}; +use crate::gpu::recomp::runner::TexDim; +use crate::gpu::recomp::{self, dxc, lower, lower_dxil, runner, Mode, Options}; + +pub(crate) enum Abi { + Kernel(KernelState), + /// interface, groups, io (user SGPRs) + Compute(CsInterface, [u32; 3], Vec<u32>), +} + +pub(crate) struct Case { + pub name: String, + pub code: Vec<u8>, + pub abi: Abi, + pub mem: Vec<u32>, + pub tex: Vec<TestTexture>, + pub samplers: Vec<TestSampler>, + /// the SGPRs at the end are compared (kernel mode) + pub scalars: bool, +} + +/// What a form gave: its output dwords, a refusal to translate, or a failure to run. +pub(crate) enum Got { + Words(Vec<u32>), + Refused(String), + Failed(String), +} + +fn decoded(code: &[u8]) -> Vec<Decoded> { + Program::new(code).list +} + +/// The registers a program writes (SGPRs, VGPRs), the dwords compared in kernel mode. +fn written(code: &[u8]) -> (Vec<usize>, Vec<usize>) { + let (mut s, mut v) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for d in decoded(code) { + s.extend(rdna2::sgpr_uses(&d).1.into_iter().filter(|&r| r < 106).map(|r| r as usize)); + v.extend(rdna2::vgpr_uses(&d).1.into_iter().filter(|&r| r < 256).map(|r| r as usize)); ~~~~ --- Changed in `forms.rs`: every kernel case now copies EXEC, VCC and SCC to s[100:105] at its end, so they are compared as SGPRs. No case or fuzz program uses V_MOVRELD; its rule is tested in the reference's own tests (`sdwa_selects_relative_moves_and_swap`). A case that uses it would copy the destination to a fixed register. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:02:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:02:00Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 58

@@ -0,0 +1,550 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, masks read as data, and (compute) LDS across two waves at a barrier. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines. Integers only, and floats that stay small integers, so every
+//! comparison is exact.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, lowering_on_the_cpu, reference, Abi, Case, Form, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[t ^ k], k below 32 (compute only, at the top)

Changed in fuzz.rs: the LDS block reads LDS[(t + k) mod threads] with k below 128, so it crosses halves and waves of 64-, 96- and 128-thread groups. Lane exchanges (DPP16, DPP8, ds_swizzle, permlanex16, readlane) are also generated outside whole-wave sections, under the EXEC of the moment. Kernel programs' float inputs now include ±0, ±inf, a NaN, -1, 2^24 + 2 and 1 + 2^-12, whose square rounds differently fused and unfused. A denormal input is left out: D3D lets a GPU flush it, and on the RTX 2070 SUPER every form did; the reference's denormal rules are covered by its own tests.

In head 66daa6c0.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776712753 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4776712753). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:02:00Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 58 ~~~~diff @@ -0,0 +1,550 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, masks read as data, and (compute) LDS across two waves at a barrier. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. Integers only, and floats that stay small integers, so every +//! comparison is exact. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, lowering_on_the_cpu, reference, Abi, Case, Form, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[t ^ k], k below 32 (compute only, at the top) ~~~~ --- Changed in `fuzz.rs`: the LDS block reads LDS[(t + k) mod threads] with k below 128, so it crosses halves and waves of 64-, 96- and 128-thread groups. Lane exchanges (DPP16, DPP8, ds_swizzle, permlanex16, readlane) are also generated outside whole-wave sections, under the EXEC of the moment. Kernel programs' float inputs now include ±0, ±inf, a NaN, -1, 2^24 + 2 and 1 + 2^-12, whose square rounds differently fused and unfused. A denormal input is left out: D3D lets a GPU flush it, and on the RTX 2070 SUPER every form did; the reference's denormal rules are covered by its own tests. In head `66daa6c0`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 22:04:55 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:04:55Z.


@fyreic-dev, thanks. Points 1 to 5 are in head 66daa6c0 (on main 5ad98adb), each change squashed into the commit it belongs to; 6 and 7 need someone else.

  1. A known mismatch that turns into a failure. KNOWN in forms.rs is gone. In forms.rs, KnownMismatch now names the first differing dword and accepts only a Mismatch that starts there. Failed is never expected.
  2. A working case that starts to refuse. EXPECTED in forms.rs pins every (case, form) pair per adapter as Match, KnownMismatch(dword) or Refused(part of the reason): 13 lines for the lowering on the CPU and 45 for the three split forms on NVIDIA. Any change fails and prints the line it would need: a new refusal, a refusal that now translates, a fixed or a new mismatch, or a missing line. To check it goes red, I made the lowering refuse "permlane16 and permlanex16" for one run. The CPU test failed with expected Match, got Refused(...).
  3. CPU fuzz. A panic in the lowering or its interpreter is now Failed. Each fuzz test prints, per form, the seeds compared, the refusals by reason and the mismatches by known class. It fails on a refusal not in REFUSALS, and when a form compares fewer seeds than its floor (MIN_COMPARED_PERCENT). You were right: at d2293dcb the lowering compared 1 of the 1,000 CPU seeds. 264 were compute, and the rest used instructions it does not translate. The CPU part now generates programs from what the lowering translates, and compares 149 of 1,000; its floor is 12 %. When I made the lowering refuse 9 seeds in 10, the comparisons fell to 8 and 7 of 500 and both CPU fuzz tests failed with "under its floor of 12 %". On the RTX 2070 SUPER, of the 100 GPU seeds, HLSL split compared 100, direct split 100 and per-lane split 29 (71 refused). Their floors are 90 %, 90 % and 10 %. The 5 mismatches were all of known classes. Known mismatches in the fuzz are recognised by class (KNOWN in fuzz.rs), not by seed, so a longer XCL_FUZZ_WAVE64_SEEDS run fails only on a mismatch of no class: today that includes CharlyRien's groups 3 and 6, until they are fixed.
  4. Float tolerance. I narrowed it. A ULP bound now holds only for the approximate instruction's own result and for bit copies of it. Anything computed from it is not compared, and counted as not compared. a_cancellation_after_an_approximate_rcp_is_not_compared gives v_rcp a 1-ULP error and checks that rcp(x)·x - 1 moves by over 2^20 ULPs. The ULP bound did not hold through that subtraction, so it now holds only for the approximate result and its copies. Details are in CharlyRien's taint thread.
  5. The f16 thread. It was fixed at d2293dcb, and the thread is resolved.
  6. AMD. There is no AMD card here, so the native wave64 forms have never run. Could someone with an RDNA2, 3 or 4 card run cargo test -p xcl --lib rdna2_ref -- --nocapture? It prints per-form counts and the EXPECTED lines for that adapter. On an adapter without lines, the forms test, the flip test and the GPU fuzz print and skip instead of failing (Foniass's point 2). Posting the printed lines would let us pin AMD.
  7. Test-only waiver. The changes are still test-only (rdna2_ref/, plus the #[cfg(test)] module line and the run_insts split in recomp/lower.rs's test module). The description check needs the maintainer's test-only waiver for this head, which we cannot apply.

Tested: RTX 2070 SUPER (driver 621.01), Windows 11 26200, debug, at 66daa6c0: cargo test --workspace -- rdna2_ref --test-threads=4 gave 47 passed, 0 failed, 1 ignored and 1 SKIPPED (no llvm-mc). Linux under Wine, CPU only: cargo check with and without --tests, and the rdna2_ref tests, at every commit; at the head, 47 passed, 0 failed, 1 ignored. The whole suite was not rerun at this head.

AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7360196947 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360196947). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:04:55Z. --- @fyreic-dev, thanks. Points 1 to 5 are in head `66daa6c0` (on `main` `5ad98adb`), each change squashed into the commit it belongs to; 6 and 7 need someone else. 1. **A known mismatch that turns into a failure.** `KNOWN` in `forms.rs` is gone. In `forms.rs`, `KnownMismatch` now names the first differing dword and accepts only a `Mismatch` that starts there. `Failed` is never expected. 2. **A working case that starts to refuse.** `EXPECTED` in `forms.rs` pins every (case, form) pair per adapter as `Match`, `KnownMismatch(dword)` or `Refused(part of the reason)`: 13 lines for the lowering on the CPU and 45 for the three split forms on NVIDIA. Any change fails and prints the line it would need: a new refusal, a refusal that now translates, a fixed or a new mismatch, or a missing line. To check it goes red, I made the lowering refuse "permlane16 and permlanex16" for one run. The CPU test failed with `expected Match, got Refused(...)`. 3. **CPU fuzz.** A panic in the lowering or its interpreter is now `Failed`. Each fuzz test prints, per form, the seeds compared, the refusals by reason and the mismatches by known class. It fails on a refusal not in `REFUSALS`, and when a form compares fewer seeds than its floor (`MIN_COMPARED_PERCENT`). You were right: at d2293dcb the lowering compared 1 of the 1,000 CPU seeds. 264 were compute, and the rest used instructions it does not translate. The CPU part now generates programs from what the lowering translates, and compares 149 of 1,000; its floor is 12 %. When I made the lowering refuse 9 seeds in 10, the comparisons fell to 8 and 7 of 500 and both CPU fuzz tests failed with "under its floor of 12 %". On the RTX 2070 SUPER, of the 100 GPU seeds, HLSL split compared 100, direct split 100 and per-lane split 29 (71 refused). Their floors are 90 %, 90 % and 10 %. The 5 mismatches were all of known classes. Known mismatches in the fuzz are recognised by class (`KNOWN` in `fuzz.rs`), not by seed, so a longer `XCL_FUZZ_WAVE64_SEEDS` run fails only on a mismatch of no class: today that includes CharlyRien's groups 3 and 6, until they are fixed. 4. **Float tolerance.** I narrowed it. A ULP bound now holds only for the approximate instruction's own result and for bit copies of it. Anything computed from it is not compared, and counted as not compared. `a_cancellation_after_an_approximate_rcp_is_not_compared` gives v_rcp a 1-ULP error and checks that rcp(x)·x - 1 moves by over 2^20 ULPs. The ULP bound did not hold through that subtraction, so it now holds only for the approximate result and its copies. Details are in CharlyRien's taint thread. 5. **The f16 thread.** It was fixed at d2293dcb, and the thread is resolved. 6. **AMD.** There is no AMD card here, so the native wave64 forms have never run. Could someone with an RDNA2, 3 or 4 card run `cargo test -p xcl --lib rdna2_ref -- --nocapture`? It prints per-form counts and the `EXPECTED` lines for that adapter. On an adapter without lines, the forms test, the flip test and the GPU fuzz print and skip instead of failing (Foniass's point 2). Posting the printed lines would let us pin AMD. 7. **Test-only waiver.** The changes are still test-only (`rdna2_ref/`, plus the `#[cfg(test)]` module line and the `run_insts` split in `recomp/lower.rs`'s test module). The description check needs the maintainer's test-only waiver for this head, which we cannot apply. **Tested:** RTX 2070 SUPER (driver 621.01), Windows 11 26200, debug, at `66daa6c0`: `cargo test --workspace -- rdna2_ref --test-threads=4` gave 47 passed, 0 failed, 1 ignored and 1 SKIPPED (no llvm-mc). Linux under Wine, CPU only: `cargo check` with and without `--tests`, and the `rdna2_ref` tests, at every commit; at the head, 47 passed, 0 failed, 1 ignored. The whole suite was not rerun at this head. AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and wrote this reply.
Royalflamejlh commented 2026-12-02 22:04:56 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:04:56Z.


@CharlyRien, thank you for the review and for the 2,000-seed run. Every inline point is answered in its thread, and the changes are in head 66daa6c0.

Reference rules: S_ABSDIFF, S_LOAD alignment, the zero sign and sNaN in min/max/med3, RCP/RSQ/SQRT flushing, OMOD and DX10_CLAMP under MODE, buffer bounds per OOB_SELECT, W out of range, CMP_CLASS_F16, FRACT(NaN), undecodable words and the 8-bit format shift are all fixed, each with a test that fails without its fix. V_CVT_F16_F32 keeps the high half, following LLVM. V_FMAC_LEGACY / V_FMA_LEGACY now stop as unsupported until measured. The LDS atomic tests no longer depend on lane order.

Test gaps: four new tests cover the rules no test used. The values were worked out by hand from the guide, and the field encodings were checked with llvm-mc. On the scalar side: s_absdiff, s_pack, s_subb_u32, s_cmp__u64, the 64-bit bfe and bitset, s_setreg/s_getreg of MODE with s_round_mode and s_denorm_mode, s_getpc/s_setpc and s_movrels/s_movreld. On the vector side: DPP16 row and bank masks below 15, FI = 1, row_ror, SDWA selects with all three dst_unused modes, v_movrel and v_swap_b32. Only S_ABSDIFF was wrong.

Your fuzz groups:

  • Already known: 1 (empty upper half), 2 (-0 from DXC's default fast-math, as you found with -Gis) and 4 (per-lane whole-wave section after an if/else or a loop).
  • New, thank you: 3 (s_mul_i32 as a signed multiply), 5/6 (direct split with one EXEC half empty), 7 (fma(+0, -4, +0) giving -0).
  • 8 was the harness. A NaN made by float arithmetic now agrees with a NaN of any bits.

What the fuzzer does with them: known mismatches are recognised by class (KNOWN in fuzz.rs), not by seed. The classes are: a group's last wave with an empty upper half; -0 for +0 (2 and 7); a whole-wave section while lanes are elsewhere (4); and a direct split kernel with one EXEC half empty (5). Groups 3 and 6 have no class, so a long run still fails on them until they are fixed. The shrinker keeps a mismatch in its class, so a group 2 seed no longer shrinks into group 1.

The new generator found one more shape in 100 GPU seeds. In HLSL split, x - x of an infinity gives 0 instead of a NaN (seeds 3000003 and 3000004). This is a guess, not checked: the cause is likely the same fast-math as group 2. It has its own class until someone checks whether -Gis covers it.

ds_bpermute: the description now cites 10.4.4 for the per-half rule. On a 64-lane GPU, EXPECTED has no lines yet, so the native forms' first run prints its lines and skips (the forms test, the flip test and the GPU fuzz); it does not fail.

Edited: we are not working on fixes for these groups after all; they are open for anyone to take. This pull request stays the test side only.

AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7360197483 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360197483). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:04:56Z. --- @CharlyRien, thank you for the review and for the 2,000-seed run. Every inline point is answered in its thread, and the changes are in head `66daa6c0`. **Reference rules:** S_ABSDIFF, S_LOAD alignment, the zero sign and sNaN in min/max/med3, RCP/RSQ/SQRT flushing, OMOD and DX10_CLAMP under MODE, buffer bounds per OOB_SELECT, W out of range, CMP_CLASS_F16, FRACT(NaN), undecodable words and the 8-bit format shift are all fixed, each with a test that fails without its fix. V_CVT_F16_F32 keeps the high half, following LLVM. V_FMAC_LEGACY / V_FMA_LEGACY now stop as unsupported until measured. The LDS atomic tests no longer depend on lane order. **Test gaps:** four new tests cover the rules no test used. The values were worked out by hand from the guide, and the field encodings were checked with llvm-mc. On the scalar side: s_absdiff, s_pack, s_subb_u32, s_cmp_*_u64, the 64-bit bfe and bitset, s_setreg/s_getreg of MODE with s_round_mode and s_denorm_mode, s_getpc/s_setpc and s_movrels/s_movreld. On the vector side: DPP16 row and bank masks below 15, FI = 1, row_ror, SDWA selects with all three dst_unused modes, v_movrel* and v_swap_b32. Only S_ABSDIFF was wrong. **Your fuzz groups:** - Already known: 1 (empty upper half), 2 (-0 from DXC's default fast-math, as you found with `-Gis`) and 4 (per-lane whole-wave section after an if/else or a loop). - New, thank you: 3 (`s_mul_i32` as a signed multiply), 5/6 (direct split with one EXEC half empty), 7 (`fma(+0, -4, +0)` giving -0). - 8 was the harness. A NaN made by float arithmetic now agrees with a NaN of any bits. **What the fuzzer does with them:** known mismatches are recognised by class (`KNOWN` in `fuzz.rs`), not by seed. The classes are: a group's last wave with an empty upper half; -0 for +0 (2 and 7); a whole-wave section while lanes are elsewhere (4); and a direct split kernel with one EXEC half empty (5). Groups 3 and 6 have no class, so a long run still fails on them until they are fixed. The shrinker keeps a mismatch in its class, so a group 2 seed no longer shrinks into group 1. The new generator found one more shape in 100 GPU seeds. In HLSL split, `x - x` of an infinity gives 0 instead of a NaN (seeds 3000003 and 3000004). This is a guess, not checked: the cause is likely the same fast-math as group 2. It has its own class until someone checks whether `-Gis` covers it. ds_bpermute: the description now cites 10.4.4 for the per-half rule. On a 64-lane GPU, `EXPECTED` has no lines yet, so the native forms' first run prints its lines and skips (the forms test, the flip test and the GPU fuzz); it does not fail. Edited: we are not working on fixes for these groups after all; they are open for anyone to take. This pull request stays the test side only. AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and wrote this reply.
Royalflamejlh commented 2026-12-02 22:04:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:04:57Z.


@Foniass, thanks. Points 2 and 3 are in head 66daa6c0.

  1. Size. This stays one pull request; that is the author's choice, made with the maintainer in mind. Each of the six commits is a self-contained phase that builds and passes on its own, so it can be reviewed commit by commit. The reviews so far (gut0to's, fyreic-dev's, CharlyRien's and yours) are being addressed in it.
  2. Known lists from one card. I keyed them by adapter. EXPECTED in forms.rs holds the outcomes per adapter: "CPU" for the lowering's interpreter, and "NVIDIA" for the split forms seen on the RTX 2070 SUPER, whose counts CharlyRien's RTX 3090 also gave at 9ceea007. The fuzz's KNOWN, REFUSALS and MIN_COMPARED_PERCENT are keyed the same way. On an adapter with no lines (AMD, Intel), the forms test, the flip test and the GPU fuzz print the lines and counts and skip instead of failing. On a pinned adapter, a pinned case whose known mismatch goes away still fails the forms test, which is what fyreic-dev asked for.
  3. Slow tests. The endless branch now runs through Wave::run with a 1,000-step budget. The llvm-mc check looks for llvm-mc, a listing or a words file before it builds the words. In a debug build under Wine, the two tests took 17.8 s and 23.5 s. They now take 0.01 s and 0.00 s.

AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7360197965 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360197965). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:04:57Z. --- @Foniass, thanks. Points 2 and 3 are in head `66daa6c0`. 1. **Size.** This stays one pull request; that is the author's choice, made with the maintainer in mind. Each of the six commits is a self-contained phase that builds and passes on its own, so it can be reviewed commit by commit. The reviews so far (gut0to's, fyreic-dev's, CharlyRien's and yours) are being addressed in it. 2. **Known lists from one card.** I keyed them by adapter. `EXPECTED` in `forms.rs` holds the outcomes per adapter: "CPU" for the lowering's interpreter, and "NVIDIA" for the split forms seen on the RTX 2070 SUPER, whose counts CharlyRien's RTX 3090 also gave at 9ceea007. The fuzz's `KNOWN`, `REFUSALS` and `MIN_COMPARED_PERCENT` are keyed the same way. On an adapter with no lines (AMD, Intel), the forms test, the flip test and the GPU fuzz print the lines and counts and skip instead of failing. On a pinned adapter, a pinned case whose known mismatch goes away still fails the forms test, which is what fyreic-dev asked for. 3. **Slow tests.** The endless branch now runs through `Wave::run` with a 1,000-step budget. The llvm-mc check looks for llvm-mc, a listing or a words file before it builds the words. In a debug build under Wine, the two tests took 17.8 s and 23.5 s. They now take 0.01 s and 0.00 s. AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and wrote this reply.
Foniass commented 2026-12-02 22:06:14 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T22:06:14Z.


Follow-up review of 66daa6c0, since d2293dcb (code reading only, not a merge-check; PR description red) · 1 high, 1 medium, 1 nit

In short: Since d2293dcb the PR was reworked, not split. It is now 5,281 hand-written lines, none generated or test data. The known-mismatch lists are now keyed by adapter, an adapter without pinned outcomes prints its results and skips, and both slow CPU tests are fixed. The size still blocks it. One new problem: on an unpinned adapter the fuzzer still shrinks every mismatch on the GPU before it skips.

High

  1. Still too large to review as one PR; please split it into a stack (still open). It grew from 4,414 to 5,281 lines, more than six times the ~800 at which CONTRIBUTING.md asks for a split. The six commits still give a natural split, as Stacked on #N PRs:

    • the core, SALU and asm.rs, with the llvm-mc decoder check as its own part;
    • integer VALU and lanes (valu.rs, lanes.rs);
    • memory, LDS and groups of waves (mem.rs);
    • f32 and images (float.rs, image.rs);
    • the harness, with the run_insts split in recomp/lower.rs (forms.rs);
    • the fuzzer (fuzz.rs).

    The larger commits need halving again to get near ~400.

Medium

  1. On an unpinned adapter the fuzzer shrinks every mismatch on the GPU, then skips.

    • In fuzz_gpu (fuzz.rs ~658), an unpinned adapter gets on = "", so no mismatch has a KNOWN class.
    • wrong (~577) then calls report, which runs shrink (~464). Each candidate program runs through the GPU form again, and the HLSL split form compiles it with DXC each time.
    • At ~672 the result is only printed before skip_test. On the maintainer's AMD batch GPU, gpu_forms() returns all six forms, so each mismatch costs a full shrink in a test that ends in a skip.

    Fix: shrink only on a pinned adapter, and otherwise print the verdict as it is.

Nit

  1. The description is out of date for this head.
    • It still says "Known mismatches are listed in KNOWN; one that goes away turns the test red". The code now has per-adapter EXPECTED tables in forms.rs, and mismatch classes in fuzz.rs.
    • It says transcendentals carry "a ULP bound carried to what is computed from them". Now anything computed from a tainted value is UNBOUNDED and not compared, and v_exp / v_log are not compared at all (mod.rs ~155-172).
    • Tested names 9ceea007b, which is not a commit of this PR.
Checked and fine
  • Earlier finding fixed: known mismatches from one NVIDIA card turned other GPUs red. Outcomes are now pinned per adapter prefix in EXPECTED (forms.rs ~719-796). With no entry, gpu_wave64_forms_agree_with_the_reference (~855), gpu_every_form_is_checked_against_every_flip (~907) and fuzz_gpu print their results and skip. The fuzzer's KNOWN (fuzz.rs ~512) is now a set of classes that allow a mismatch, not seeds that require one.
  • Earlier finding fixed: an_instruction_outside_the_model_stops_the_run ran to 4,000,000 steps. It now has a budget of 1,000 (tests.rs ~152-154).
  • Earlier finding fixed: modelled_instructions_decode_as_llvm_disassembles_them built modelled_words() before looking for llvm-mc. It now looks first and skips before building them (tests.rs ~194-215).
  • Spot-checked interpreter changes:
    • the fall-through check in Wave::step (mod.rs ~309-344);
    • per-dword OOB_SELECT range checks (mem.rs ~137-171);
    • S_ABSDIFF_I32 wrapping at 32 bits;
    • v_cvt_f16_f32 keeping the high 16 bits.
  • Outside rdna2_ref/, the only changes are still the #[cfg(test)] module line in gpu/mod.rs and the run_insts split in recomp/lower.rs's test module.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7360227738 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360227738). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T22:06:14Z. --- **Follow-up review** of `66daa6c0`, since `d2293dcb` (code reading only, not a merge-check; `PR description` red) · 1 high, 1 medium, 1 nit **In short:** Since `d2293dcb` the PR was reworked, not split. It is now 5,281 hand-written lines, none generated or test data. The known-mismatch lists are now keyed by adapter, an adapter without pinned outcomes prints its results and skips, and both slow CPU tests are fixed. The size still blocks it. One new problem: on an unpinned adapter the fuzzer still shrinks every mismatch on the GPU before it skips. #### High 1. **Still too large to review as one PR; please split it into a stack (still open).** It grew from 4,414 to 5,281 lines, more than six times the ~800 at which CONTRIBUTING.md asks for a split. The six commits still give a natural split, as `Stacked on #N` PRs: - the core, SALU and `asm.rs`, with the llvm-mc decoder check as its own part; - integer VALU and lanes (`valu.rs`, `lanes.rs`); - memory, LDS and groups of waves (`mem.rs`); - f32 and images (`float.rs`, `image.rs`); - the harness, with the `run_insts` split in `recomp/lower.rs` (`forms.rs`); - the fuzzer (`fuzz.rs`). The larger commits need halving again to get near ~400. #### Medium 2. **On an unpinned adapter the fuzzer shrinks every mismatch on the GPU, then skips.** - In `fuzz_gpu` (`fuzz.rs` ~658), an unpinned adapter gets `on = ""`, so no mismatch has a `KNOWN` class. - `wrong` (~577) then calls `report`, which runs `shrink` (~464). Each candidate program runs through the GPU form again, and the `HLSL split` form compiles it with DXC each time. - At ~672 the result is only printed before `skip_test`. On the maintainer's AMD batch GPU, `gpu_forms()` returns all six forms, so each mismatch costs a full shrink in a test that ends in a skip. Fix: shrink only on a pinned adapter, and otherwise print the verdict as it is. #### Nit 3. **The description is out of date for this head.** - It still says "Known mismatches are listed in `KNOWN`; one that goes away turns the test red". The code now has per-adapter `EXPECTED` tables in `forms.rs`, and mismatch classes in `fuzz.rs`. - It says transcendentals carry "a ULP bound carried to what is computed from them". Now anything computed from a tainted value is `UNBOUNDED` and not compared, and `v_exp` / `v_log` are not compared at all (`mod.rs` ~155-172). - **Tested** names `9ceea007b`, which is not a commit of this PR. <details><summary>Checked and fine</summary> - Earlier finding fixed: known mismatches from one NVIDIA card turned other GPUs red. Outcomes are now pinned per adapter prefix in `EXPECTED` (`forms.rs` ~719-796). With no entry, `gpu_wave64_forms_agree_with_the_reference` (~855), `gpu_every_form_is_checked_against_every_flip` (~907) and `fuzz_gpu` print their results and skip. The fuzzer's `KNOWN` (`fuzz.rs` ~512) is now a set of classes that allow a mismatch, not seeds that require one. - Earlier finding fixed: `an_instruction_outside_the_model_stops_the_run` ran to 4,000,000 steps. It now has a budget of 1,000 (`tests.rs` ~152-154). - Earlier finding fixed: `modelled_instructions_decode_as_llvm_disassembles_them` built `modelled_words()` before looking for llvm-mc. It now looks first and skips before building them (`tests.rs` ~194-215). - Spot-checked interpreter changes: - the fall-through check in `Wave::step` (`mod.rs` ~309-344); - per-dword `OOB_SELECT` range checks (`mem.rs` ~137-171); - `S_ABSDIFF_I32` wrapping at 32 bits; - `v_cvt_f16_f32` keeping the high 16 bits. - Outside `rdna2_ref/`, the only changes are still the `#[cfg(test)]` module line in `gpu/mod.rs` and the `run_insts` split in `recomp/lower.rs`'s test module. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Foniass commented 2026-12-02 22:16:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T22:16:40Z.


Follow-up review of 3de8793f, since 66daa6c0 (code reading only, not a merge-check; PR description red) · 1 high, 1 nit

In short: This push fixes the fuzzer point from my last review: on an adapter without pinned outcomes, report now prints the mismatch with its listing and does not shrink it, so the form is not run again. A test counts the runs. The other five commits are unchanged. The size still blocks it.

High

  1. Still too large to review as one PR; please split it into a stack (still open). 5,305 hand-written lines. The six commits still give a natural split (core with SALU and asm.rs; integer VALU and lanes; memory, LDS and groups of waves; f32 and images; the harness; the fuzzer), and the larger ones need halving again to get near ~400.

Nit

  1. The description is out of date (still open). It still describes KNOWN turning the test red and a ULP bound on transcendentals, and Tested names 9ceea007b, which is not a commit of this PR.
Checked and fine
  • Earlier finding fixed: an unpinned adapter shrank every mismatch on the GPU before skipping. report (fuzz.rs) returns the head line and the program's listing when on is empty. an_unpinned_adapter_reports_a_mismatch_without_running_the_form_again checks the form ran 0 times.
  • On a pinned adapter the shrink and its report are as before.
  • Commits 1-5 are identical to 66daa6c0 (git range-diff).

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7360470990 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360470990). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T22:16:40Z. --- **Follow-up review** of `3de8793f`, since `66daa6c0` (code reading only, not a merge-check; `PR description` red) · 1 high, 1 nit **In short:** This push fixes the fuzzer point from my last review: on an adapter without pinned outcomes, `report` now prints the mismatch with its listing and does not shrink it, so the form is not run again. A test counts the runs. The other five commits are unchanged. The size still blocks it. #### High 1. **Still too large to review as one PR; please split it into a stack (still open).** 5,305 hand-written lines. The six commits still give a natural split (core with SALU and `asm.rs`; integer VALU and lanes; memory, LDS and groups of waves; f32 and images; the harness; the fuzzer), and the larger ones need halving again to get near ~400. #### Nit 2. **The description is out of date (still open).** It still describes `KNOWN` turning the test red and a ULP bound on transcendentals, and **Tested** names `9ceea007b`, which is not a commit of this PR. <details><summary>Checked and fine</summary> - Earlier finding fixed: an unpinned adapter shrank every mismatch on the GPU before skipping. `report` (`fuzz.rs`) returns the head line and the program's listing when `on` is empty. `an_unpinned_adapter_reports_a_mismatch_without_running_the_form_again` checks the form ran 0 times. - On a pinned adapter the shrink and its report are as before. - Commits 1-5 are identical to `66daa6c0` (`git range-diff`). </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
thehollowedone commented 2026-12-02 22:26:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by thehollowedone on 2026-12-02T22:26:29Z.


Independent NVIDIA check of head 3de8793f, test-merged cleanly into current main (078358a0). git diff --check found no whitespace errors.

On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (driver 621.35), and the installed llvm-mc, I ran cargo test --offline --locked -p xcl --lib rdna2_ref -- --nocapture --test-threads=4: 48 passed, 0 failed, 1 ignored, 0 skip notices. The ignored test is the opt-in pack census. The decoder-name check ran and passed; the forms and four flipped-rule controls passed on this GPU. Across the four GPU fuzz tests, HLSL split and direct split each compared 100/100 seeds; per-lane split compared 29/100 and refused the remaining 71, as the test reports. The listed known mismatches remained within their pinned classes.

This adds RTX 3080 Ti coverage for the current head. I did not run the full workspace suite or a title, and this is not a merge-check. The existing review about PR size and description and the red description check still need resolution.

AI use: OpenAI Codex (GPT-6 Sol) prepared and ran this test and drafted the report.

<!-- greyfinch-sync:ivall/xcl:comment:7360696451 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360696451). Originally posted by [thehollowedone](https://github.com/thehollowedone) on 2026-12-02T22:26:29Z. --- Independent NVIDIA check of [head `3de8793f`](https://github.com/xcl-dev/xcl/commit/3de8793f8ec6ed2da27c97db494102ad5acb947a), test-merged cleanly into current `main` (`078358a0`). `git diff --check` found no whitespace errors. On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (driver 621.35), and the installed `llvm-mc`, I ran `cargo test --offline --locked -p xcl --lib rdna2_ref -- --nocapture --test-threads=4`: **48 passed, 0 failed, 1 ignored, 0 skip notices**. The ignored test is the opt-in pack census. The decoder-name check ran and passed; the forms and four flipped-rule controls passed on this GPU. Across the four GPU fuzz tests, HLSL split and direct split each compared 100/100 seeds; per-lane split compared 29/100 and refused the remaining 71, as the test reports. The listed known mismatches remained within their pinned classes. This adds RTX 3080 Ti coverage for the current head. I did not run the full workspace suite or a title, and this is not a merge-check. The existing [review about PR size and description](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360470990) and the red description check still need resolution. AI use: OpenAI Codex (GPT-6 Sol) prepared and ran this test and drafted the report.
Royalflamejlh commented 2026-12-02 22:29:49 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:29:49Z.


@Foniass, thanks for both follow-ups. Head 3de8793f is unchanged since your second one; this reply answers both.

  1. It stays one pull request. Each of the six commits builds and passes on its own, so it can be reviewed commit by commit.
  2. (The shrink, from your first follow-up.) On an unpinned adapter, report prints the mismatch with the unshrunk program and does not run the form again; you confirmed this. Without the change, the new test counts 81 runs of the form, and with it 0.
  3. The description:
    • The 9ceea007b lines no longer name a hash: they say what ran on this PR's first head, before the reviews, and that the whole suite was not rerun.
    • The KNOWN it mentions is the one in fuzz.rs: classes of mismatch, not seeds.
    • The ULP bound applies only to rcp/rsq/sqrt's own result; exp/log, and anything computed from an approximate value, are not compared. Both are now said that way.

Tested at 3de8793f: rdna2_ref on the RTX 2070 SUPER gave 48 passed, 0 failed, 1 ignored and 1 SKIPPED (no llvm-mc); the 100 fuzz seeds were compared as before (HLSL and direct split 100, per-lane split 29), with only known classes of mismatch. Under Wine on the CPU: 48 passed, 0 failed, 1 ignored.

AI use: Claude Code (Claude Opus 5.5) made the change, ran the tests and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7360772446 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360772446). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:29:49Z. --- @Foniass, thanks for both follow-ups. Head `3de8793f` is unchanged since your second one; this reply answers both. 1. It stays one pull request. Each of the six commits builds and passes on its own, so it can be reviewed commit by commit. 2. (The shrink, from your first follow-up.) On an unpinned adapter, `report` prints the mismatch with the unshrunk program and does not run the form again; you confirmed this. Without the change, the new test counts 81 runs of the form, and with it 0. 3. The description: - The `9ceea007b` lines no longer name a hash: they say what ran on this PR's first head, before the reviews, and that the whole suite was not rerun. - The `KNOWN` it mentions is the one in `fuzz.rs`: classes of mismatch, not seeds. - The ULP bound applies only to rcp/rsq/sqrt's own result; exp/log, and anything computed from an approximate value, are not compared. Both are now said that way. Tested at `3de8793f`: `rdna2_ref` on the RTX 2070 SUPER gave 48 passed, 0 failed, 1 ignored and 1 SKIPPED (no llvm-mc); the 100 fuzz seeds were compared as before (HLSL and direct split 100, per-lane split 29), with only known classes of mismatch. Under Wine on the CPU: 48 passed, 0 failed, 1 ignored. AI use: Claude Code (Claude Opus 5.5) made the change, ran the tests and wrote this reply.
thehollowedone commented 2026-12-02 22:36:26 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by thehollowedone on 2026-12-02T22:36:26Z.


Source follow-up on head 3de8793f. My earlier RTX 3080 Ti run passed its existing tests, but I would not call the reference and fuzzer complete yet. These are two new, independently checked points; this is a focused source review, not a merge-check.

  1. The V_SAD_U32 reference panics on a valid wraparound result. valu.rs:124 adds c with ordinary u32 +. The RDNA2 ISA's V_SAD_U32 rule produces a dword result. For a = 0xffffffff, b = 0, c = 1, that result is 0; the reference instead panics with attempt to add with overflow in the debug build. A focused regression failed on the unchanged head (0 passed, 1 failed) and passed after the one-line wrapping_add change (1 passed, 0 failed). The new fuzz generator does not emit this opcode, so its passing seeds do not cover the case.

  2. Two known-mismatch classes can hide a different bug. In fuzz.rs:552-570, section_with_lanes_off and half_exec_empty ignore the Verdict and accept any mismatch whenever the program has the matching shape. wrong then suppresses that mismatch. Two synthetic injected-verdict regressions, one for CPU lowering and one for NVIDIA direct split, each failed on this head (0 passed, 1 failed). Please classify these known differences by their observed output location and value/signature, then assert that an unrelated differing output is reported. Otherwise a new arithmetic or lane error in the same generated program shape can pass the fuzz test.

Candidate `V_SAD_U32` fix and focused regression
diff --git a/crates/xcl/src/gpu/rdna2_ref/valu.rs b/crates/xcl/src/gpu/rdna2_ref/valu.rs
@@
-        "V_SAD_U32" => out((i64::from(a) - i64::from(b)).unsigned_abs() as u32 + c),
+        "V_SAD_U32" => out(((i64::from(a) - i64::from(b)).unsigned_abs() as u32).wrapping_add(c)),
@@
+#[cfg(test)]
+mod sad_overflow_regression {
+    #[test]
+    fn sad_u32_wraps_at_the_dword_boundary() {
+        let out = super::int("V_SAD_U32", [u32::MAX, 0, 1], [0; 3], 0, false).unwrap();
+        assert_eq!(out.v, 0);
+    }
+}

These were local, CPU-only checks of the exact PR head. I did not rerun the full workspace suite after the candidate fix. The existing size and description review remains separate. AI use: OpenAI Codex (GPT-6 Sol) traced the paths, ran the regressions, and drafted this report.

<!-- greyfinch-sync:ivall/xcl:comment:7360920667 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360920667). Originally posted by [thehollowedone](https://github.com/thehollowedone) on 2026-12-02T22:36:26Z. --- Source follow-up on [head `3de8793f`](https://github.com/xcl-dev/xcl/commit/3de8793f8ec6ed2da27c97db494102ad5acb947a). My earlier [RTX 3080 Ti run](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360696451) passed its existing tests, but I would not call the reference and fuzzer complete yet. These are two new, independently checked points; this is a focused source review, not a merge-check. 1. **The `V_SAD_U32` reference panics on a valid wraparound result.** [`valu.rs:124`](https://github.com/xcl-dev/xcl/blob/3de8793f8ec6ed2da27c97db494102ad5acb947a/crates/xcl/src/gpu/rdna2_ref/valu.rs#L124) adds `c` with ordinary `u32` `+`. The [RDNA2 ISA's `V_SAD_U32` rule](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) produces a dword result. For `a = 0xffffffff`, `b = 0`, `c = 1`, that result is `0`; the reference instead panics with `attempt to add with overflow` in the debug build. A focused regression failed on the unchanged head (0 passed, 1 failed) and passed after the one-line `wrapping_add` change (1 passed, 0 failed). The new fuzz generator does not emit this opcode, so its passing seeds do not cover the case. 2. **Two known-mismatch classes can hide a different bug.** In [`fuzz.rs:552-570`](https://github.com/xcl-dev/xcl/blob/3de8793f8ec6ed2da27c97db494102ad5acb947a/crates/xcl/src/gpu/rdna2_ref/fuzz.rs#L552-L570), `section_with_lanes_off` and `half_exec_empty` ignore the `Verdict` and accept *any* mismatch whenever the program has the matching shape. [`wrong`](https://github.com/xcl-dev/xcl/blob/3de8793f8ec6ed2da27c97db494102ad5acb947a/crates/xcl/src/gpu/rdna2_ref/fuzz.rs#L578-L585) then suppresses that mismatch. Two synthetic injected-verdict regressions, one for CPU lowering and one for NVIDIA direct split, each failed on this head (0 passed, 1 failed). Please classify these known differences by their observed output location and value/signature, then assert that an unrelated differing output is reported. Otherwise a new arithmetic or lane error in the same generated program shape can pass the fuzz test. <details> <summary>Candidate `V_SAD_U32` fix and focused regression</summary> ```diff diff --git a/crates/xcl/src/gpu/rdna2_ref/valu.rs b/crates/xcl/src/gpu/rdna2_ref/valu.rs @@ - "V_SAD_U32" => out((i64::from(a) - i64::from(b)).unsigned_abs() as u32 + c), + "V_SAD_U32" => out(((i64::from(a) - i64::from(b)).unsigned_abs() as u32).wrapping_add(c)), @@ +#[cfg(test)] +mod sad_overflow_regression { + #[test] + fn sad_u32_wraps_at_the_dword_boundary() { + let out = super::int("V_SAD_U32", [u32::MAX, 0, 1], [0; 3], 0, false).unwrap(); + assert_eq!(out.v, 0); + } +} ``` </details> These were local, CPU-only checks of the exact PR head. I did not rerun the full workspace suite after the candidate fix. The existing [size and description review](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7360470990) remains separate. AI use: OpenAI Codex (GPT-6 Sol) traced the paths, ran the regressions, and drafted this report.
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 544

@@ -0,0 +1,734 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute)
+//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers,
+//! zeros of both signs, infinities, a NaN and values whose products round. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// lane exchanges under the EXEC of the moment
+    Lanes(Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top)
+    Lds(u64, u64, u64),
+}
+
+struct Gen<'a> {
+    r: &'a mut Rng,
+    /// only instructions the lowering translates
+    lowered: bool,
+}
+
+impl Gen<'_> {
+    fn v(&mut self) -> u64 {
+        V + self.r.below(12) + 1
+    }
+    fn vd(&mut self) -> u64 {
+        self.r.below(12) + 1
+    }
+    fn s(&mut self) -> u64 {
+        self.r.below(12) + 4
+    }
+    fn fv(&mut self) -> u64 {
+        13 + self.r.below(4)
+    }
+    /// a scalar or vector source: a register, an inline constant or a literal
+    fn src(&mut self) -> (u64, Option<u32>) {
+        match self.r.below(6) {
+            0 => (self.s(), None),
+            1 => (128 + self.r.below(65), None),
+            2 => (255, Some(self.r.word())),
+            _ => (self.v(), None),
+        }
+    }
+
+    fn op(&mut self) -> I {
+        loop {
+            let x = self.any_op();
+            if !self.lowered || lowered_alone(&x) {
+                return x;
+            }
+        }
+    }
+
+    fn any_op(&mut self) -> I {
+        let k = self.r.below(100);
+        if k < 22 {
+            const SOP2: [&str; 16] = [
+                "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32",
+                "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32",
+            ];
+            let (a, b) = (self.s(), self.s());
+            return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]);
+        }
+        if k < 30 {
+            const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"];
+            return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]);
+        }
+        if k < 35 {
+            let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]);
+            return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]);
+        }
+        if k < 60 {
+            const VOP2: [&str; 13] = [
+                "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32",
+                "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32",
+            ];
+            let (s0, l) = self.src();
+            let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)];
+            return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l);
+        }
+        if k < 78 {
+            const VOP3: [&str; 14] = [
+                "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32",
+                "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32",
+            ];
+            let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())];
+            return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None);
+        }
+        if k < 84 {
+            let s = self.s();
+            return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]);
+        }
+        if k < 92 {
+            let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]);
+            return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]);
+        }
+        if k < 95 {
+            return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]);
+        }
+        // masks read as data
+        let m = 30 + 2 * self.r.below(3);
+        match self.r.below(5) {
+            0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]),
+            1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]),
+            2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]),
+            3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]),
+            _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]),
+        }
+    }
+
+    /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form).
+    fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> {
+        let t = 18;
+        match self.r.below(6) {
+            0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))],
+            1 => {
+                let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]);
+                vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])]
+            }
+            2 => vec![
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            3 => vec![
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            4 => vec![
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]),
+            ],
+            _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])],
+        }
+    }
+
+    fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> {
+        let mut out = Vec::new();
+        for _ in 0..n {
+            let k = self.r.below(100);
+            if k < 10 && depth < 3 {
+                let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]);
+                let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]);
+                let (a, b) = (1 + self.r.below(4), self.r.below(3));
+                out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false)));
+            } else if k < 16 && depth < 2 {
+                let n = 1 + self.r.below(4);
+                out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false)));
+            } else if k < 24 {
+                let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]);
+                let id = match op {
+                    "V_AND_B32" | "V_MIN_U32" => 193,
+                    _ => 128,
+                };
+                let x = 17;
+                let mut steps = Vec::new();
+                for _ in 0..1 + self.r.below(4) {
+                    steps.extend(self.wave_step(op, x));
+                }
+                steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)]));
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Wave(self.v(), id, steps));
+                }
+            } else if k < 27 {
+                let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]);
+                let x = self.vd();
+                let steps = self.wave_step(op, x);
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Lanes(steps));
+                }
+            } else if k < 30 && top {
+                out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127)));
+            } else {
+                out.push(Item::Op(self.op()));
+            }
+        }
+        out
+    }
+}
+
+/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k
+/// uses s[40 + 4k ..], loop counters v20 + k.
+fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) {
+    let ctl = 40 + 4 * depth;
+    for it in items {
+        match it {
+            Item::Op(x) => out.push(x.clone()),
+            Item::If(cmp, then, els) => {
+                let mut c = cmp.clone();
+                c.2[0].1 = ctl;
+                out.push(c);
+                out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(then, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(els, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Loop(trip, body) => {
+                let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth);
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)]));
+                out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)]));
+                out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)]));
+                let top = out.len();
+                out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)]));
+                out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)]));
+                let leave = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(body, depth + 1, threads, out);
+                out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)]));
+                out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)]));
+                out[leave].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Wave(src, id, steps) => {
+                out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)]));
+                out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)]));
+                out.extend(steps.iter().cloned());
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Lanes(steps) => out.extend(steps.iter().cloned()),
+            Item::Lds(src, dst, k) => {
+                // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)]));
+                out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+                out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32));
+                out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads));
+                out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)]));
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)]));
+                out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+            }
+        }
+    }
+}
+
+/// A generated program: its items and how it runs.
+#[derive(Clone)]
+pub(crate) struct Prog {
+    pub items: Vec<Item>,
+    pub compute: bool,
+    /// a compute group's threads
+    pub threads: u32,
+    /// kernel programs: the EXEC their first instructions set (every lane exists)
+    pub exec: u64,
+    pub seed: u64,
+}
+
+/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread.
+fn lines(p: &Prog) -> Vec<I> {
+    let mut out = Vec::new();
+    if p.compute {
+        // v1..v16 from the thread index; s4..s15 from s0
+        for r in 1..=16u64 {
+            out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9)));
+        }
+        for r in VFLOAT {
+            out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)]));
+            out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)]));
+        }
+        for r in SDATA {
+            out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B)));
+        }
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)]));
+    } else {
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32));
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32));
+    }
+    emit(&p.items, 0, p.threads, &mut out);
+    if p.compute {
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)]));
+        // (group · threads + thread) · 112, in v[24:25]
+        out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112));
+        out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112));
+        out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)]));
+        out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)]));
+        for k in 0..12u64 {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)]));
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)]));
+        }
+        for k in 0..16u64 {
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)]));
+        }
+    } else {
+        // the scalars as the lanes see them, all lanes on
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]));
+        for k in SDATA {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)]));
+        }
+    }
+    out.push(super::asm::end());
+    out
+}
+
+/// The case of a program: kernel mode with random registers, its first instructions setting
+/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads.
+pub(crate) fn case(p: &Prog) -> Case {
+    let mut r = Rng::new(p.seed ^ 0x5EED);
+    let code = asm(&lines(p));
+    if p.compute {
+        let threads = p.threads;
+        let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+        return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true };
+    }
+    let mut st = KernelState::default();
+    for s in SDATA {
+        st.sgpr[s as usize] = r.word();
+    }
+    for regs in st.vgpr.iter_mut() {
+        for v in VDATA {
+            regs[v as usize] = r.word();
+        }
+        for v in VFLOAT {
+            regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() };
+        }
+    }
+    Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }
+}
+
+/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks).
+fn lowered_alone(x: &I) -> bool {
+    let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false };
+    !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported"))
+}
+
+/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which
+/// D3D lets a GPU flush.
+const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001];
+
+pub(crate) fn program(seed: u64) -> Prog {
+    generate(seed, false)
+}
+
+/// A kernel program of the instructions the lowering translates, for the CPU part.
+pub(crate) fn lowered_program(seed: u64) -> Prog {
+    generate(seed, true)
+}
+
+fn generate(seed: u64, lowered: bool) -> Prog {
+    let mut r = Rng::new(seed);
+    let compute = r.below(4) == 0 && !lowered;
+    let n = 6 + r.below(18);
+    let threads = r.pick(&[64, 96, 128]);
+    let exec: u64 = match r.below(5) {
+        0 => !0,
+        1 => !0 >> r.below(64),
+        2 => 0xFFFF_FFFF << 32,
+        3 => 0xFFFF_FFFF,
+        _ => r.next() | 1 << 40,
+    };
+    let items = Gen { r: &mut r, lowered }.items(n, 0, compute);
+    Prog { items, compute, threads, exec, seed }
+}
+
+/// `items` with one part taken out, each way there is.
+fn smaller(items: &[Item]) -> Vec<Vec<Item>> {
+    let mut out = Vec::new();
+    for k in 0..items.len() {
+        let mut v = items.to_vec();
+        v.remove(k);
+        out.push(v);
+        let inner: Vec<Vec<Item>> = match &items[k] {
+            Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(),
+            Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(),
+            Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| {
+                let mut st = steps.clone();
+                st.remove(j);
+                vec![Item::Wave(*s, *id, st)]
+            }).collect(),
+            _ => Vec::new(),
+        };
+        for x in inner {
+            let mut v = items.to_vec();
+            v.splice(k..=k, x);
+            out.push(v);
+        }
+    }
+    out
+}
+
+fn verdict(p: &Prog, form: &Form) -> Option<Verdict> {
+    let c = case(p);
+    let want = reference(&c, Flip::None).ok()?;
+    Some(judge(&c, &want, (form.1)(&c)))
+}
+
+fn differs(p: &Prog, form: &Form) -> bool {
+    matches!(verdict(p, form), Some(Verdict::Mismatch(..)))
+}
+
+/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report.
+fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String {
+    let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" });
+    if on.is_empty() {
+        return format!("{head}\n{}", listing(p));
+    }
+    let s = shrink(on, p, form);
+    format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s))
+}
+
+/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out
+/// one part at a time.
+pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog {
+    let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v));
+    let was = class(p);
+    let mut p = p.clone();
+    'again: loop {
+        for items in smaller(&p.items) {
+            let q = Prog { items, ..p.clone() };
+            if differs(&q, form) && class(&q) == was {
+                p = q;
+                continue 'again;
+            }
+        }
+        return p;
+    }
+}
+
+/// `p`'s lines, ready to paste as a regression test.
+pub(crate) fn listing(p: &Prog) -> String {
+    lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect()
+}
+
+fn seeds(base: u64, count: u64) -> std::ops::Range<u64> {
+    let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count);
+    base..base + n
+}
+
+/// The share of seeds (%) a form compares with the reference at least (adapter as in
+/// `forms::EXPECTED`, form, floor).
+const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[
+    ("CPU", "lowering on CPU", 12),
+    ("NVIDIA", "HLSL split", 90),
+    ("NVIDIA", "direct split", 90),
+    ("NVIDIA", "per-lane split", 10),
+];
+
+/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other
+/// is a failure.
+const REFUSALS: &[(&str, &str, &str)] = &[
+    ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "a number read as a mask (through a join)"),
+    ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"),
+    ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"),
+    ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"),
+    ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"),
+    ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"),
+    ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"),
+    ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"),
+    ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"),
+    ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"),
+];
+
+/// Mismatches main's forms make, known by what the program does (adapter, form, what, test).
+const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[
+    ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "HLSL split", "-0 for +0", negative_zero),
+    ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero),
+    ("NVIDIA", "direct split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty),
+];
+
+fn upper_half_empty(p: &Prog, v: &Verdict) -> bool {
+    let Verdict::Mismatch(at, ..) = v else { return false };
+    let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads);
+    p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64)
+}
+
+fn negative_zero(_: &Prog, v: &Verdict) -> bool {

This class matches any word where the reference has 0 and the form 0x80000000, not only float words. In a kernel program the SGPRs are copied to v26-v37, and Rng::word gives 0x80000000 one time in 20. Example: v3 has 0 in lane 32 and 0x80000000 in lane 0, and the program does v_readlane_b32 s5, v3, 32. A form that reads lane 0 (the Lane31 mistake) gives the first mismatch ("v27 of lane 0", 0, 0x80000000), which counts as known on all three forms, and the seed's other wrong words are hidden with it. Floats only live in v13-v16 in these programs (fv(), and v() stops at v12), so the class could require the label to be v13-v16 in a kernel, or memory dword k with k % 28 in 12..=15 in compute. nan_as_zero (line 548) could take the same guard.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221843 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221843). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 544 ~~~~diff @@ -0,0 +1,734 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute) +//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers, +//! zeros of both signs, infinities, a NaN and values whose products round. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// lane exchanges under the EXEC of the moment + Lanes(Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top) + Lds(u64, u64, u64), +} + +struct Gen<'a> { + r: &'a mut Rng, + /// only instructions the lowering translates + lowered: bool, +} + +impl Gen<'_> { + fn v(&mut self) -> u64 { + V + self.r.below(12) + 1 + } + fn vd(&mut self) -> u64 { + self.r.below(12) + 1 + } + fn s(&mut self) -> u64 { + self.r.below(12) + 4 + } + fn fv(&mut self) -> u64 { + 13 + self.r.below(4) + } + /// a scalar or vector source: a register, an inline constant or a literal + fn src(&mut self) -> (u64, Option<u32>) { + match self.r.below(6) { + 0 => (self.s(), None), + 1 => (128 + self.r.below(65), None), + 2 => (255, Some(self.r.word())), + _ => (self.v(), None), + } + } + + fn op(&mut self) -> I { + loop { + let x = self.any_op(); + if !self.lowered || lowered_alone(&x) { + return x; + } + } + } + + fn any_op(&mut self) -> I { + let k = self.r.below(100); + if k < 22 { + const SOP2: [&str; 16] = [ + "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32", + "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32", + ]; + let (a, b) = (self.s(), self.s()); + return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]); + } + if k < 30 { + const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"]; + return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]); + } + if k < 35 { + let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]); + return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]); + } + if k < 60 { + const VOP2: [&str; 13] = [ + "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32", + "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32", + ]; + let (s0, l) = self.src(); + let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)]; + return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l); + } + if k < 78 { + const VOP3: [&str; 14] = [ + "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32", + "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32", + ]; + let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())]; + return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None); + } + if k < 84 { + let s = self.s(); + return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]); + } + if k < 92 { + let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]); + return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]); + } + if k < 95 { + return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]); + } + // masks read as data + let m = 30 + 2 * self.r.below(3); + match self.r.below(5) { + 0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]), + 1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]), + 2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]), + 3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]), + _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]), + } + } + + /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form). + fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> { + let t = 18; + match self.r.below(6) { + 0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))], + 1 => { + let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]); + vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])] + } + 2 => vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 3 => vec![ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 4 => vec![ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]), + ], + _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])], + } + } + + fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> { + let mut out = Vec::new(); + for _ in 0..n { + let k = self.r.below(100); + if k < 10 && depth < 3 { + let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]); + let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]); + let (a, b) = (1 + self.r.below(4), self.r.below(3)); + out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false))); + } else if k < 16 && depth < 2 { + let n = 1 + self.r.below(4); + out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false))); + } else if k < 24 { + let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]); + let id = match op { + "V_AND_B32" | "V_MIN_U32" => 193, + _ => 128, + }; + let x = 17; + let mut steps = Vec::new(); + for _ in 0..1 + self.r.below(4) { + steps.extend(self.wave_step(op, x)); + } + steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)])); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Wave(self.v(), id, steps)); + } + } else if k < 27 { + let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]); + let x = self.vd(); + let steps = self.wave_step(op, x); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Lanes(steps)); + } + } else if k < 30 && top { + out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127))); + } else { + out.push(Item::Op(self.op())); + } + } + out + } +} + +/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k +/// uses s[40 + 4k ..], loop counters v20 + k. +fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) { + let ctl = 40 + 4 * depth; + for it in items { + match it { + Item::Op(x) => out.push(x.clone()), + Item::If(cmp, then, els) => { + let mut c = cmp.clone(); + c.2[0].1 = ctl; + out.push(c); + out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(then, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(els, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Loop(trip, body) => { + let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)])); + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)])); + let top = out.len(); + out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)])); + out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)])); + let leave = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(body, depth + 1, threads, out); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)])); + out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)])); + out[leave].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Wave(src, id, steps) => { + out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)])); + out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)])); + out.extend(steps.iter().cloned()); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Lanes(steps) => out.extend(steps.iter().cloned()), + Item::Lds(src, dst, k) => { + // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)])); + out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32)); + out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads)); + out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)])); + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)])); + out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + } + } + } +} + +/// A generated program: its items and how it runs. +#[derive(Clone)] +pub(crate) struct Prog { + pub items: Vec<Item>, + pub compute: bool, + /// a compute group's threads + pub threads: u32, + /// kernel programs: the EXEC their first instructions set (every lane exists) + pub exec: u64, + pub seed: u64, +} + +/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread. +fn lines(p: &Prog) -> Vec<I> { + let mut out = Vec::new(); + if p.compute { + // v1..v16 from the thread index; s4..s15 from s0 + for r in 1..=16u64 { + out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9))); + } + for r in VFLOAT { + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)])); + out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)])); + } + for r in SDATA { + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B))); + } + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)])); + } else { + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32)); + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32)); + } + emit(&p.items, 0, p.threads, &mut out); + if p.compute { + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)])); + // (group · threads + thread) · 112, in v[24:25] + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112)); + out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112)); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)])); + for k in 0..12u64 { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)])); + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)])); + } + for k in 0..16u64 { + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)])); + } + } else { + // the scalars as the lanes see them, all lanes on + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); + for k in SDATA { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)])); + } + } + out.push(super::asm::end()); + out +} + +/// The case of a program: kernel mode with random registers, its first instructions setting +/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads. +pub(crate) fn case(p: &Prog) -> Case { + let mut r = Rng::new(p.seed ^ 0x5EED); + let code = asm(&lines(p)); + if p.compute { + let threads = p.threads; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true }; + } + let mut st = KernelState::default(); + for s in SDATA { + st.sgpr[s as usize] = r.word(); + } + for regs in st.vgpr.iter_mut() { + for v in VDATA { + regs[v as usize] = r.word(); + } + for v in VFLOAT { + regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() }; + } + } + Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false } +} + +/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks). +fn lowered_alone(x: &I) -> bool { + let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }; + !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported")) +} + +/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which +/// D3D lets a GPU flush. +const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001]; + +pub(crate) fn program(seed: u64) -> Prog { + generate(seed, false) +} + +/// A kernel program of the instructions the lowering translates, for the CPU part. +pub(crate) fn lowered_program(seed: u64) -> Prog { + generate(seed, true) +} + +fn generate(seed: u64, lowered: bool) -> Prog { + let mut r = Rng::new(seed); + let compute = r.below(4) == 0 && !lowered; + let n = 6 + r.below(18); + let threads = r.pick(&[64, 96, 128]); + let exec: u64 = match r.below(5) { + 0 => !0, + 1 => !0 >> r.below(64), + 2 => 0xFFFF_FFFF << 32, + 3 => 0xFFFF_FFFF, + _ => r.next() | 1 << 40, + }; + let items = Gen { r: &mut r, lowered }.items(n, 0, compute); + Prog { items, compute, threads, exec, seed } +} + +/// `items` with one part taken out, each way there is. +fn smaller(items: &[Item]) -> Vec<Vec<Item>> { + let mut out = Vec::new(); + for k in 0..items.len() { + let mut v = items.to_vec(); + v.remove(k); + out.push(v); + let inner: Vec<Vec<Item>> = match &items[k] { + Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(), + Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(), + Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| { + let mut st = steps.clone(); + st.remove(j); + vec![Item::Wave(*s, *id, st)] + }).collect(), + _ => Vec::new(), + }; + for x in inner { + let mut v = items.to_vec(); + v.splice(k..=k, x); + out.push(v); + } + } + out +} + +fn verdict(p: &Prog, form: &Form) -> Option<Verdict> { + let c = case(p); + let want = reference(&c, Flip::None).ok()?; + Some(judge(&c, &want, (form.1)(&c))) +} + +fn differs(p: &Prog, form: &Form) -> bool { + matches!(verdict(p, form), Some(Verdict::Mismatch(..))) +} + +/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report. +fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String { + let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" }); + if on.is_empty() { + return format!("{head}\n{}", listing(p)); + } + let s = shrink(on, p, form); + format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s)) +} + +/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out +/// one part at a time. +pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog { + let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v)); + let was = class(p); + let mut p = p.clone(); + 'again: loop { + for items in smaller(&p.items) { + let q = Prog { items, ..p.clone() }; + if differs(&q, form) && class(&q) == was { + p = q; + continue 'again; + } + } + return p; + } +} + +/// `p`'s lines, ready to paste as a regression test. +pub(crate) fn listing(p: &Prog) -> String { + lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect() +} + +fn seeds(base: u64, count: u64) -> std::ops::Range<u64> { + let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count); + base..base + n +} + +/// The share of seeds (%) a form compares with the reference at least (adapter as in +/// `forms::EXPECTED`, form, floor). +const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[ + ("CPU", "lowering on CPU", 12), + ("NVIDIA", "HLSL split", 90), + ("NVIDIA", "direct split", 90), + ("NVIDIA", "per-lane split", 10), +]; + +/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other +/// is a failure. +const REFUSALS: &[(&str, &str, &str)] = &[ + ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "a number read as a mask (through a join)"), + ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"), + ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"), + ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"), + ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"), + ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"), + ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"), + ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"), + ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"), + ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"), +]; + +/// Mismatches main's forms make, known by what the program does (adapter, form, what, test). +const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[ + ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "HLSL split", "-0 for +0", negative_zero), + ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero), + ("NVIDIA", "direct split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty), +]; + +fn upper_half_empty(p: &Prog, v: &Verdict) -> bool { + let Verdict::Mismatch(at, ..) = v else { return false }; + let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads); + p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64) +} + +fn negative_zero(_: &Prog, v: &Verdict) -> bool { ~~~~ --- This class matches any word where the reference has 0 and the form 0x80000000, not only float words. In a kernel program the SGPRs are copied to v26-v37, and `Rng::word` gives 0x80000000 one time in 20. Example: v3 has 0 in lane 32 and 0x80000000 in lane 0, and the program does `v_readlane_b32 s5, v3, 32`. A form that reads lane 0 (the Lane31 mistake) gives the first mismatch `("v27 of lane 0", 0, 0x80000000)`, which counts as known on all three forms, and the seed's other wrong words are hidden with it. Floats only live in v13-v16 in these programs (`fv()`, and `v()` stops at v12), so the class could require the label to be v13-v16 in a kernel, or memory dword k with k % 28 in 12..=15 in compute. `nan_as_zero` (line 548) could take the same guard.
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 567

@@ -0,0 +1,734 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute)
+//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers,
+//! zeros of both signs, infinities, a NaN and values whose products round. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// lane exchanges under the EXEC of the moment
+    Lanes(Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top)
+    Lds(u64, u64, u64),
+}
+
+struct Gen<'a> {
+    r: &'a mut Rng,
+    /// only instructions the lowering translates
+    lowered: bool,
+}
+
+impl Gen<'_> {
+    fn v(&mut self) -> u64 {
+        V + self.r.below(12) + 1
+    }
+    fn vd(&mut self) -> u64 {
+        self.r.below(12) + 1
+    }
+    fn s(&mut self) -> u64 {
+        self.r.below(12) + 4
+    }
+    fn fv(&mut self) -> u64 {
+        13 + self.r.below(4)
+    }
+    /// a scalar or vector source: a register, an inline constant or a literal
+    fn src(&mut self) -> (u64, Option<u32>) {
+        match self.r.below(6) {
+            0 => (self.s(), None),
+            1 => (128 + self.r.below(65), None),
+            2 => (255, Some(self.r.word())),
+            _ => (self.v(), None),
+        }
+    }
+
+    fn op(&mut self) -> I {
+        loop {
+            let x = self.any_op();
+            if !self.lowered || lowered_alone(&x) {
+                return x;
+            }
+        }
+    }
+
+    fn any_op(&mut self) -> I {
+        let k = self.r.below(100);
+        if k < 22 {
+            const SOP2: [&str; 16] = [
+                "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32",
+                "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32",
+            ];
+            let (a, b) = (self.s(), self.s());
+            return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]);
+        }
+        if k < 30 {
+            const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"];
+            return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]);
+        }
+        if k < 35 {
+            let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]);
+            return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]);
+        }
+        if k < 60 {
+            const VOP2: [&str; 13] = [
+                "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32",
+                "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32",
+            ];
+            let (s0, l) = self.src();
+            let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)];
+            return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l);
+        }
+        if k < 78 {
+            const VOP3: [&str; 14] = [
+                "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32",
+                "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32",
+            ];
+            let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())];
+            return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None);
+        }
+        if k < 84 {
+            let s = self.s();
+            return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]);
+        }
+        if k < 92 {
+            let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]);
+            return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]);
+        }
+        if k < 95 {
+            return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]);
+        }
+        // masks read as data
+        let m = 30 + 2 * self.r.below(3);
+        match self.r.below(5) {
+            0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]),
+            1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]),
+            2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]),
+            3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]),
+            _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]),
+        }
+    }
+
+    /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form).
+    fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> {
+        let t = 18;
+        match self.r.below(6) {
+            0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))],
+            1 => {
+                let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]);
+                vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])]
+            }
+            2 => vec![
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            3 => vec![
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            4 => vec![
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]),
+            ],
+            _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])],
+        }
+    }
+
+    fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> {
+        let mut out = Vec::new();
+        for _ in 0..n {
+            let k = self.r.below(100);
+            if k < 10 && depth < 3 {
+                let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]);
+                let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]);
+                let (a, b) = (1 + self.r.below(4), self.r.below(3));
+                out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false)));
+            } else if k < 16 && depth < 2 {
+                let n = 1 + self.r.below(4);
+                out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false)));
+            } else if k < 24 {
+                let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]);
+                let id = match op {
+                    "V_AND_B32" | "V_MIN_U32" => 193,
+                    _ => 128,
+                };
+                let x = 17;
+                let mut steps = Vec::new();
+                for _ in 0..1 + self.r.below(4) {
+                    steps.extend(self.wave_step(op, x));
+                }
+                steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)]));
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Wave(self.v(), id, steps));
+                }
+            } else if k < 27 {
+                let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]);
+                let x = self.vd();
+                let steps = self.wave_step(op, x);
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Lanes(steps));
+                }
+            } else if k < 30 && top {
+                out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127)));
+            } else {
+                out.push(Item::Op(self.op()));
+            }
+        }
+        out
+    }
+}
+
+/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k
+/// uses s[40 + 4k ..], loop counters v20 + k.
+fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) {
+    let ctl = 40 + 4 * depth;
+    for it in items {
+        match it {
+            Item::Op(x) => out.push(x.clone()),
+            Item::If(cmp, then, els) => {
+                let mut c = cmp.clone();
+                c.2[0].1 = ctl;
+                out.push(c);
+                out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(then, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(els, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Loop(trip, body) => {
+                let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth);
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)]));
+                out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)]));
+                out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)]));
+                let top = out.len();
+                out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)]));
+                out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)]));
+                let leave = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(body, depth + 1, threads, out);
+                out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)]));
+                out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)]));
+                out[leave].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Wave(src, id, steps) => {
+                out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)]));
+                out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)]));
+                out.extend(steps.iter().cloned());
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Lanes(steps) => out.extend(steps.iter().cloned()),
+            Item::Lds(src, dst, k) => {
+                // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)]));
+                out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+                out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32));
+                out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads));
+                out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)]));
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)]));
+                out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+            }
+        }
+    }
+}
+
+/// A generated program: its items and how it runs.
+#[derive(Clone)]
+pub(crate) struct Prog {
+    pub items: Vec<Item>,
+    pub compute: bool,
+    /// a compute group's threads
+    pub threads: u32,
+    /// kernel programs: the EXEC their first instructions set (every lane exists)
+    pub exec: u64,
+    pub seed: u64,
+}
+
+/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread.
+fn lines(p: &Prog) -> Vec<I> {
+    let mut out = Vec::new();
+    if p.compute {
+        // v1..v16 from the thread index; s4..s15 from s0
+        for r in 1..=16u64 {
+            out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9)));
+        }
+        for r in VFLOAT {
+            out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)]));
+            out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)]));
+        }
+        for r in SDATA {
+            out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B)));
+        }
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)]));
+    } else {
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32));
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32));
+    }
+    emit(&p.items, 0, p.threads, &mut out);
+    if p.compute {
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)]));
+        // (group · threads + thread) · 112, in v[24:25]
+        out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112));
+        out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112));
+        out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)]));
+        out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)]));
+        for k in 0..12u64 {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)]));
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)]));
+        }
+        for k in 0..16u64 {
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)]));
+        }
+    } else {
+        // the scalars as the lanes see them, all lanes on
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]));
+        for k in SDATA {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)]));
+        }
+    }
+    out.push(super::asm::end());
+    out
+}
+
+/// The case of a program: kernel mode with random registers, its first instructions setting
+/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads.
+pub(crate) fn case(p: &Prog) -> Case {
+    let mut r = Rng::new(p.seed ^ 0x5EED);
+    let code = asm(&lines(p));
+    if p.compute {
+        let threads = p.threads;
+        let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+        return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true };
+    }
+    let mut st = KernelState::default();
+    for s in SDATA {
+        st.sgpr[s as usize] = r.word();
+    }
+    for regs in st.vgpr.iter_mut() {
+        for v in VDATA {
+            regs[v as usize] = r.word();
+        }
+        for v in VFLOAT {
+            regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() };
+        }
+    }
+    Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }
+}
+
+/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks).
+fn lowered_alone(x: &I) -> bool {
+    let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false };
+    !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported"))
+}
+
+/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which
+/// D3D lets a GPU flush.
+const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001];
+
+pub(crate) fn program(seed: u64) -> Prog {
+    generate(seed, false)
+}
+
+/// A kernel program of the instructions the lowering translates, for the CPU part.
+pub(crate) fn lowered_program(seed: u64) -> Prog {
+    generate(seed, true)
+}
+
+fn generate(seed: u64, lowered: bool) -> Prog {
+    let mut r = Rng::new(seed);
+    let compute = r.below(4) == 0 && !lowered;
+    let n = 6 + r.below(18);
+    let threads = r.pick(&[64, 96, 128]);
+    let exec: u64 = match r.below(5) {
+        0 => !0,
+        1 => !0 >> r.below(64),
+        2 => 0xFFFF_FFFF << 32,
+        3 => 0xFFFF_FFFF,
+        _ => r.next() | 1 << 40,
+    };
+    let items = Gen { r: &mut r, lowered }.items(n, 0, compute);
+    Prog { items, compute, threads, exec, seed }
+}
+
+/// `items` with one part taken out, each way there is.
+fn smaller(items: &[Item]) -> Vec<Vec<Item>> {
+    let mut out = Vec::new();
+    for k in 0..items.len() {
+        let mut v = items.to_vec();
+        v.remove(k);
+        out.push(v);
+        let inner: Vec<Vec<Item>> = match &items[k] {
+            Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(),
+            Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(),
+            Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| {
+                let mut st = steps.clone();
+                st.remove(j);
+                vec![Item::Wave(*s, *id, st)]
+            }).collect(),
+            _ => Vec::new(),
+        };
+        for x in inner {
+            let mut v = items.to_vec();
+            v.splice(k..=k, x);
+            out.push(v);
+        }
+    }
+    out
+}
+
+fn verdict(p: &Prog, form: &Form) -> Option<Verdict> {
+    let c = case(p);
+    let want = reference(&c, Flip::None).ok()?;
+    Some(judge(&c, &want, (form.1)(&c)))
+}
+
+fn differs(p: &Prog, form: &Form) -> bool {
+    matches!(verdict(p, form), Some(Verdict::Mismatch(..)))
+}
+
+/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report.
+fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String {
+    let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" });
+    if on.is_empty() {
+        return format!("{head}\n{}", listing(p));
+    }
+    let s = shrink(on, p, form);
+    format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s))
+}
+
+/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out
+/// one part at a time.
+pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog {
+    let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v));
+    let was = class(p);
+    let mut p = p.clone();
+    'again: loop {
+        for items in smaller(&p.items) {
+            let q = Prog { items, ..p.clone() };
+            if differs(&q, form) && class(&q) == was {
+                p = q;
+                continue 'again;
+            }
+        }
+        return p;
+    }
+}
+
+/// `p`'s lines, ready to paste as a regression test.
+pub(crate) fn listing(p: &Prog) -> String {
+    lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect()
+}
+
+fn seeds(base: u64, count: u64) -> std::ops::Range<u64> {
+    let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count);
+    base..base + n
+}
+
+/// The share of seeds (%) a form compares with the reference at least (adapter as in
+/// `forms::EXPECTED`, form, floor).
+const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[
+    ("CPU", "lowering on CPU", 12),
+    ("NVIDIA", "HLSL split", 90),
+    ("NVIDIA", "direct split", 90),
+    ("NVIDIA", "per-lane split", 10),
+];
+
+/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other
+/// is a failure.
+const REFUSALS: &[(&str, &str, &str)] = &[
+    ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "a number read as a mask (through a join)"),
+    ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"),
+    ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"),
+    ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"),
+    ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"),
+    ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"),
+    ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"),
+    ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"),
+    ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"),
+    ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"),
+];
+
+/// Mismatches main's forms make, known by what the program does (adapter, form, what, test).
+const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[
+    ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "HLSL split", "-0 for +0", negative_zero),
+    ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero),
+    ("NVIDIA", "direct split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty),
+];
+
+fn upper_half_empty(p: &Prog, v: &Verdict) -> bool {
+    let Verdict::Mismatch(at, ..) = v else { return false };
+    let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads);
+    p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64)
+}
+
+fn negative_zero(_: &Prog, v: &Verdict) -> bool {
+    matches!(v, Verdict::Mismatch(_, 0, 0x8000_0000, _))
+}
+
+fn nan_as_zero(_: &Prog, v: &Verdict) -> bool {
+    matches!(v, Verdict::Mismatch(_, w, 0, _) if f32::from_bits(*w).is_nan())
+}
+
+fn section_with_lanes_off(p: &Prog, _: &Verdict) -> bool {
+    fn section(items: &[Item]) -> bool {
+        items.iter().any(|it| match it {
+            Item::Wave(..) => true,
+            Item::If(_, t, e) => section(t) || section(e),
+            Item::Loop(_, b) => section(b),
+            _ => false,
+        })
+    }
+    let branch = |it: &&Item| matches!(it, Item::If(..) | Item::Loop(..));
+    let in_branch = p.items.iter().filter(branch).any(|it| section(std::slice::from_ref(it)));
+    let partial = !p.compute && p.exec != !0 && p.items.iter().any(|it| branch(&it));
+    in_branch || (partial && section(&p.items))
+}
+
+fn half_exec_empty(p: &Prog, _: &Verdict) -> bool {

With the EXEC choices at lines 409-415 (cases 2 and 3, and case 1 with a shift of 32 or more), about half of all kernel programs start with an empty half, so this entry accepts every direct-split mismatch on half of the kernel corpus. On the 3090 the bug is in the driver (summary above): the HLSL repro needs a dead if before the section and the section's readlane + groupshared exchange inside an if. Could the class require that shape, for example an Item::Wave inside an Item::If in a kernel with an empty half, and say in its text that it is a driver issue? Then a new direct-split bug in those programs would still show.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221854 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221854). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 567 ~~~~diff @@ -0,0 +1,734 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute) +//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers, +//! zeros of both signs, infinities, a NaN and values whose products round. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// lane exchanges under the EXEC of the moment + Lanes(Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top) + Lds(u64, u64, u64), +} + +struct Gen<'a> { + r: &'a mut Rng, + /// only instructions the lowering translates + lowered: bool, +} + +impl Gen<'_> { + fn v(&mut self) -> u64 { + V + self.r.below(12) + 1 + } + fn vd(&mut self) -> u64 { + self.r.below(12) + 1 + } + fn s(&mut self) -> u64 { + self.r.below(12) + 4 + } + fn fv(&mut self) -> u64 { + 13 + self.r.below(4) + } + /// a scalar or vector source: a register, an inline constant or a literal + fn src(&mut self) -> (u64, Option<u32>) { + match self.r.below(6) { + 0 => (self.s(), None), + 1 => (128 + self.r.below(65), None), + 2 => (255, Some(self.r.word())), + _ => (self.v(), None), + } + } + + fn op(&mut self) -> I { + loop { + let x = self.any_op(); + if !self.lowered || lowered_alone(&x) { + return x; + } + } + } + + fn any_op(&mut self) -> I { + let k = self.r.below(100); + if k < 22 { + const SOP2: [&str; 16] = [ + "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32", + "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32", + ]; + let (a, b) = (self.s(), self.s()); + return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]); + } + if k < 30 { + const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"]; + return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]); + } + if k < 35 { + let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]); + return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]); + } + if k < 60 { + const VOP2: [&str; 13] = [ + "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32", + "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32", + ]; + let (s0, l) = self.src(); + let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)]; + return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l); + } + if k < 78 { + const VOP3: [&str; 14] = [ + "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32", + "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32", + ]; + let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())]; + return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None); + } + if k < 84 { + let s = self.s(); + return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]); + } + if k < 92 { + let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]); + return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]); + } + if k < 95 { + return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]); + } + // masks read as data + let m = 30 + 2 * self.r.below(3); + match self.r.below(5) { + 0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]), + 1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]), + 2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]), + 3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]), + _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]), + } + } + + /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form). + fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> { + let t = 18; + match self.r.below(6) { + 0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))], + 1 => { + let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]); + vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])] + } + 2 => vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 3 => vec![ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 4 => vec![ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]), + ], + _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])], + } + } + + fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> { + let mut out = Vec::new(); + for _ in 0..n { + let k = self.r.below(100); + if k < 10 && depth < 3 { + let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]); + let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]); + let (a, b) = (1 + self.r.below(4), self.r.below(3)); + out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false))); + } else if k < 16 && depth < 2 { + let n = 1 + self.r.below(4); + out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false))); + } else if k < 24 { + let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]); + let id = match op { + "V_AND_B32" | "V_MIN_U32" => 193, + _ => 128, + }; + let x = 17; + let mut steps = Vec::new(); + for _ in 0..1 + self.r.below(4) { + steps.extend(self.wave_step(op, x)); + } + steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)])); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Wave(self.v(), id, steps)); + } + } else if k < 27 { + let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]); + let x = self.vd(); + let steps = self.wave_step(op, x); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Lanes(steps)); + } + } else if k < 30 && top { + out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127))); + } else { + out.push(Item::Op(self.op())); + } + } + out + } +} + +/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k +/// uses s[40 + 4k ..], loop counters v20 + k. +fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) { + let ctl = 40 + 4 * depth; + for it in items { + match it { + Item::Op(x) => out.push(x.clone()), + Item::If(cmp, then, els) => { + let mut c = cmp.clone(); + c.2[0].1 = ctl; + out.push(c); + out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(then, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(els, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Loop(trip, body) => { + let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)])); + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)])); + let top = out.len(); + out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)])); + out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)])); + let leave = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(body, depth + 1, threads, out); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)])); + out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)])); + out[leave].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Wave(src, id, steps) => { + out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)])); + out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)])); + out.extend(steps.iter().cloned()); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Lanes(steps) => out.extend(steps.iter().cloned()), + Item::Lds(src, dst, k) => { + // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)])); + out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32)); + out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads)); + out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)])); + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)])); + out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + } + } + } +} + +/// A generated program: its items and how it runs. +#[derive(Clone)] +pub(crate) struct Prog { + pub items: Vec<Item>, + pub compute: bool, + /// a compute group's threads + pub threads: u32, + /// kernel programs: the EXEC their first instructions set (every lane exists) + pub exec: u64, + pub seed: u64, +} + +/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread. +fn lines(p: &Prog) -> Vec<I> { + let mut out = Vec::new(); + if p.compute { + // v1..v16 from the thread index; s4..s15 from s0 + for r in 1..=16u64 { + out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9))); + } + for r in VFLOAT { + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)])); + out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)])); + } + for r in SDATA { + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B))); + } + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)])); + } else { + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32)); + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32)); + } + emit(&p.items, 0, p.threads, &mut out); + if p.compute { + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)])); + // (group · threads + thread) · 112, in v[24:25] + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112)); + out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112)); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)])); + for k in 0..12u64 { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)])); + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)])); + } + for k in 0..16u64 { + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)])); + } + } else { + // the scalars as the lanes see them, all lanes on + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); + for k in SDATA { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)])); + } + } + out.push(super::asm::end()); + out +} + +/// The case of a program: kernel mode with random registers, its first instructions setting +/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads. +pub(crate) fn case(p: &Prog) -> Case { + let mut r = Rng::new(p.seed ^ 0x5EED); + let code = asm(&lines(p)); + if p.compute { + let threads = p.threads; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true }; + } + let mut st = KernelState::default(); + for s in SDATA { + st.sgpr[s as usize] = r.word(); + } + for regs in st.vgpr.iter_mut() { + for v in VDATA { + regs[v as usize] = r.word(); + } + for v in VFLOAT { + regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() }; + } + } + Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false } +} + +/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks). +fn lowered_alone(x: &I) -> bool { + let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }; + !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported")) +} + +/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which +/// D3D lets a GPU flush. +const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001]; + +pub(crate) fn program(seed: u64) -> Prog { + generate(seed, false) +} + +/// A kernel program of the instructions the lowering translates, for the CPU part. +pub(crate) fn lowered_program(seed: u64) -> Prog { + generate(seed, true) +} + +fn generate(seed: u64, lowered: bool) -> Prog { + let mut r = Rng::new(seed); + let compute = r.below(4) == 0 && !lowered; + let n = 6 + r.below(18); + let threads = r.pick(&[64, 96, 128]); + let exec: u64 = match r.below(5) { + 0 => !0, + 1 => !0 >> r.below(64), + 2 => 0xFFFF_FFFF << 32, + 3 => 0xFFFF_FFFF, + _ => r.next() | 1 << 40, + }; + let items = Gen { r: &mut r, lowered }.items(n, 0, compute); + Prog { items, compute, threads, exec, seed } +} + +/// `items` with one part taken out, each way there is. +fn smaller(items: &[Item]) -> Vec<Vec<Item>> { + let mut out = Vec::new(); + for k in 0..items.len() { + let mut v = items.to_vec(); + v.remove(k); + out.push(v); + let inner: Vec<Vec<Item>> = match &items[k] { + Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(), + Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(), + Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| { + let mut st = steps.clone(); + st.remove(j); + vec![Item::Wave(*s, *id, st)] + }).collect(), + _ => Vec::new(), + }; + for x in inner { + let mut v = items.to_vec(); + v.splice(k..=k, x); + out.push(v); + } + } + out +} + +fn verdict(p: &Prog, form: &Form) -> Option<Verdict> { + let c = case(p); + let want = reference(&c, Flip::None).ok()?; + Some(judge(&c, &want, (form.1)(&c))) +} + +fn differs(p: &Prog, form: &Form) -> bool { + matches!(verdict(p, form), Some(Verdict::Mismatch(..))) +} + +/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report. +fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String { + let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" }); + if on.is_empty() { + return format!("{head}\n{}", listing(p)); + } + let s = shrink(on, p, form); + format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s)) +} + +/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out +/// one part at a time. +pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog { + let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v)); + let was = class(p); + let mut p = p.clone(); + 'again: loop { + for items in smaller(&p.items) { + let q = Prog { items, ..p.clone() }; + if differs(&q, form) && class(&q) == was { + p = q; + continue 'again; + } + } + return p; + } +} + +/// `p`'s lines, ready to paste as a regression test. +pub(crate) fn listing(p: &Prog) -> String { + lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect() +} + +fn seeds(base: u64, count: u64) -> std::ops::Range<u64> { + let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count); + base..base + n +} + +/// The share of seeds (%) a form compares with the reference at least (adapter as in +/// `forms::EXPECTED`, form, floor). +const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[ + ("CPU", "lowering on CPU", 12), + ("NVIDIA", "HLSL split", 90), + ("NVIDIA", "direct split", 90), + ("NVIDIA", "per-lane split", 10), +]; + +/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other +/// is a failure. +const REFUSALS: &[(&str, &str, &str)] = &[ + ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "a number read as a mask (through a join)"), + ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"), + ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"), + ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"), + ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"), + ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"), + ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"), + ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"), + ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"), + ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"), +]; + +/// Mismatches main's forms make, known by what the program does (adapter, form, what, test). +const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[ + ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "HLSL split", "-0 for +0", negative_zero), + ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero), + ("NVIDIA", "direct split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty), +]; + +fn upper_half_empty(p: &Prog, v: &Verdict) -> bool { + let Verdict::Mismatch(at, ..) = v else { return false }; + let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads); + p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64) +} + +fn negative_zero(_: &Prog, v: &Verdict) -> bool { + matches!(v, Verdict::Mismatch(_, 0, 0x8000_0000, _)) +} + +fn nan_as_zero(_: &Prog, v: &Verdict) -> bool { + matches!(v, Verdict::Mismatch(_, w, 0, _) if f32::from_bits(*w).is_nan()) +} + +fn section_with_lanes_off(p: &Prog, _: &Verdict) -> bool { + fn section(items: &[Item]) -> bool { + items.iter().any(|it| match it { + Item::Wave(..) => true, + Item::If(_, t, e) => section(t) || section(e), + Item::Loop(_, b) => section(b), + _ => false, + }) + } + let branch = |it: &&Item| matches!(it, Item::If(..) | Item::Loop(..)); + let in_branch = p.items.iter().filter(branch).any(|it| section(std::slice::from_ref(it))); + let partial = !p.compute && p.exec != !0 && p.items.iter().any(|it| branch(&it)); + in_branch || (partial && section(&p.items)) +} + +fn half_exec_empty(p: &Prog, _: &Verdict) -> bool { ~~~~ --- With the EXEC choices at lines 409-415 (cases 2 and 3, and case 1 with a shift of 32 or more), about half of all kernel programs start with an empty half, so this entry accepts every direct-split mismatch on half of the kernel corpus. On the 3090 the bug is in the driver (summary above): the HLSL repro needs a dead `if` before the section and the section's readlane + groupshared exchange inside an `if`. Could the class require that shape, for example an `Item::Wave` inside an `Item::If` in a kernel with an empty half, and say in its text that it is a driver issue? Then a new direct-split bug in those programs would still show.
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 525

@@ -0,0 +1,734 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute)
+//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers,
+//! zeros of both signs, infinities, a NaN and values whose products round. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// lane exchanges under the EXEC of the moment
+    Lanes(Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top)
+    Lds(u64, u64, u64),
+}
+
+struct Gen<'a> {
+    r: &'a mut Rng,
+    /// only instructions the lowering translates
+    lowered: bool,
+}
+
+impl Gen<'_> {
+    fn v(&mut self) -> u64 {
+        V + self.r.below(12) + 1
+    }
+    fn vd(&mut self) -> u64 {
+        self.r.below(12) + 1
+    }
+    fn s(&mut self) -> u64 {
+        self.r.below(12) + 4
+    }
+    fn fv(&mut self) -> u64 {
+        13 + self.r.below(4)
+    }
+    /// a scalar or vector source: a register, an inline constant or a literal
+    fn src(&mut self) -> (u64, Option<u32>) {
+        match self.r.below(6) {
+            0 => (self.s(), None),
+            1 => (128 + self.r.below(65), None),
+            2 => (255, Some(self.r.word())),
+            _ => (self.v(), None),
+        }
+    }
+
+    fn op(&mut self) -> I {
+        loop {
+            let x = self.any_op();
+            if !self.lowered || lowered_alone(&x) {
+                return x;
+            }
+        }
+    }
+
+    fn any_op(&mut self) -> I {
+        let k = self.r.below(100);
+        if k < 22 {
+            const SOP2: [&str; 16] = [
+                "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32",
+                "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32",
+            ];
+            let (a, b) = (self.s(), self.s());
+            return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]);
+        }
+        if k < 30 {
+            const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"];
+            return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]);
+        }
+        if k < 35 {
+            let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]);
+            return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]);
+        }
+        if k < 60 {
+            const VOP2: [&str; 13] = [
+                "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32",
+                "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32",
+            ];
+            let (s0, l) = self.src();
+            let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)];
+            return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l);
+        }
+        if k < 78 {
+            const VOP3: [&str; 14] = [
+                "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32",
+                "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32",
+            ];
+            let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())];
+            return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None);
+        }
+        if k < 84 {
+            let s = self.s();
+            return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]);
+        }
+        if k < 92 {
+            let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]);
+            return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]);
+        }
+        if k < 95 {
+            return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]);
+        }
+        // masks read as data
+        let m = 30 + 2 * self.r.below(3);
+        match self.r.below(5) {
+            0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]),
+            1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]),
+            2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]),
+            3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]),
+            _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]),
+        }
+    }
+
+    /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form).
+    fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> {
+        let t = 18;
+        match self.r.below(6) {
+            0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))],
+            1 => {
+                let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]);
+                vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])]
+            }
+            2 => vec![
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            3 => vec![
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            4 => vec![
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]),
+            ],
+            _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])],
+        }
+    }
+
+    fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> {
+        let mut out = Vec::new();
+        for _ in 0..n {
+            let k = self.r.below(100);
+            if k < 10 && depth < 3 {
+                let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]);
+                let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]);
+                let (a, b) = (1 + self.r.below(4), self.r.below(3));
+                out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false)));
+            } else if k < 16 && depth < 2 {
+                let n = 1 + self.r.below(4);
+                out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false)));
+            } else if k < 24 {
+                let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]);
+                let id = match op {
+                    "V_AND_B32" | "V_MIN_U32" => 193,
+                    _ => 128,
+                };
+                let x = 17;
+                let mut steps = Vec::new();
+                for _ in 0..1 + self.r.below(4) {
+                    steps.extend(self.wave_step(op, x));
+                }
+                steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)]));
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Wave(self.v(), id, steps));
+                }
+            } else if k < 27 {
+                let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]);
+                let x = self.vd();
+                let steps = self.wave_step(op, x);
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Lanes(steps));
+                }
+            } else if k < 30 && top {
+                out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127)));
+            } else {
+                out.push(Item::Op(self.op()));
+            }
+        }
+        out
+    }
+}
+
+/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k
+/// uses s[40 + 4k ..], loop counters v20 + k.
+fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) {
+    let ctl = 40 + 4 * depth;
+    for it in items {
+        match it {
+            Item::Op(x) => out.push(x.clone()),
+            Item::If(cmp, then, els) => {
+                let mut c = cmp.clone();
+                c.2[0].1 = ctl;
+                out.push(c);
+                out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(then, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(els, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Loop(trip, body) => {
+                let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth);
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)]));
+                out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)]));
+                out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)]));
+                let top = out.len();
+                out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)]));
+                out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)]));
+                let leave = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(body, depth + 1, threads, out);
+                out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)]));
+                out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)]));
+                out[leave].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Wave(src, id, steps) => {
+                out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)]));
+                out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)]));
+                out.extend(steps.iter().cloned());
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Lanes(steps) => out.extend(steps.iter().cloned()),
+            Item::Lds(src, dst, k) => {
+                // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)]));
+                out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+                out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32));
+                out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads));
+                out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)]));
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)]));
+                out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+            }
+        }
+    }
+}
+
+/// A generated program: its items and how it runs.
+#[derive(Clone)]
+pub(crate) struct Prog {
+    pub items: Vec<Item>,
+    pub compute: bool,
+    /// a compute group's threads
+    pub threads: u32,
+    /// kernel programs: the EXEC their first instructions set (every lane exists)
+    pub exec: u64,
+    pub seed: u64,
+}
+
+/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread.
+fn lines(p: &Prog) -> Vec<I> {
+    let mut out = Vec::new();
+    if p.compute {
+        // v1..v16 from the thread index; s4..s15 from s0
+        for r in 1..=16u64 {
+            out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9)));
+        }
+        for r in VFLOAT {
+            out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)]));
+            out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)]));
+        }
+        for r in SDATA {
+            out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B)));
+        }
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)]));
+    } else {
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32));
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32));
+    }
+    emit(&p.items, 0, p.threads, &mut out);
+    if p.compute {
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)]));
+        // (group · threads + thread) · 112, in v[24:25]
+        out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112));
+        out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112));
+        out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)]));
+        out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)]));
+        for k in 0..12u64 {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)]));
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)]));
+        }
+        for k in 0..16u64 {
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)]));
+        }
+    } else {
+        // the scalars as the lanes see them, all lanes on
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]));
+        for k in SDATA {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)]));
+        }
+    }
+    out.push(super::asm::end());
+    out
+}
+
+/// The case of a program: kernel mode with random registers, its first instructions setting
+/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads.
+pub(crate) fn case(p: &Prog) -> Case {
+    let mut r = Rng::new(p.seed ^ 0x5EED);
+    let code = asm(&lines(p));
+    if p.compute {
+        let threads = p.threads;
+        let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+        return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true };
+    }
+    let mut st = KernelState::default();
+    for s in SDATA {
+        st.sgpr[s as usize] = r.word();
+    }
+    for regs in st.vgpr.iter_mut() {
+        for v in VDATA {
+            regs[v as usize] = r.word();
+        }
+        for v in VFLOAT {
+            regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() };
+        }
+    }
+    Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }
+}
+
+/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks).
+fn lowered_alone(x: &I) -> bool {
+    let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false };
+    !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported"))
+}
+
+/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which
+/// D3D lets a GPU flush.
+const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001];
+
+pub(crate) fn program(seed: u64) -> Prog {
+    generate(seed, false)
+}
+
+/// A kernel program of the instructions the lowering translates, for the CPU part.
+pub(crate) fn lowered_program(seed: u64) -> Prog {
+    generate(seed, true)
+}
+
+fn generate(seed: u64, lowered: bool) -> Prog {
+    let mut r = Rng::new(seed);
+    let compute = r.below(4) == 0 && !lowered;
+    let n = 6 + r.below(18);
+    let threads = r.pick(&[64, 96, 128]);
+    let exec: u64 = match r.below(5) {
+        0 => !0,
+        1 => !0 >> r.below(64),
+        2 => 0xFFFF_FFFF << 32,
+        3 => 0xFFFF_FFFF,
+        _ => r.next() | 1 << 40,
+    };
+    let items = Gen { r: &mut r, lowered }.items(n, 0, compute);
+    Prog { items, compute, threads, exec, seed }
+}
+
+/// `items` with one part taken out, each way there is.
+fn smaller(items: &[Item]) -> Vec<Vec<Item>> {
+    let mut out = Vec::new();
+    for k in 0..items.len() {
+        let mut v = items.to_vec();
+        v.remove(k);
+        out.push(v);
+        let inner: Vec<Vec<Item>> = match &items[k] {
+            Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(),
+            Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(),
+            Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| {
+                let mut st = steps.clone();
+                st.remove(j);
+                vec![Item::Wave(*s, *id, st)]
+            }).collect(),
+            _ => Vec::new(),
+        };
+        for x in inner {
+            let mut v = items.to_vec();
+            v.splice(k..=k, x);
+            out.push(v);
+        }
+    }
+    out
+}
+
+fn verdict(p: &Prog, form: &Form) -> Option<Verdict> {
+    let c = case(p);
+    let want = reference(&c, Flip::None).ok()?;
+    Some(judge(&c, &want, (form.1)(&c)))
+}
+
+fn differs(p: &Prog, form: &Form) -> bool {
+    matches!(verdict(p, form), Some(Verdict::Mismatch(..)))
+}
+
+/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report.
+fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String {
+    let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" });
+    if on.is_empty() {
+        return format!("{head}\n{}", listing(p));
+    }
+    let s = shrink(on, p, form);
+    format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s))
+}
+
+/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out
+/// one part at a time.
+pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog {
+    let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v));
+    let was = class(p);
+    let mut p = p.clone();
+    'again: loop {
+        for items in smaller(&p.items) {
+            let q = Prog { items, ..p.clone() };
+            if differs(&q, form) && class(&q) == was {
+                p = q;
+                continue 'again;
+            }
+        }
+        return p;
+    }
+}
+
+/// `p`'s lines, ready to paste as a regression test.
+pub(crate) fn listing(p: &Prog) -> String {
+    lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect()
+}
+
+fn seeds(base: u64, count: u64) -> std::ops::Range<u64> {
+    let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count);
+    base..base + n
+}
+
+/// The share of seeds (%) a form compares with the reference at least (adapter as in
+/// `forms::EXPECTED`, form, floor).
+const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[
+    ("CPU", "lowering on CPU", 12),
+    ("NVIDIA", "HLSL split", 90),
+    ("NVIDIA", "direct split", 90),
+    ("NVIDIA", "per-lane split", 10),
+];
+
+/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other
+/// is a failure.
+const REFUSALS: &[(&str, &str, &str)] = &[
+    ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "a number read as a mask (through a join)"),
+    ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"),
+    ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"),
+    ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"),
+    ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"),
+    ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"),
+    ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"),
+    ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"),
+    ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"),
+    ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"),
+];
+
+/// Mismatches main's forms make, known by what the program does (adapter, form, what, test).
+const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[

Two classes from my fuzz comment are not here. s_mul_i32 as (uint)((int)a * (int)b) (recomp/emit.rs:1703, unchanged) gave 15 of my 8,000 HLSL-split seeds at 9ceea007; and the compute nested if/else class of direct split (my group 6, 11 seeds) is not covered by half_exec_empty, which requires a kernel. So XCL_FUZZ_WAVE64_SEEDS=2000 on NVIDIA should still fail, while the description says "this pull request pins each as a known class". Either add the two classes or change that sentence. The s_mul_i32 fix itself is one line (multiply as uint) and belongs in a separate pull request.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221861 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221861). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 525 ~~~~diff @@ -0,0 +1,734 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute) +//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers, +//! zeros of both signs, infinities, a NaN and values whose products round. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// lane exchanges under the EXEC of the moment + Lanes(Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top) + Lds(u64, u64, u64), +} + +struct Gen<'a> { + r: &'a mut Rng, + /// only instructions the lowering translates + lowered: bool, +} + +impl Gen<'_> { + fn v(&mut self) -> u64 { + V + self.r.below(12) + 1 + } + fn vd(&mut self) -> u64 { + self.r.below(12) + 1 + } + fn s(&mut self) -> u64 { + self.r.below(12) + 4 + } + fn fv(&mut self) -> u64 { + 13 + self.r.below(4) + } + /// a scalar or vector source: a register, an inline constant or a literal + fn src(&mut self) -> (u64, Option<u32>) { + match self.r.below(6) { + 0 => (self.s(), None), + 1 => (128 + self.r.below(65), None), + 2 => (255, Some(self.r.word())), + _ => (self.v(), None), + } + } + + fn op(&mut self) -> I { + loop { + let x = self.any_op(); + if !self.lowered || lowered_alone(&x) { + return x; + } + } + } + + fn any_op(&mut self) -> I { + let k = self.r.below(100); + if k < 22 { + const SOP2: [&str; 16] = [ + "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32", + "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32", + ]; + let (a, b) = (self.s(), self.s()); + return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]); + } + if k < 30 { + const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"]; + return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]); + } + if k < 35 { + let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]); + return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]); + } + if k < 60 { + const VOP2: [&str; 13] = [ + "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32", + "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32", + ]; + let (s0, l) = self.src(); + let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)]; + return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l); + } + if k < 78 { + const VOP3: [&str; 14] = [ + "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32", + "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32", + ]; + let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())]; + return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None); + } + if k < 84 { + let s = self.s(); + return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]); + } + if k < 92 { + let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]); + return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]); + } + if k < 95 { + return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]); + } + // masks read as data + let m = 30 + 2 * self.r.below(3); + match self.r.below(5) { + 0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]), + 1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]), + 2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]), + 3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]), + _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]), + } + } + + /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form). + fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> { + let t = 18; + match self.r.below(6) { + 0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))], + 1 => { + let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]); + vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])] + } + 2 => vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 3 => vec![ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 4 => vec![ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]), + ], + _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])], + } + } + + fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> { + let mut out = Vec::new(); + for _ in 0..n { + let k = self.r.below(100); + if k < 10 && depth < 3 { + let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]); + let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]); + let (a, b) = (1 + self.r.below(4), self.r.below(3)); + out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false))); + } else if k < 16 && depth < 2 { + let n = 1 + self.r.below(4); + out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false))); + } else if k < 24 { + let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]); + let id = match op { + "V_AND_B32" | "V_MIN_U32" => 193, + _ => 128, + }; + let x = 17; + let mut steps = Vec::new(); + for _ in 0..1 + self.r.below(4) { + steps.extend(self.wave_step(op, x)); + } + steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)])); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Wave(self.v(), id, steps)); + } + } else if k < 27 { + let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]); + let x = self.vd(); + let steps = self.wave_step(op, x); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Lanes(steps)); + } + } else if k < 30 && top { + out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127))); + } else { + out.push(Item::Op(self.op())); + } + } + out + } +} + +/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k +/// uses s[40 + 4k ..], loop counters v20 + k. +fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) { + let ctl = 40 + 4 * depth; + for it in items { + match it { + Item::Op(x) => out.push(x.clone()), + Item::If(cmp, then, els) => { + let mut c = cmp.clone(); + c.2[0].1 = ctl; + out.push(c); + out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(then, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(els, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Loop(trip, body) => { + let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)])); + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)])); + let top = out.len(); + out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)])); + out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)])); + let leave = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(body, depth + 1, threads, out); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)])); + out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)])); + out[leave].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Wave(src, id, steps) => { + out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)])); + out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)])); + out.extend(steps.iter().cloned()); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Lanes(steps) => out.extend(steps.iter().cloned()), + Item::Lds(src, dst, k) => { + // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)])); + out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32)); + out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads)); + out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)])); + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)])); + out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + } + } + } +} + +/// A generated program: its items and how it runs. +#[derive(Clone)] +pub(crate) struct Prog { + pub items: Vec<Item>, + pub compute: bool, + /// a compute group's threads + pub threads: u32, + /// kernel programs: the EXEC their first instructions set (every lane exists) + pub exec: u64, + pub seed: u64, +} + +/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread. +fn lines(p: &Prog) -> Vec<I> { + let mut out = Vec::new(); + if p.compute { + // v1..v16 from the thread index; s4..s15 from s0 + for r in 1..=16u64 { + out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9))); + } + for r in VFLOAT { + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)])); + out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)])); + } + for r in SDATA { + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B))); + } + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)])); + } else { + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32)); + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32)); + } + emit(&p.items, 0, p.threads, &mut out); + if p.compute { + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)])); + // (group · threads + thread) · 112, in v[24:25] + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112)); + out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112)); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)])); + for k in 0..12u64 { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)])); + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)])); + } + for k in 0..16u64 { + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)])); + } + } else { + // the scalars as the lanes see them, all lanes on + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); + for k in SDATA { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)])); + } + } + out.push(super::asm::end()); + out +} + +/// The case of a program: kernel mode with random registers, its first instructions setting +/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads. +pub(crate) fn case(p: &Prog) -> Case { + let mut r = Rng::new(p.seed ^ 0x5EED); + let code = asm(&lines(p)); + if p.compute { + let threads = p.threads; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true }; + } + let mut st = KernelState::default(); + for s in SDATA { + st.sgpr[s as usize] = r.word(); + } + for regs in st.vgpr.iter_mut() { + for v in VDATA { + regs[v as usize] = r.word(); + } + for v in VFLOAT { + regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() }; + } + } + Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false } +} + +/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks). +fn lowered_alone(x: &I) -> bool { + let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }; + !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported")) +} + +/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which +/// D3D lets a GPU flush. +const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001]; + +pub(crate) fn program(seed: u64) -> Prog { + generate(seed, false) +} + +/// A kernel program of the instructions the lowering translates, for the CPU part. +pub(crate) fn lowered_program(seed: u64) -> Prog { + generate(seed, true) +} + +fn generate(seed: u64, lowered: bool) -> Prog { + let mut r = Rng::new(seed); + let compute = r.below(4) == 0 && !lowered; + let n = 6 + r.below(18); + let threads = r.pick(&[64, 96, 128]); + let exec: u64 = match r.below(5) { + 0 => !0, + 1 => !0 >> r.below(64), + 2 => 0xFFFF_FFFF << 32, + 3 => 0xFFFF_FFFF, + _ => r.next() | 1 << 40, + }; + let items = Gen { r: &mut r, lowered }.items(n, 0, compute); + Prog { items, compute, threads, exec, seed } +} + +/// `items` with one part taken out, each way there is. +fn smaller(items: &[Item]) -> Vec<Vec<Item>> { + let mut out = Vec::new(); + for k in 0..items.len() { + let mut v = items.to_vec(); + v.remove(k); + out.push(v); + let inner: Vec<Vec<Item>> = match &items[k] { + Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(), + Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(), + Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| { + let mut st = steps.clone(); + st.remove(j); + vec![Item::Wave(*s, *id, st)] + }).collect(), + _ => Vec::new(), + }; + for x in inner { + let mut v = items.to_vec(); + v.splice(k..=k, x); + out.push(v); + } + } + out +} + +fn verdict(p: &Prog, form: &Form) -> Option<Verdict> { + let c = case(p); + let want = reference(&c, Flip::None).ok()?; + Some(judge(&c, &want, (form.1)(&c))) +} + +fn differs(p: &Prog, form: &Form) -> bool { + matches!(verdict(p, form), Some(Verdict::Mismatch(..))) +} + +/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report. +fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String { + let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" }); + if on.is_empty() { + return format!("{head}\n{}", listing(p)); + } + let s = shrink(on, p, form); + format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s)) +} + +/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out +/// one part at a time. +pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog { + let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v)); + let was = class(p); + let mut p = p.clone(); + 'again: loop { + for items in smaller(&p.items) { + let q = Prog { items, ..p.clone() }; + if differs(&q, form) && class(&q) == was { + p = q; + continue 'again; + } + } + return p; + } +} + +/// `p`'s lines, ready to paste as a regression test. +pub(crate) fn listing(p: &Prog) -> String { + lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect() +} + +fn seeds(base: u64, count: u64) -> std::ops::Range<u64> { + let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count); + base..base + n +} + +/// The share of seeds (%) a form compares with the reference at least (adapter as in +/// `forms::EXPECTED`, form, floor). +const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[ + ("CPU", "lowering on CPU", 12), + ("NVIDIA", "HLSL split", 90), + ("NVIDIA", "direct split", 90), + ("NVIDIA", "per-lane split", 10), +]; + +/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other +/// is a failure. +const REFUSALS: &[(&str, &str, &str)] = &[ + ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "a number read as a mask (through a join)"), + ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"), + ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"), + ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"), + ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"), + ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"), + ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"), + ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"), + ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"), + ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"), +]; + +/// Mismatches main's forms make, known by what the program does (adapter, form, what, test). +const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[ ~~~~ --- Two classes from my fuzz comment are not here. `s_mul_i32` as `(uint)((int)a * (int)b)` (`recomp/emit.rs:1703`, unchanged) gave 15 of my 8,000 HLSL-split seeds at 9ceea007; and the compute nested if/else class of direct split (my group 6, 11 seeds) is not covered by `half_exec_empty`, which requires a kernel. So `XCL_FUZZ_WAVE64_SEEDS=2000` on NVIDIA should still fail, while the description says "this pull request pins each as a known class". Either add the two classes or change that sentence. The `s_mul_i32` fix itself is one line (multiply as uint) and belongs in a separate pull request.
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 356

@@ -0,0 +1,496 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals
+/// kept, DX10_CLAMP set, IEEE clear.
+pub(crate) const MODE: u32 = 0x1F0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stop {
+    /// an instruction (or an operand or modifier of one) outside the modelled set
+    Unsupported { pc: u64, name: String },
+    /// the program did something the console would not survive: a branch into nothing, an
+    /// access outside `mem`, an unaligned LDS dword
+    Fault { pc: u64, why: String },
+    /// the step limit
+    Steps(u64),
+}
+
+impl std::fmt::Display for Stop {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"),
+            Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"),
+            Stop::Steps(n) => write!(f, "no end after {n} steps"),
+        }
+    }
+}
+
+/// A rule of the ISA turned the wrong way, for tests that prove a check sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub(crate) enum Flip {
+    #[default]
+    None,
+    /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would
+    Lane31,
+    /// v_permlanex16 reads its own row instead of the other row of its half
+    PermlaneOwnRow,
+    /// vector instructions write the lanes EXEC has off
+    ExecIgnored,
+    /// VCC reads and branches see only its low half
+    VccLow,
+}
+
+pub(crate) fn unsupported(d: &Decoded) -> Stop {
+    Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) }
+}
+
+pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop {
+    Stop::Fault { pc: d.pc, why: why.into() }
+}
+
+pub(crate) fn field(d: &Decoded, name: &str) -> u64 {
+    field_value(d.enc, &d.words, name).unwrap_or(0)
+}
+
+/// A program decoded once: its instructions and where each starts.
+pub(crate) struct Program {
+    pub list: Vec<Decoded>,
+    pub index: HashMap<u64, usize>,
+}
+
+impl Program {
+    /// Words that do not decode (constants after the code) are left out; reaching one faults.
+    pub fn new(code: &[u8]) -> Program {
+        let mut list = Vec::new();
+        let mut off = 0;
+        while off + 4 <= code.len() {
+            match rdna2::decode(&code[off..], off as u64) {
+                Ok(d) => {
+                    off += d.len;
+                    list.push(d);
+                }
+                Err(_) => off += 4,
+            }
+        }
+        rdna2::resolve_far_jumps(&mut list);
+        let index = list.iter().enumerate().map(|(k, d)| (d.pc, k)).collect();
+        Program { list, index }
+    }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(crate) enum State {
+    Run,
+    Barrier,
+    Done,
+}
+
+/// One wave. A taint is the ULP bound a value may be off by (0: exact), set by an instruction
+/// the D3D rules let a GPU approximate and kept by copies; anything computed from it is
+/// `UNBOUNDED`.
+#[derive(Clone)]
+pub(crate) struct Wave {
+    pub lanes: usize,
+    pub s: [u32; 128],
+    pub scc: bool,
+    pub v: Vec<[u32; 256]>,
+    pub st: [u8; 128],
+    pub vt: Vec<[u8; 256]>,
+    pub mode: u32,
+    pub pc: usize,
+    pub state: State,
+}
+
+/// What every wave of a run shares: flat memory, the group's LDS, textures and samplers.
+pub(crate) struct Ctx<'a> {
+    pub mem: &'a mut Vec<u32>,
+    pub mt: HashMap<usize, u8>,
+    pub lds: Vec<u32>,
+    pub lt: Vec<u8>,
+    pub tex: &'a mut [TestTexture],
+    pub samplers: &'a [TestSampler],
+    /// textures a tainted value was stored to
+    pub tex_taint: Vec<bool>,
+    pub flip: Flip,
+}
+
+impl<'a> Ctx<'a> {
+    pub fn new(mem: &'a mut Vec<u32>, tex: &'a mut [TestTexture], samplers: &'a [TestSampler]) -> Ctx<'a> {
+        let n = tex.len();
+        Ctx { mem, mt: HashMap::new(), lds: vec![0; LDS_DWORDS], lt: vec![0; LDS_DWORDS], tex, samplers, tex_taint: vec![false; n], flip: Flip::None }
+    }
+}
+
+const TRANSCENDENTAL: [(&str, u8); 9] = [
+    // D3D11.3 functional spec 3.1.3.2: rcp and sqrt within 1 ULP
+    ("V_RCP_F32", 1),
+    ("V_SQRT_F32", 1),
+    // our own bounds; the spec puts these on its instruction pages
+    ("V_RCP_IFLAG_F32", 1),
+    ("V_RSQ_F32", 2),
+    // bounds that are not in ULPs
+    ("V_EXP_F32", UNBOUNDED),
+    ("V_LOG_F32", UNBOUNDED),
+    ("V_SIN_F32", SINCOS),
+    ("V_COS_F32", SINCOS),
+    ("V_LDEXP_F32", 0),
+];
+
+/// The taint of a value computed from an approximate one: a 1-ULP input can be any number of
+/// ULPs out (x - y with x close to y), so it is not compared.
+pub(crate) const UNBOUNDED: u8 = u8::MAX;
+
+/// The taint of v_sin and v_cos: within D3D's absolute 0.0008.
+pub(crate) const SINCOS: u8 = u8::MAX - 1;
+
+/// The taint of a NaN made by float arithmetic: its bits are the host's, so any NaN agrees.
+pub(crate) const NAN: u8 = u8::MAX - 2;
+
+/// The taint of a value computed (not copied) from values of taint `t`.
+pub(crate) fn computed(t: u8) -> u8 {
+    if t == 0 { 0 } else { UNBOUNDED }
+}
+
+/// Instructions that copy a value's bits (from a lane, a register, or one of two): they keep its
+/// taint.
+const COPY: &[&str] = &[
+    "S_MOV_B32", "S_MOV_B64", "S_CSELECT_B32", "S_CSELECT_B64", "V_MOV_B32", "V_CNDMASK_B32", "V_READLANE_B32", "V_WRITELANE_B32",
+    "V_READFIRSTLANE_B32", "V_PERMLANE16_B32", "V_PERMLANEX16_B32", "DS_SWIZZLE_B32", "DS_PERMUTE_B32", "DS_BPERMUTE_B32",
+];
+
+/// Instructions whose lanes read other lanes: every output takes the taint of every lane read.
+fn cross_lane(d: &Decoded) -> bool {
+    d.variant != rdna2::Variant::Plain
+        || matches!(
+            d.inst.name,
+            "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" | "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" | "DS_SWIZZLE_B32" | "DS_PERMUTE_B32" | "DS_BPERMUTE_B32"
+        )
+}
+
+impl Wave {
+    pub fn new(lanes: usize) -> Wave {
+        Wave { lanes, s: [0; 128], scc: false, v: vec![[0; 256]; lanes], st: [0; 128], vt: vec![[0; 256]; lanes], mode: MODE, pc: 0, state: State::Run }
+    }
+
+    /// A mask register (VCC, EXEC, an SGPR pair): its low dword alone in a wave of 32.
+    pub fn mask(&self, r: usize) -> u64 {
+        if self.lanes == 64 { self.pair(r) } else { u64::from(self.s[r]) }
+    }
+
+    pub fn set_mask(&mut self, r: usize, m: u64) {
+        if r == 125 {
+            return;
+        }
+        self.s[r] = m as u32;
+        if self.lanes == 64 {
+            self.s[r + 1] = (m >> 32) as u32;
+        }
+    }
+
+    pub fn exec(&self) -> u64 {
+        self.mask(126)
+    }
+
+    pub fn vcc(&self, flip: Flip) -> u64 {
+        if flip == Flip::VccLow { u64::from(self.s[106]) } else { self.mask(106) }
+    }
+
+    pub fn pair(&self, r: usize) -> u64 {
+        u64::from(self.s[r]) | u64::from(self.s[r + 1]) << 32
+    }
+
+    pub fn set_pair(&mut self, r: usize, x: u64) {
+        if r != 125 {
+            self.s[r] = x as u32;
+            self.s[r + 1] = (x >> 32) as u32;
+        }
+    }
+
+    pub fn set_s(&mut self, d: &Decoded, r: u64, x: u32) -> Result<(), Stop> {
+        match r {
+            125 => Ok(()),
+            0..=127 => {
+                self.s[r as usize] = x;
+                Ok(())
+            }
+            _ => Err(fault(d, format!("scalar destination {r}"))),
+        }
+    }
+
+    /// A 32-bit scalar operand (an SGPR, a constant or the literal).
+    pub fn scalar(&self, d: &Decoded, code: u64) -> Result<u32, Stop> {
+        Ok(match code {
+            125 => 0,
+            0..=127 => self.s[code as usize],
+            128..=192 => (code - 128) as u32,
+            193..=208 => (192 - code as i64) as u32,
+            240 => 0.5f32.to_bits(),
+            241 => (-0.5f32).to_bits(),
+            242 => 1.0f32.to_bits(),
+            243 => (-1.0f32).to_bits(),
+            244 => 2.0f32.to_bits(),
+            245 => (-2.0f32).to_bits(),
+            246 => 4.0f32.to_bits(),
+            247 => (-4.0f32).to_bits(),
+            248 => 0x3E22_F983,
+            251 => u32::from(self.vcc(Flip::None) == 0),
+            252 => u32::from(self.exec() == 0),
+            253 => u32::from(self.scc),
+            255 => d.literal.ok_or_else(|| fault(d, "no literal"))?,
+            _ => return Err(unsupported(d)),
+        })
+    }
+
+    /// A 64-bit integer scalar operand: a pair, a constant sign-extended, a literal
+    /// zero-extended (`signed`: sign-extended).
+    pub fn scalar64(&self, d: &Decoded, code: u64, signed: bool) -> Result<u64, Stop> {
+        Ok(match code {
+            125 => 0,
+            0..=127 => self.pair(code as usize),
+            128..=208 => self.scalar(d, code)? as i32 as i64 as u64,
+            251..=253 => u64::from(self.scalar(d, code)?),
+            255 if signed => self.scalar(d, code)? as i32 as i64 as u64,
+            255 => u64::from(self.scalar(d, code)?),
+            _ => return Err(unsupported(d)),
+        })
+    }
+
+    /// A 32-bit vector source of `lane`.
+    pub fn vsrc(&self, d: &Decoded, code: u64, lane: usize) -> Result<u32, Stop> {
+        if code >= 256 { Ok(self.v[lane][code as usize - 256]) } else { self.scalar(d, code) }
+    }
+
+    /// A 64-bit vector source of `lane` (a VGPR pair, an SGPR pair or a constant).
+    pub fn vsrc64(&self, d: &Decoded, code: u64, lane: usize) -> Result<u64, Stop> {
+        if code >= 256 {
+            let r = code as usize - 256;
+            if r == 255 {
+                return Err(fault(d, "VGPR pair past v255"));
+            }
+            Ok(u64::from(self.v[lane][r]) | u64::from(self.v[lane][r + 1]) << 32)
+        } else {
+            self.scalar64(d, code, true)
+        }
+    }
+
+    fn taint_of(&self, sregs: &[u64], vregs: &[u64], lane: usize) -> u8 {
+        let s = sregs.iter().map(|&r| self.st[r as usize]).max().unwrap_or(0);
+        let v = vregs.iter().filter(|&&r| r < 256).map(|&r| self.vt[lane][r as usize]).max().unwrap_or(0);
+        s.max(v)
+    }
+
+    /// One instruction.
+    pub fn step(&mut self, p: &Program, cx: &mut Ctx) -> Result<(), Stop> {
+        let d = p.list.get(self.pc).ok_or(Stop::Fault { pc: u64::MAX, why: "ran past the code".into() })?;
+        let k = self.pc;
+        // a jump replaces it
+        self.pc = usize::MAX;
+        let (sr, sw) = rdna2::sgpr_uses(d);
+        let (vr, vw) = rdna2::vgpr_uses(d);
+        let exec = self.exec();
+        let mut tin: Vec<u8> = (0..self.lanes).map(|l| self.taint_of(&sr, &vr, l)).collect();
+        if cross_lane(d) {
+            let all = tin.iter().copied().max().unwrap_or(0);
+            tin.iter_mut().for_each(|t| *t = all);
+        }
+        let own = TRANSCENDENTAL.iter().find(|x| x.0 == d.inst.name).map_or(0, |x| x.1);
+        let copy = COPY.contains(&d.inst.name);
+        let out = |t: u8| if t == 0 { own } else if copy { t } else { computed(t) };
+        let f32_out = float::is_float(d.inst.name) && !["_I32_F32", "_U32_F32", "F16", "PK"].iter().any(|x| d.inst.name.contains(x));
+        match d.enc.name {
+            "ENC_SOPP" => salu::sopp(self, d, p, cx)?,
+            "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => salu::run(self, d, p)?,
+            "ENC_SMEM" => mem::smem(self, d, cx)?,
+            "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "VOP3_SDST_ENC" | "ENC_VOP3P" => valu::run(self, d, cx)?,
+            "ENC_DS" => mem::ds(self, d, cx)?,
+            "ENC_MUBUF" | "ENC_MTBUF" => mem::buffer(self, d, cx)?,
+            "ENC_FLAT_GLBL" => mem::global(self, d, cx)?,
+            "ENC_MIMG" => image::run(self, d, cx)?,
+            _ => return Err(unsupported(d)),
+        }
+        if self.pc == usize::MAX {
+            let next = d.pc + d.len as u64;
+            self.pc = k + 1;
+            if self.state != State::Done && p.list.get(k + 1).is_some_and(|n| n.pc != next) {
+                return Err(fault(d, format!("falls into {next:#x}, not an instruction")));
+            }
+        }
+        let memory = matches!(d.enc.name, "ENC_SMEM" | "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT_GLBL" | "ENC_MIMG");
+        if !memory || d.inst.name.starts_with("DS_SWIZZLE") || d.inst.name.contains("PERMUTE") {
+            let any = out(tin.iter().copied().max().unwrap_or(0));
+            for &r in sw.iter().filter(|&&r| r < 126) {
+                self.st[r as usize] = any;
+            }
+            if d.enc.name == "ENC_VOPC" || (d.enc.name == "ENC_VOP2" && matches!(d.inst.name, "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32")) {
+                self.st[106] = any;
+                self.st[107] = any;
+            }
+            for l in 0..self.lanes {
+                if exec >> l & 1 == 1 || d.inst.name == "V_WRITELANE_B32" {
+                    for &r in vw.iter().filter(|&&r| r < 256) {
+                        let nan = f32_out && f32::from_bits(self.v[l][r as usize]).is_nan();
+                        self.vt[l][r as usize] = if nan && tin[l] == 0 { NAN } else { out(tin[l]) };

A NaN from float arithmetic gets taint NAN, but the next float op that reads it gets computed(NAN) = UNBOUNDED, so it is not compared at all. Example with v4 = 0x7FC00000 (one of the new FLOAT_EDGES): v_add_f32 v5, v4, v4 gives NAN (checked: must be a NaN), then v_mul_f32 v6, v5, 1.0 gives UNBOUNDED, so a form that writes 0 to v6 is judged a match. NaN in, NaN out is fixed for add/mul/fma, and min/max/cmp of a NaN are exact. Could a float op treat a NAN input like an exact one (NaN result: NAN, other result: 0), and keep UNBOUNDED for integer ops that read NaN bits?

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221869 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221869). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 356 ~~~~diff @@ -0,0 +1,496 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals +/// kept, DX10_CLAMP set, IEEE clear. +pub(crate) const MODE: u32 = 0x1F0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stop { + /// an instruction (or an operand or modifier of one) outside the modelled set + Unsupported { pc: u64, name: String }, + /// the program did something the console would not survive: a branch into nothing, an + /// access outside `mem`, an unaligned LDS dword + Fault { pc: u64, why: String }, + /// the step limit + Steps(u64), +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"), + Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"), + Stop::Steps(n) => write!(f, "no end after {n} steps"), + } + } +} + +/// A rule of the ISA turned the wrong way, for tests that prove a check sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub(crate) enum Flip { + #[default] + None, + /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would + Lane31, + /// v_permlanex16 reads its own row instead of the other row of its half + PermlaneOwnRow, + /// vector instructions write the lanes EXEC has off + ExecIgnored, + /// VCC reads and branches see only its low half + VccLow, +} + +pub(crate) fn unsupported(d: &Decoded) -> Stop { + Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) } +} + +pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop { + Stop::Fault { pc: d.pc, why: why.into() } +} + +pub(crate) fn field(d: &Decoded, name: &str) -> u64 { + field_value(d.enc, &d.words, name).unwrap_or(0) +} + +/// A program decoded once: its instructions and where each starts. +pub(crate) struct Program { + pub list: Vec<Decoded>, + pub index: HashMap<u64, usize>, +} + +impl Program { + /// Words that do not decode (constants after the code) are left out; reaching one faults. + pub fn new(code: &[u8]) -> Program { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + list.push(d); + } + Err(_) => off += 4, + } + } + rdna2::resolve_far_jumps(&mut list); + let index = list.iter().enumerate().map(|(k, d)| (d.pc, k)).collect(); + Program { list, index } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum State { + Run, + Barrier, + Done, +} + +/// One wave. A taint is the ULP bound a value may be off by (0: exact), set by an instruction +/// the D3D rules let a GPU approximate and kept by copies; anything computed from it is +/// `UNBOUNDED`. +#[derive(Clone)] +pub(crate) struct Wave { + pub lanes: usize, + pub s: [u32; 128], + pub scc: bool, + pub v: Vec<[u32; 256]>, + pub st: [u8; 128], + pub vt: Vec<[u8; 256]>, + pub mode: u32, + pub pc: usize, + pub state: State, +} + +/// What every wave of a run shares: flat memory, the group's LDS, textures and samplers. +pub(crate) struct Ctx<'a> { + pub mem: &'a mut Vec<u32>, + pub mt: HashMap<usize, u8>, + pub lds: Vec<u32>, + pub lt: Vec<u8>, + pub tex: &'a mut [TestTexture], + pub samplers: &'a [TestSampler], + /// textures a tainted value was stored to + pub tex_taint: Vec<bool>, + pub flip: Flip, +} + +impl<'a> Ctx<'a> { + pub fn new(mem: &'a mut Vec<u32>, tex: &'a mut [TestTexture], samplers: &'a [TestSampler]) -> Ctx<'a> { + let n = tex.len(); + Ctx { mem, mt: HashMap::new(), lds: vec![0; LDS_DWORDS], lt: vec![0; LDS_DWORDS], tex, samplers, tex_taint: vec![false; n], flip: Flip::None } + } +} + +const TRANSCENDENTAL: [(&str, u8); 9] = [ + // D3D11.3 functional spec 3.1.3.2: rcp and sqrt within 1 ULP + ("V_RCP_F32", 1), + ("V_SQRT_F32", 1), + // our own bounds; the spec puts these on its instruction pages + ("V_RCP_IFLAG_F32", 1), + ("V_RSQ_F32", 2), + // bounds that are not in ULPs + ("V_EXP_F32", UNBOUNDED), + ("V_LOG_F32", UNBOUNDED), + ("V_SIN_F32", SINCOS), + ("V_COS_F32", SINCOS), + ("V_LDEXP_F32", 0), +]; + +/// The taint of a value computed from an approximate one: a 1-ULP input can be any number of +/// ULPs out (x - y with x close to y), so it is not compared. +pub(crate) const UNBOUNDED: u8 = u8::MAX; + +/// The taint of v_sin and v_cos: within D3D's absolute 0.0008. +pub(crate) const SINCOS: u8 = u8::MAX - 1; + +/// The taint of a NaN made by float arithmetic: its bits are the host's, so any NaN agrees. +pub(crate) const NAN: u8 = u8::MAX - 2; + +/// The taint of a value computed (not copied) from values of taint `t`. +pub(crate) fn computed(t: u8) -> u8 { + if t == 0 { 0 } else { UNBOUNDED } +} + +/// Instructions that copy a value's bits (from a lane, a register, or one of two): they keep its +/// taint. +const COPY: &[&str] = &[ + "S_MOV_B32", "S_MOV_B64", "S_CSELECT_B32", "S_CSELECT_B64", "V_MOV_B32", "V_CNDMASK_B32", "V_READLANE_B32", "V_WRITELANE_B32", + "V_READFIRSTLANE_B32", "V_PERMLANE16_B32", "V_PERMLANEX16_B32", "DS_SWIZZLE_B32", "DS_PERMUTE_B32", "DS_BPERMUTE_B32", +]; + +/// Instructions whose lanes read other lanes: every output takes the taint of every lane read. +fn cross_lane(d: &Decoded) -> bool { + d.variant != rdna2::Variant::Plain + || matches!( + d.inst.name, + "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" | "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" | "DS_SWIZZLE_B32" | "DS_PERMUTE_B32" | "DS_BPERMUTE_B32" + ) +} + +impl Wave { + pub fn new(lanes: usize) -> Wave { + Wave { lanes, s: [0; 128], scc: false, v: vec![[0; 256]; lanes], st: [0; 128], vt: vec![[0; 256]; lanes], mode: MODE, pc: 0, state: State::Run } + } + + /// A mask register (VCC, EXEC, an SGPR pair): its low dword alone in a wave of 32. + pub fn mask(&self, r: usize) -> u64 { + if self.lanes == 64 { self.pair(r) } else { u64::from(self.s[r]) } + } + + pub fn set_mask(&mut self, r: usize, m: u64) { + if r == 125 { + return; + } + self.s[r] = m as u32; + if self.lanes == 64 { + self.s[r + 1] = (m >> 32) as u32; + } + } + + pub fn exec(&self) -> u64 { + self.mask(126) + } + + pub fn vcc(&self, flip: Flip) -> u64 { + if flip == Flip::VccLow { u64::from(self.s[106]) } else { self.mask(106) } + } + + pub fn pair(&self, r: usize) -> u64 { + u64::from(self.s[r]) | u64::from(self.s[r + 1]) << 32 + } + + pub fn set_pair(&mut self, r: usize, x: u64) { + if r != 125 { + self.s[r] = x as u32; + self.s[r + 1] = (x >> 32) as u32; + } + } + + pub fn set_s(&mut self, d: &Decoded, r: u64, x: u32) -> Result<(), Stop> { + match r { + 125 => Ok(()), + 0..=127 => { + self.s[r as usize] = x; + Ok(()) + } + _ => Err(fault(d, format!("scalar destination {r}"))), + } + } + + /// A 32-bit scalar operand (an SGPR, a constant or the literal). + pub fn scalar(&self, d: &Decoded, code: u64) -> Result<u32, Stop> { + Ok(match code { + 125 => 0, + 0..=127 => self.s[code as usize], + 128..=192 => (code - 128) as u32, + 193..=208 => (192 - code as i64) as u32, + 240 => 0.5f32.to_bits(), + 241 => (-0.5f32).to_bits(), + 242 => 1.0f32.to_bits(), + 243 => (-1.0f32).to_bits(), + 244 => 2.0f32.to_bits(), + 245 => (-2.0f32).to_bits(), + 246 => 4.0f32.to_bits(), + 247 => (-4.0f32).to_bits(), + 248 => 0x3E22_F983, + 251 => u32::from(self.vcc(Flip::None) == 0), + 252 => u32::from(self.exec() == 0), + 253 => u32::from(self.scc), + 255 => d.literal.ok_or_else(|| fault(d, "no literal"))?, + _ => return Err(unsupported(d)), + }) + } + + /// A 64-bit integer scalar operand: a pair, a constant sign-extended, a literal + /// zero-extended (`signed`: sign-extended). + pub fn scalar64(&self, d: &Decoded, code: u64, signed: bool) -> Result<u64, Stop> { + Ok(match code { + 125 => 0, + 0..=127 => self.pair(code as usize), + 128..=208 => self.scalar(d, code)? as i32 as i64 as u64, + 251..=253 => u64::from(self.scalar(d, code)?), + 255 if signed => self.scalar(d, code)? as i32 as i64 as u64, + 255 => u64::from(self.scalar(d, code)?), + _ => return Err(unsupported(d)), + }) + } + + /// A 32-bit vector source of `lane`. + pub fn vsrc(&self, d: &Decoded, code: u64, lane: usize) -> Result<u32, Stop> { + if code >= 256 { Ok(self.v[lane][code as usize - 256]) } else { self.scalar(d, code) } + } + + /// A 64-bit vector source of `lane` (a VGPR pair, an SGPR pair or a constant). + pub fn vsrc64(&self, d: &Decoded, code: u64, lane: usize) -> Result<u64, Stop> { + if code >= 256 { + let r = code as usize - 256; + if r == 255 { + return Err(fault(d, "VGPR pair past v255")); + } + Ok(u64::from(self.v[lane][r]) | u64::from(self.v[lane][r + 1]) << 32) + } else { + self.scalar64(d, code, true) + } + } + + fn taint_of(&self, sregs: &[u64], vregs: &[u64], lane: usize) -> u8 { + let s = sregs.iter().map(|&r| self.st[r as usize]).max().unwrap_or(0); + let v = vregs.iter().filter(|&&r| r < 256).map(|&r| self.vt[lane][r as usize]).max().unwrap_or(0); + s.max(v) + } + + /// One instruction. + pub fn step(&mut self, p: &Program, cx: &mut Ctx) -> Result<(), Stop> { + let d = p.list.get(self.pc).ok_or(Stop::Fault { pc: u64::MAX, why: "ran past the code".into() })?; + let k = self.pc; + // a jump replaces it + self.pc = usize::MAX; + let (sr, sw) = rdna2::sgpr_uses(d); + let (vr, vw) = rdna2::vgpr_uses(d); + let exec = self.exec(); + let mut tin: Vec<u8> = (0..self.lanes).map(|l| self.taint_of(&sr, &vr, l)).collect(); + if cross_lane(d) { + let all = tin.iter().copied().max().unwrap_or(0); + tin.iter_mut().for_each(|t| *t = all); + } + let own = TRANSCENDENTAL.iter().find(|x| x.0 == d.inst.name).map_or(0, |x| x.1); + let copy = COPY.contains(&d.inst.name); + let out = |t: u8| if t == 0 { own } else if copy { t } else { computed(t) }; + let f32_out = float::is_float(d.inst.name) && !["_I32_F32", "_U32_F32", "F16", "PK"].iter().any(|x| d.inst.name.contains(x)); + match d.enc.name { + "ENC_SOPP" => salu::sopp(self, d, p, cx)?, + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => salu::run(self, d, p)?, + "ENC_SMEM" => mem::smem(self, d, cx)?, + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "VOP3_SDST_ENC" | "ENC_VOP3P" => valu::run(self, d, cx)?, + "ENC_DS" => mem::ds(self, d, cx)?, + "ENC_MUBUF" | "ENC_MTBUF" => mem::buffer(self, d, cx)?, + "ENC_FLAT_GLBL" => mem::global(self, d, cx)?, + "ENC_MIMG" => image::run(self, d, cx)?, + _ => return Err(unsupported(d)), + } + if self.pc == usize::MAX { + let next = d.pc + d.len as u64; + self.pc = k + 1; + if self.state != State::Done && p.list.get(k + 1).is_some_and(|n| n.pc != next) { + return Err(fault(d, format!("falls into {next:#x}, not an instruction"))); + } + } + let memory = matches!(d.enc.name, "ENC_SMEM" | "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT_GLBL" | "ENC_MIMG"); + if !memory || d.inst.name.starts_with("DS_SWIZZLE") || d.inst.name.contains("PERMUTE") { + let any = out(tin.iter().copied().max().unwrap_or(0)); + for &r in sw.iter().filter(|&&r| r < 126) { + self.st[r as usize] = any; + } + if d.enc.name == "ENC_VOPC" || (d.enc.name == "ENC_VOP2" && matches!(d.inst.name, "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32")) { + self.st[106] = any; + self.st[107] = any; + } + for l in 0..self.lanes { + if exec >> l & 1 == 1 || d.inst.name == "V_WRITELANE_B32" { + for &r in vw.iter().filter(|&&r| r < 256) { + let nan = f32_out && f32::from_bits(self.v[l][r as usize]).is_nan(); + self.vt[l][r as usize] = if nan && tin[l] == 0 { NAN } else { out(tin[l]) }; ~~~~ --- A NaN from float arithmetic gets taint `NAN`, but the next float op that reads it gets `computed(NAN)` = `UNBOUNDED`, so it is not compared at all. Example with v4 = 0x7FC00000 (one of the new `FLOAT_EDGES`): `v_add_f32 v5, v4, v4` gives `NAN` (checked: must be a NaN), then `v_mul_f32 v6, v5, 1.0` gives `UNBOUNDED`, so a form that writes 0 to v6 is judged a match. NaN in, NaN out is fixed for add/mul/fma, and min/max/cmp of a NaN are exact. Could a float op treat a `NAN` input like an exact one (NaN result: `NAN`, other result: 0), and keep `UNBOUNDED` for integer ops that read NaN bits?
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 29

@@ -0,0 +1,496 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals
+/// kept, DX10_CLAMP set, IEEE clear.
+pub(crate) const MODE: u32 = 0x1F0;

With MODE 0x1F0 the reference ignores OMOD (f32 output denormals on), and XCL always applies it (recomp/emit.rs:3166-3171, whatever MODE says). A compiler only emits OMOD when f32 denormals are flushed and IEEE is off (LLVM SIFoldOperands, isOMod / tryFoldOMod), so a real program with OMOD and no MODE write ran with output denormals off, and the reference would blame XCL for it. Example: v_add_f32 v10, v4, 0 mul:2 with v4 = 1.5 and no s_denorm_mode: reference 1.5, XCL 3.0. No case or fuzz program hits this today ("exact float rules" sets s_denorm_mode 0xC), but real programs would once they are compared. Since MODE at the start is an assumption, could a nonzero OMOD stop the run until the program has set the denormal mode itself?

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221876 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221876). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 29 ~~~~diff @@ -0,0 +1,496 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals +/// kept, DX10_CLAMP set, IEEE clear. +pub(crate) const MODE: u32 = 0x1F0; ~~~~ --- With MODE 0x1F0 the reference ignores OMOD (f32 output denormals on), and XCL always applies it (`recomp/emit.rs:3166-3171`, whatever MODE says). A compiler only emits OMOD when f32 denormals are flushed and IEEE is off (LLVM `SIFoldOperands`, `isOMod` / `tryFoldOMod`), so a real program with OMOD and no MODE write ran with output denormals off, and the reference would blame XCL for it. Example: `v_add_f32 v10, v4, 0 mul:2` with v4 = 1.5 and no `s_denorm_mode`: reference 1.5, XCL 3.0. No case or fuzz program hits this today ("exact float rules" sets `s_denorm_mode 0xC`), but real programs would once they are compared. Since MODE at the start is an assumption, could a nonzero OMOD stop the run until the program has set the denormal mode itself?
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 57

@@ -0,0 +1,506 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        ((w.pair(base) & !3).wrapping_add(imm & !3).wrapping_add(soff & !3) & 0xFFFF_FFFF_FFFF, None)
+    } else if name.starts_with("S_BUFFER_LOAD_DWORD") {
+        let v = [w.s[base], w.s[base + 1], w.s[base + 2]];
+        let stride = u64::from(v[1] >> 16 & 0x3FFF);
+        let records = u64::from(v[2]);
+        let limit = if stride == 0 { records } else { records * stride };
+        (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit)))
+    } else {
+        return Err(unsupported(d));
+    };
+    for k in 0..n {
+        let (x, t) = match limit {
+            Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0),
+            Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?,

For S_BUFFER_LOAD the reply quotes addr = (m_base + offset) & ~0x3, but the code reads base + ((OFFSET + SOFFSET) & ~3) and load drops the low bits of that, which is (base & ~3) + ((OFFSET + SOFFSET) & ~3). With base 0x1002, OFFSET 0 and SOFFSET 2, the quoted rule reads 0x1004 and the code 0x1000. The test (base 0x1002, offset 2 + 2) gives 0x1004 both ways. Bases of S_BUFFER V#s are normally aligned, so this is minor; ((base + off) & ~3) + 4 * k would match the quote.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221886 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221886). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 57 ~~~~diff @@ -0,0 +1,506 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + ((w.pair(base) & !3).wrapping_add(imm & !3).wrapping_add(soff & !3) & 0xFFFF_FFFF_FFFF, None) + } else if name.starts_with("S_BUFFER_LOAD_DWORD") { + let v = [w.s[base], w.s[base + 1], w.s[base + 2]]; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + let limit = if stride == 0 { records } else { records * stride }; + (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit))) + } else { + return Err(unsupported(d)); + }; + for k in 0..n { + let (x, t) = match limit { + Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0), + Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?, ~~~~ --- For S_BUFFER_LOAD the reply quotes `addr = (m_base + offset) & ~0x3`, but the code reads `base + ((OFFSET + SOFFSET) & ~3)` and `load` drops the low bits of that, which is `(base & ~3) + ((OFFSET + SOFFSET) & ~3)`. With base 0x1002, OFFSET 0 and SOFFSET 2, the quoted rule reads 0x1004 and the code 0x1000. The test (base 0x1002, offset 2 + 2) gives 0x1004 both ways. Bases of S_BUFFER V#s are normally aligned, so this is minor; `((base + off) & ~3) + 4 * k` would match the quote.
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 96

@@ -0,0 +1,496 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals
+/// kept, DX10_CLAMP set, IEEE clear.
+pub(crate) const MODE: u32 = 0x1F0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stop {
+    /// an instruction (or an operand or modifier of one) outside the modelled set
+    Unsupported { pc: u64, name: String },
+    /// the program did something the console would not survive: a branch into nothing, an
+    /// access outside `mem`, an unaligned LDS dword
+    Fault { pc: u64, why: String },
+    /// the step limit
+    Steps(u64),
+}
+
+impl std::fmt::Display for Stop {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"),
+            Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"),
+            Stop::Steps(n) => write!(f, "no end after {n} steps"),
+        }
+    }
+}
+
+/// A rule of the ISA turned the wrong way, for tests that prove a check sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub(crate) enum Flip {
+    #[default]
+    None,
+    /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would
+    Lane31,
+    /// v_permlanex16 reads its own row instead of the other row of its half
+    PermlaneOwnRow,
+    /// vector instructions write the lanes EXEC has off
+    ExecIgnored,
+    /// VCC reads and branches see only its low half
+    VccLow,
+}
+
+pub(crate) fn unsupported(d: &Decoded) -> Stop {
+    Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) }
+}
+
+pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop {
+    Stop::Fault { pc: d.pc, why: why.into() }
+}
+
+pub(crate) fn field(d: &Decoded, name: &str) -> u64 {
+    field_value(d.enc, &d.words, name).unwrap_or(0)
+}
+
+/// A program decoded once: its instructions and where each starts.
+pub(crate) struct Program {
+    pub list: Vec<Decoded>,
+    pub index: HashMap<u64, usize>,
+}
+
+impl Program {
+    /// Words that do not decode (constants after the code) are left out; reaching one faults.
+    pub fn new(code: &[u8]) -> Program {
+        let mut list = Vec::new();
+        let mut off = 0;
+        while off + 4 <= code.len() {
+            match rdna2::decode(&code[off..], off as u64) {
+                Ok(d) => {
+                    off += d.len;
+                    list.push(d);
+                }
+                Err(_) => off += 4,

The new fall-through check catches a gap after an instruction, but not one at offset 0: execution starts at list[0] whatever its pc. Code [0xFFFFFFFF, s_mov_b32 s2, 1, s_endpgm] runs the move and ends normally. Checking that list[0].pc == 0 (or faulting when it is not) would close it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221893 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221893). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 96 ~~~~diff @@ -0,0 +1,496 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals +/// kept, DX10_CLAMP set, IEEE clear. +pub(crate) const MODE: u32 = 0x1F0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stop { + /// an instruction (or an operand or modifier of one) outside the modelled set + Unsupported { pc: u64, name: String }, + /// the program did something the console would not survive: a branch into nothing, an + /// access outside `mem`, an unaligned LDS dword + Fault { pc: u64, why: String }, + /// the step limit + Steps(u64), +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"), + Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"), + Stop::Steps(n) => write!(f, "no end after {n} steps"), + } + } +} + +/// A rule of the ISA turned the wrong way, for tests that prove a check sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub(crate) enum Flip { + #[default] + None, + /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would + Lane31, + /// v_permlanex16 reads its own row instead of the other row of its half + PermlaneOwnRow, + /// vector instructions write the lanes EXEC has off + ExecIgnored, + /// VCC reads and branches see only its low half + VccLow, +} + +pub(crate) fn unsupported(d: &Decoded) -> Stop { + Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) } +} + +pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop { + Stop::Fault { pc: d.pc, why: why.into() } +} + +pub(crate) fn field(d: &Decoded, name: &str) -> u64 { + field_value(d.enc, &d.words, name).unwrap_or(0) +} + +/// A program decoded once: its instructions and where each starts. +pub(crate) struct Program { + pub list: Vec<Decoded>, + pub index: HashMap<u64, usize>, +} + +impl Program { + /// Words that do not decode (constants after the code) are left out; reaching one faults. + pub fn new(code: &[u8]) -> Program { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + list.push(d); + } + Err(_) => off += 4, ~~~~ --- The new fall-through check catches a gap after an instruction, but not one at offset 0: execution starts at `list[0]` whatever its pc. Code `[0xFFFFFFFF, s_mov_b32 s2, 1, s_endpgm]` runs the move and ends normally. Checking that `list[0].pc == 0` (or faulting when it is not) would close it.
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 9

@@ -0,0 +1,506 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;

Taint does not reach addresses or control flow: a global, buffer or LDS load takes the taint of the memory it reads, not of its address, and EXEC and SCC carry no taint. So after v_rcp_f32 v3, v2 and v_cvt_u32_f32 v4, v3 (UNBOUNDED), global_load_dword v5, v4, s[...] gives v5 taint 0 and it is compared exactly, although a GPU within the bound can round v4 to the other integer and read another address. The same goes for a v_cmp of a tainted value that feeds s_and_saveexec. Nothing in the cases or the fuzz does this today. Either propagate the address taint to the loaded value (and a compare's taint to EXEC), or narrow the description's "anything computed from it is not compared".

<!-- greyfinch-sync:ivall/xcl:review-comment:4777221902 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777221902). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 9 ~~~~diff @@ -0,0 +1,506 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; ~~~~ --- Taint does not reach addresses or control flow: a global, buffer or LDS load takes the taint of the memory it reads, not of its address, and EXEC and SCC carry no taint. So after `v_rcp_f32 v3, v2` and `v_cvt_u32_f32 v4, v3` (`UNBOUNDED`), `global_load_dword v5, v4, s[...]` gives v5 taint 0 and it is compared exactly, although a GPU within the bound can round v4 to the other integer and read another address. The same goes for a `v_cmp` of a tainted value that feeds `s_and_saveexec`. Nothing in the cases or the fuzz does this today. Either propagate the address taint to the loaded value (and a compare's taint to EXEC), or narrow the description's "anything computed from it is not compared".
CharlyRien commented 2026-12-02 22:48:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by CharlyRien on 2026-12-02T22:48:48Z.

Review: COMMENTED


Thanks for the quick and thorough round. I read 3de8793f (base main 5ad98adb) against each of my 20 comments: every fix is there, every test you cite exists and checks the rule in question, so all 20 threads can be resolved (GitHub does not let me resolve them here). I have not built or run this head yet; a 2,000-seed run on the RTX 3090 (driver 616.56) is queued. From the code, two classes from my fuzz comment are not in fuzz.rs's KNOWN and will fail a long run on NVIDIA: s_mul_i32 emitted as a signed multiply (HLSL split; the description says each is pinned) and the compute nested if/else class of direct split (my group 6). Since that comment I measured group 5 further (RTX 3090, driver 616.56, d2293dcb plus env-gated local probes, WARP 1.0.23 with Agility SDK 1.621.0 as a second adapter): the shrunk program rewritten as plain HLSL and compiled by DXC (cs_6_6, -O3) is wrong on the 3090 and right on WARP from the same DXIL, so it looks like an NVIDIA driver miscompile, not XCL. Group 6 is a different thing: XCL_DXIL_NO_OPT=all fixes it on the 3090, and WARP crashes on those dispatches, so it is still open. The comments below are new and mostly about the new fuzz classes and the taint rules; the first two can hide real wave64 bugs.

AI use: Claude Code (Claude Opus 5.5) checked the fixes and wrote this review; checked and posted by me.

<!-- greyfinch-sync:ivall/xcl:review:6160420293 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#pullrequestreview-6160420293). Originally posted by [CharlyRien](https://github.com/CharlyRien) on 2026-12-02T22:48:48Z. **Review:** COMMENTED --- Thanks for the quick and thorough round. I read 3de8793f (base main 5ad98adb) against each of my 20 comments: every fix is there, every test you cite exists and checks the rule in question, so all 20 threads can be resolved (GitHub does not let me resolve them here). I have not built or run this head yet; a 2,000-seed run on the RTX 3090 (driver 616.56) is queued. From the code, two classes from my fuzz comment are not in `fuzz.rs`'s `KNOWN` and will fail a long run on NVIDIA: `s_mul_i32` emitted as a signed multiply (HLSL split; the description says each is pinned) and the compute nested if/else class of direct split (my group 6). Since that comment I measured group 5 further (RTX 3090, driver 616.56, d2293dcb plus env-gated local probes, WARP 1.0.23 with Agility SDK 1.621.0 as a second adapter): the shrunk program rewritten as plain HLSL and compiled by DXC (`cs_6_6`, `-O3`) is wrong on the 3090 and right on WARP from the same DXIL, so it looks like an NVIDIA driver miscompile, not XCL. Group 6 is a different thing: `XCL_DXIL_NO_OPT=all` fixes it on the 3090, and WARP crashes on those dispatches, so it is still open. The comments below are new and mostly about the new fuzz classes and the taint rules; the first two can hide real wave64 bugs. AI use: Claude Code (Claude Opus 5.5) checked the fixes and wrote this review; checked and posted by me.
Royalflamejlh commented 2026-12-02 23:36:11 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:11Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 544

@@ -0,0 +1,734 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute)
+//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers,
+//! zeros of both signs, infinities, a NaN and values whose products round. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// lane exchanges under the EXEC of the moment
+    Lanes(Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top)
+    Lds(u64, u64, u64),
+}
+
+struct Gen<'a> {
+    r: &'a mut Rng,
+    /// only instructions the lowering translates
+    lowered: bool,
+}
+
+impl Gen<'_> {
+    fn v(&mut self) -> u64 {
+        V + self.r.below(12) + 1
+    }
+    fn vd(&mut self) -> u64 {
+        self.r.below(12) + 1
+    }
+    fn s(&mut self) -> u64 {
+        self.r.below(12) + 4
+    }
+    fn fv(&mut self) -> u64 {
+        13 + self.r.below(4)
+    }
+    /// a scalar or vector source: a register, an inline constant or a literal
+    fn src(&mut self) -> (u64, Option<u32>) {
+        match self.r.below(6) {
+            0 => (self.s(), None),
+            1 => (128 + self.r.below(65), None),
+            2 => (255, Some(self.r.word())),
+            _ => (self.v(), None),
+        }
+    }
+
+    fn op(&mut self) -> I {
+        loop {
+            let x = self.any_op();
+            if !self.lowered || lowered_alone(&x) {
+                return x;
+            }
+        }
+    }
+
+    fn any_op(&mut self) -> I {
+        let k = self.r.below(100);
+        if k < 22 {
+            const SOP2: [&str; 16] = [
+                "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32",
+                "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32",
+            ];
+            let (a, b) = (self.s(), self.s());
+            return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]);
+        }
+        if k < 30 {
+            const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"];
+            return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]);
+        }
+        if k < 35 {
+            let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]);
+            return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]);
+        }
+        if k < 60 {
+            const VOP2: [&str; 13] = [
+                "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32",
+                "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32",
+            ];
+            let (s0, l) = self.src();
+            let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)];
+            return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l);
+        }
+        if k < 78 {
+            const VOP3: [&str; 14] = [
+                "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32",
+                "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32",
+            ];
+            let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())];
+            return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None);
+        }
+        if k < 84 {
+            let s = self.s();
+            return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]);
+        }
+        if k < 92 {
+            let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]);
+            return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]);
+        }
+        if k < 95 {
+            return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]);
+        }
+        // masks read as data
+        let m = 30 + 2 * self.r.below(3);
+        match self.r.below(5) {
+            0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]),
+            1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]),
+            2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]),
+            3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]),
+            _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]),
+        }
+    }
+
+    /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form).
+    fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> {
+        let t = 18;
+        match self.r.below(6) {
+            0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))],
+            1 => {
+                let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]);
+                vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])]
+            }
+            2 => vec![
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            3 => vec![
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            4 => vec![
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]),
+            ],
+            _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])],
+        }
+    }
+
+    fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> {
+        let mut out = Vec::new();
+        for _ in 0..n {
+            let k = self.r.below(100);
+            if k < 10 && depth < 3 {
+                let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]);
+                let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]);
+                let (a, b) = (1 + self.r.below(4), self.r.below(3));
+                out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false)));
+            } else if k < 16 && depth < 2 {
+                let n = 1 + self.r.below(4);
+                out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false)));
+            } else if k < 24 {
+                let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]);
+                let id = match op {
+                    "V_AND_B32" | "V_MIN_U32" => 193,
+                    _ => 128,
+                };
+                let x = 17;
+                let mut steps = Vec::new();
+                for _ in 0..1 + self.r.below(4) {
+                    steps.extend(self.wave_step(op, x));
+                }
+                steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)]));
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Wave(self.v(), id, steps));
+                }
+            } else if k < 27 {
+                let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]);
+                let x = self.vd();
+                let steps = self.wave_step(op, x);
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Lanes(steps));
+                }
+            } else if k < 30 && top {
+                out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127)));
+            } else {
+                out.push(Item::Op(self.op()));
+            }
+        }
+        out
+    }
+}
+
+/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k
+/// uses s[40 + 4k ..], loop counters v20 + k.
+fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) {
+    let ctl = 40 + 4 * depth;
+    for it in items {
+        match it {
+            Item::Op(x) => out.push(x.clone()),
+            Item::If(cmp, then, els) => {
+                let mut c = cmp.clone();
+                c.2[0].1 = ctl;
+                out.push(c);
+                out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(then, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(els, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Loop(trip, body) => {
+                let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth);
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)]));
+                out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)]));
+                out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)]));
+                let top = out.len();
+                out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)]));
+                out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)]));
+                let leave = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(body, depth + 1, threads, out);
+                out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)]));
+                out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)]));
+                out[leave].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Wave(src, id, steps) => {
+                out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)]));
+                out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)]));
+                out.extend(steps.iter().cloned());
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Lanes(steps) => out.extend(steps.iter().cloned()),
+            Item::Lds(src, dst, k) => {
+                // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)]));
+                out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+                out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32));
+                out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads));
+                out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)]));
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)]));
+                out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+            }
+        }
+    }
+}
+
+/// A generated program: its items and how it runs.
+#[derive(Clone)]
+pub(crate) struct Prog {
+    pub items: Vec<Item>,
+    pub compute: bool,
+    /// a compute group's threads
+    pub threads: u32,
+    /// kernel programs: the EXEC their first instructions set (every lane exists)
+    pub exec: u64,
+    pub seed: u64,
+}
+
+/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread.
+fn lines(p: &Prog) -> Vec<I> {
+    let mut out = Vec::new();
+    if p.compute {
+        // v1..v16 from the thread index; s4..s15 from s0
+        for r in 1..=16u64 {
+            out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9)));
+        }
+        for r in VFLOAT {
+            out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)]));
+            out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)]));
+        }
+        for r in SDATA {
+            out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B)));
+        }
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)]));
+    } else {
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32));
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32));
+    }
+    emit(&p.items, 0, p.threads, &mut out);
+    if p.compute {
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)]));
+        // (group · threads + thread) · 112, in v[24:25]
+        out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112));
+        out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112));
+        out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)]));
+        out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)]));
+        for k in 0..12u64 {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)]));
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)]));
+        }
+        for k in 0..16u64 {
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)]));
+        }
+    } else {
+        // the scalars as the lanes see them, all lanes on
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]));
+        for k in SDATA {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)]));
+        }
+    }
+    out.push(super::asm::end());
+    out
+}
+
+/// The case of a program: kernel mode with random registers, its first instructions setting
+/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads.
+pub(crate) fn case(p: &Prog) -> Case {
+    let mut r = Rng::new(p.seed ^ 0x5EED);
+    let code = asm(&lines(p));
+    if p.compute {
+        let threads = p.threads;
+        let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+        return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true };
+    }
+    let mut st = KernelState::default();
+    for s in SDATA {
+        st.sgpr[s as usize] = r.word();
+    }
+    for regs in st.vgpr.iter_mut() {
+        for v in VDATA {
+            regs[v as usize] = r.word();
+        }
+        for v in VFLOAT {
+            regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() };
+        }
+    }
+    Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }
+}
+
+/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks).
+fn lowered_alone(x: &I) -> bool {
+    let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false };
+    !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported"))
+}
+
+/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which
+/// D3D lets a GPU flush.
+const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001];
+
+pub(crate) fn program(seed: u64) -> Prog {
+    generate(seed, false)
+}
+
+/// A kernel program of the instructions the lowering translates, for the CPU part.
+pub(crate) fn lowered_program(seed: u64) -> Prog {
+    generate(seed, true)
+}
+
+fn generate(seed: u64, lowered: bool) -> Prog {
+    let mut r = Rng::new(seed);
+    let compute = r.below(4) == 0 && !lowered;
+    let n = 6 + r.below(18);
+    let threads = r.pick(&[64, 96, 128]);
+    let exec: u64 = match r.below(5) {
+        0 => !0,
+        1 => !0 >> r.below(64),
+        2 => 0xFFFF_FFFF << 32,
+        3 => 0xFFFF_FFFF,
+        _ => r.next() | 1 << 40,
+    };
+    let items = Gen { r: &mut r, lowered }.items(n, 0, compute);
+    Prog { items, compute, threads, exec, seed }
+}
+
+/// `items` with one part taken out, each way there is.
+fn smaller(items: &[Item]) -> Vec<Vec<Item>> {
+    let mut out = Vec::new();
+    for k in 0..items.len() {
+        let mut v = items.to_vec();
+        v.remove(k);
+        out.push(v);
+        let inner: Vec<Vec<Item>> = match &items[k] {
+            Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(),
+            Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(),
+            Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| {
+                let mut st = steps.clone();
+                st.remove(j);
+                vec![Item::Wave(*s, *id, st)]
+            }).collect(),
+            _ => Vec::new(),
+        };
+        for x in inner {
+            let mut v = items.to_vec();
+            v.splice(k..=k, x);
+            out.push(v);
+        }
+    }
+    out
+}
+
+fn verdict(p: &Prog, form: &Form) -> Option<Verdict> {
+    let c = case(p);
+    let want = reference(&c, Flip::None).ok()?;
+    Some(judge(&c, &want, (form.1)(&c)))
+}
+
+fn differs(p: &Prog, form: &Form) -> bool {
+    matches!(verdict(p, form), Some(Verdict::Mismatch(..)))
+}
+
+/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report.
+fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String {
+    let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" });
+    if on.is_empty() {
+        return format!("{head}\n{}", listing(p));
+    }
+    let s = shrink(on, p, form);
+    format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s))
+}
+
+/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out
+/// one part at a time.
+pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog {
+    let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v));
+    let was = class(p);
+    let mut p = p.clone();
+    'again: loop {
+        for items in smaller(&p.items) {
+            let q = Prog { items, ..p.clone() };
+            if differs(&q, form) && class(&q) == was {
+                p = q;
+                continue 'again;
+            }
+        }
+        return p;
+    }
+}
+
+/// `p`'s lines, ready to paste as a regression test.
+pub(crate) fn listing(p: &Prog) -> String {
+    lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect()
+}
+
+fn seeds(base: u64, count: u64) -> std::ops::Range<u64> {
+    let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count);
+    base..base + n
+}
+
+/// The share of seeds (%) a form compares with the reference at least (adapter as in
+/// `forms::EXPECTED`, form, floor).
+const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[
+    ("CPU", "lowering on CPU", 12),
+    ("NVIDIA", "HLSL split", 90),
+    ("NVIDIA", "direct split", 90),
+    ("NVIDIA", "per-lane split", 10),
+];
+
+/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other
+/// is a failure.
+const REFUSALS: &[(&str, &str, &str)] = &[
+    ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "a number read as a mask (through a join)"),
+    ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"),
+    ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"),
+    ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"),
+    ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"),
+    ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"),
+    ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"),
+    ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"),
+    ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"),
+    ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"),
+];
+
+/// Mismatches main's forms make, known by what the program does (adapter, form, what, test).
+const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[
+    ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "HLSL split", "-0 for +0", negative_zero),
+    ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero),
+    ("NVIDIA", "direct split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty),
+];
+
+fn upper_half_empty(p: &Prog, v: &Verdict) -> bool {
+    let Verdict::Mismatch(at, ..) = v else { return false };
+    let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads);
+    p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64)
+}
+
+fn negative_zero(_: &Prog, v: &Verdict) -> bool {

Right: the class now also requires the word to be a float register. float_word in fuzz.rs accepts v13-v16 in a kernel, and memory dword k with k % 28 in 12..=15 in compute. nan_as_zero takes the same guard. a_float_class_holds_only_for_a_float_register checks that "v13 of lane 0" and dword 40 are accepted and that "v27 of lane 0" and dword 44 are not.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777682530 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777682530). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:11Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 544 ~~~~diff @@ -0,0 +1,734 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute) +//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers, +//! zeros of both signs, infinities, a NaN and values whose products round. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// lane exchanges under the EXEC of the moment + Lanes(Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top) + Lds(u64, u64, u64), +} + +struct Gen<'a> { + r: &'a mut Rng, + /// only instructions the lowering translates + lowered: bool, +} + +impl Gen<'_> { + fn v(&mut self) -> u64 { + V + self.r.below(12) + 1 + } + fn vd(&mut self) -> u64 { + self.r.below(12) + 1 + } + fn s(&mut self) -> u64 { + self.r.below(12) + 4 + } + fn fv(&mut self) -> u64 { + 13 + self.r.below(4) + } + /// a scalar or vector source: a register, an inline constant or a literal + fn src(&mut self) -> (u64, Option<u32>) { + match self.r.below(6) { + 0 => (self.s(), None), + 1 => (128 + self.r.below(65), None), + 2 => (255, Some(self.r.word())), + _ => (self.v(), None), + } + } + + fn op(&mut self) -> I { + loop { + let x = self.any_op(); + if !self.lowered || lowered_alone(&x) { + return x; + } + } + } + + fn any_op(&mut self) -> I { + let k = self.r.below(100); + if k < 22 { + const SOP2: [&str; 16] = [ + "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32", + "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32", + ]; + let (a, b) = (self.s(), self.s()); + return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]); + } + if k < 30 { + const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"]; + return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]); + } + if k < 35 { + let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]); + return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]); + } + if k < 60 { + const VOP2: [&str; 13] = [ + "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32", + "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32", + ]; + let (s0, l) = self.src(); + let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)]; + return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l); + } + if k < 78 { + const VOP3: [&str; 14] = [ + "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32", + "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32", + ]; + let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())]; + return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None); + } + if k < 84 { + let s = self.s(); + return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]); + } + if k < 92 { + let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]); + return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]); + } + if k < 95 { + return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]); + } + // masks read as data + let m = 30 + 2 * self.r.below(3); + match self.r.below(5) { + 0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]), + 1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]), + 2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]), + 3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]), + _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]), + } + } + + /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form). + fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> { + let t = 18; + match self.r.below(6) { + 0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))], + 1 => { + let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]); + vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])] + } + 2 => vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 3 => vec![ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 4 => vec![ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]), + ], + _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])], + } + } + + fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> { + let mut out = Vec::new(); + for _ in 0..n { + let k = self.r.below(100); + if k < 10 && depth < 3 { + let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]); + let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]); + let (a, b) = (1 + self.r.below(4), self.r.below(3)); + out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false))); + } else if k < 16 && depth < 2 { + let n = 1 + self.r.below(4); + out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false))); + } else if k < 24 { + let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]); + let id = match op { + "V_AND_B32" | "V_MIN_U32" => 193, + _ => 128, + }; + let x = 17; + let mut steps = Vec::new(); + for _ in 0..1 + self.r.below(4) { + steps.extend(self.wave_step(op, x)); + } + steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)])); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Wave(self.v(), id, steps)); + } + } else if k < 27 { + let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]); + let x = self.vd(); + let steps = self.wave_step(op, x); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Lanes(steps)); + } + } else if k < 30 && top { + out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127))); + } else { + out.push(Item::Op(self.op())); + } + } + out + } +} + +/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k +/// uses s[40 + 4k ..], loop counters v20 + k. +fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) { + let ctl = 40 + 4 * depth; + for it in items { + match it { + Item::Op(x) => out.push(x.clone()), + Item::If(cmp, then, els) => { + let mut c = cmp.clone(); + c.2[0].1 = ctl; + out.push(c); + out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(then, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(els, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Loop(trip, body) => { + let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)])); + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)])); + let top = out.len(); + out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)])); + out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)])); + let leave = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(body, depth + 1, threads, out); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)])); + out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)])); + out[leave].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Wave(src, id, steps) => { + out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)])); + out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)])); + out.extend(steps.iter().cloned()); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Lanes(steps) => out.extend(steps.iter().cloned()), + Item::Lds(src, dst, k) => { + // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)])); + out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32)); + out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads)); + out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)])); + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)])); + out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + } + } + } +} + +/// A generated program: its items and how it runs. +#[derive(Clone)] +pub(crate) struct Prog { + pub items: Vec<Item>, + pub compute: bool, + /// a compute group's threads + pub threads: u32, + /// kernel programs: the EXEC their first instructions set (every lane exists) + pub exec: u64, + pub seed: u64, +} + +/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread. +fn lines(p: &Prog) -> Vec<I> { + let mut out = Vec::new(); + if p.compute { + // v1..v16 from the thread index; s4..s15 from s0 + for r in 1..=16u64 { + out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9))); + } + for r in VFLOAT { + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)])); + out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)])); + } + for r in SDATA { + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B))); + } + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)])); + } else { + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32)); + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32)); + } + emit(&p.items, 0, p.threads, &mut out); + if p.compute { + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)])); + // (group · threads + thread) · 112, in v[24:25] + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112)); + out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112)); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)])); + for k in 0..12u64 { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)])); + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)])); + } + for k in 0..16u64 { + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)])); + } + } else { + // the scalars as the lanes see them, all lanes on + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); + for k in SDATA { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)])); + } + } + out.push(super::asm::end()); + out +} + +/// The case of a program: kernel mode with random registers, its first instructions setting +/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads. +pub(crate) fn case(p: &Prog) -> Case { + let mut r = Rng::new(p.seed ^ 0x5EED); + let code = asm(&lines(p)); + if p.compute { + let threads = p.threads; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true }; + } + let mut st = KernelState::default(); + for s in SDATA { + st.sgpr[s as usize] = r.word(); + } + for regs in st.vgpr.iter_mut() { + for v in VDATA { + regs[v as usize] = r.word(); + } + for v in VFLOAT { + regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() }; + } + } + Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false } +} + +/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks). +fn lowered_alone(x: &I) -> bool { + let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }; + !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported")) +} + +/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which +/// D3D lets a GPU flush. +const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001]; + +pub(crate) fn program(seed: u64) -> Prog { + generate(seed, false) +} + +/// A kernel program of the instructions the lowering translates, for the CPU part. +pub(crate) fn lowered_program(seed: u64) -> Prog { + generate(seed, true) +} + +fn generate(seed: u64, lowered: bool) -> Prog { + let mut r = Rng::new(seed); + let compute = r.below(4) == 0 && !lowered; + let n = 6 + r.below(18); + let threads = r.pick(&[64, 96, 128]); + let exec: u64 = match r.below(5) { + 0 => !0, + 1 => !0 >> r.below(64), + 2 => 0xFFFF_FFFF << 32, + 3 => 0xFFFF_FFFF, + _ => r.next() | 1 << 40, + }; + let items = Gen { r: &mut r, lowered }.items(n, 0, compute); + Prog { items, compute, threads, exec, seed } +} + +/// `items` with one part taken out, each way there is. +fn smaller(items: &[Item]) -> Vec<Vec<Item>> { + let mut out = Vec::new(); + for k in 0..items.len() { + let mut v = items.to_vec(); + v.remove(k); + out.push(v); + let inner: Vec<Vec<Item>> = match &items[k] { + Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(), + Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(), + Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| { + let mut st = steps.clone(); + st.remove(j); + vec![Item::Wave(*s, *id, st)] + }).collect(), + _ => Vec::new(), + }; + for x in inner { + let mut v = items.to_vec(); + v.splice(k..=k, x); + out.push(v); + } + } + out +} + +fn verdict(p: &Prog, form: &Form) -> Option<Verdict> { + let c = case(p); + let want = reference(&c, Flip::None).ok()?; + Some(judge(&c, &want, (form.1)(&c))) +} + +fn differs(p: &Prog, form: &Form) -> bool { + matches!(verdict(p, form), Some(Verdict::Mismatch(..))) +} + +/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report. +fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String { + let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" }); + if on.is_empty() { + return format!("{head}\n{}", listing(p)); + } + let s = shrink(on, p, form); + format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s)) +} + +/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out +/// one part at a time. +pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog { + let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v)); + let was = class(p); + let mut p = p.clone(); + 'again: loop { + for items in smaller(&p.items) { + let q = Prog { items, ..p.clone() }; + if differs(&q, form) && class(&q) == was { + p = q; + continue 'again; + } + } + return p; + } +} + +/// `p`'s lines, ready to paste as a regression test. +pub(crate) fn listing(p: &Prog) -> String { + lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect() +} + +fn seeds(base: u64, count: u64) -> std::ops::Range<u64> { + let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count); + base..base + n +} + +/// The share of seeds (%) a form compares with the reference at least (adapter as in +/// `forms::EXPECTED`, form, floor). +const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[ + ("CPU", "lowering on CPU", 12), + ("NVIDIA", "HLSL split", 90), + ("NVIDIA", "direct split", 90), + ("NVIDIA", "per-lane split", 10), +]; + +/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other +/// is a failure. +const REFUSALS: &[(&str, &str, &str)] = &[ + ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "a number read as a mask (through a join)"), + ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"), + ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"), + ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"), + ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"), + ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"), + ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"), + ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"), + ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"), + ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"), +]; + +/// Mismatches main's forms make, known by what the program does (adapter, form, what, test). +const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[ + ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "HLSL split", "-0 for +0", negative_zero), + ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero), + ("NVIDIA", "direct split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty), +]; + +fn upper_half_empty(p: &Prog, v: &Verdict) -> bool { + let Verdict::Mismatch(at, ..) = v else { return false }; + let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads); + p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64) +} + +fn negative_zero(_: &Prog, v: &Verdict) -> bool { ~~~~ --- Right: the class now also requires the word to be a float register. `float_word` in `fuzz.rs` accepts v13-v16 in a kernel, and memory dword k with k % 28 in 12..=15 in compute. `nan_as_zero` takes the same guard. `a_float_class_holds_only_for_a_float_register` checks that "v13 of lane 0" and dword 40 are accepted and that "v27 of lane 0" and dword 44 are not. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:13Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 567

@@ -0,0 +1,734 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute)
+//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers,
+//! zeros of both signs, infinities, a NaN and values whose products round. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// lane exchanges under the EXEC of the moment
+    Lanes(Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top)
+    Lds(u64, u64, u64),
+}
+
+struct Gen<'a> {
+    r: &'a mut Rng,
+    /// only instructions the lowering translates
+    lowered: bool,
+}
+
+impl Gen<'_> {
+    fn v(&mut self) -> u64 {
+        V + self.r.below(12) + 1
+    }
+    fn vd(&mut self) -> u64 {
+        self.r.below(12) + 1
+    }
+    fn s(&mut self) -> u64 {
+        self.r.below(12) + 4
+    }
+    fn fv(&mut self) -> u64 {
+        13 + self.r.below(4)
+    }
+    /// a scalar or vector source: a register, an inline constant or a literal
+    fn src(&mut self) -> (u64, Option<u32>) {
+        match self.r.below(6) {
+            0 => (self.s(), None),
+            1 => (128 + self.r.below(65), None),
+            2 => (255, Some(self.r.word())),
+            _ => (self.v(), None),
+        }
+    }
+
+    fn op(&mut self) -> I {
+        loop {
+            let x = self.any_op();
+            if !self.lowered || lowered_alone(&x) {
+                return x;
+            }
+        }
+    }
+
+    fn any_op(&mut self) -> I {
+        let k = self.r.below(100);
+        if k < 22 {
+            const SOP2: [&str; 16] = [
+                "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32",
+                "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32",
+            ];
+            let (a, b) = (self.s(), self.s());
+            return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]);
+        }
+        if k < 30 {
+            const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"];
+            return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]);
+        }
+        if k < 35 {
+            let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]);
+            return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]);
+        }
+        if k < 60 {
+            const VOP2: [&str; 13] = [
+                "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32",
+                "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32",
+            ];
+            let (s0, l) = self.src();
+            let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)];
+            return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l);
+        }
+        if k < 78 {
+            const VOP3: [&str; 14] = [
+                "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32",
+                "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32",
+            ];
+            let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())];
+            return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None);
+        }
+        if k < 84 {
+            let s = self.s();
+            return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]);
+        }
+        if k < 92 {
+            let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]);
+            return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]);
+        }
+        if k < 95 {
+            return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]);
+        }
+        // masks read as data
+        let m = 30 + 2 * self.r.below(3);
+        match self.r.below(5) {
+            0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]),
+            1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]),
+            2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]),
+            3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]),
+            _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]),
+        }
+    }
+
+    /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form).
+    fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> {
+        let t = 18;
+        match self.r.below(6) {
+            0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))],
+            1 => {
+                let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]);
+                vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])]
+            }
+            2 => vec![
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            3 => vec![
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            4 => vec![
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]),
+            ],
+            _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])],
+        }
+    }
+
+    fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> {
+        let mut out = Vec::new();
+        for _ in 0..n {
+            let k = self.r.below(100);
+            if k < 10 && depth < 3 {
+                let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]);
+                let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]);
+                let (a, b) = (1 + self.r.below(4), self.r.below(3));
+                out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false)));
+            } else if k < 16 && depth < 2 {
+                let n = 1 + self.r.below(4);
+                out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false)));
+            } else if k < 24 {
+                let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]);
+                let id = match op {
+                    "V_AND_B32" | "V_MIN_U32" => 193,
+                    _ => 128,
+                };
+                let x = 17;
+                let mut steps = Vec::new();
+                for _ in 0..1 + self.r.below(4) {
+                    steps.extend(self.wave_step(op, x));
+                }
+                steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)]));
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Wave(self.v(), id, steps));
+                }
+            } else if k < 27 {
+                let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]);
+                let x = self.vd();
+                let steps = self.wave_step(op, x);
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Lanes(steps));
+                }
+            } else if k < 30 && top {
+                out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127)));
+            } else {
+                out.push(Item::Op(self.op()));
+            }
+        }
+        out
+    }
+}
+
+/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k
+/// uses s[40 + 4k ..], loop counters v20 + k.
+fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) {
+    let ctl = 40 + 4 * depth;
+    for it in items {
+        match it {
+            Item::Op(x) => out.push(x.clone()),
+            Item::If(cmp, then, els) => {
+                let mut c = cmp.clone();
+                c.2[0].1 = ctl;
+                out.push(c);
+                out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(then, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(els, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Loop(trip, body) => {
+                let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth);
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)]));
+                out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)]));
+                out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)]));
+                let top = out.len();
+                out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)]));
+                out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)]));
+                let leave = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(body, depth + 1, threads, out);
+                out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)]));
+                out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)]));
+                out[leave].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Wave(src, id, steps) => {
+                out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)]));
+                out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)]));
+                out.extend(steps.iter().cloned());
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Lanes(steps) => out.extend(steps.iter().cloned()),
+            Item::Lds(src, dst, k) => {
+                // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)]));
+                out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+                out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32));
+                out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads));
+                out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)]));
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)]));
+                out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+            }
+        }
+    }
+}
+
+/// A generated program: its items and how it runs.
+#[derive(Clone)]
+pub(crate) struct Prog {
+    pub items: Vec<Item>,
+    pub compute: bool,
+    /// a compute group's threads
+    pub threads: u32,
+    /// kernel programs: the EXEC their first instructions set (every lane exists)
+    pub exec: u64,
+    pub seed: u64,
+}
+
+/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread.
+fn lines(p: &Prog) -> Vec<I> {
+    let mut out = Vec::new();
+    if p.compute {
+        // v1..v16 from the thread index; s4..s15 from s0
+        for r in 1..=16u64 {
+            out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9)));
+        }
+        for r in VFLOAT {
+            out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)]));
+            out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)]));
+        }
+        for r in SDATA {
+            out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B)));
+        }
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)]));
+    } else {
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32));
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32));
+    }
+    emit(&p.items, 0, p.threads, &mut out);
+    if p.compute {
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)]));
+        // (group · threads + thread) · 112, in v[24:25]
+        out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112));
+        out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112));
+        out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)]));
+        out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)]));
+        for k in 0..12u64 {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)]));
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)]));
+        }
+        for k in 0..16u64 {
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)]));
+        }
+    } else {
+        // the scalars as the lanes see them, all lanes on
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]));
+        for k in SDATA {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)]));
+        }
+    }
+    out.push(super::asm::end());
+    out
+}
+
+/// The case of a program: kernel mode with random registers, its first instructions setting
+/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads.
+pub(crate) fn case(p: &Prog) -> Case {
+    let mut r = Rng::new(p.seed ^ 0x5EED);
+    let code = asm(&lines(p));
+    if p.compute {
+        let threads = p.threads;
+        let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+        return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true };
+    }
+    let mut st = KernelState::default();
+    for s in SDATA {
+        st.sgpr[s as usize] = r.word();
+    }
+    for regs in st.vgpr.iter_mut() {
+        for v in VDATA {
+            regs[v as usize] = r.word();
+        }
+        for v in VFLOAT {
+            regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() };
+        }
+    }
+    Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }
+}
+
+/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks).
+fn lowered_alone(x: &I) -> bool {
+    let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false };
+    !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported"))
+}
+
+/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which
+/// D3D lets a GPU flush.
+const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001];
+
+pub(crate) fn program(seed: u64) -> Prog {
+    generate(seed, false)
+}
+
+/// A kernel program of the instructions the lowering translates, for the CPU part.
+pub(crate) fn lowered_program(seed: u64) -> Prog {
+    generate(seed, true)
+}
+
+fn generate(seed: u64, lowered: bool) -> Prog {
+    let mut r = Rng::new(seed);
+    let compute = r.below(4) == 0 && !lowered;
+    let n = 6 + r.below(18);
+    let threads = r.pick(&[64, 96, 128]);
+    let exec: u64 = match r.below(5) {
+        0 => !0,
+        1 => !0 >> r.below(64),
+        2 => 0xFFFF_FFFF << 32,
+        3 => 0xFFFF_FFFF,
+        _ => r.next() | 1 << 40,
+    };
+    let items = Gen { r: &mut r, lowered }.items(n, 0, compute);
+    Prog { items, compute, threads, exec, seed }
+}
+
+/// `items` with one part taken out, each way there is.
+fn smaller(items: &[Item]) -> Vec<Vec<Item>> {
+    let mut out = Vec::new();
+    for k in 0..items.len() {
+        let mut v = items.to_vec();
+        v.remove(k);
+        out.push(v);
+        let inner: Vec<Vec<Item>> = match &items[k] {
+            Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(),
+            Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(),
+            Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| {
+                let mut st = steps.clone();
+                st.remove(j);
+                vec![Item::Wave(*s, *id, st)]
+            }).collect(),
+            _ => Vec::new(),
+        };
+        for x in inner {
+            let mut v = items.to_vec();
+            v.splice(k..=k, x);
+            out.push(v);
+        }
+    }
+    out
+}
+
+fn verdict(p: &Prog, form: &Form) -> Option<Verdict> {
+    let c = case(p);
+    let want = reference(&c, Flip::None).ok()?;
+    Some(judge(&c, &want, (form.1)(&c)))
+}
+
+fn differs(p: &Prog, form: &Form) -> bool {
+    matches!(verdict(p, form), Some(Verdict::Mismatch(..)))
+}
+
+/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report.
+fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String {
+    let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" });
+    if on.is_empty() {
+        return format!("{head}\n{}", listing(p));
+    }
+    let s = shrink(on, p, form);
+    format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s))
+}
+
+/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out
+/// one part at a time.
+pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog {
+    let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v));
+    let was = class(p);
+    let mut p = p.clone();
+    'again: loop {
+        for items in smaller(&p.items) {
+            let q = Prog { items, ..p.clone() };
+            if differs(&q, form) && class(&q) == was {
+                p = q;
+                continue 'again;
+            }
+        }
+        return p;
+    }
+}
+
+/// `p`'s lines, ready to paste as a regression test.
+pub(crate) fn listing(p: &Prog) -> String {
+    lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect()
+}
+
+fn seeds(base: u64, count: u64) -> std::ops::Range<u64> {
+    let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count);
+    base..base + n
+}
+
+/// The share of seeds (%) a form compares with the reference at least (adapter as in
+/// `forms::EXPECTED`, form, floor).
+const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[
+    ("CPU", "lowering on CPU", 12),
+    ("NVIDIA", "HLSL split", 90),
+    ("NVIDIA", "direct split", 90),
+    ("NVIDIA", "per-lane split", 10),
+];
+
+/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other
+/// is a failure.
+const REFUSALS: &[(&str, &str, &str)] = &[
+    ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "a number read as a mask (through a join)"),
+    ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"),
+    ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"),
+    ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"),
+    ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"),
+    ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"),
+    ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"),
+    ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"),
+    ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"),
+    ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"),
+];
+
+/// Mismatches main's forms make, known by what the program does (adapter, form, what, test).
+const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[
+    ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty),
+    ("NVIDIA", "HLSL split", "-0 for +0", negative_zero),
+    ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero),
+    ("NVIDIA", "direct split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "-0 for +0", negative_zero),
+    ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off),
+    ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty),
+];
+
+fn upper_half_empty(p: &Prog, v: &Verdict) -> bool {
+    let Verdict::Mismatch(at, ..) = v else { return false };
+    let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads);
+    p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64)
+}
+
+fn negative_zero(_: &Prog, v: &Verdict) -> bool {
+    matches!(v, Verdict::Mismatch(_, 0, 0x8000_0000, _))
+}
+
+fn nan_as_zero(_: &Prog, v: &Verdict) -> bool {
+    matches!(v, Verdict::Mismatch(_, w, 0, _) if f32::from_bits(*w).is_nan())
+}
+
+fn section_with_lanes_off(p: &Prog, _: &Verdict) -> bool {
+    fn section(items: &[Item]) -> bool {
+        items.iter().any(|it| match it {
+            Item::Wave(..) => true,
+            Item::If(_, t, e) => section(t) || section(e),
+            Item::Loop(_, b) => section(b),
+            _ => false,
+        })
+    }
+    let branch = |it: &&Item| matches!(it, Item::If(..) | Item::Loop(..));
+    let in_branch = p.items.iter().filter(branch).any(|it| section(std::slice::from_ref(it)));
+    let partial = !p.compute && p.exec != !0 && p.items.iter().any(|it| branch(&it));
+    in_branch || (partial && section(&p.items))
+}
+
+fn half_exec_empty(p: &Prog, _: &Verdict) -> bool {

Changed in fuzz.rs. half_exec_empty now requires a kernel with an empty EXEC half and a whole-wave section inside an if. It also requires the cause: with the program's sections taken out, the form must agree with the reference (sections_cause_it). A new direct-split bug in those programs is therefore reported. The class's text says it is the driver ("right on WARP"), from your measurement; the description says the same.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777682841 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777682841). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:13Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 567 ~~~~diff @@ -0,0 +1,734 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute) +//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers, +//! zeros of both signs, infinities, a NaN and values whose products round. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// lane exchanges under the EXEC of the moment + Lanes(Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top) + Lds(u64, u64, u64), +} + +struct Gen<'a> { + r: &'a mut Rng, + /// only instructions the lowering translates + lowered: bool, +} + +impl Gen<'_> { + fn v(&mut self) -> u64 { + V + self.r.below(12) + 1 + } + fn vd(&mut self) -> u64 { + self.r.below(12) + 1 + } + fn s(&mut self) -> u64 { + self.r.below(12) + 4 + } + fn fv(&mut self) -> u64 { + 13 + self.r.below(4) + } + /// a scalar or vector source: a register, an inline constant or a literal + fn src(&mut self) -> (u64, Option<u32>) { + match self.r.below(6) { + 0 => (self.s(), None), + 1 => (128 + self.r.below(65), None), + 2 => (255, Some(self.r.word())), + _ => (self.v(), None), + } + } + + fn op(&mut self) -> I { + loop { + let x = self.any_op(); + if !self.lowered || lowered_alone(&x) { + return x; + } + } + } + + fn any_op(&mut self) -> I { + let k = self.r.below(100); + if k < 22 { + const SOP2: [&str; 16] = [ + "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32", + "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32", + ]; + let (a, b) = (self.s(), self.s()); + return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]); + } + if k < 30 { + const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"]; + return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]); + } + if k < 35 { + let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]); + return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]); + } + if k < 60 { + const VOP2: [&str; 13] = [ + "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32", + "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32", + ]; + let (s0, l) = self.src(); + let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)]; + return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l); + } + if k < 78 { + const VOP3: [&str; 14] = [ + "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32", + "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32", + ]; + let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())]; + return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None); + } + if k < 84 { + let s = self.s(); + return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]); + } + if k < 92 { + let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]); + return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]); + } + if k < 95 { + return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]); + } + // masks read as data + let m = 30 + 2 * self.r.below(3); + match self.r.below(5) { + 0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]), + 1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]), + 2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]), + 3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]), + _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]), + } + } + + /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form). + fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> { + let t = 18; + match self.r.below(6) { + 0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))], + 1 => { + let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]); + vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])] + } + 2 => vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 3 => vec![ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 4 => vec![ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]), + ], + _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])], + } + } + + fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> { + let mut out = Vec::new(); + for _ in 0..n { + let k = self.r.below(100); + if k < 10 && depth < 3 { + let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]); + let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]); + let (a, b) = (1 + self.r.below(4), self.r.below(3)); + out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false))); + } else if k < 16 && depth < 2 { + let n = 1 + self.r.below(4); + out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false))); + } else if k < 24 { + let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]); + let id = match op { + "V_AND_B32" | "V_MIN_U32" => 193, + _ => 128, + }; + let x = 17; + let mut steps = Vec::new(); + for _ in 0..1 + self.r.below(4) { + steps.extend(self.wave_step(op, x)); + } + steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)])); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Wave(self.v(), id, steps)); + } + } else if k < 27 { + let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]); + let x = self.vd(); + let steps = self.wave_step(op, x); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Lanes(steps)); + } + } else if k < 30 && top { + out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127))); + } else { + out.push(Item::Op(self.op())); + } + } + out + } +} + +/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k +/// uses s[40 + 4k ..], loop counters v20 + k. +fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) { + let ctl = 40 + 4 * depth; + for it in items { + match it { + Item::Op(x) => out.push(x.clone()), + Item::If(cmp, then, els) => { + let mut c = cmp.clone(); + c.2[0].1 = ctl; + out.push(c); + out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(then, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(els, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Loop(trip, body) => { + let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)])); + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)])); + let top = out.len(); + out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)])); + out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)])); + let leave = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(body, depth + 1, threads, out); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)])); + out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)])); + out[leave].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Wave(src, id, steps) => { + out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)])); + out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)])); + out.extend(steps.iter().cloned()); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Lanes(steps) => out.extend(steps.iter().cloned()), + Item::Lds(src, dst, k) => { + // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)])); + out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32)); + out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads)); + out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)])); + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)])); + out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + } + } + } +} + +/// A generated program: its items and how it runs. +#[derive(Clone)] +pub(crate) struct Prog { + pub items: Vec<Item>, + pub compute: bool, + /// a compute group's threads + pub threads: u32, + /// kernel programs: the EXEC their first instructions set (every lane exists) + pub exec: u64, + pub seed: u64, +} + +/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread. +fn lines(p: &Prog) -> Vec<I> { + let mut out = Vec::new(); + if p.compute { + // v1..v16 from the thread index; s4..s15 from s0 + for r in 1..=16u64 { + out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9))); + } + for r in VFLOAT { + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)])); + out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)])); + } + for r in SDATA { + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B))); + } + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)])); + } else { + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32)); + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32)); + } + emit(&p.items, 0, p.threads, &mut out); + if p.compute { + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)])); + // (group · threads + thread) · 112, in v[24:25] + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112)); + out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112)); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)])); + for k in 0..12u64 { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)])); + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)])); + } + for k in 0..16u64 { + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)])); + } + } else { + // the scalars as the lanes see them, all lanes on + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); + for k in SDATA { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)])); + } + } + out.push(super::asm::end()); + out +} + +/// The case of a program: kernel mode with random registers, its first instructions setting +/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads. +pub(crate) fn case(p: &Prog) -> Case { + let mut r = Rng::new(p.seed ^ 0x5EED); + let code = asm(&lines(p)); + if p.compute { + let threads = p.threads; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true }; + } + let mut st = KernelState::default(); + for s in SDATA { + st.sgpr[s as usize] = r.word(); + } + for regs in st.vgpr.iter_mut() { + for v in VDATA { + regs[v as usize] = r.word(); + } + for v in VFLOAT { + regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() }; + } + } + Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false } +} + +/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks). +fn lowered_alone(x: &I) -> bool { + let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }; + !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported")) +} + +/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which +/// D3D lets a GPU flush. +const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001]; + +pub(crate) fn program(seed: u64) -> Prog { + generate(seed, false) +} + +/// A kernel program of the instructions the lowering translates, for the CPU part. +pub(crate) fn lowered_program(seed: u64) -> Prog { + generate(seed, true) +} + +fn generate(seed: u64, lowered: bool) -> Prog { + let mut r = Rng::new(seed); + let compute = r.below(4) == 0 && !lowered; + let n = 6 + r.below(18); + let threads = r.pick(&[64, 96, 128]); + let exec: u64 = match r.below(5) { + 0 => !0, + 1 => !0 >> r.below(64), + 2 => 0xFFFF_FFFF << 32, + 3 => 0xFFFF_FFFF, + _ => r.next() | 1 << 40, + }; + let items = Gen { r: &mut r, lowered }.items(n, 0, compute); + Prog { items, compute, threads, exec, seed } +} + +/// `items` with one part taken out, each way there is. +fn smaller(items: &[Item]) -> Vec<Vec<Item>> { + let mut out = Vec::new(); + for k in 0..items.len() { + let mut v = items.to_vec(); + v.remove(k); + out.push(v); + let inner: Vec<Vec<Item>> = match &items[k] { + Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(), + Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(), + Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| { + let mut st = steps.clone(); + st.remove(j); + vec![Item::Wave(*s, *id, st)] + }).collect(), + _ => Vec::new(), + }; + for x in inner { + let mut v = items.to_vec(); + v.splice(k..=k, x); + out.push(v); + } + } + out +} + +fn verdict(p: &Prog, form: &Form) -> Option<Verdict> { + let c = case(p); + let want = reference(&c, Flip::None).ok()?; + Some(judge(&c, &want, (form.1)(&c))) +} + +fn differs(p: &Prog, form: &Form) -> bool { + matches!(verdict(p, form), Some(Verdict::Mismatch(..))) +} + +/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report. +fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String { + let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" }); + if on.is_empty() { + return format!("{head}\n{}", listing(p)); + } + let s = shrink(on, p, form); + format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s)) +} + +/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out +/// one part at a time. +pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog { + let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v)); + let was = class(p); + let mut p = p.clone(); + 'again: loop { + for items in smaller(&p.items) { + let q = Prog { items, ..p.clone() }; + if differs(&q, form) && class(&q) == was { + p = q; + continue 'again; + } + } + return p; + } +} + +/// `p`'s lines, ready to paste as a regression test. +pub(crate) fn listing(p: &Prog) -> String { + lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect() +} + +fn seeds(base: u64, count: u64) -> std::ops::Range<u64> { + let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count); + base..base + n +} + +/// The share of seeds (%) a form compares with the reference at least (adapter as in +/// `forms::EXPECTED`, form, floor). +const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[ + ("CPU", "lowering on CPU", 12), + ("NVIDIA", "HLSL split", 90), + ("NVIDIA", "direct split", 90), + ("NVIDIA", "per-lane split", 10), +]; + +/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other +/// is a failure. +const REFUSALS: &[(&str, &str, &str)] = &[ + ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "a number read as a mask (through a join)"), + ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"), + ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"), + ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"), + ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"), + ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"), + ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"), + ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"), + ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"), + ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"), +]; + +/// Mismatches main's forms make, known by what the program does (adapter, form, what, test). +const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[ + ("NVIDIA", "HLSL split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "direct split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "per-lane split", "a group's last wave with an empty upper half", upper_half_empty), + ("NVIDIA", "HLSL split", "-0 for +0", negative_zero), + ("NVIDIA", "HLSL split", "0 for x - x of an infinity", nan_as_zero), + ("NVIDIA", "direct split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "-0 for +0", negative_zero), + ("NVIDIA", "per-lane split", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("CPU", "lowering on CPU", "a whole-wave section while lanes are elsewhere", section_with_lanes_off), + ("NVIDIA", "direct split", "a kernel with one half of EXEC empty at the start", half_exec_empty), +]; + +fn upper_half_empty(p: &Prog, v: &Verdict) -> bool { + let Verdict::Mismatch(at, ..) = v else { return false }; + let thread = at.strip_prefix("memory dword ").and_then(|k| k.parse::<u32>().ok()).map(|k| k / 28 % p.threads); + p.compute && p.threads == 96 && thread.is_some_and(|t| t >= 64) +} + +fn negative_zero(_: &Prog, v: &Verdict) -> bool { + matches!(v, Verdict::Mismatch(_, 0, 0x8000_0000, _)) +} + +fn nan_as_zero(_: &Prog, v: &Verdict) -> bool { + matches!(v, Verdict::Mismatch(_, w, 0, _) if f32::from_bits(*w).is_nan()) +} + +fn section_with_lanes_off(p: &Prog, _: &Verdict) -> bool { + fn section(items: &[Item]) -> bool { + items.iter().any(|it| match it { + Item::Wave(..) => true, + Item::If(_, t, e) => section(t) || section(e), + Item::Loop(_, b) => section(b), + _ => false, + }) + } + let branch = |it: &&Item| matches!(it, Item::If(..) | Item::Loop(..)); + let in_branch = p.items.iter().filter(branch).any(|it| section(std::slice::from_ref(it))); + let partial = !p.compute && p.exec != !0 && p.items.iter().any(|it| branch(&it)); + in_branch || (partial && section(&p.items)) +} + +fn half_exec_empty(p: &Prog, _: &Verdict) -> bool { ~~~~ --- Changed in `fuzz.rs`. `half_exec_empty` now requires a kernel with an empty EXEC half and a whole-wave section inside an `if`. It also requires the cause: with the program's sections taken out, the form must agree with the reference (`sections_cause_it`). A new direct-split bug in those programs is therefore reported. The class's text says it is the driver ("right on WARP"), from your measurement; the description says the same. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:15Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/fuzz.rs; line 525

@@ -0,0 +1,734 @@
+//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else
+//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane
+//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute)
+//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers,
+//! zeros of both signs, infinities, a NaN and values whose products round. Seeded;
+//! a mismatch is shrunk to the fewest instructions that still show it and printed as
+//! `rdna2::encode` lines.
+
+use super::asm::{asm, i, lit, I, TO, V};
+use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict};
+use super::*;
+use crate::gpu::recomp::runner;
+
+pub(crate) struct Rng(u64);
+
+impl Rng {
+    pub fn new(seed: u64) -> Rng {
+        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
+    }
+    pub fn next(&mut self) -> u64 {
+        // xorshift64*
+        self.0 ^= self.0 >> 12;
+        self.0 ^= self.0 << 25;
+        self.0 ^= self.0 >> 27;
+        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+    }
+    pub fn below(&mut self, n: u64) -> u64 {
+        self.next() % n
+    }
+    pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
+        xs[self.below(xs.len() as u64) as usize]
+    }
+    /// small values, edges and plain random bits
+    pub fn word(&mut self) -> u32 {
+        match self.below(5) {
+            0 => self.below(8) as u32,
+            1 => (self.below(8) as u32).wrapping_neg(),
+            2 => 0x8000_0000 >> self.below(4),
+            _ => self.next() as u32,
+        }
+    }
+}
+
+/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control
+/// flow keeps its masks in s40.. and its counters in v20..
+const VDATA: std::ops::RangeInclusive<u64> = 1..=12;
+const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16;
+const SDATA: std::ops::RangeInclusive<u64> = 4..=15;
+
+#[derive(Clone, Debug)]
+pub(crate) enum Item {
+    Op(I),
+    /// compare into a mask, then / else
+    If(I, Vec<Item>, Vec<Item>),
+    /// trip count from a VGPR's low 2 bits
+    Loop(u64, Vec<Item>),
+    /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back
+    Wave(u64, u64, Vec<I>),
+    /// lane exchanges under the EXEC of the moment
+    Lanes(Vec<I>),
+    /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top)
+    Lds(u64, u64, u64),
+}
+
+struct Gen<'a> {
+    r: &'a mut Rng,
+    /// only instructions the lowering translates
+    lowered: bool,
+}
+
+impl Gen<'_> {
+    fn v(&mut self) -> u64 {
+        V + self.r.below(12) + 1
+    }
+    fn vd(&mut self) -> u64 {
+        self.r.below(12) + 1
+    }
+    fn s(&mut self) -> u64 {
+        self.r.below(12) + 4
+    }
+    fn fv(&mut self) -> u64 {
+        13 + self.r.below(4)
+    }
+    /// a scalar or vector source: a register, an inline constant or a literal
+    fn src(&mut self) -> (u64, Option<u32>) {
+        match self.r.below(6) {
+            0 => (self.s(), None),
+            1 => (128 + self.r.below(65), None),
+            2 => (255, Some(self.r.word())),
+            _ => (self.v(), None),
+        }
+    }
+
+    fn op(&mut self) -> I {
+        loop {
+            let x = self.any_op();
+            if !self.lowered || lowered_alone(&x) {
+                return x;
+            }
+        }
+    }
+
+    fn any_op(&mut self) -> I {
+        let k = self.r.below(100);
+        if k < 22 {
+            const SOP2: [&str; 16] = [
+                "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32",
+                "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32",
+            ];
+            let (a, b) = (self.s(), self.s());
+            return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]);
+        }
+        if k < 30 {
+            const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"];
+            return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]);
+        }
+        if k < 35 {
+            let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]);
+            return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]);
+        }
+        if k < 60 {
+            const VOP2: [&str; 13] = [
+                "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32",
+                "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32",
+            ];
+            let (s0, l) = self.src();
+            let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)];
+            return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l);
+        }
+        if k < 78 {
+            const VOP3: [&str; 14] = [
+                "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32",
+                "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32",
+            ];
+            let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())];
+            return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None);
+        }
+        if k < 84 {
+            let s = self.s();
+            return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]);
+        }
+        if k < 92 {
+            let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]);
+            return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]);
+        }
+        if k < 95 {
+            return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]);
+        }
+        // masks read as data
+        let m = 30 + 2 * self.r.below(3);
+        match self.r.below(5) {
+            0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]),
+            1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]),
+            2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]),
+            3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]),
+            _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]),
+        }
+    }
+
+    /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form).
+    fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> {
+        let t = 18;
+        match self.r.below(6) {
+            0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))],
+            1 => {
+                let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]);
+                vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])]
+            }
+            2 => vec![
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210),
+                lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98),
+                i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            3 => vec![
+                i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]),
+                i("S_WAITCNT", "ENC_SOPP", &[]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]),
+            ],
+            4 => vec![
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]),
+                i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]),
+                i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]),
+                i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]),
+            ],
+            _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])],
+        }
+    }
+
+    fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> {
+        let mut out = Vec::new();
+        for _ in 0..n {
+            let k = self.r.below(100);
+            if k < 10 && depth < 3 {
+                let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]);
+                let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]);
+                let (a, b) = (1 + self.r.below(4), self.r.below(3));
+                out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false)));
+            } else if k < 16 && depth < 2 {
+                let n = 1 + self.r.below(4);
+                out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false)));
+            } else if k < 24 {
+                let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]);
+                let id = match op {
+                    "V_AND_B32" | "V_MIN_U32" => 193,
+                    _ => 128,
+                };
+                let x = 17;
+                let mut steps = Vec::new();
+                for _ in 0..1 + self.r.below(4) {
+                    steps.extend(self.wave_step(op, x));
+                }
+                steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)]));
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Wave(self.v(), id, steps));
+                }
+            } else if k < 27 {
+                let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]);
+                let x = self.vd();
+                let steps = self.wave_step(op, x);
+                if self.lowered && !steps.iter().all(lowered_alone) {
+                    out.push(Item::Op(self.op()));
+                } else {
+                    out.push(Item::Lanes(steps));
+                }
+            } else if k < 30 && top {
+                out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127)));
+            } else {
+                out.push(Item::Op(self.op()));
+            }
+        }
+        out
+    }
+}
+
+/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k
+/// uses s[40 + 4k ..], loop counters v20 + k.
+fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) {
+    let ctl = 40 + 4 * depth;
+    for it in items {
+        match it {
+            Item::Op(x) => out.push(x.clone()),
+            Item::If(cmp, then, els) => {
+                let mut c = cmp.clone();
+                c.2[0].1 = ctl;
+                out.push(c);
+                out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(then, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)]));
+                let skip = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(els, depth + 1, threads, out);
+                out[skip].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Loop(trip, body) => {
+                let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth);
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)]));
+                out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)]));
+                out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)]));
+                let top = out.len();
+                out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)]));
+                out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)]));
+                let leave = out.len();
+                out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)]));
+                emit(body, depth + 1, threads, out);
+                out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)]));
+                out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)]));
+                out[leave].2[0].1 = out.len() as u64;
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Wave(src, id, steps) => {
+                out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)]));
+                out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)]));
+                out.extend(steps.iter().cloned());
+                out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)]));
+            }
+            Item::Lanes(steps) => out.extend(steps.iter().cloned()),
+            Item::Lds(src, dst, k) => {
+                // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)]));
+                out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+                out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32));
+                out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads));
+                out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)]));
+                out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)]));
+                out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)]));
+                out.push(i("S_WAITCNT", "ENC_SOPP", &[]));
+                out.push(i("S_BARRIER", "ENC_SOPP", &[]));
+            }
+        }
+    }
+}
+
+/// A generated program: its items and how it runs.
+#[derive(Clone)]
+pub(crate) struct Prog {
+    pub items: Vec<Item>,
+    pub compute: bool,
+    /// a compute group's threads
+    pub threads: u32,
+    /// kernel programs: the EXEC their first instructions set (every lane exists)
+    pub exec: u64,
+    pub seed: u64,
+}
+
+/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread.
+fn lines(p: &Prog) -> Vec<I> {
+    let mut out = Vec::new();
+    if p.compute {
+        // v1..v16 from the thread index; s4..s15 from s0
+        for r in 1..=16u64 {
+            out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9)));
+        }
+        for r in VFLOAT {
+            out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)]));
+            out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)]));
+        }
+        for r in SDATA {
+            out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B)));
+        }
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)]));
+    } else {
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32));
+        out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32));
+    }
+    emit(&p.items, 0, p.threads, &mut out);
+    if p.compute {
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)]));
+        // (group · threads + thread) · 112, in v[24:25]
+        out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112));
+        out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112));
+        out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)]));
+        out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)]));
+        for k in 0..12u64 {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)]));
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)]));
+        }
+        for k in 0..16u64 {
+            out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)]));
+        }
+    } else {
+        // the scalars as the lanes see them, all lanes on
+        out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]));
+        for k in SDATA {
+            out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)]));
+        }
+    }
+    out.push(super::asm::end());
+    out
+}
+
+/// The case of a program: kernel mode with random registers, its first instructions setting
+/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads.
+pub(crate) fn case(p: &Prog) -> Case {
+    let mut r = Rng::new(p.seed ^ 0x5EED);
+    let code = asm(&lines(p));
+    if p.compute {
+        let threads = p.threads;
+        let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 };
+        return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true };
+    }
+    let mut st = KernelState::default();
+    for s in SDATA {
+        st.sgpr[s as usize] = r.word();
+    }
+    for regs in st.vgpr.iter_mut() {
+        for v in VDATA {
+            regs[v as usize] = r.word();
+        }
+        for v in VFLOAT {
+            regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() };
+        }
+    }
+    Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }
+}
+
+/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks).
+fn lowered_alone(x: &I) -> bool {
+    let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false };
+    !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported"))
+}
+
+/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which
+/// D3D lets a GPU flush.
+const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001];
+
+pub(crate) fn program(seed: u64) -> Prog {
+    generate(seed, false)
+}
+
+/// A kernel program of the instructions the lowering translates, for the CPU part.
+pub(crate) fn lowered_program(seed: u64) -> Prog {
+    generate(seed, true)
+}
+
+fn generate(seed: u64, lowered: bool) -> Prog {
+    let mut r = Rng::new(seed);
+    let compute = r.below(4) == 0 && !lowered;
+    let n = 6 + r.below(18);
+    let threads = r.pick(&[64, 96, 128]);
+    let exec: u64 = match r.below(5) {
+        0 => !0,
+        1 => !0 >> r.below(64),
+        2 => 0xFFFF_FFFF << 32,
+        3 => 0xFFFF_FFFF,
+        _ => r.next() | 1 << 40,
+    };
+    let items = Gen { r: &mut r, lowered }.items(n, 0, compute);
+    Prog { items, compute, threads, exec, seed }
+}
+
+/// `items` with one part taken out, each way there is.
+fn smaller(items: &[Item]) -> Vec<Vec<Item>> {
+    let mut out = Vec::new();
+    for k in 0..items.len() {
+        let mut v = items.to_vec();
+        v.remove(k);
+        out.push(v);
+        let inner: Vec<Vec<Item>> = match &items[k] {
+            Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(),
+            Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(),
+            Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| {
+                let mut st = steps.clone();
+                st.remove(j);
+                vec![Item::Wave(*s, *id, st)]
+            }).collect(),
+            _ => Vec::new(),
+        };
+        for x in inner {
+            let mut v = items.to_vec();
+            v.splice(k..=k, x);
+            out.push(v);
+        }
+    }
+    out
+}
+
+fn verdict(p: &Prog, form: &Form) -> Option<Verdict> {
+    let c = case(p);
+    let want = reference(&c, Flip::None).ok()?;
+    Some(judge(&c, &want, (form.1)(&c)))
+}
+
+fn differs(p: &Prog, form: &Form) -> bool {
+    matches!(verdict(p, form), Some(Verdict::Mismatch(..)))
+}
+
+/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report.
+fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String {
+    let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" });
+    if on.is_empty() {
+        return format!("{head}\n{}", listing(p));
+    }
+    let s = shrink(on, p, form);
+    format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s))
+}
+
+/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out
+/// one part at a time.
+pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog {
+    let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v));
+    let was = class(p);
+    let mut p = p.clone();
+    'again: loop {
+        for items in smaller(&p.items) {
+            let q = Prog { items, ..p.clone() };
+            if differs(&q, form) && class(&q) == was {
+                p = q;
+                continue 'again;
+            }
+        }
+        return p;
+    }
+}
+
+/// `p`'s lines, ready to paste as a regression test.
+pub(crate) fn listing(p: &Prog) -> String {
+    lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect()
+}
+
+fn seeds(base: u64, count: u64) -> std::ops::Range<u64> {
+    let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count);
+    base..base + n
+}
+
+/// The share of seeds (%) a form compares with the reference at least (adapter as in
+/// `forms::EXPECTED`, form, floor).
+const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[
+    ("CPU", "lowering on CPU", 12),
+    ("NVIDIA", "HLSL split", 90),
+    ("NVIDIA", "direct split", 90),
+    ("NVIDIA", "per-lane split", 10),
+];
+
+/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other
+/// is a failure.
+const REFUSALS: &[(&str, &str, &str)] = &[
+    ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "a number read as a mask (through a join)"),
+    ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"),
+    ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"),
+    ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"),
+    ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"),
+    ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"),
+    ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"),
+    ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"),
+    ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"),
+    ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"),
+    ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"),
+];
+
+/// Mismatches main's forms make, known by what the program does (adapter, form, what, test).
+const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[

I corrected the description instead of adding them as classes. Neither has a signature that would not hide other mismatches: s_mul_i32 is in every compute program's prologue, and group 6 has no narrow shape yet. The description now says that a long run on NVIDIA still fails on both, and records your XCL_DXIL_NO_OPT=all and WARP results for group 6. The s_mul_i32 fix belongs in a separate pull request, as you say; this one stays on the test side.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777683150 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777683150). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:15Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/fuzz.rs`; line 525 ~~~~diff @@ -0,0 +1,734 @@ +//! Random wave64 programs against the reference in every form: straight SALU and VALU, if/else +//! nested to depth 3, loops each lane leaves on its own pass, whole-wave sections of lane +//! exchanges, lane exchanges under the EXEC of the moment, masks read as data, and (compute) +//! LDS across the waves of a group at a barrier. Kernel programs' floats are small integers, +//! zeros of both signs, infinities, a NaN and values whose products round. Seeded; +//! a mismatch is shrunk to the fewest instructions that still show it and printed as +//! `rdna2::encode` lines. + +use super::asm::{asm, i, lit, I, TO, V}; +use super::forms::{gpu_forms, judge, kind, lowering_on_the_cpu, pinned, print_counts, reference, Abi, Case, Form, Got, Verdict}; +use super::*; +use crate::gpu::recomp::runner; + +pub(crate) struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + pub fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + pub fn pick<T: Copy>(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len() as u64) as usize] + } + /// small values, edges and plain random bits + pub fn word(&mut self) -> u32 { + match self.below(5) { + 0 => self.below(8) as u32, + 1 => (self.below(8) as u32).wrapping_neg(), + 2 => 0x8000_0000 >> self.below(4), + _ => self.next() as u32, + } + } +} + +/// Data registers: VGPRs v1..v12, small-integer floats v13..v16, SGPRs s4..s15. Control +/// flow keeps its masks in s40.. and its counters in v20.. +const VDATA: std::ops::RangeInclusive<u64> = 1..=12; +const VFLOAT: std::ops::RangeInclusive<u64> = 13..=16; +const SDATA: std::ops::RangeInclusive<u64> = 4..=15; + +#[derive(Clone, Debug)] +pub(crate) enum Item { + Op(I), + /// compare into a mask, then / else + If(I, Vec<Item>, Vec<Item>), + /// trip count from a VGPR's low 2 bits + Loop(u64, Vec<Item>), + /// EXEC all lanes, an identity where lanes were off, the steps, EXEC back + Wave(u64, u64, Vec<I>), + /// lane exchanges under the EXEC of the moment + Lanes(Vec<I>), + /// LDS[t] = v, barrier, v' = LDS[(t + k) mod threads] (compute only, at the top) + Lds(u64, u64, u64), +} + +struct Gen<'a> { + r: &'a mut Rng, + /// only instructions the lowering translates + lowered: bool, +} + +impl Gen<'_> { + fn v(&mut self) -> u64 { + V + self.r.below(12) + 1 + } + fn vd(&mut self) -> u64 { + self.r.below(12) + 1 + } + fn s(&mut self) -> u64 { + self.r.below(12) + 4 + } + fn fv(&mut self) -> u64 { + 13 + self.r.below(4) + } + /// a scalar or vector source: a register, an inline constant or a literal + fn src(&mut self) -> (u64, Option<u32>) { + match self.r.below(6) { + 0 => (self.s(), None), + 1 => (128 + self.r.below(65), None), + 2 => (255, Some(self.r.word())), + _ => (self.v(), None), + } + } + + fn op(&mut self) -> I { + loop { + let x = self.any_op(); + if !self.lowered || lowered_alone(&x) { + return x; + } + } + } + + fn any_op(&mut self) -> I { + let k = self.r.below(100); + if k < 22 { + const SOP2: [&str; 16] = [ + "S_ADD_U32", "S_SUB_U32", "S_ADD_I32", "S_ADDC_U32", "S_MIN_U32", "S_MAX_I32", "S_AND_B32", "S_OR_B32", "S_XOR_B32", "S_ANDN2_B32", "S_LSHL_B32", + "S_LSHR_B32", "S_ASHR_I32", "S_MUL_I32", "S_BFE_U32", "S_CSELECT_B32", + ]; + let (a, b) = (self.s(), self.s()); + return i(self.r.pick(&SOP2), "ENC_SOP2", &[("SDST", self.s()), ("SSRC0", a), ("SSRC1", b)]); + } + if k < 30 { + const SOP1: [&str; 6] = ["S_MOV_B32", "S_NOT_B32", "S_BREV_B32", "S_BCNT1_I32_B32", "S_FF1_I32_B32", "S_FLBIT_I32_B32"]; + return i(self.r.pick(&SOP1), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.s())]); + } + if k < 35 { + let rel = self.r.pick(&["S_CMP_EQ_U32", "S_CMP_LG_U32", "S_CMP_GT_I32", "S_CMP_LT_U32"]); + return i(rel, "ENC_SOPC", &[("SSRC0", self.s()), ("SSRC1", self.s())]); + } + if k < 60 { + const VOP2: [&str; 13] = [ + "V_ADD_NC_U32", "V_SUB_NC_U32", "V_SUBREV_NC_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", "V_MIN_U32", + "V_MAX_I32", "V_MUL_U32_U24", "V_CNDMASK_B32", + ]; + let (s0, l) = self.src(); + let f = [("VDST", self.vd()), ("SRC0", s0), ("VSRC1", self.v() - V)]; + return (self.r.pick(&VOP2), "ENC_VOP2", f.to_vec(), l); + } + if k < 78 { + const VOP3: [&str; 14] = [ + "V_ADD3_U32", "V_LSHL_ADD_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XAD_U32", "V_BFE_U32", "V_BFE_I32", "V_BFI_B32", "V_ALIGNBIT_B32", + "V_PERM_B32", "V_MED3_U32", "V_MAX3_I32", "V_MUL_LO_U32", + ]; + let f = [("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", self.v())]; + return (self.r.pick(&VOP3), "ENC_VOP3", f.to_vec(), None); + } + if k < 84 { + let s = self.s(); + return i("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", s), ("SRC2", self.v())]); + } + if k < 92 { + let name = self.r.pick(&["V_ADD_F32", "V_SUB_F32", "V_MUL_F32"]); + return i(name, "ENC_VOP2", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("VSRC1", self.fv())]); + } + if k < 95 { + return i("V_FMA_F32", "ENC_VOP3", &[("VDST", self.fv()), ("SRC0", V + self.fv()), ("SRC1", V + self.fv()), ("SRC2", V + self.fv())]); + } + // masks read as data + let m = 30 + 2 * self.r.below(3); + match self.r.below(5) { + 0 => i("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", m), ("SRC0", self.v()), ("SRC1", self.v())]), + 1 => i(self.r.pick(&["S_BCNT1_I32_B64", "S_FF1_I32_B64"]), "ENC_SOP1", &[("SDST", self.s()), ("SSRC0", self.r.pick(&[126, 106, m]))]), + 2 => i(self.r.pick(&["V_MBCNT_LO_U32_B32", "V_MBCNT_HI_U32_B32"]), "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.r.pick(&[126, 127, m, m + 1])), ("SRC1", self.v())]), + 3 => i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", self.vd()), ("SRC0", self.v()), ("SRC1", self.v()), ("SRC2", m)]), + _ => i("V_READLANE_B32", "ENC_VOP3", &[("VDST", self.s()), ("SRC0", self.v()), ("SRC1", self.r.pick(&[128, 128 + 31, 128 + 32, 128 + 47, 128 + 63]))]), + } + } + + /// One step of a whole-wave section on `x` (an op `op`, its VOP2 form). + fn wave_step(&mut self, op: &'static str, x: u64) -> Vec<I> { + let t = 18; + match self.r.below(6) { + 0 => vec![super::forms::dpp8_xor(op, x, x, x, 1 << self.r.below(3))], + 1 => { + let ctrl = self.r.pick(&[0x140, 0x141, 0x111, 0x118, 0x1B, 0x168, 0x15F]); + vec![i(op, "VOP2_VOP_DPP16", &[("VDST", x), ("SRC0", 0xFA), ("VSRC0", x), ("VSRC1", x), ("DPP_CTRL", ctrl), ("ROW_MASK", 15), ("BANK_MASK", 15), ("BOUND_CTRL", 1)])] + } + 2 => vec![ + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 38), ("SSRC0", 255)], 0x7654_3210), + lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 39), ("SSRC0", 255)], 0xFEDC_BA98), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", t), ("SRC0", V + x), ("SRC1", 38), ("SRC2", 39), ("OP_SEL", 3)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 3 => vec![ + i("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", t), ("ADDR", x), ("OFFSET0", 0x1F), ("OFFSET1", 4 << self.r.below(5))]), + i("S_WAITCNT", "ENC_SOPP", &[]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", V + t), ("VSRC1", x)]), + ], + 4 => vec![ + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + x), ("SRC1", 128 + 32)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + x), ("SRC1", 128)]), + i("V_MOV_B32", "ENC_VOP1", &[("VDST", t), ("SRC0", 36)]), + i(op, "ENC_VOP2", &[("VDST", x), ("SRC0", 37), ("VSRC1", t)]), + ], + _ => vec![i("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", self.s()), ("SRC0", V + x)])], + } + } + + fn items(&mut self, n: u64, depth: u64, top: bool) -> Vec<Item> { + let mut out = Vec::new(); + for _ in 0..n { + let k = self.r.below(100); + if k < 10 && depth < 3 { + let rel = self.r.pick(&["V_CMP_GT_U32", "V_CMP_LT_U32", "V_CMP_NE_U32"]); + let cmp = i(rel, "ENC_VOP3", &[("VDST", 0), ("SRC0", self.v()), ("SRC1", self.v())]); + let (a, b) = (1 + self.r.below(4), self.r.below(3)); + out.push(Item::If(cmp, self.items(a, depth + 1, false), self.items(b, depth + 1, false))); + } else if k < 16 && depth < 2 { + let n = 1 + self.r.below(4); + out.push(Item::Loop(self.vd(), self.items(n, depth + 1, false))); + } else if k < 24 { + let op = self.r.pick(&["V_OR_B32", "V_AND_B32", "V_MIN_U32", "V_MAX_U32", "V_ADD_NC_U32"]); + let id = match op { + "V_AND_B32" | "V_MIN_U32" => 193, + _ => 128, + }; + let x = 17; + let mut steps = Vec::new(); + for _ in 0..1 + self.r.below(4) { + steps.extend(self.wave_step(op, x)); + } + steps.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", self.vd()), ("SRC0", V + x)])); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Wave(self.v(), id, steps)); + } + } else if k < 27 { + let op = self.r.pick(&["V_OR_B32", "V_MIN_U32", "V_ADD_NC_U32"]); + let x = self.vd(); + let steps = self.wave_step(op, x); + if self.lowered && !steps.iter().all(lowered_alone) { + out.push(Item::Op(self.op())); + } else { + out.push(Item::Lanes(steps)); + } + } else if k < 30 && top { + out.push(Item::Lds(self.vd(), self.vd(), 1 + self.r.below(127))); + } else { + out.push(Item::Op(self.op())); + } + } + out + } +} + +/// The instructions of `items`, branches to the indices `TO` names. Control masks: depth k +/// uses s[40 + 4k ..], loop counters v20 + k. +fn emit(items: &[Item], depth: u64, threads: u32, out: &mut Vec<I>) { + let ctl = 40 + 4 * depth; + for it in items { + match it { + Item::Op(x) => out.push(x.clone()), + Item::If(cmp, then, els) => { + let mut c = cmp.clone(); + c.2[0].1 = ctl; + out.push(c); + out.push(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(then, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", ctl + 2), ("SSRC1", ctl)])); + let skip = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(els, depth + 1, threads, out); + out[skip].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Loop(trip, body) => { + let (cnt, tr) = (20 + 2 * depth, 21 + 2 * depth); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 126)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", cnt), ("SRC0", 128)])); + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", tr), ("SRC0", 131), ("VSRC1", *trip)])); + let top = out.len(); + out.push(i("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", ctl), ("SRC0", V + cnt), ("SRC1", V + tr)])); + out.push(i("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", ctl)])); + let leave = out.len(); + out.push(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[(TO, 0)])); + emit(body, depth + 1, threads, out); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", cnt), ("SRC0", 129), ("VSRC1", cnt)])); + out.push(i("S_BRANCH", "ENC_SOPP", &[(TO, top as u64)])); + out[leave].2[0].1 = out.len() as u64; + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Wave(src, id, steps) => { + out.push(i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", ctl + 2), ("SSRC0", 193)])); + out.push(i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", *id), ("SRC1", *src), ("SRC2", ctl + 2)])); + out.extend(steps.iter().cloned()); + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", ctl + 2)])); + } + Item::Lanes(steps) => out.extend(steps.iter().cloned()), + Item::Lds(src, dst, k) => { + // v0 is the thread index in compute programs: LDS[t] = src, LDS[min(t + k, t + k - threads)] read + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 0)])); + out.push(i("DS_WRITE_B32", "ENC_DS", &[("ADDR", 19), ("DATA0", *src)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + out.push(lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 255), ("VSRC1", 0)], (*k % u64::from(threads)) as u32)); + out.push(lit("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 255), ("VSRC1", 19)], threads)); + out.push(i("V_MIN_U32", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 18), ("VSRC1", 19)])); + out.push(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 130), ("VSRC1", 19)])); + out.push(i("DS_READ_B32", "ENC_DS", &[("VDST", *dst), ("ADDR", 19)])); + out.push(i("S_WAITCNT", "ENC_SOPP", &[])); + out.push(i("S_BARRIER", "ENC_SOPP", &[])); + } + } + } +} + +/// A generated program: its items and how it runs. +#[derive(Clone)] +pub(crate) struct Prog { + pub items: Vec<Item>, + pub compute: bool, + /// a compute group's threads + pub threads: u32, + /// kernel programs: the EXEC their first instructions set (every lane exists) + pub exec: u64, + pub seed: u64, +} + +/// Kernel programs end; compute programs store v1..v16 and s4..s15 at 112 bytes a thread. +fn lines(p: &Prog) -> Vec<I> { + let mut out = Vec::new(); + if p.compute { + // v1..v16 from the thread index; s4..s15 from s0 + for r in 1..=16u64 { + out.push(lit("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", r), ("SRC0", V), ("SRC1", 128 + r), ("SRC2", 255)], (r as u32).wrapping_mul(0x9E37_79B9))); + } + for r in VFLOAT { + out.push(i("V_AND_B32", "ENC_VOP2", &[("VDST", r), ("SRC0", 128 + 7), ("VSRC1", r)])); + out.push(i("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", r), ("SRC0", V + r)])); + } + for r in SDATA { + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", r), ("SSRC0", 0), ("SSRC1", 255)], (r as u32).wrapping_mul(0x85EB_CA6B))); + } + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 60), ("SSRC0", 126)])); + } else { + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], p.exec as u32)); + out.push(lit("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], (p.exec >> 32) as u32)); + } + emit(&p.items, 0, p.threads, &mut out); + if p.compute { + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 60)])); + // (group · threads + thread) · 112, in v[24:25] + out.push(lit("S_MUL_I32", "ENC_SOP2", &[("SDST", 62), ("SSRC0", 1), ("SSRC1", 255)], p.threads * 112)); + out.push(lit("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 0)], 112)); + out.push(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 62), ("VSRC1", 24)])); + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 128)])); + for k in 0..12u64 { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", 4 + k)])); + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 22), ("SADDR", 0x7D), ("OFFSET", 64 + 4 * k)])); + } + for k in 0..16u64 { + out.push(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 24), ("DATA", 1 + k), ("SADDR", 0x7D), ("OFFSET", 4 * k)])); + } + } else { + // the scalars as the lanes see them, all lanes on + out.push(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); + for k in SDATA { + out.push(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 26 + k - 4), ("SRC0", k)])); + } + } + out.push(super::asm::end()); + out +} + +/// The case of a program: kernel mode with random registers, its first instructions setting +/// EXEC (a half empty, a prefix of lanes, holes), or two groups of 64, 96 or 128 threads. +pub(crate) fn case(p: &Prog) -> Case { + let mut r = Rng::new(p.seed ^ 0x5EED); + let code = asm(&lines(p)); + if p.compute { + let threads = p.threads; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 1, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + return Case { name: format!("seed {}", p.seed), code, abi: Abi::Compute(cs, [2, 1, 1], vec![r.word()]), mem: vec![0; 2 * threads as usize * 28], tex: Vec::new(), samplers: Vec::new(), scalars: true }; + } + let mut st = KernelState::default(); + for s in SDATA { + st.sgpr[s as usize] = r.word(); + } + for regs in st.vgpr.iter_mut() { + for v in VDATA { + regs[v as usize] = r.word(); + } + for v in VFLOAT { + regs[v as usize] = if r.below(8) == 0 { r.pick(&FLOAT_EDGES) } else { (r.below(15) as f32 - 7.0).to_bits() }; + } + } + Case { name: format!("seed {}", p.seed), code, abi: Abi::Kernel(st), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false } +} + +/// Whether the lowering translates `x` (it refuses a program with any instruction it lacks). +fn lowered_alone(x: &I) -> bool { + let c = Case { name: String::new(), code: asm(&[x.clone(), super::asm::end()]), abi: Abi::Kernel(KernelState::default()), mem: vec![0; 64], tex: Vec::new(), samplers: Vec::new(), scalars: false }; + !matches!(lowering_on_the_cpu(&c), Got::Refused(e) if e.starts_with("unsupported")) +} + +/// -0, the infinities, a NaN, 1 + 2^-12 (its square rounds), -1, 2^24 + 2; no denormal, which +/// D3D lets a GPU flush. +const FLOAT_EDGES: [u32; 7] = [0x8000_0000, 0x7F80_0000, 0xFF80_0000, 0x7FC0_0000, 0x3F80_0800, 0xBF80_0000, 0x4B80_0001]; + +pub(crate) fn program(seed: u64) -> Prog { + generate(seed, false) +} + +/// A kernel program of the instructions the lowering translates, for the CPU part. +pub(crate) fn lowered_program(seed: u64) -> Prog { + generate(seed, true) +} + +fn generate(seed: u64, lowered: bool) -> Prog { + let mut r = Rng::new(seed); + let compute = r.below(4) == 0 && !lowered; + let n = 6 + r.below(18); + let threads = r.pick(&[64, 96, 128]); + let exec: u64 = match r.below(5) { + 0 => !0, + 1 => !0 >> r.below(64), + 2 => 0xFFFF_FFFF << 32, + 3 => 0xFFFF_FFFF, + _ => r.next() | 1 << 40, + }; + let items = Gen { r: &mut r, lowered }.items(n, 0, compute); + Prog { items, compute, threads, exec, seed } +} + +/// `items` with one part taken out, each way there is. +fn smaller(items: &[Item]) -> Vec<Vec<Item>> { + let mut out = Vec::new(); + for k in 0..items.len() { + let mut v = items.to_vec(); + v.remove(k); + out.push(v); + let inner: Vec<Vec<Item>> = match &items[k] { + Item::If(c, t, e) => smaller(t).into_iter().map(|t| Item::If(c.clone(), t, e.clone())).chain(smaller(e).into_iter().map(|e| Item::If(c.clone(), t.clone(), e))).map(|x| vec![x]).collect(), + Item::Loop(n, b) => smaller(b).into_iter().map(|b| vec![Item::Loop(*n, b)]).collect(), + Item::Wave(s, id, steps) if steps.len() > 1 => (0..steps.len()).map(|j| { + let mut st = steps.clone(); + st.remove(j); + vec![Item::Wave(*s, *id, st)] + }).collect(), + _ => Vec::new(), + }; + for x in inner { + let mut v = items.to_vec(); + v.splice(k..=k, x); + out.push(v); + } + } + out +} + +fn verdict(p: &Prog, form: &Form) -> Option<Verdict> { + let c = case(p); + let want = reference(&c, Flip::None).ok()?; + Some(judge(&c, &want, (form.1)(&c))) +} + +fn differs(p: &Prog, form: &Form) -> bool { + matches!(verdict(p, form), Some(Verdict::Mismatch(..))) +} + +/// A mismatch of `p` in `form`, shrunk on a pinned adapter, for the report. +fn report(on: &str, p: &Prog, form: &Form, v: &Verdict) -> String { + let head = format!("{} seed {} ({}): {v:?}", form.0, p.seed, if p.compute { "compute" } else { "kernel" }); + if on.is_empty() { + return format!("{head}\n{}", listing(p)); + } + let s = shrink(on, p, form); + format!("{head}\nshrunk: {:?}\n{}", verdict(&s, form), listing(&s)) +} + +/// The smallest program that still differs in `form`, and is known or not as `p` is, taking out +/// one part at a time. +pub(crate) fn shrink(on: &str, p: &Prog, form: &Form) -> Prog { + let class = |p: &Prog| verdict(p, form).and_then(|v| known_as(on, form.0, p, &v)); + let was = class(p); + let mut p = p.clone(); + 'again: loop { + for items in smaller(&p.items) { + let q = Prog { items, ..p.clone() }; + if differs(&q, form) && class(&q) == was { + p = q; + continue 'again; + } + } + return p; + } +} + +/// `p`'s lines, ready to paste as a regression test. +pub(crate) fn listing(p: &Prog) -> String { + lines(p).iter().map(|(n, e, f, l)| format!("({n:?}, {e:?}, &{f:?}, {l:?}),\n")).collect() +} + +fn seeds(base: u64, count: u64) -> std::ops::Range<u64> { + let n = std::env::var("XCL_FUZZ_WAVE64_SEEDS").ok().and_then(|x| x.parse().ok()).unwrap_or(count); + base..base + n +} + +/// The share of seeds (%) a form compares with the reference at least (adapter as in +/// `forms::EXPECTED`, form, floor). +const MIN_COMPARED_PERCENT: &[(&str, &str, u64)] = &[ + ("CPU", "lowering on CPU", 12), + ("NVIDIA", "HLSL split", 90), + ("NVIDIA", "direct split", 90), + ("NVIDIA", "per-lane split", 10), +]; + +/// Refusals a form makes of generated programs (adapter, form, part of the reason); any other +/// is a failure. +const REFUSALS: &[(&str, &str, &str)] = &[ + ("CPU", "lowering on CPU", "a mask read as a number where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "a number read as a mask (through a join)"), + ("CPU", "lowering on CPU", "a scalar read of the SCC of a mask op"), + ("CPU", "lowering on CPU", "a value written while some lanes were elsewhere"), + ("CPU", "lowering on CPU", "unsupported S_BCNT1_I32_B64"), + ("CPU", "lowering on CPU", "unsupported S_FF1_I32_B64"), + ("CPU", "lowering on CPU", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("CPU", "lowering on CPU", "v_readlane where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a mask read as a number where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "a number read as a mask (through a join)"), + ("NVIDIA", "per-lane split", "a scalar read of the SCC of a mask op"), + ("NVIDIA", "per-lane split", "a value written while some lanes were elsewhere"), + ("NVIDIA", "per-lane split", "EXEC as a number in the split form where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "split wave64 LDS access needs the HLSL path"), + ("NVIDIA", "per-lane split", "v_permlane fetch-inactive where some lanes are elsewhere"), + ("NVIDIA", "per-lane split", "v_readlane where some lanes are elsewhere"), +]; + +/// Mismatches main's forms make, known by what the program does (adapter, form, what, test). +const KNOWN: &[(&str, &str, &str, fn(&Prog, &Verdict) -> bool)] = &[ ~~~~ --- I corrected the description instead of adding them as classes. Neither has a signature that would not hide other mismatches: `s_mul_i32` is in every compute program's prologue, and group 6 has no narrow shape yet. The description now says that a long run on NVIDIA still fails on both, and records your `XCL_DXIL_NO_OPT=all` and WARP results for group 6. The `s_mul_i32` fix belongs in a separate pull request, as you say; this one stays on the test side. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:16 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:16Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 356

@@ -0,0 +1,496 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals
+/// kept, DX10_CLAMP set, IEEE clear.
+pub(crate) const MODE: u32 = 0x1F0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stop {
+    /// an instruction (or an operand or modifier of one) outside the modelled set
+    Unsupported { pc: u64, name: String },
+    /// the program did something the console would not survive: a branch into nothing, an
+    /// access outside `mem`, an unaligned LDS dword
+    Fault { pc: u64, why: String },
+    /// the step limit
+    Steps(u64),
+}
+
+impl std::fmt::Display for Stop {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"),
+            Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"),
+            Stop::Steps(n) => write!(f, "no end after {n} steps"),
+        }
+    }
+}
+
+/// A rule of the ISA turned the wrong way, for tests that prove a check sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub(crate) enum Flip {
+    #[default]
+    None,
+    /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would
+    Lane31,
+    /// v_permlanex16 reads its own row instead of the other row of its half
+    PermlaneOwnRow,
+    /// vector instructions write the lanes EXEC has off
+    ExecIgnored,
+    /// VCC reads and branches see only its low half
+    VccLow,
+}
+
+pub(crate) fn unsupported(d: &Decoded) -> Stop {
+    Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) }
+}
+
+pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop {
+    Stop::Fault { pc: d.pc, why: why.into() }
+}
+
+pub(crate) fn field(d: &Decoded, name: &str) -> u64 {
+    field_value(d.enc, &d.words, name).unwrap_or(0)
+}
+
+/// A program decoded once: its instructions and where each starts.
+pub(crate) struct Program {
+    pub list: Vec<Decoded>,
+    pub index: HashMap<u64, usize>,
+}
+
+impl Program {
+    /// Words that do not decode (constants after the code) are left out; reaching one faults.
+    pub fn new(code: &[u8]) -> Program {
+        let mut list = Vec::new();
+        let mut off = 0;
+        while off + 4 <= code.len() {
+            match rdna2::decode(&code[off..], off as u64) {
+                Ok(d) => {
+                    off += d.len;
+                    list.push(d);
+                }
+                Err(_) => off += 4,
+            }
+        }
+        rdna2::resolve_far_jumps(&mut list);
+        let index = list.iter().enumerate().map(|(k, d)| (d.pc, k)).collect();
+        Program { list, index }
+    }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(crate) enum State {
+    Run,
+    Barrier,
+    Done,
+}
+
+/// One wave. A taint is the ULP bound a value may be off by (0: exact), set by an instruction
+/// the D3D rules let a GPU approximate and kept by copies; anything computed from it is
+/// `UNBOUNDED`.
+#[derive(Clone)]
+pub(crate) struct Wave {
+    pub lanes: usize,
+    pub s: [u32; 128],
+    pub scc: bool,
+    pub v: Vec<[u32; 256]>,
+    pub st: [u8; 128],
+    pub vt: Vec<[u8; 256]>,
+    pub mode: u32,
+    pub pc: usize,
+    pub state: State,
+}
+
+/// What every wave of a run shares: flat memory, the group's LDS, textures and samplers.
+pub(crate) struct Ctx<'a> {
+    pub mem: &'a mut Vec<u32>,
+    pub mt: HashMap<usize, u8>,
+    pub lds: Vec<u32>,
+    pub lt: Vec<u8>,
+    pub tex: &'a mut [TestTexture],
+    pub samplers: &'a [TestSampler],
+    /// textures a tainted value was stored to
+    pub tex_taint: Vec<bool>,
+    pub flip: Flip,
+}
+
+impl<'a> Ctx<'a> {
+    pub fn new(mem: &'a mut Vec<u32>, tex: &'a mut [TestTexture], samplers: &'a [TestSampler]) -> Ctx<'a> {
+        let n = tex.len();
+        Ctx { mem, mt: HashMap::new(), lds: vec![0; LDS_DWORDS], lt: vec![0; LDS_DWORDS], tex, samplers, tex_taint: vec![false; n], flip: Flip::None }
+    }
+}
+
+const TRANSCENDENTAL: [(&str, u8); 9] = [
+    // D3D11.3 functional spec 3.1.3.2: rcp and sqrt within 1 ULP
+    ("V_RCP_F32", 1),
+    ("V_SQRT_F32", 1),
+    // our own bounds; the spec puts these on its instruction pages
+    ("V_RCP_IFLAG_F32", 1),
+    ("V_RSQ_F32", 2),
+    // bounds that are not in ULPs
+    ("V_EXP_F32", UNBOUNDED),
+    ("V_LOG_F32", UNBOUNDED),
+    ("V_SIN_F32", SINCOS),
+    ("V_COS_F32", SINCOS),
+    ("V_LDEXP_F32", 0),
+];
+
+/// The taint of a value computed from an approximate one: a 1-ULP input can be any number of
+/// ULPs out (x - y with x close to y), so it is not compared.
+pub(crate) const UNBOUNDED: u8 = u8::MAX;
+
+/// The taint of v_sin and v_cos: within D3D's absolute 0.0008.
+pub(crate) const SINCOS: u8 = u8::MAX - 1;
+
+/// The taint of a NaN made by float arithmetic: its bits are the host's, so any NaN agrees.
+pub(crate) const NAN: u8 = u8::MAX - 2;
+
+/// The taint of a value computed (not copied) from values of taint `t`.
+pub(crate) fn computed(t: u8) -> u8 {
+    if t == 0 { 0 } else { UNBOUNDED }
+}
+
+/// Instructions that copy a value's bits (from a lane, a register, or one of two): they keep its
+/// taint.
+const COPY: &[&str] = &[
+    "S_MOV_B32", "S_MOV_B64", "S_CSELECT_B32", "S_CSELECT_B64", "V_MOV_B32", "V_CNDMASK_B32", "V_READLANE_B32", "V_WRITELANE_B32",
+    "V_READFIRSTLANE_B32", "V_PERMLANE16_B32", "V_PERMLANEX16_B32", "DS_SWIZZLE_B32", "DS_PERMUTE_B32", "DS_BPERMUTE_B32",
+];
+
+/// Instructions whose lanes read other lanes: every output takes the taint of every lane read.
+fn cross_lane(d: &Decoded) -> bool {
+    d.variant != rdna2::Variant::Plain
+        || matches!(
+            d.inst.name,
+            "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" | "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" | "DS_SWIZZLE_B32" | "DS_PERMUTE_B32" | "DS_BPERMUTE_B32"
+        )
+}
+
+impl Wave {
+    pub fn new(lanes: usize) -> Wave {
+        Wave { lanes, s: [0; 128], scc: false, v: vec![[0; 256]; lanes], st: [0; 128], vt: vec![[0; 256]; lanes], mode: MODE, pc: 0, state: State::Run }
+    }
+
+    /// A mask register (VCC, EXEC, an SGPR pair): its low dword alone in a wave of 32.
+    pub fn mask(&self, r: usize) -> u64 {
+        if self.lanes == 64 { self.pair(r) } else { u64::from(self.s[r]) }
+    }
+
+    pub fn set_mask(&mut self, r: usize, m: u64) {
+        if r == 125 {
+            return;
+        }
+        self.s[r] = m as u32;
+        if self.lanes == 64 {
+            self.s[r + 1] = (m >> 32) as u32;
+        }
+    }
+
+    pub fn exec(&self) -> u64 {
+        self.mask(126)
+    }
+
+    pub fn vcc(&self, flip: Flip) -> u64 {
+        if flip == Flip::VccLow { u64::from(self.s[106]) } else { self.mask(106) }
+    }
+
+    pub fn pair(&self, r: usize) -> u64 {
+        u64::from(self.s[r]) | u64::from(self.s[r + 1]) << 32
+    }
+
+    pub fn set_pair(&mut self, r: usize, x: u64) {
+        if r != 125 {
+            self.s[r] = x as u32;
+            self.s[r + 1] = (x >> 32) as u32;
+        }
+    }
+
+    pub fn set_s(&mut self, d: &Decoded, r: u64, x: u32) -> Result<(), Stop> {
+        match r {
+            125 => Ok(()),
+            0..=127 => {
+                self.s[r as usize] = x;
+                Ok(())
+            }
+            _ => Err(fault(d, format!("scalar destination {r}"))),
+        }
+    }
+
+    /// A 32-bit scalar operand (an SGPR, a constant or the literal).
+    pub fn scalar(&self, d: &Decoded, code: u64) -> Result<u32, Stop> {
+        Ok(match code {
+            125 => 0,
+            0..=127 => self.s[code as usize],
+            128..=192 => (code - 128) as u32,
+            193..=208 => (192 - code as i64) as u32,
+            240 => 0.5f32.to_bits(),
+            241 => (-0.5f32).to_bits(),
+            242 => 1.0f32.to_bits(),
+            243 => (-1.0f32).to_bits(),
+            244 => 2.0f32.to_bits(),
+            245 => (-2.0f32).to_bits(),
+            246 => 4.0f32.to_bits(),
+            247 => (-4.0f32).to_bits(),
+            248 => 0x3E22_F983,
+            251 => u32::from(self.vcc(Flip::None) == 0),
+            252 => u32::from(self.exec() == 0),
+            253 => u32::from(self.scc),
+            255 => d.literal.ok_or_else(|| fault(d, "no literal"))?,
+            _ => return Err(unsupported(d)),
+        })
+    }
+
+    /// A 64-bit integer scalar operand: a pair, a constant sign-extended, a literal
+    /// zero-extended (`signed`: sign-extended).
+    pub fn scalar64(&self, d: &Decoded, code: u64, signed: bool) -> Result<u64, Stop> {
+        Ok(match code {
+            125 => 0,
+            0..=127 => self.pair(code as usize),
+            128..=208 => self.scalar(d, code)? as i32 as i64 as u64,
+            251..=253 => u64::from(self.scalar(d, code)?),
+            255 if signed => self.scalar(d, code)? as i32 as i64 as u64,
+            255 => u64::from(self.scalar(d, code)?),
+            _ => return Err(unsupported(d)),
+        })
+    }
+
+    /// A 32-bit vector source of `lane`.
+    pub fn vsrc(&self, d: &Decoded, code: u64, lane: usize) -> Result<u32, Stop> {
+        if code >= 256 { Ok(self.v[lane][code as usize - 256]) } else { self.scalar(d, code) }
+    }
+
+    /// A 64-bit vector source of `lane` (a VGPR pair, an SGPR pair or a constant).
+    pub fn vsrc64(&self, d: &Decoded, code: u64, lane: usize) -> Result<u64, Stop> {
+        if code >= 256 {
+            let r = code as usize - 256;
+            if r == 255 {
+                return Err(fault(d, "VGPR pair past v255"));
+            }
+            Ok(u64::from(self.v[lane][r]) | u64::from(self.v[lane][r + 1]) << 32)
+        } else {
+            self.scalar64(d, code, true)
+        }
+    }
+
+    fn taint_of(&self, sregs: &[u64], vregs: &[u64], lane: usize) -> u8 {
+        let s = sregs.iter().map(|&r| self.st[r as usize]).max().unwrap_or(0);
+        let v = vregs.iter().filter(|&&r| r < 256).map(|&r| self.vt[lane][r as usize]).max().unwrap_or(0);
+        s.max(v)
+    }
+
+    /// One instruction.
+    pub fn step(&mut self, p: &Program, cx: &mut Ctx) -> Result<(), Stop> {
+        let d = p.list.get(self.pc).ok_or(Stop::Fault { pc: u64::MAX, why: "ran past the code".into() })?;
+        let k = self.pc;
+        // a jump replaces it
+        self.pc = usize::MAX;
+        let (sr, sw) = rdna2::sgpr_uses(d);
+        let (vr, vw) = rdna2::vgpr_uses(d);
+        let exec = self.exec();
+        let mut tin: Vec<u8> = (0..self.lanes).map(|l| self.taint_of(&sr, &vr, l)).collect();
+        if cross_lane(d) {
+            let all = tin.iter().copied().max().unwrap_or(0);
+            tin.iter_mut().for_each(|t| *t = all);
+        }
+        let own = TRANSCENDENTAL.iter().find(|x| x.0 == d.inst.name).map_or(0, |x| x.1);
+        let copy = COPY.contains(&d.inst.name);
+        let out = |t: u8| if t == 0 { own } else if copy { t } else { computed(t) };
+        let f32_out = float::is_float(d.inst.name) && !["_I32_F32", "_U32_F32", "F16", "PK"].iter().any(|x| d.inst.name.contains(x));
+        match d.enc.name {
+            "ENC_SOPP" => salu::sopp(self, d, p, cx)?,
+            "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => salu::run(self, d, p)?,
+            "ENC_SMEM" => mem::smem(self, d, cx)?,
+            "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "VOP3_SDST_ENC" | "ENC_VOP3P" => valu::run(self, d, cx)?,
+            "ENC_DS" => mem::ds(self, d, cx)?,
+            "ENC_MUBUF" | "ENC_MTBUF" => mem::buffer(self, d, cx)?,
+            "ENC_FLAT_GLBL" => mem::global(self, d, cx)?,
+            "ENC_MIMG" => image::run(self, d, cx)?,
+            _ => return Err(unsupported(d)),
+        }
+        if self.pc == usize::MAX {
+            let next = d.pc + d.len as u64;
+            self.pc = k + 1;
+            if self.state != State::Done && p.list.get(k + 1).is_some_and(|n| n.pc != next) {
+                return Err(fault(d, format!("falls into {next:#x}, not an instruction")));
+            }
+        }
+        let memory = matches!(d.enc.name, "ENC_SMEM" | "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT_GLBL" | "ENC_MIMG");
+        if !memory || d.inst.name.starts_with("DS_SWIZZLE") || d.inst.name.contains("PERMUTE") {
+            let any = out(tin.iter().copied().max().unwrap_or(0));
+            for &r in sw.iter().filter(|&&r| r < 126) {
+                self.st[r as usize] = any;
+            }
+            if d.enc.name == "ENC_VOPC" || (d.enc.name == "ENC_VOP2" && matches!(d.inst.name, "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32")) {
+                self.st[106] = any;
+                self.st[107] = any;
+            }
+            for l in 0..self.lanes {
+                if exec >> l & 1 == 1 || d.inst.name == "V_WRITELANE_B32" {
+                    for &r in vw.iter().filter(|&&r| r < 256) {
+                        let nan = f32_out && f32::from_bits(self.v[l][r as usize]).is_nan();
+                        self.vt[l][r as usize] = if nan && tin[l] == 0 { NAN } else { out(tin[l]) };

Changed in mod.rs: a float instruction (or a float compare) now reads a NAN input as exact, so its result gets NAN again if it is a NaN and 0 if not. An integer instruction that reads the bits still gets UNBOUNDED. Your example is a_nan_from_float_arithmetic_is_exact_to_the_next_float_instruction: v_add of a NaN gives NAN, v_mul of that gives NAN, v_cvt_u32 of it gives 0 and v_and of it gives UNBOUNDED. It failed before the change.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777683425 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777683425). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:16Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 356 ~~~~diff @@ -0,0 +1,496 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals +/// kept, DX10_CLAMP set, IEEE clear. +pub(crate) const MODE: u32 = 0x1F0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stop { + /// an instruction (or an operand or modifier of one) outside the modelled set + Unsupported { pc: u64, name: String }, + /// the program did something the console would not survive: a branch into nothing, an + /// access outside `mem`, an unaligned LDS dword + Fault { pc: u64, why: String }, + /// the step limit + Steps(u64), +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"), + Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"), + Stop::Steps(n) => write!(f, "no end after {n} steps"), + } + } +} + +/// A rule of the ISA turned the wrong way, for tests that prove a check sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub(crate) enum Flip { + #[default] + None, + /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would + Lane31, + /// v_permlanex16 reads its own row instead of the other row of its half + PermlaneOwnRow, + /// vector instructions write the lanes EXEC has off + ExecIgnored, + /// VCC reads and branches see only its low half + VccLow, +} + +pub(crate) fn unsupported(d: &Decoded) -> Stop { + Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) } +} + +pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop { + Stop::Fault { pc: d.pc, why: why.into() } +} + +pub(crate) fn field(d: &Decoded, name: &str) -> u64 { + field_value(d.enc, &d.words, name).unwrap_or(0) +} + +/// A program decoded once: its instructions and where each starts. +pub(crate) struct Program { + pub list: Vec<Decoded>, + pub index: HashMap<u64, usize>, +} + +impl Program { + /// Words that do not decode (constants after the code) are left out; reaching one faults. + pub fn new(code: &[u8]) -> Program { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + list.push(d); + } + Err(_) => off += 4, + } + } + rdna2::resolve_far_jumps(&mut list); + let index = list.iter().enumerate().map(|(k, d)| (d.pc, k)).collect(); + Program { list, index } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum State { + Run, + Barrier, + Done, +} + +/// One wave. A taint is the ULP bound a value may be off by (0: exact), set by an instruction +/// the D3D rules let a GPU approximate and kept by copies; anything computed from it is +/// `UNBOUNDED`. +#[derive(Clone)] +pub(crate) struct Wave { + pub lanes: usize, + pub s: [u32; 128], + pub scc: bool, + pub v: Vec<[u32; 256]>, + pub st: [u8; 128], + pub vt: Vec<[u8; 256]>, + pub mode: u32, + pub pc: usize, + pub state: State, +} + +/// What every wave of a run shares: flat memory, the group's LDS, textures and samplers. +pub(crate) struct Ctx<'a> { + pub mem: &'a mut Vec<u32>, + pub mt: HashMap<usize, u8>, + pub lds: Vec<u32>, + pub lt: Vec<u8>, + pub tex: &'a mut [TestTexture], + pub samplers: &'a [TestSampler], + /// textures a tainted value was stored to + pub tex_taint: Vec<bool>, + pub flip: Flip, +} + +impl<'a> Ctx<'a> { + pub fn new(mem: &'a mut Vec<u32>, tex: &'a mut [TestTexture], samplers: &'a [TestSampler]) -> Ctx<'a> { + let n = tex.len(); + Ctx { mem, mt: HashMap::new(), lds: vec![0; LDS_DWORDS], lt: vec![0; LDS_DWORDS], tex, samplers, tex_taint: vec![false; n], flip: Flip::None } + } +} + +const TRANSCENDENTAL: [(&str, u8); 9] = [ + // D3D11.3 functional spec 3.1.3.2: rcp and sqrt within 1 ULP + ("V_RCP_F32", 1), + ("V_SQRT_F32", 1), + // our own bounds; the spec puts these on its instruction pages + ("V_RCP_IFLAG_F32", 1), + ("V_RSQ_F32", 2), + // bounds that are not in ULPs + ("V_EXP_F32", UNBOUNDED), + ("V_LOG_F32", UNBOUNDED), + ("V_SIN_F32", SINCOS), + ("V_COS_F32", SINCOS), + ("V_LDEXP_F32", 0), +]; + +/// The taint of a value computed from an approximate one: a 1-ULP input can be any number of +/// ULPs out (x - y with x close to y), so it is not compared. +pub(crate) const UNBOUNDED: u8 = u8::MAX; + +/// The taint of v_sin and v_cos: within D3D's absolute 0.0008. +pub(crate) const SINCOS: u8 = u8::MAX - 1; + +/// The taint of a NaN made by float arithmetic: its bits are the host's, so any NaN agrees. +pub(crate) const NAN: u8 = u8::MAX - 2; + +/// The taint of a value computed (not copied) from values of taint `t`. +pub(crate) fn computed(t: u8) -> u8 { + if t == 0 { 0 } else { UNBOUNDED } +} + +/// Instructions that copy a value's bits (from a lane, a register, or one of two): they keep its +/// taint. +const COPY: &[&str] = &[ + "S_MOV_B32", "S_MOV_B64", "S_CSELECT_B32", "S_CSELECT_B64", "V_MOV_B32", "V_CNDMASK_B32", "V_READLANE_B32", "V_WRITELANE_B32", + "V_READFIRSTLANE_B32", "V_PERMLANE16_B32", "V_PERMLANEX16_B32", "DS_SWIZZLE_B32", "DS_PERMUTE_B32", "DS_BPERMUTE_B32", +]; + +/// Instructions whose lanes read other lanes: every output takes the taint of every lane read. +fn cross_lane(d: &Decoded) -> bool { + d.variant != rdna2::Variant::Plain + || matches!( + d.inst.name, + "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" | "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" | "DS_SWIZZLE_B32" | "DS_PERMUTE_B32" | "DS_BPERMUTE_B32" + ) +} + +impl Wave { + pub fn new(lanes: usize) -> Wave { + Wave { lanes, s: [0; 128], scc: false, v: vec![[0; 256]; lanes], st: [0; 128], vt: vec![[0; 256]; lanes], mode: MODE, pc: 0, state: State::Run } + } + + /// A mask register (VCC, EXEC, an SGPR pair): its low dword alone in a wave of 32. + pub fn mask(&self, r: usize) -> u64 { + if self.lanes == 64 { self.pair(r) } else { u64::from(self.s[r]) } + } + + pub fn set_mask(&mut self, r: usize, m: u64) { + if r == 125 { + return; + } + self.s[r] = m as u32; + if self.lanes == 64 { + self.s[r + 1] = (m >> 32) as u32; + } + } + + pub fn exec(&self) -> u64 { + self.mask(126) + } + + pub fn vcc(&self, flip: Flip) -> u64 { + if flip == Flip::VccLow { u64::from(self.s[106]) } else { self.mask(106) } + } + + pub fn pair(&self, r: usize) -> u64 { + u64::from(self.s[r]) | u64::from(self.s[r + 1]) << 32 + } + + pub fn set_pair(&mut self, r: usize, x: u64) { + if r != 125 { + self.s[r] = x as u32; + self.s[r + 1] = (x >> 32) as u32; + } + } + + pub fn set_s(&mut self, d: &Decoded, r: u64, x: u32) -> Result<(), Stop> { + match r { + 125 => Ok(()), + 0..=127 => { + self.s[r as usize] = x; + Ok(()) + } + _ => Err(fault(d, format!("scalar destination {r}"))), + } + } + + /// A 32-bit scalar operand (an SGPR, a constant or the literal). + pub fn scalar(&self, d: &Decoded, code: u64) -> Result<u32, Stop> { + Ok(match code { + 125 => 0, + 0..=127 => self.s[code as usize], + 128..=192 => (code - 128) as u32, + 193..=208 => (192 - code as i64) as u32, + 240 => 0.5f32.to_bits(), + 241 => (-0.5f32).to_bits(), + 242 => 1.0f32.to_bits(), + 243 => (-1.0f32).to_bits(), + 244 => 2.0f32.to_bits(), + 245 => (-2.0f32).to_bits(), + 246 => 4.0f32.to_bits(), + 247 => (-4.0f32).to_bits(), + 248 => 0x3E22_F983, + 251 => u32::from(self.vcc(Flip::None) == 0), + 252 => u32::from(self.exec() == 0), + 253 => u32::from(self.scc), + 255 => d.literal.ok_or_else(|| fault(d, "no literal"))?, + _ => return Err(unsupported(d)), + }) + } + + /// A 64-bit integer scalar operand: a pair, a constant sign-extended, a literal + /// zero-extended (`signed`: sign-extended). + pub fn scalar64(&self, d: &Decoded, code: u64, signed: bool) -> Result<u64, Stop> { + Ok(match code { + 125 => 0, + 0..=127 => self.pair(code as usize), + 128..=208 => self.scalar(d, code)? as i32 as i64 as u64, + 251..=253 => u64::from(self.scalar(d, code)?), + 255 if signed => self.scalar(d, code)? as i32 as i64 as u64, + 255 => u64::from(self.scalar(d, code)?), + _ => return Err(unsupported(d)), + }) + } + + /// A 32-bit vector source of `lane`. + pub fn vsrc(&self, d: &Decoded, code: u64, lane: usize) -> Result<u32, Stop> { + if code >= 256 { Ok(self.v[lane][code as usize - 256]) } else { self.scalar(d, code) } + } + + /// A 64-bit vector source of `lane` (a VGPR pair, an SGPR pair or a constant). + pub fn vsrc64(&self, d: &Decoded, code: u64, lane: usize) -> Result<u64, Stop> { + if code >= 256 { + let r = code as usize - 256; + if r == 255 { + return Err(fault(d, "VGPR pair past v255")); + } + Ok(u64::from(self.v[lane][r]) | u64::from(self.v[lane][r + 1]) << 32) + } else { + self.scalar64(d, code, true) + } + } + + fn taint_of(&self, sregs: &[u64], vregs: &[u64], lane: usize) -> u8 { + let s = sregs.iter().map(|&r| self.st[r as usize]).max().unwrap_or(0); + let v = vregs.iter().filter(|&&r| r < 256).map(|&r| self.vt[lane][r as usize]).max().unwrap_or(0); + s.max(v) + } + + /// One instruction. + pub fn step(&mut self, p: &Program, cx: &mut Ctx) -> Result<(), Stop> { + let d = p.list.get(self.pc).ok_or(Stop::Fault { pc: u64::MAX, why: "ran past the code".into() })?; + let k = self.pc; + // a jump replaces it + self.pc = usize::MAX; + let (sr, sw) = rdna2::sgpr_uses(d); + let (vr, vw) = rdna2::vgpr_uses(d); + let exec = self.exec(); + let mut tin: Vec<u8> = (0..self.lanes).map(|l| self.taint_of(&sr, &vr, l)).collect(); + if cross_lane(d) { + let all = tin.iter().copied().max().unwrap_or(0); + tin.iter_mut().for_each(|t| *t = all); + } + let own = TRANSCENDENTAL.iter().find(|x| x.0 == d.inst.name).map_or(0, |x| x.1); + let copy = COPY.contains(&d.inst.name); + let out = |t: u8| if t == 0 { own } else if copy { t } else { computed(t) }; + let f32_out = float::is_float(d.inst.name) && !["_I32_F32", "_U32_F32", "F16", "PK"].iter().any(|x| d.inst.name.contains(x)); + match d.enc.name { + "ENC_SOPP" => salu::sopp(self, d, p, cx)?, + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => salu::run(self, d, p)?, + "ENC_SMEM" => mem::smem(self, d, cx)?, + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "VOP3_SDST_ENC" | "ENC_VOP3P" => valu::run(self, d, cx)?, + "ENC_DS" => mem::ds(self, d, cx)?, + "ENC_MUBUF" | "ENC_MTBUF" => mem::buffer(self, d, cx)?, + "ENC_FLAT_GLBL" => mem::global(self, d, cx)?, + "ENC_MIMG" => image::run(self, d, cx)?, + _ => return Err(unsupported(d)), + } + if self.pc == usize::MAX { + let next = d.pc + d.len as u64; + self.pc = k + 1; + if self.state != State::Done && p.list.get(k + 1).is_some_and(|n| n.pc != next) { + return Err(fault(d, format!("falls into {next:#x}, not an instruction"))); + } + } + let memory = matches!(d.enc.name, "ENC_SMEM" | "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT_GLBL" | "ENC_MIMG"); + if !memory || d.inst.name.starts_with("DS_SWIZZLE") || d.inst.name.contains("PERMUTE") { + let any = out(tin.iter().copied().max().unwrap_or(0)); + for &r in sw.iter().filter(|&&r| r < 126) { + self.st[r as usize] = any; + } + if d.enc.name == "ENC_VOPC" || (d.enc.name == "ENC_VOP2" && matches!(d.inst.name, "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32")) { + self.st[106] = any; + self.st[107] = any; + } + for l in 0..self.lanes { + if exec >> l & 1 == 1 || d.inst.name == "V_WRITELANE_B32" { + for &r in vw.iter().filter(|&&r| r < 256) { + let nan = f32_out && f32::from_bits(self.v[l][r as usize]).is_nan(); + self.vt[l][r as usize] = if nan && tin[l] == 0 { NAN } else { out(tin[l]) }; ~~~~ --- Changed in `mod.rs`: a float instruction (or a float compare) now reads a `NAN` input as exact, so its result gets `NAN` again if it is a NaN and 0 if not. An integer instruction that reads the bits still gets `UNBOUNDED`. Your example is `a_nan_from_float_arithmetic_is_exact_to_the_next_float_instruction`: v_add of a NaN gives `NAN`, v_mul of that gives `NAN`, v_cvt_u32 of it gives 0 and v_and of it gives `UNBOUNDED`. It failed before the change. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:18 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:18Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 29

@@ -0,0 +1,496 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals
+/// kept, DX10_CLAMP set, IEEE clear.
+pub(crate) const MODE: u32 = 0x1F0;

Agreed. A nonzero OMOD now stops the run until the program has written MODE (s_setreg, s_denorm_mode or s_round_mode), since the start value is an assumption (float.rs, Wave::mode_set). omod_under_the_assumed_mode_stops_the_run is your v_add_f32 with mul:2 and no MODE write; it failed before. The two float tests that check OMOD under denormals now write s_denorm_mode 0xF first, and "exact float rules" already starts with s_denorm_mode 0xC.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777683783 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777683783). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:18Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 29 ~~~~diff @@ -0,0 +1,496 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals +/// kept, DX10_CLAMP set, IEEE clear. +pub(crate) const MODE: u32 = 0x1F0; ~~~~ --- Agreed. A nonzero OMOD now stops the run until the program has written MODE (s_setreg, s_denorm_mode or s_round_mode), since the start value is an assumption (`float.rs`, `Wave::mode_set`). `omod_under_the_assumed_mode_stops_the_run` is your v_add_f32 with mul:2 and no MODE write; it failed before. The two float tests that check OMOD under denormals now write `s_denorm_mode 0xF` first, and "exact float rules" already starts with `s_denorm_mode 0xC`. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:20 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:20Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 57

@@ -0,0 +1,506 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;
+    let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?;
+    Ok((x, cx.mt.get(&at).copied().unwrap_or(0)))
+}
+
+fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> {
+    let at = (byte / 4) as usize;
+    let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?;
+    *m = *m & !mask | x & mask;
+    if taint > 0 {
+        cx.mt.insert(at, taint);
+    } else {
+        cx.mt.remove(&at);
+    }
+    Ok(())
+}
+
+fn dwords(name: &str) -> usize {
+    ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap())
+}
+
+/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past
+/// num_records read 0).
+pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> {
+    let name = d.inst.name;
+    let n = dwords(name);
+    let f = |x: &str| field(d, x);
+    let base = 2 * f("SBASE") as usize;
+    let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64;
+    let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) };
+    let dst = f("SDATA") as usize;
+    if dst + n > 106 {
+        return Err(unsupported(d));
+    }
+    let (addr, limit) = if name.starts_with("S_LOAD_DWORD") {
+        ((w.pair(base) & !3).wrapping_add(imm & !3).wrapping_add(soff & !3) & 0xFFFF_FFFF_FFFF, None)
+    } else if name.starts_with("S_BUFFER_LOAD_DWORD") {
+        let v = [w.s[base], w.s[base + 1], w.s[base + 2]];
+        let stride = u64::from(v[1] >> 16 & 0x3FFF);
+        let records = u64::from(v[2]);
+        let limit = if stride == 0 { records } else { records * stride };
+        (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit)))
+    } else {
+        return Err(unsupported(d));
+    };
+    for k in 0..n {
+        let (x, t) = match limit {
+            Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0),
+            Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?,

Fixed in mem.rs: S_BUFFER_LOAD now reads ((base + offset) & ~3) + 4 * k, as the quoted rule says. The test adds your case, base 0x1002 with OFFSET 0 and SOFFSET 2, which now reads 0x1004. It read 0x1000 before the change.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777684152 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777684152). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:20Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 57 ~~~~diff @@ -0,0 +1,506 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; + let x = *cx.mem.get(at).ok_or_else(|| fault(d, format!("a read at {byte:#x}, past memory")))?; + Ok((x, cx.mt.get(&at).copied().unwrap_or(0))) +} + +fn store(d: &Decoded, cx: &mut Ctx, byte: u64, x: u32, mask: u32, taint: u8) -> Result<(), Stop> { + let at = (byte / 4) as usize; + let m = cx.mem.get_mut(at).ok_or_else(|| fault(d, format!("a write at {byte:#x}, past memory")))?; + *m = *m & !mask | x & mask; + if taint > 0 { + cx.mt.insert(at, taint); + } else { + cx.mt.remove(&at); + } + Ok(()) +} + +fn dwords(name: &str) -> usize { + ["X16", "X8", "X4", "X3", "X2"].iter().find(|s| name.ends_with(*s)).map_or(1, |s| s[1..].parse().unwrap()) +} + +/// s_load_dword* (an address in an SGPR pair) and s_buffer_load_dword* (a V#; dwords past +/// num_records read 0). +pub(super) fn smem(w: &mut Wave, d: &Decoded, cx: &mut Ctx) -> Result<(), Stop> { + let name = d.inst.name; + let n = dwords(name); + let f = |x: &str| field(d, x); + let base = 2 * f("SBASE") as usize; + let imm = ((f("OFFSET") as i64) << 43 >> 43) as u64; + let soff = if f("SOFFSET") == 125 { 0 } else { u64::from(w.scalar(d, f("SOFFSET"))?) }; + let dst = f("SDATA") as usize; + if dst + n > 106 { + return Err(unsupported(d)); + } + let (addr, limit) = if name.starts_with("S_LOAD_DWORD") { + ((w.pair(base) & !3).wrapping_add(imm & !3).wrapping_add(soff & !3) & 0xFFFF_FFFF_FFFF, None) + } else if name.starts_with("S_BUFFER_LOAD_DWORD") { + let v = [w.s[base], w.s[base + 1], w.s[base + 2]]; + let stride = u64::from(v[1] >> 16 & 0x3FFF); + let records = u64::from(v[2]); + let limit = if stride == 0 { records } else { records * stride }; + (u64::from(v[0]) | u64::from(v[1] & 0xFFFF) << 32, Some((imm.wrapping_add(soff) & 0xFFFF_FFFF, limit))) + } else { + return Err(unsupported(d)); + }; + for k in 0..n { + let (x, t) = match limit { + Some((off, lim)) if (off & !3) + 4 * k as u64 >= lim => (0, 0), + Some((off, _)) => load(d, cx, addr + (off & !3) + 4 * k as u64)?, ~~~~ --- Fixed in `mem.rs`: S_BUFFER_LOAD now reads `((base + offset) & ~3) + 4 * k`, as the quoted rule says. The test adds your case, base 0x1002 with OFFSET 0 and SOFFSET 2, which now reads 0x1004. It read 0x1000 before the change. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:22 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:22Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mod.rs; line 96

@@ -0,0 +1,496 @@
+//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2"
+//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64
+//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and
+//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model
+//! stops it (`Stop::Unsupported`); none is skipped.
+
+use std::collections::HashMap;
+
+use crate::gpu::rdna2::{self, field_value, Decoded};
+use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture};
+use crate::gpu::recomp::CsInterface;
+
+mod float;
+mod image;
+mod lanes;
+mod mem;
+mod salu;
+mod valu;
+
+mod asm;
+mod forms;
+mod fuzz;
+mod tests;
+
+/// LDS of a group, as the console has it (64 KB).
+pub(crate) const LDS_DWORDS: usize = 16384;
+/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals
+/// kept, DX10_CLAMP set, IEEE clear.
+pub(crate) const MODE: u32 = 0x1F0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stop {
+    /// an instruction (or an operand or modifier of one) outside the modelled set
+    Unsupported { pc: u64, name: String },
+    /// the program did something the console would not survive: a branch into nothing, an
+    /// access outside `mem`, an unaligned LDS dword
+    Fault { pc: u64, why: String },
+    /// the step limit
+    Steps(u64),
+}
+
+impl std::fmt::Display for Stop {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"),
+            Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"),
+            Stop::Steps(n) => write!(f, "no end after {n} steps"),
+        }
+    }
+}
+
+/// A rule of the ISA turned the wrong way, for tests that prove a check sees it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub(crate) enum Flip {
+    #[default]
+    None,
+    /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would
+    Lane31,
+    /// v_permlanex16 reads its own row instead of the other row of its half
+    PermlaneOwnRow,
+    /// vector instructions write the lanes EXEC has off
+    ExecIgnored,
+    /// VCC reads and branches see only its low half
+    VccLow,
+}
+
+pub(crate) fn unsupported(d: &Decoded) -> Stop {
+    Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) }
+}
+
+pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop {
+    Stop::Fault { pc: d.pc, why: why.into() }
+}
+
+pub(crate) fn field(d: &Decoded, name: &str) -> u64 {
+    field_value(d.enc, &d.words, name).unwrap_or(0)
+}
+
+/// A program decoded once: its instructions and where each starts.
+pub(crate) struct Program {
+    pub list: Vec<Decoded>,
+    pub index: HashMap<u64, usize>,
+}
+
+impl Program {
+    /// Words that do not decode (constants after the code) are left out; reaching one faults.
+    pub fn new(code: &[u8]) -> Program {
+        let mut list = Vec::new();
+        let mut off = 0;
+        while off + 4 <= code.len() {
+            match rdna2::decode(&code[off..], off as u64) {
+                Ok(d) => {
+                    off += d.len;
+                    list.push(d);
+                }
+                Err(_) => off += 4,

Fixed in mod.rs: a run whose first decoded instruction is not at offset 0 stops with a fault. execution_stops_at_a_word_that_does_not_decode now also runs [0xFFFFFFFF, s_mov_b32 s2, 1, s_endpgm], which ran to the end before.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777684477 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777684477). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:22Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mod.rs`; line 96 ~~~~diff @@ -0,0 +1,496 @@ +//! A reference interpreter of RDNA2 code with true wave64 semantics, written from AMD's "RDNA 2" +//! Instruction Set Architecture reference guide (document 70648): the ground truth each wave64 +//! form is compared with. Test-only. It uses `rdna2`'s decoder and the runner's ABI types and +//! nothing else of `recomp` or `dxil`. An instruction, operand or modifier it does not model +//! stops it (`Stop::Unsupported`); none is skipped. + +use std::collections::HashMap; + +use crate::gpu::rdna2::{self, field_value, Decoded}; +use crate::gpu::recomp::runner::{KernelState, TestSampler, TestTexture}; +use crate::gpu::recomp::CsInterface; + +mod float; +mod image; +mod lanes; +mod mem; +mod salu; +mod valu; + +mod asm; +mod forms; +mod fuzz; +mod tests; + +/// LDS of a group, as the console has it (64 KB). +pub(crate) const LDS_DWORDS: usize = 16384; +/// MODE at a wave's start (neither ABI carries an RSRC1): round to nearest even, denormals +/// kept, DX10_CLAMP set, IEEE clear. +pub(crate) const MODE: u32 = 0x1F0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stop { + /// an instruction (or an operand or modifier of one) outside the modelled set + Unsupported { pc: u64, name: String }, + /// the program did something the console would not survive: a branch into nothing, an + /// access outside `mem`, an unaligned LDS dword + Fault { pc: u64, why: String }, + /// the step limit + Steps(u64), +} + +impl std::fmt::Display for Stop { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Stop::Unsupported { pc, name } => write!(f, "unsupported at {pc:#x}: {name}"), + Stop::Fault { pc, why } => write!(f, "fault at {pc:#x}: {why}"), + Stop::Steps(n) => write!(f, "no end after {n} steps"), + } + } +} + +/// A rule of the ISA turned the wrong way, for tests that prove a check sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub(crate) enum Flip { + #[default] + None, + /// v_readlane / v_writelane select lane & 31, as a 32-lane wave would + Lane31, + /// v_permlanex16 reads its own row instead of the other row of its half + PermlaneOwnRow, + /// vector instructions write the lanes EXEC has off + ExecIgnored, + /// VCC reads and branches see only its low half + VccLow, +} + +pub(crate) fn unsupported(d: &Decoded) -> Stop { + Stop::Unsupported { pc: d.pc, name: rdna2::mnemonic(d) } +} + +pub(crate) fn fault(d: &Decoded, why: impl Into<String>) -> Stop { + Stop::Fault { pc: d.pc, why: why.into() } +} + +pub(crate) fn field(d: &Decoded, name: &str) -> u64 { + field_value(d.enc, &d.words, name).unwrap_or(0) +} + +/// A program decoded once: its instructions and where each starts. +pub(crate) struct Program { + pub list: Vec<Decoded>, + pub index: HashMap<u64, usize>, +} + +impl Program { + /// Words that do not decode (constants after the code) are left out; reaching one faults. + pub fn new(code: &[u8]) -> Program { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + list.push(d); + } + Err(_) => off += 4, ~~~~ --- Fixed in `mod.rs`: a run whose first decoded instruction is not at offset 0 stops with a fault. `execution_stops_at_a_word_that_does_not_decode` now also runs `[0xFFFFFFFF, s_mov_b32 s2, 1, s_endpgm]`, which ran to the end before. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:24 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:24Z.

Code review location: crates/xcl/src/gpu/rdna2_ref/mem.rs; line 9

@@ -0,0 +1,506 @@
+//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their
+//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset
+//! into `mem`. Lanes access memory in order of their number.
+
+use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS};
+use crate::gpu::rdna2::Decoded;
+
+fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> {
+    let at = (byte / 4) as usize;

I narrowed the description rather than propagating the taint. Nothing in the cases or the fuzz loads through a tainted address or branches on a tainted compare today. The description now says the taint does not reach addresses or control flow, and that such a load, or EXEC from such a compare, is compared exactly. If a case ever needs it, propagating the address's taint to the loaded value is the first step.

In head de05c50e.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777684757 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#discussion_r4777684757). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:24Z. **Code review location:** `crates/xcl/src/gpu/rdna2_ref/mem.rs`; line 9 ~~~~diff @@ -0,0 +1,506 @@ +//! Memory (ISA chapters 8 to 10): scalar loads, buffer and global loads and stores with their +//! formats and atomics, and the LDS. Flat memory is `runner`'s: a byte address is an offset +//! into `mem`. Lanes access memory in order of their number. + +use super::{computed, fault, field, lanes, unsupported, Ctx, Flip, Stop, Wave, LDS_DWORDS}; +use crate::gpu::rdna2::Decoded; + +fn load(d: &Decoded, cx: &Ctx, byte: u64) -> Result<(u32, u8), Stop> { + let at = (byte / 4) as usize; ~~~~ --- I narrowed the description rather than propagating the taint. Nothing in the cases or the fuzz loads through a tainted address or branches on a tainted compare today. The description now says the taint does not reach addresses or control flow, and that such a load, or EXEC from such a compare, is compared exactly. If a case ever needs it, propagating the address's taint to the loaded value is the first step. In head `de05c50e`. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Royalflamejlh commented 2026-12-02 23:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:36:28Z.


@thehollowedone, thank you; both points were right and are fixed in head de05c50e.

  1. V_SAD_U32. I took your one-line fix: the add of c now wraps (valu.rs). The test is sad_u32_wraps_at_the_dword in tests.rs. It runs v_sad_u32 with 0xffffffff, 0 and 1 and expects 0. It panicked with "attempt to add with overflow" in a debug build before the change and passes after it. It is credited to you in this reply. I checked the other VALU, SALU and lane rules for an unchecked + or * on 32-bit values. The others wrap, widen to i64/u64 first, or work on addresses in u64, so this was the only one.

  2. Classes that hid other mismatches. section_with_lanes_off and half_exec_empty (fuzz.rs) now also require the cause. The form must agree with the reference once the program's whole-wave sections are taken out; a mismatch that stays without them is reported. The test is a_known_class_holds_only_for_the_mismatch_its_shape_causes. It finds a lowered program of the section shape and injects two fake verdicts. One differs only when the program has a section, and is still known. The other always differs in one word, and is reported by wrong. With the old shape-only class, the second fake verdict was accepted and the test failed. I don't run the forms a second time for the other classes: they check the first differing dword itself (its thread range, or -0 for +0 and a number for a NaN). After CharlyRien's comment in the same round, that dword must also be one of the float registers.

    One cost: with XCL_FUZZ_WAVE64_SEEDS=5000, 3 of the 12 lowering mismatches are no longer classified (seeds 1646, 1002359, 1004544). Without its sections, each of those programs is refused by the lowering, so the cause cannot be confirmed and they are reported. The default 1,000 seeds have none.

Tested at de05c50e: rdna2_ref on the RTX 2070 SUPER gave 53 passed, 0 failed, 1 ignored and 1 SKIPPED (no llvm-mc); every fuzz mismatch was of a known class. Under Wine on the CPU: 53 passed, 0 failed, 1 ignored. Each commit builds and passes on its own.

AI use: Claude Code (Claude Opus 5.5) checked both points, made the changes, ran the tests and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7362209131 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7362209131). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:36:28Z. --- @thehollowedone, thank you; both points were right and are fixed in head `de05c50e`. 1. **`V_SAD_U32`.** I took your one-line fix: the add of `c` now wraps (`valu.rs`). The test is `sad_u32_wraps_at_the_dword` in `tests.rs`. It runs v_sad_u32 with 0xffffffff, 0 and 1 and expects 0. It panicked with "attempt to add with overflow" in a debug build before the change and passes after it. It is credited to you in this reply. I checked the other VALU, SALU and lane rules for an unchecked `+` or `*` on 32-bit values. The others wrap, widen to i64/u64 first, or work on addresses in u64, so this was the only one. 2. **Classes that hid other mismatches.** `section_with_lanes_off` and `half_exec_empty` (`fuzz.rs`) now also require the cause. The form must agree with the reference once the program's whole-wave sections are taken out; a mismatch that stays without them is reported. The test is `a_known_class_holds_only_for_the_mismatch_its_shape_causes`. It finds a lowered program of the section shape and injects two fake verdicts. One differs only when the program has a section, and is still known. The other always differs in one word, and is reported by `wrong`. With the old shape-only class, the second fake verdict was accepted and the test failed. I don't run the forms a second time for the other classes: they check the first differing dword itself (its thread range, or -0 for +0 and a number for a NaN). After CharlyRien's comment in the same round, that dword must also be one of the float registers. One cost: with `XCL_FUZZ_WAVE64_SEEDS=5000`, 3 of the 12 lowering mismatches are no longer classified (seeds 1646, 1002359, 1004544). Without its sections, each of those programs is refused by the lowering, so the cause cannot be confirmed and they are reported. The default 1,000 seeds have none. Tested at `de05c50e`: `rdna2_ref` on the RTX 2070 SUPER gave 53 passed, 0 failed, 1 ignored and 1 SKIPPED (no llvm-mc); every fuzz mismatch was of a known class. Under Wine on the CPU: 53 passed, 0 failed, 1 ignored. Each commit builds and passes on its own. AI use: Claude Code (Claude Opus 5.5) checked both points, made the changes, ran the tests and wrote this reply.
Foniass commented 2026-12-02 23:37:20 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T23:37:20Z.


Follow-up review of de05c50e, since 3de8793f (code reading only, not a merge-check) · 1 high

In short: This push fixes several interpreter details:

  • v_sad_u32 wraps at the dword;
  • an unaligned buffer load aligns the whole offset;
  • code that starts with a word that does not decode is a fault;
  • OMOD stops the run until the program has written MODE;
  • a NaN made by float arithmetic is exact to the next float instruction.

Each has a test, and the description now describes the current KNOWN classes and taint rules. The size still blocks it.

High

  1. Still too large to review as one PR; please split it into a stack (still open). 5,420 hand-written lines. The six commits still give a natural split: the core with SALU and asm.rs; integer VALU and lanes; memory, LDS and groups of waves; f32 and images; the harness; the fuzzer. The larger ones need halving again to get near ~400.
Checked and fine
  • Earlier nit fixed: the description now matches the code. KNOWN holds classes of mismatch keyed by adapter, the taint of transcendentals is described as it is implemented, and the stale 9ceea007b is gone.
  • V_SAD_U32 uses wrapping_add(c), and sad_u32_wraps_at_the_dword checks a sum past u32::MAX.
  • The buffer load now computes ((addr + off) & !3) + 4k. The test adds an S_BUFFER_LOAD_DWORD with OFFSET 0, and corrects the expected-value comment.
  • A non-decoding first word gives Stop::Fault, with a test.
  • mode_set is set by every MODE write. output refuses OMOD until then.
  • taint_of(.., nan_exact) treats NAN taint as exact only for float instructions and f32 compares.
  • Commit 5 (the harness) is unchanged.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7362226567 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3716#issuecomment-7362226567). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T23:37:20Z. --- **Follow-up review** of `de05c50e`, since `3de8793f` (code reading only, not a merge-check) · 1 high **In short:** This push fixes several interpreter details: - `v_sad_u32` wraps at the dword; - an unaligned buffer load aligns the whole offset; - code that starts with a word that does not decode is a fault; - OMOD stops the run until the program has written MODE; - a NaN made by float arithmetic is exact to the next float instruction. Each has a test, and the description now describes the current `KNOWN` classes and taint rules. The size still blocks it. #### High 1. **Still too large to review as one PR; please split it into a stack (still open).** 5,420 hand-written lines. The six commits still give a natural split: the core with SALU and `asm.rs`; integer VALU and lanes; memory, LDS and groups of waves; f32 and images; the harness; the fuzzer. The larger ones need halving again to get near ~400. <details><summary>Checked and fine</summary> - Earlier nit fixed: the description now matches the code. `KNOWN` holds classes of mismatch keyed by adapter, the taint of transcendentals is described as it is implemented, and the stale `9ceea007b` is gone. - `V_SAD_U32` uses `wrapping_add(c)`, and `sad_u32_wraps_at_the_dword` checks a sum past `u32::MAX`. - The buffer load now computes `((addr + off) & !3) + 4k`. The test adds an `S_BUFFER_LOAD_DWORD` with `OFFSET` 0, and corrects the expected-value comment. - A non-decoding first word gives `Stop::Fault`, with a test. - `mode_set` is set by every MODE write. `output` refuses OMOD until then. - `taint_of(.., nan_exact)` treats `NAN` taint as exact only for float instructions and f32 compares. - Commit 5 (the harness) is unchanged. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3716:upstream-pr/3716'
git switch 'upstream-pr/3716'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3716'
git switch 'upstream-pr/3716'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3716'
git switch 'upstream-pr/3716'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3716'
git switch 'main'
git merge --squash 'upstream-pr/3716'
git switch 'main'
git merge --ff-only 'upstream-pr/3716'
git switch 'main'
git merge 'upstream-pr/3716'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3716
No description provided.