Recompiler: pre-emission RDNA2 optimizer, dominator SMEM hoisting, and lane-local mask scalarization #1620

Open
auswhalen999-debug wants to merge 2 commits from upstream-pr/1630 into main
auswhalen999-debug commented 2026-11-24 18:25:33 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by auswhalen999-debug on 2026-11-24T18:25:33Z.


Add a pre-emission RDNA2 CFG/liveness optimizer (opt.rs) and matching HLSL lowering improvements (emit.rs, mod.rs) that reduce basic-block explosion, redundant scalar memory loads, convergent wave ballots, and branchy HLSL 2021 helpers across large retail compute shaders. Part of #1269.

Measured across 12 stratified retail compute shaders (150 KB – 1.15 MB DXIL, 131,048 RDNA2 instructions) on an NVIDIA GeForce GTX 1070 with cold driver-cache salt (109.0x cold/warm verified): -31.2% cold driver CreateComputePipelineState time (281.84 s -> 194.01 s, 12/12 faster, up to -40.7%), -18.7% DXC compile time (177.52 s -> 144.39 s), -26.1% end-to-end compile time (460.12 s -> 339.87 s, 12/12 faster), and -13.6% DXIL size (8,400.1 KB -> 7,256.3 KB).

This PR is kept together as one cohesive optimizer pass because the dominator/reaching-def/liveness/hazard analysis in opt.rs directly drives the emitter lowering in emit.rs and early-exit CFG in mod.rs; splitting them would leave dead unexercised analysis code or lose the combined CFG/driver-compile reduction measured below (if review bandwidth prefers a stacked split of opt.rs ahead of emit.rs/mod.rs, happy to split on request).

Relationship to other #1269 PRs

  • Strictly complementary to #1524 (dynamic-index format helpers): this PR intentionally leaves bits_at, put_bits, bvh_intersect, dst_sel, and xcl_lv untouched (0 lines changed on those helpers) so #1524 and #1630 stack cleanly without conflict or double-work.
  • Zero overlap with #680 (rebased onto 9e3831e and supports both default switch and heap_windows forms), #1356, #1380, #1439, #1345, #1315/#1316, #1043, #1111/#1596/#1597, or #1426 direct-DXIL.

What is in it

  • Pre-emission RDNA2 CFG analysis (crates/xcl/src/gpu/recomp/opt.rs, registered in crates/xcl/build.rs TRANSLATOR_SOURCES):
    • Exact backward liveness (scc, SGPRs, carry sdst, and conservative RMW VGPR liveness under divergent EXEC, preserving Mode::Kernel live-outs) for dead scc, dead carry-out WaveActiveBallot (including Dst::Null and wave64 pairs), and dead pure ALU elimination.
    • Cooper–Harvey–Kennedy dominator tree, CFG-wide SGPR reaching-def/constant propagation, and backwards-BFS memory-hazard reachability (loop-safe) for cross-block s_load_* and s_buffer_load_* CSE/hoisting (HoistedSmemGroup, HoistedSbufGroup), non-consecutive intra-block s_buffer_load_* grouping (IntraBlockSbufGroup), and known_zero_hi Window-0 fast paths (s[sbase+1] == 0 / (s[sbase+1] & 0xFFFF) == 0, with Mode::Kernel 4 GiB wrap guards).
    • Wave32 and native-Wave64 strictly intra-block lane-local bool mask scalarization (v_cmp_* / v_add_co* / v_sub_co* and dead-scc bitwise SALU chains consumed only per-lane by v_cndmask_b32 / carry-in ops, disabled in Mode::Kernel and split_wave64), with explicit convergence & EXEC-widening hazard model documented in opt.rs.
    • Whole-program 4-condition memory-coherence check (mem_coherent: zero GLC/DLC/SLC, zero memory atomics, zero cache inv/wb ops, and !(has_s_barrier && has_mem_store)).
    • Unit tests covering all analyses and soundness guardrails (opt::tests).
  • Recompiler HLSL lowering (crates/xcl/src/gpu/recomp/emit.rs):
    • Consumes ProgramOpt for dead scc / dead carry-out / dead pure-inst elision, hoisted/grouped SMEM & SBUF lowering (zero-loop single-switch in default switch mode, ResourceDescriptorHeap[MEM_HEAP_BASE + xcl_w] in heap_windows mode, direct Window-0 fast path using ResourceDescriptorHeap[0u] under heap_windows or xcl_mem0 under switch mode), and lane-local bool ml_* masks (avoiding convergent WaveActiveBallot).
    • Omits NonUniformResourceIndex on wave-uniform SGPR handles in Compute | Mesh | Geometry (and non-split Kernel), keeping it in Pixel, Vertex, and split Kernel; replaces img_cls FMT_INFO table lookup with constant bitmasks.
    • Conditional globallycoherent on Compute mem..mem3 (and heap_windows XCL_MW) gated on program_opt.mem_coherent; prunes non-ABI scratch SGPR io.Load() calls in Mode::Compute and dead exec_lo/exec_hi entry loads in non-Kernel modes.
    • Replaces HLSL 2021 short-circuit ?:/&&/|| diamonds in ALU/conversion helpers (fma_legacy, f32_to_f16_rm, cvt_norm_*, perm_b32, fclass*, sdwa_*, lanemask_lt_*, s_cmp_*_u64, s_bfm_*, v_ffbh/v_ffbl, etc.) with branch-free select/bitwise equivalents (leaving #1524's bits_at/put_bits/bvh_intersect/dst_sel untouched), and simplifies v_mul_legacy_f32 / float_compare on known constants while preserving -0.0f sign semantics.
    • Unit tests for bit-exact branchless helpers, img_cls, uniform_sgpr_handles, and heap_windows Window-0 descriptor-heap emission (emit::opt_helper_tests).
  • Structured/fallback CFG early-exit lowering (crates/xcl/src/gpu/recomp/mod.rs):
    • Wires opt::analyze into translate() and routes block emission through Em::emit_block_insts.
    • Emits direct return; ({ xcl_s_barrier_exit(); return; } when safe_barrier is active, return xo; for Vertex) on early s_endpgm in Compute | Mesh | Vertex (preserving xcl_skip_end in Kernel | Geometry | Pixel), extends structured_span past Term::End, and emits continue; / break; in emit_range loops.
  • GPU output-parity tests & assertion updates (crates/xcl/src/gpu/recomp/tests.rs):
    • Added gpu_opt_lane_local_mask_exec_restore_and_carry_parity (Wave32 & Wave64 real GPU dispatch verifying s_and_saveexec + v_cmp + s_or + EXEC restore + v_cndmask_b32 + 64-bit v_add_co -> v_add_co_ci carry chain with dead carry-out, bit-exact on every lane) and gpu_opt_hoisted_smem_store_hazard_and_branchless_helpers_parity (real GPU dispatch verifying hoisted/subsumed s_load_*, grouped s_buffer_load_* partial OOB, store-hazard non-hoisting, branchless fma_legacy(0, NaN, 7), and constant mul_legacy(2.0, -0.0) == +0.0).
    • Updated 4 existing HLSL string-count assertions where dead scc, dead final carry-out, and Dst::Null compare ballots are now elided.

Tested

  • Hardware & toolchain: NVIDIA GeForce GTX 1070 (driver 32.0.15.8180, Wave32, no HW mesh shaders), AMD Ryzen 5 3500X 6-Core Processor, Windows 11 (NT 10.0.26300.0), rustc 1.100.0 (0ef1bc386 2026-11-09), DXC 1.9.2609.5, release build.
  • cargo test --workspace --release -- --test-threads=4 (after cargo build --workspace --release, with XCL_DXC_DIR set) at 91ae2c6: 797 passed, 0 failed, 41 ignored (748 lib including both new GPU output-parity tests + 49 integration/e2e/oracle, including gpu_compute_e2e 4 passed, 0 failed and #680 heap_window_tests).
  • SKIPPED GPU tests on GTX 1070:
    • gpu::recomp::tests::gpu_geometry_mode_es_gs_strip: no mesh shaders
    • gpu::recomp::tests::gpu_geometry_wave32_prefix_count_over_a_mask: no wave64
    • gpu::recomp::tests::gpu_mesh_mode_two_passes: no mesh shaders
    • gpu::recomp::tests::gpu_wave32_program_in_wave64_hardware: no wave64
  • Paired cold-PSO compile benchmark across 12 stratified retail compute shaders (150 KB – 1.15 MB DXIL, split_wave64=true, mem_windows=4, heap_windows=false, retail -O1/-O3 threshold, per-run non-DCE-able io.Load(508u) salt defeating %LOCALAPPDATA%\NVIDIA\DXCache, coldness self-check on #0: cold1=3788.3 ms, warm=35.6 ms, cold2=3882.6 ms, ratio 109.0x; note: compile-time benchmark only, as standalone retail CS expect live title UMA/descriptors — output parity is verified by the workspace GPU suite, gpu_compute_e2e, and the new GPU dispatch tests above):
# Hash (fnv64) Insts DXC base -> PR (ms) DXIL base -> PR (KB) Cold PSO base -> PR (ms) Cold PSO delta
0 0019989e 2,632 3,172 -> 2,724 (-14.1%) 204.0 -> 180.4 (-11.6%) 4,588 -> 3,788 -17.4%
1 00daa26e 4,497 7,273 (-O1) -> 7,511 (-O3)* 312.8 -> 254.9 (-18.5%) 8,454 -> 5,873 -30.5%
2 076191bb 5,187 9,114 -> 7,106 (-22.0%) 362.7 -> 302.0 (-16.7%) 10,365 -> 7,671 -26.0%
3 0526ab24 8,462 8,211 -> 6,355 (-22.6%) 526.1 -> 450.2 (-14.4%) 13,945 -> 10,097 -27.6%
4 0452488a 10,753 21,887 -> 17,103 (-21.9%) 539.6 -> 422.5 (-21.7%) 14,361 -> 9,768 -32.0%
5 1f04a85e 11,044 13,120 -> 10,491 (-20.0%) 618.1 -> 544.9 (-11.8%) 14,101 -> 11,983 -15.0%
6 001714bf 12,152 12,447 -> 9,083 (-27.0%) 784.3 -> 619.6 (-21.0%) 22,519 -> 15,647 -30.5%
7 0155621c 12,931 14,104 -> 11,356 (-19.5%) 858.7 -> 792.8 (-7.7%) 26,700 -> 19,983 -25.2%
8 0291d282 13,488 17,032 -> 11,944 (-29.9%) 909.3 -> 722.5 (-20.5%) 30,415 -> 20,939 -31.2%
9 008bfb7a 16,334 21,388 -> 14,837 (-30.6%) 1,055.0 -> 853.4 (-19.1%) 35,833 -> 24,425 -31.8%
10 008d625c 16,876 20,109 -> 16,293 (-19.0%) 1,092.9 -> 1,038.1 (-5.0%) 50,586 -> 30,020 -40.7%
11 04fd77f7 16,692 29,665 -> 29,588 (-0.3%) 1,136.7 -> 1,075.0 (-5.4%) 49,969 -> 33,812 -32.3%
TOTAL 12 CS 131,048 177,521 -> 144,390 (-18.7%) 8,400.1 -> 7,256.3 (-13.6%) 281,838 -> 194,007 -31.2%

*Note: #1 (00daa26e) shrank HLSL from 1,085.4 KB -> 978.4 KB, crossing dxc.rs's 1 MiB threshold from -O1 to -O3, and still reduced total E2E compile time by -14.8% (15.76 s -> 13.42 s). Across the 12 shaders, NonUniformResourceIndex dropped 2,500 -> 0, xcl_mLoad* calls dropped 8,506 -> 2,829 (-66.7%), entry io.Load dropped 1,248 -> 145 (-88.4%), and globallycoherent dropped 48 -> 16.

Regression run
main:

xcl-smoke v1
commit: 9e3831e1f570d3646e53ab753b19ec07eb8f1485
gpu: NVIDIA GeForce GTX 1070
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1055 (PresentX 1055)
presents per 2 s (last 3): 60 59 60
device removals: 0
crashes: 0
peak commit: 14086 MB

PR:

xcl-smoke v1
commit: 91ae2c62e89f049f241df4fed3d47295f19f2793
gpu: NVIDIA GeForce GTX 1070
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 938 (PresentX 938)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14197 MB

Not tested

  • Retail shader output-buffer comparison on the 12-shader compile benchmark corpus (standalone retail CS require live title UMA state/descriptors).
  • AMD RDNA / Intel GPUs, native hardware Wave64 (gpu_wave32_program_in_wave64_hardware, gpu_geometry_wave32_prefix_count_over_a_mask), and hardware mesh-shader tests (gpu_mesh_mode_two_passes, gpu_geometry_mode_es_gs_strip) on this machine — GTX 1070 is Pascal Wave32 without mesh shaders (independently verified on AMD Radeon native-wave64 + mesh at 17c0233 in comments below).
  • Paired cold-PSO timings under XCL_HEAP_WINDOWS=1 (functional unit/GPU coverage via heap_window_tests, gpu_compute_e2e, and heap_windows_window0_fast_paths_use_descriptor_heap passed).
  • Linux / Wine, XCL_SAMPLE_* tests, and retail gameplay past the 60 s smoke window.

AI use
Antigravity (Google DeepMind Gemini agent) — audited gpu/recomp/ and open PRs for zero overlap, profiled baseline DXIL IR and cold GTX 1070 PSO compile times, implemented opt.rs and the emit.rs/mod.rs/build.rs changes and unit/GPU parity tests, ran the workspace test suite, paired cold-PSO benchmarks, and scripts/smoke.ps1 runs, and drafted the commits and PR description.

<!-- greyfinch-sync:ivall/xcl:issue:5477961183 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630). Originally posted by [auswhalen999-debug](https://github.com/auswhalen999-debug) on 2026-11-24T18:25:33Z. --- Add a pre-emission RDNA2 CFG/liveness optimizer (`opt.rs`) and matching HLSL lowering improvements (`emit.rs`, `mod.rs`) that reduce basic-block explosion, redundant scalar memory loads, convergent wave ballots, and branchy HLSL 2021 helpers across large retail compute shaders. Part of #1269. Measured across 12 stratified retail compute shaders (`150 KB – 1.15 MB` DXIL, `131,048` RDNA2 instructions) on an NVIDIA GeForce GTX 1070 with cold driver-cache salt (`109.0x` cold/warm verified): **-31.2% cold driver `CreateComputePipelineState` time (`281.84 s -> 194.01 s`, 12/12 faster, up to -40.7%)**, **-18.7% DXC compile time (`177.52 s -> 144.39 s`)**, **-26.1% end-to-end compile time (`460.12 s -> 339.87 s`, 12/12 faster)**, and **-13.6% DXIL size (`8,400.1 KB -> 7,256.3 KB`)**. This PR is kept together as one cohesive optimizer pass because the dominator/reaching-def/liveness/hazard analysis in `opt.rs` directly drives the emitter lowering in `emit.rs` and early-exit CFG in `mod.rs`; splitting them would leave dead unexercised analysis code or lose the combined CFG/driver-compile reduction measured below (if review bandwidth prefers a stacked split of `opt.rs` ahead of `emit.rs`/`mod.rs`, happy to split on request). **Relationship to other `#1269` PRs** - Strictly complementary to **#1524** (dynamic-index format helpers): this PR intentionally leaves `bits_at`, `put_bits`, `bvh_intersect`, `dst_sel`, and `xcl_lv` untouched (0 lines changed on those helpers) so `#1524` and `#1630` stack cleanly without conflict or double-work. - Zero overlap with `#680` (rebased onto `9e3831e` and supports both default switch and `heap_windows` forms), `#1356`, `#1380`, `#1439`, `#1345`, `#1315`/`#1316`, `#1043`, `#1111`/`#1596`/`#1597`, or `#1426` direct-DXIL. **What is in it** - Pre-emission RDNA2 CFG analysis (`crates/xcl/src/gpu/recomp/opt.rs`, registered in `crates/xcl/build.rs` `TRANSLATOR_SOURCES`): - Exact backward liveness (`scc`, SGPRs, carry `sdst`, and conservative RMW VGPR liveness under divergent `EXEC`, preserving `Mode::Kernel` live-outs) for dead `scc`, dead carry-out `WaveActiveBallot` (including `Dst::Null` and wave64 pairs), and dead pure ALU elimination. - Cooper–Harvey–Kennedy dominator tree, CFG-wide SGPR reaching-def/constant propagation, and backwards-BFS memory-hazard reachability (loop-safe) for cross-block `s_load_*` and `s_buffer_load_*` CSE/hoisting (`HoistedSmemGroup`, `HoistedSbufGroup`), non-consecutive intra-block `s_buffer_load_*` grouping (`IntraBlockSbufGroup`), and `known_zero_hi` Window-0 fast paths (`s[sbase+1] == 0` / `(s[sbase+1] & 0xFFFF) == 0`, with `Mode::Kernel` 4 GiB wrap guards). - Wave32 and native-Wave64 strictly intra-block lane-local `bool` mask scalarization (`v_cmp_*` / `v_add_co*` / `v_sub_co*` and dead-`scc` bitwise SALU chains consumed only per-lane by `v_cndmask_b32` / carry-in ops, disabled in `Mode::Kernel` and `split_wave64`), with explicit convergence & `EXEC`-widening hazard model documented in `opt.rs`. - Whole-program 4-condition memory-coherence check (`mem_coherent`: zero `GLC`/`DLC`/`SLC`, zero memory atomics, zero cache inv/wb ops, and `!(has_s_barrier && has_mem_store)`). - Unit tests covering all analyses and soundness guardrails (`opt::tests`). - Recompiler HLSL lowering (`crates/xcl/src/gpu/recomp/emit.rs`): - Consumes `ProgramOpt` for dead `scc` / dead carry-out / dead pure-inst elision, hoisted/grouped SMEM & SBUF lowering (zero-loop single-switch in default switch mode, `ResourceDescriptorHeap[MEM_HEAP_BASE + xcl_w]` in `heap_windows` mode, direct Window-0 fast path using `ResourceDescriptorHeap[0u]` under `heap_windows` or `xcl_mem0` under switch mode), and lane-local `bool ml_*` masks (avoiding convergent `WaveActiveBallot`). - Omits `NonUniformResourceIndex` on wave-uniform SGPR handles in `Compute | Mesh | Geometry` (and non-split `Kernel`), keeping it in `Pixel`, `Vertex`, and split `Kernel`; replaces `img_cls` `FMT_INFO` table lookup with constant bitmasks. - Conditional `globallycoherent` on Compute `mem..mem3` (and `heap_windows` `XCL_MW`) gated on `program_opt.mem_coherent`; prunes non-ABI scratch SGPR `io.Load()` calls in `Mode::Compute` and dead `exec_lo`/`exec_hi` entry loads in non-`Kernel` modes. - Replaces HLSL 2021 short-circuit `?:`/`&&`/`||` diamonds in ALU/conversion helpers (`fma_legacy`, `f32_to_f16_rm`, `cvt_norm_*`, `perm_b32`, `fclass*`, `sdwa_*`, `lanemask_lt_*`, `s_cmp_*_u64`, `s_bfm_*`, `v_ffbh`/`v_ffbl`, etc.) with branch-free `select`/bitwise equivalents (leaving `#1524`'s `bits_at`/`put_bits`/`bvh_intersect`/`dst_sel` untouched), and simplifies `v_mul_legacy_f32` / `float_compare` on known constants while preserving `-0.0f` sign semantics. - Unit tests for bit-exact branchless helpers, `img_cls`, `uniform_sgpr_handles`, and `heap_windows` Window-0 descriptor-heap emission (`emit::opt_helper_tests`). - Structured/fallback CFG early-exit lowering (`crates/xcl/src/gpu/recomp/mod.rs`): - Wires `opt::analyze` into `translate()` and routes block emission through `Em::emit_block_insts`. - Emits direct `return;` (`{ xcl_s_barrier_exit(); return; }` when `safe_barrier` is active, `return xo;` for `Vertex`) on early `s_endpgm` in `Compute | Mesh | Vertex` (preserving `xcl_skip_end` in `Kernel | Geometry | Pixel`), extends `structured_span` past `Term::End`, and emits `continue;` / `break;` in `emit_range` loops. - GPU output-parity tests & assertion updates (`crates/xcl/src/gpu/recomp/tests.rs`): - Added `gpu_opt_lane_local_mask_exec_restore_and_carry_parity` (Wave32 & Wave64 real GPU dispatch verifying `s_and_saveexec` + `v_cmp` + `s_or` + `EXEC` restore + `v_cndmask_b32` + 64-bit `v_add_co` -> `v_add_co_ci` carry chain with dead carry-out, bit-exact on every lane) and `gpu_opt_hoisted_smem_store_hazard_and_branchless_helpers_parity` (real GPU dispatch verifying hoisted/subsumed `s_load_*`, grouped `s_buffer_load_*` partial OOB, store-hazard non-hoisting, branchless `fma_legacy(0, NaN, 7)`, and constant `mul_legacy(2.0, -0.0) == +0.0`). - Updated 4 existing HLSL string-count assertions where dead `scc`, dead final carry-out, and `Dst::Null` compare ballots are now elided. **Tested** - Hardware & toolchain: NVIDIA GeForce GTX 1070 (driver `32.0.15.8180`, Wave32, no HW mesh shaders), AMD Ryzen 5 3500X 6-Core Processor, Windows 11 (`NT 10.0.26300.0`), `rustc 1.100.0 (0ef1bc386 2026-11-09)`, DXC `1.9.2609.5`, release build. - `cargo test --workspace --release -- --test-threads=4` (after `cargo build --workspace --release`, with `XCL_DXC_DIR` set) at `91ae2c6`: **797 passed, 0 failed, 41 ignored** (`748` lib including both new GPU output-parity tests + `49` integration/e2e/oracle, including **`gpu_compute_e2e` 4 passed, 0 failed** and `#680` `heap_window_tests`). - `SKIPPED` GPU tests on GTX 1070: - `gpu::recomp::tests::gpu_geometry_mode_es_gs_strip: no mesh shaders` - `gpu::recomp::tests::gpu_geometry_wave32_prefix_count_over_a_mask: no wave64` - `gpu::recomp::tests::gpu_mesh_mode_two_passes: no mesh shaders` - `gpu::recomp::tests::gpu_wave32_program_in_wave64_hardware: no wave64` - Paired cold-PSO compile benchmark across 12 stratified retail compute shaders (`150 KB – 1.15 MB` DXIL, `split_wave64=true`, `mem_windows=4`, `heap_windows=false`, retail `-O1`/`-O3` threshold, per-run non-DCE-able `io.Load(508u)` salt defeating `%LOCALAPPDATA%\NVIDIA\DXCache`, coldness self-check on `#0`: `cold1=3788.3 ms`, `warm=35.6 ms`, `cold2=3882.6 ms`, ratio `109.0x`; note: compile-time benchmark only, as standalone retail CS expect live title UMA/descriptors — output parity is verified by the workspace GPU suite, `gpu_compute_e2e`, and the new GPU dispatch tests above): | # | Hash (`fnv64`) | Insts | DXC base -> PR (ms) | DXIL base -> PR (KB) | Cold PSO base -> PR (ms) | Cold PSO delta | |---:|---|---:|---:|---:|---:|---:| | 0 | `0019989e` | 2,632 | 3,172 -> 2,724 (-14.1%) | 204.0 -> 180.4 (-11.6%) | 4,588 -> 3,788 | **-17.4%** | | 1 | `00daa26e` | 4,497 | 7,273 (`-O1`) -> 7,511 (`-O3`)* | 312.8 -> 254.9 (-18.5%) | 8,454 -> 5,873 | **-30.5%** | | 2 | `076191bb` | 5,187 | 9,114 -> 7,106 (-22.0%) | 362.7 -> 302.0 (-16.7%) | 10,365 -> 7,671 | **-26.0%** | | 3 | `0526ab24` | 8,462 | 8,211 -> 6,355 (-22.6%) | 526.1 -> 450.2 (-14.4%) | 13,945 -> 10,097 | **-27.6%** | | 4 | `0452488a` | 10,753 | 21,887 -> 17,103 (-21.9%) | 539.6 -> 422.5 (-21.7%) | 14,361 -> 9,768 | **-32.0%** | | 5 | `1f04a85e` | 11,044 | 13,120 -> 10,491 (-20.0%) | 618.1 -> 544.9 (-11.8%) | 14,101 -> 11,983 | **-15.0%** | | 6 | `001714bf` | 12,152 | 12,447 -> 9,083 (-27.0%) | 784.3 -> 619.6 (-21.0%) | 22,519 -> 15,647 | **-30.5%** | | 7 | `0155621c` | 12,931 | 14,104 -> 11,356 (-19.5%) | 858.7 -> 792.8 (-7.7%) | 26,700 -> 19,983 | **-25.2%** | | 8 | `0291d282` | 13,488 | 17,032 -> 11,944 (-29.9%) | 909.3 -> 722.5 (-20.5%) | 30,415 -> 20,939 | **-31.2%** | | 9 | `008bfb7a` | 16,334 | 21,388 -> 14,837 (-30.6%) | 1,055.0 -> 853.4 (-19.1%) | 35,833 -> 24,425 | **-31.8%** | | 10 | `008d625c` | 16,876 | 20,109 -> 16,293 (-19.0%) | 1,092.9 -> 1,038.1 (-5.0%) | 50,586 -> 30,020 | **-40.7%** | | 11 | `04fd77f7` | 16,692 | 29,665 -> 29,588 (-0.3%) | 1,136.7 -> 1,075.0 (-5.4%) | 49,969 -> 33,812 | **-32.3%** | | **TOTAL** | **12 CS** | **131,048** | **177,521 -> 144,390 (-18.7%)** | **8,400.1 -> 7,256.3 (-13.6%)** | **281,838 -> 194,007** | **-31.2%** | *\*Note: `#1` (`00daa26e`) shrank HLSL from `1,085.4 KB -> 978.4 KB`, crossing `dxc.rs`'s 1 MiB threshold from `-O1` to `-O3`, and still reduced total E2E compile time by `-14.8%` (`15.76 s -> 13.42 s`). Across the 12 shaders, `NonUniformResourceIndex` dropped `2,500 -> 0`, `xcl_mLoad*` calls dropped `8,506 -> 2,829` (-66.7%), entry `io.Load` dropped `1,248 -> 145` (-88.4%), and `globallycoherent` dropped `48 -> 16`.* **Regression run** main: ``` xcl-smoke v1 commit: 9e3831e1f570d3646e53ab753b19ec07eb8f1485 gpu: NVIDIA GeForce GTX 1070 title: 3c290c16 seconds: 60 exit: 0x0 frames shown: 1055 (PresentX 1055) presents per 2 s (last 3): 60 59 60 device removals: 0 crashes: 0 peak commit: 14086 MB ``` PR: ``` xcl-smoke v1 commit: 91ae2c62e89f049f241df4fed3d47295f19f2793 gpu: NVIDIA GeForce GTX 1070 title: 3c290c16 seconds: 60 exit: 0x0 frames shown: 938 (PresentX 938) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 14197 MB ``` **Not tested** - Retail shader output-buffer comparison on the 12-shader compile benchmark corpus (standalone retail CS require live title UMA state/descriptors). - AMD RDNA / Intel GPUs, native hardware Wave64 (`gpu_wave32_program_in_wave64_hardware`, `gpu_geometry_wave32_prefix_count_over_a_mask`), and hardware mesh-shader tests (`gpu_mesh_mode_two_passes`, `gpu_geometry_mode_es_gs_strip`) on this machine — GTX 1070 is Pascal Wave32 without mesh shaders (independently verified on AMD Radeon native-wave64 + mesh at `17c0233` in comments below). - Paired cold-PSO timings under `XCL_HEAP_WINDOWS=1` (functional unit/GPU coverage via `heap_window_tests`, `gpu_compute_e2e`, and `heap_windows_window0_fast_paths_use_descriptor_heap` passed). - Linux / Wine, `XCL_SAMPLE_*` tests, and retail gameplay past the 60 s smoke window. **AI use** Antigravity (Google DeepMind Gemini agent) — audited `gpu/recomp/` and open PRs for zero overlap, profiled baseline DXIL IR and cold GTX 1070 PSO compile times, implemented `opt.rs` and the `emit.rs`/`mod.rs`/`build.rs` changes and unit/GPU parity tests, ran the workspace test suite, paired cold-PSO benchmarks, and `scripts/smoke.ps1` runs, and drafted the commits and PR description.
pickles976 commented 2026-11-24 19:07:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by pickles976 on 2026-11-24T18:29:36Z.


Measurements read as the best-designed perf post in this repo yet — stratified corpus (150 KB–1.15 MB, 131k instructions), cold-cache salt, per-shader distribution not just mean (12/12, up to −40.7%), and cold/warm verified at 109× so the cold number cannot be cache luck. And it lands directly on the thread that measured one helper pattern at 230 s→63 s (#1524): if both hold, the cold-run watchdog arithmetic changes materially — worth a cross-reference in each PR description so the reviewers of one know the other exists. Four review-lane points on a 7,298-line optimizer rather than a rubber stamp: ① correctness artifact, not speed artifact — the single most valuable addition is the boring one: state (or add) whether the 12-shader corpus compares outputs, not just times, before/after the pass, and whether the full gpu_compute_e2e suite ran at this head; for an optimizer whose failure mode is silently wrong pixels, "12/12 faster" and "12/12 bit-identical" are different sentences and the second is the merge prerequisite. ② The convergent-wave-ballot removal is the sharpest edge in the PR: wave intrinsics are convergence operations before they are values, so ballot dedup is only sound under a convergence-aware hazard model — name the model in the pass doc (which CFG shapes may the analysis move a ballot across, and what makes a region convergence-safe) so the next person extending opt.rs inherits the constraint, not just the code. ③ Review bandwidth is the known graveyard here (see the validated-but-unmerged data fix): if review stalls on size, the natural seam is analysis passes (opt.rs) landing before the HLSL lowering changes (emit.rs/mod.rs) if they are behavior-preserving without each other — but the cohesion argument is plausible as written, so this is Plan B, not a request. ④ emit.rs "branchy HLSL 2021 helpers" reduction intersects #1524 commit 1 (dynamic-index helpers) — please rebase against each other before merge so the two helper-lowering rewrites do not half-cancel.

<!-- greyfinch-sync:ivall/xcl:comment:7140721105 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7140721105). Originally posted by [pickles976](https://github.com/pickles976) on 2026-11-24T18:29:36Z. --- Measurements read as the best-designed perf post in this repo yet — stratified corpus (150 KB–1.15 MB, 131k instructions), cold-cache **salt**, per-shader distribution not just mean (12/12, up to −40.7%), and cold/warm verified at 109× so the cold number cannot be cache luck. And it lands directly on the thread that measured one helper pattern at 230 s→63 s (#1524): if both hold, the cold-run watchdog arithmetic changes materially — worth a cross-reference in each PR description so the reviewers of one know the other exists. Four review-lane points on a 7,298-line optimizer rather than a rubber stamp: ① **correctness artifact, not speed artifact** — the single most valuable addition is the boring one: state (or add) whether the 12-shader corpus **compares outputs**, not just times, before/after the pass, and whether the full `gpu_compute_e2e` suite ran at this head; for an optimizer whose failure mode is *silently wrong pixels*, "12/12 faster" and "12/12 bit-identical" are different sentences and the second is the merge prerequisite. ② The **convergent-wave-ballot** removal is the sharpest edge in the PR: wave intrinsics are convergence operations before they are values, so ballot dedup is only sound under a convergence-aware hazard model — name the model in the pass doc (which CFG shapes may the analysis move a ballot across, and what makes a region convergence-safe) so the next person extending `opt.rs` inherits the constraint, not just the code. ③ Review bandwidth is the known graveyard here (see the validated-but-unmerged data fix): if review stalls on size, the natural seam is analysis passes (`opt.rs`) landing before the HLSL lowering changes (`emit.rs`/`mod.rs`) if they are behavior-preserving without each other — but the cohesion argument is plausible as written, so this is Plan B, not a request. ④ `emit.rs` "branchy HLSL 2021 helpers" reduction intersects #1524 commit 1 (dynamic-index helpers) — please rebase against each other before merge so the two helper-lowering rewrites do not half-cancel.
vitor127wt commented 2026-11-24 19:07:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by vitor127wt on 2026-11-24T18:50:26Z.


Independent cold compute PSO timings on Linux / Proton

This is the #1630 data point for campaign #1269 (A14).

Tested

  • PR head 17c02330d8b5a78c938a1cc52f04874e1fb9087a against its main base 9e3831e1f570d3646e53ab753b19ec07eb8f1485, using five shaders matched by container hash from the PR's sample.
  • Ryzen 7 9700X, 32 GB DDR5, RTX 5070 Ti (16 GB), NVIDIA 620.73.04, CachyOS 7.3.5-2-cachyos, Proton Experimental 11.0 (2026-11-12), DXC 1.9.2609.5. Rust 1.100.0, Windows x64 release build with LLVM-MinGW 20261117 (x86_64-pc-windows-gnullvm). vkd3d-proton ec207194 with the Wine kit #257 patch, dxil-spirv 7c048638.
  • The same temporary benchmark example in each checkout called XCL's recompiler and DXC wrapper with four switch-form memory windows, split wave64 and fixed -O1. Built with cargo build --locked -j 5 --target x86_64-pc-windows-gnullvm --release -p xcl --example shader_bench. Ran wine shader_bench.exe compile <record> -O1 <dxil> and wine shader_bench.exe pipeline <record> <dxil> with Proton's Wine. PSO time is the CreateComputePipelineState call using XCL's ABI root signature and the matching build's precompiled DXIL.
  • Three runs per shader and build. All 30 DXC compiles and 30 PSO creations succeeded. The vkd3d and NVIDIA disk caches were disabled, with no cached PSO blob and a fresh process per creation. Vulkan feedback confirmed no cache reuse for all 26 calls with feedback enabled. Feedback was off for the first 4 calls.
Sample (RDNA2 instructions) DXC (s), main → PR Cold PSO (s), main → PR DXIL bytes, main → PR
0019989e (2,632) 1.017 → 0.872 1.805 → 1.544 208,944 → 184,672
00daa26e (4,497) 2.829 → 2.059 4.104 → 2.763 320,056 → 261,652
076191bb (5,187) 3.593 → 2.857 5.384 → 4.263 371,216 → 309,032
0452488a (10,753) 8.717 → 6.718 8.584 → 5.293 552,296 → 432,420
04fd77f7 (16,692) 12.987 → 12.380 26.010 → 19.388 1,163,756 → 1,100,536
Total 29.142 → 24.887 45.887 → 33.251 2,616,268 → 2,288,312

Totals are sums of per-shader medians. DXC time fell 14.6%, cold PSO creation time fell 27.5%, and DXIL bytes fell 12.5%. All five PSOs were faster.

Not tested

Native Windows, gameplay or shader execution correctness, and the full workspace suite.

AI use — OpenAI Codex (GPT-6, exact variant unavailable) wrote the local benchmark example, ran the tests and prepared the report.

<!-- greyfinch-sync:ivall/xcl:comment:7141225439 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7141225439). Originally posted by [vitor127wt](https://github.com/vitor127wt) on 2026-11-24T18:50:26Z. --- **Independent cold compute PSO timings on Linux / Proton** This is the #1630 data point for campaign #1269 (A14). **Tested** - PR head `17c02330d8b5a78c938a1cc52f04874e1fb9087a` against its `main` base `9e3831e1f570d3646e53ab753b19ec07eb8f1485`, using five shaders matched by container hash from the PR's sample. - Ryzen 7 9700X, 32 GB DDR5, RTX 5070 Ti (16 GB), NVIDIA 620.73.04, CachyOS 7.3.5-2-cachyos, Proton Experimental 11.0 (2026-11-12), DXC 1.9.2609.5. Rust 1.100.0, Windows x64 release build with LLVM-MinGW 20261117 (`x86_64-pc-windows-gnullvm`). vkd3d-proton `ec207194` with the Wine kit #257 patch, dxil-spirv `7c048638`. - The same temporary benchmark example in each checkout called XCL's recompiler and DXC wrapper with four switch-form memory windows, split wave64 and fixed `-O1`. Built with `cargo build --locked -j 5 --target x86_64-pc-windows-gnullvm --release -p xcl --example shader_bench`. Ran `wine shader_bench.exe compile <record> -O1 <dxil>` and `wine shader_bench.exe pipeline <record> <dxil>` with Proton's Wine. PSO time is the `CreateComputePipelineState` call using XCL's ABI root signature and the matching build's precompiled DXIL. - Three runs per shader and build. All 30 DXC compiles and 30 PSO creations succeeded. The vkd3d and NVIDIA disk caches were disabled, with no cached PSO blob and a fresh process per creation. Vulkan feedback confirmed no cache reuse for all 26 calls with feedback enabled. Feedback was off for the first 4 calls. | Sample (RDNA2 instructions) | DXC (s), main → PR | Cold PSO (s), main → PR | DXIL bytes, main → PR | |---|---:|---:|---:| | `0019989e` (2,632) | 1.017 → 0.872 | 1.805 → 1.544 | 208,944 → 184,672 | | `00daa26e` (4,497) | 2.829 → 2.059 | 4.104 → 2.763 | 320,056 → 261,652 | | `076191bb` (5,187) | 3.593 → 2.857 | 5.384 → 4.263 | 371,216 → 309,032 | | `0452488a` (10,753) | 8.717 → 6.718 | 8.584 → 5.293 | 552,296 → 432,420 | | `04fd77f7` (16,692) | 12.987 → 12.380 | 26.010 → 19.388 | 1,163,756 → 1,100,536 | | **Total** | **29.142 → 24.887** | **45.887 → 33.251** | **2,616,268 → 2,288,312** | Totals are sums of per-shader medians. DXC time fell **14.6%**, cold PSO creation time fell **27.5%**, and DXIL bytes fell **12.5%**. All five PSOs were faster. **Not tested** Native Windows, gameplay or shader execution correctness, and the full workspace suite. **AI use** — OpenAI Codex (GPT-6, exact variant unavailable) wrote the local benchmark example, ran the tests and prepared the report.
auswhalen999-debug commented 2026-11-24 19:07:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by auswhalen999-debug on 2026-11-24T18:54:26Z.


@pickles976 Thanks for the sharp review — followed through on all four points in 91ae2c6 (and updated the PR description + fresh xcl-smoke):

  1. Correctness artifact & gpu_compute_e2e: Clarified honestly that the 12-shader retail corpus measures compile time only (standalone retail CS need live title UMA/descriptors), and that gpu_compute_e2e ran and passed (4/4) in the workspace suite. Added two permanent GPU dispatch output-parity tests in crates/xcl/src/gpu/recomp/tests.rs:
    • gpu_opt_lane_local_mask_exec_restore_and_carry_parity (runs on both Wave32 and Wave64, testing s_and_saveexec -> v_cmp + s_or -> EXEC restore -> v_cndmask_b32 + 64-bit v_add_co -> v_add_co_ci with dead final carry-out, verifying bit-exact output on every lane and 0 ballot(and( on Wave32 / native Wave64).
    • gpu_opt_hoisted_smem_store_hazard_and_branchless_helpers_parity (real GPU dispatch verifying hoisted/subsumed s_load_*, grouped s_buffer_load_* partial OOB bounds, store-hazard non-hoisting across global_store_dword, branchless fma_legacy(0, NaN, 7), and constant mul_legacy(2.0, -0.0) == +0.0).
    • Full cargo test --workspace --release -- --test-threads=4 at 91ae2c6: 797 passed, 0 failed, 41 ignored.
  2. Convergence & hazard model in opt.rs: Documented the formal constraint explicitly in both the module header and analyze_lane_local_masks() — the pass never moves, hoists, or deduplicates WaveActiveBallot across CFG boundaries (strictly intra-block, dead at block exit !live_out_s[bi]), rejects any whole-mask/cross-lane consumer so lanebit(WaveActiveBallot(and(act, cond))) == and(act, cond) per lane identically, and sets needs_exec_mask = true whenever any EXEC-widening op can intervene between def and use.
  3. Plan B split seam: Noted in the PR body — happy to split opt.rs ahead of emit.rs/mod.rs as a 2-PR stack if maintainers prefer.
  4. #1524 cross-reference & zero conflict: Cross-referenced #1524 in the PR description and confirmed 0 lines of diff on #1524 commit 1's helpers (bits_at, put_bits, bvh_intersect, dst_sel, xcl_lv were intentionally left untouched so both PRs stack cleanly).

@nnonno91 Huge thanks for the independent AMD native-Wave64, mesh, XCL_HEAP_WINDOWS=1, and EXEC-restore output-parity verification — promoted that exact EXEC-restore scenario into the permanent gpu_opt_lane_local_mask_exec_restore_and_carry_parity test in 91ae2c6!

<!-- greyfinch-sync:ivall/xcl:comment:7141318303 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7141318303). Originally posted by [auswhalen999-debug](https://github.com/auswhalen999-debug) on 2026-11-24T18:54:26Z. --- @pickles976 Thanks for the sharp review — followed through on all four points in `91ae2c6` (and updated the PR description + fresh `xcl-smoke`): 1. **Correctness artifact & `gpu_compute_e2e`**: Clarified honestly that the 12-shader retail corpus measures compile time only (standalone retail CS need live title UMA/descriptors), and that `gpu_compute_e2e` ran and passed (4/4) in the workspace suite. Added two permanent GPU dispatch output-parity tests in `crates/xcl/src/gpu/recomp/tests.rs`: - `gpu_opt_lane_local_mask_exec_restore_and_carry_parity` (runs on both Wave32 and Wave64, testing `s_and_saveexec` -> `v_cmp` + `s_or` -> `EXEC` restore -> `v_cndmask_b32` + 64-bit `v_add_co` -> `v_add_co_ci` with dead final carry-out, verifying bit-exact output on every lane and 0 `ballot(and(` on Wave32 / native Wave64). - `gpu_opt_hoisted_smem_store_hazard_and_branchless_helpers_parity` (real GPU dispatch verifying hoisted/subsumed `s_load_*`, grouped `s_buffer_load_*` partial OOB bounds, store-hazard non-hoisting across `global_store_dword`, branchless `fma_legacy(0, NaN, 7)`, and constant `mul_legacy(2.0, -0.0) == +0.0`). - Full `cargo test --workspace --release -- --test-threads=4` at `91ae2c6`: **797 passed, 0 failed, 41 ignored**. 2. **Convergence & hazard model in `opt.rs`**: Documented the formal constraint explicitly in both the module header and `analyze_lane_local_masks()` — the pass never moves, hoists, or deduplicates `WaveActiveBallot` across CFG boundaries (strictly intra-block, dead at block exit `!live_out_s[bi]`), rejects any whole-mask/cross-lane consumer so `lanebit(WaveActiveBallot(and(act, cond))) == and(act, cond)` per lane identically, and sets `needs_exec_mask = true` whenever any `EXEC`-widening op can intervene between def and use. 3. **Plan B split seam**: Noted in the PR body — happy to split `opt.rs` ahead of `emit.rs`/`mod.rs` as a 2-PR stack if maintainers prefer. 4. **#1524 cross-reference & zero conflict**: Cross-referenced #1524 in the PR description and confirmed 0 lines of diff on #1524 commit 1's helpers (`bits_at`, `put_bits`, `bvh_intersect`, `dst_sel`, `xcl_lv` were intentionally left untouched so both PRs stack cleanly). @nnonno91 Huge thanks for the independent AMD native-Wave64, mesh, `XCL_HEAP_WINDOWS=1`, and EXEC-restore output-parity verification — promoted that exact EXEC-restore scenario into the permanent `gpu_opt_lane_local_mask_exec_restore_and_carry_parity` test in `91ae2c6`!
nnonno91 commented 2026-11-24 19:07:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by nnonno91 on 2026-11-24T18:37:39Z.


Independent AMD native-wave64 and mesh coverage at 17c02330d8b5a78c938a1cc52f04874e1fb9087a.

Tested

  • AMD Radeon(TM) Graphics (Ryzen 7 9800X3D integrated GPU, driver 32.0.21042.62), Windows 11 25H2 build 26200.9974, Rust 1.100.0 MSVC, SDK DXC 1.8.2502.11, debug. XCL_ADAPTER='AMD Radeon'.
  • cargo build --workspace --locked and cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --show-output completed. The suite reported 795 passed, 0 failed, 41 ignored. One GPU skip was counted among the passes (heap_window_out_of_memory_falls_back_to_the_switch_form, heap windows off in this run). The bundled title test passed.
  • With XCL_REQUIRE_GPU=wave64,mesh, cargo test --locked -p xcl --lib -- gpu_geometry_mode_es_gs_strip gpu_geometry_wave32_prefix_count_over_a_mask gpu_mesh_mode_two_passes gpu_wave32_program_in_wave64_hardware gpu::recomp::opt::tests gpu::recomp::emit::opt_helper_tests --test-threads=1 --show-output gave 23 passed, 0 failed, 0 ignored, 0 skips. All four GPU tests skipped in the GTX 1070 run executed here.
  • With XCL_HEAP_WINDOWS=1, cargo test --locked -p xcl --test gpu_compute_e2e -- --test-threads=1 --show-output gave 4 passed, 0 failed, 0 ignored, 0 skips. The log confirmed use of the shared descriptor heap and a rebuild in switch form after the test injected an out-of-memory result.
  • For an output check specific to the new lane-local lowering, I ran the same temporary synthetic compute test at the PR head and its base 9e3831e1f570d3646e53ab753b19ec07eb8f1485: cargo test --locked -p xcl --test lane_mask_probe -- --exact native_wave64_mask_survives_exec_restore --nocapture --test-threads=1 (one pass each, no skips). A native wave64 group enabled only lanes 0–39 with s_and_saveexec_b64, compared lane < 48 into VCC, restored EXEC and wrote each lane's v_cndmask_b32 result to memory. The PR emitted a lane-local boolean guarded by the pre-restore EXEC bit. Both builds matched all 64 expected outputs (2 for lanes 0–39 and 1 for lanes 40–63, including the eight restored lanes that would otherwise satisfy the compare).

Not tested

Retail shader output parity, retail title smoke, performance, or other GPUs in this run.

AI use

OpenAI Codex (GPT-6 family, exact variant unavailable) wrote the temporary probe, ran the checks, and drafted this report.

Follow-up at 91ae2c62e89f049f241df4fed3d47295f19f2793

Tested

  • Windows 11 25H2 build 26200.9974, Ryzen 7 9800X3D, AMD Radeon(TM) Graphics (32.0.21042.62) and RTX 5090 (617.42 / 32.0.16.1742), Rust 1.100.0 MSVC, SDK DXC 1.8.2502.11, unoptimized debug/test builds with debug info disabled. Selected each adapter with XCL_ADAPTER and used separate caches.
  • cargo build --workspace --locked passed. cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --show-output reported 797 passed, 0 failed, 41 ignored on each adapter. The bundled title passed on both. Both pass counts include heap_window_out_of_memory_falls_back_to_the_switch_form (heap windows off). NVIDIA also counted two native-wave64 skips (gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware).
  • cargo test --locked -p xcl --lib -- gpu_opt_lane_local_mask_exec_restore_and_carry_parity gpu_opt_hoisted_smem_store_hazard_and_branchless_helpers_parity --test-threads=1 --nocapture with XCL_REQUIRE_GPU=mesh gave 2 passed, 0 failed, 0 ignored, 0 skips on each adapter. The earlier EXEC-restore scenario now runs in the permanent tests. It checked the restored mask and carry output on wave32 and native wave64 on AMD, and wave32 and split wave64 on the RTX 5090.
  • A temporary adaptation of the new memory fixture ran the same shader down both branch paths using the two inputs for s1 at DXC -O0 and -O3. cargo test --locked -p xcl --test hoist_branch_probe -- --exact hoisted_loads_agree_on_both_branch_paths --test-threads=1 --nocapture passed once per adapter, with no skips. All eight dispatches returned the same six expected words, including zero for the out-of-bounds word and 0xDEADBEEF for the read after the store.

Not tested in this follow-up

Retail shader output parity, retail title smoke, performance, or the optional heap-window mode.

AI use

OpenAI Codex (GPT-6 family, exact variant unavailable) adapted the temporary memory probe, ran the checks, and drafted the update.

<!-- greyfinch-sync:ivall/xcl:comment:7140910249 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7140910249). Originally posted by [nnonno91](https://github.com/nnonno91) on 2026-11-24T18:37:39Z. --- Independent AMD native-wave64 and mesh coverage at `17c02330d8b5a78c938a1cc52f04874e1fb9087a`. **Tested** - AMD Radeon(TM) Graphics (Ryzen 7 9800X3D integrated GPU, driver 32.0.21042.62), Windows 11 25H2 build 26200.9974, Rust 1.100.0 MSVC, SDK DXC 1.8.2502.11, debug. `XCL_ADAPTER='AMD Radeon'`. - `cargo build --workspace --locked` and `cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --show-output` completed. The suite reported 795 passed, 0 failed, 41 ignored. One GPU skip was counted among the passes (`heap_window_out_of_memory_falls_back_to_the_switch_form`, heap windows off in this run). The bundled title test passed. - With `XCL_REQUIRE_GPU=wave64,mesh`, `cargo test --locked -p xcl --lib -- gpu_geometry_mode_es_gs_strip gpu_geometry_wave32_prefix_count_over_a_mask gpu_mesh_mode_two_passes gpu_wave32_program_in_wave64_hardware gpu::recomp::opt::tests gpu::recomp::emit::opt_helper_tests --test-threads=1 --show-output` gave 23 passed, 0 failed, 0 ignored, 0 skips. All four GPU tests skipped in the GTX 1070 run executed here. - With `XCL_HEAP_WINDOWS=1`, `cargo test --locked -p xcl --test gpu_compute_e2e -- --test-threads=1 --show-output` gave 4 passed, 0 failed, 0 ignored, 0 skips. The log confirmed use of the shared descriptor heap and a rebuild in switch form after the test injected an out-of-memory result. - For an output check specific to the new lane-local lowering, I ran the same temporary synthetic compute test at the PR head and its base `9e3831e1f570d3646e53ab753b19ec07eb8f1485`: `cargo test --locked -p xcl --test lane_mask_probe -- --exact native_wave64_mask_survives_exec_restore --nocapture --test-threads=1` (one pass each, no skips). A native wave64 group enabled only lanes 0–39 with `s_and_saveexec_b64`, compared `lane < 48` into VCC, restored EXEC and wrote each lane's `v_cndmask_b32` result to memory. The PR emitted a lane-local boolean guarded by the pre-restore EXEC bit. Both builds matched all 64 expected outputs (2 for lanes 0–39 and 1 for lanes 40–63, including the eight restored lanes that would otherwise satisfy the compare). **Not tested** Retail shader output parity, retail title smoke, performance, or other GPUs in this run. **AI use** OpenAI Codex (GPT-6 family, exact variant unavailable) wrote the temporary probe, ran the checks, and drafted this report. ### Follow-up at `91ae2c62e89f049f241df4fed3d47295f19f2793` **Tested** - Windows 11 25H2 build 26200.9974, Ryzen 7 9800X3D, AMD Radeon(TM) Graphics (32.0.21042.62) and RTX 5090 (617.42 / 32.0.16.1742), Rust 1.100.0 MSVC, SDK DXC 1.8.2502.11, unoptimized debug/test builds with debug info disabled. Selected each adapter with `XCL_ADAPTER` and used separate caches. - `cargo build --workspace --locked` passed. `cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --show-output` reported **797 passed, 0 failed, 41 ignored on each adapter**. The bundled title passed on both. Both pass counts include `heap_window_out_of_memory_falls_back_to_the_switch_form` (heap windows off). NVIDIA also counted two native-wave64 skips (`gpu_geometry_wave32_prefix_count_over_a_mask`, `gpu_wave32_program_in_wave64_hardware`). - `cargo test --locked -p xcl --lib -- gpu_opt_lane_local_mask_exec_restore_and_carry_parity gpu_opt_hoisted_smem_store_hazard_and_branchless_helpers_parity --test-threads=1 --nocapture` with `XCL_REQUIRE_GPU=mesh` gave **2 passed, 0 failed, 0 ignored, 0 skips** on each adapter. The earlier EXEC-restore scenario now runs in the permanent tests. It checked the restored mask and carry output on wave32 and native wave64 on AMD, and wave32 and split wave64 on the RTX 5090. - A temporary adaptation of the new memory fixture ran the same shader down both branch paths using the two inputs for `s1` at DXC `-O0` and `-O3`. `cargo test --locked -p xcl --test hoist_branch_probe -- --exact hoisted_loads_agree_on_both_branch_paths --test-threads=1 --nocapture` passed once per adapter, with no skips. All eight dispatches returned the same six expected words, including zero for the out-of-bounds word and `0xDEADBEEF` for the read after the store. **Not tested in this follow-up** Retail shader output parity, retail title smoke, performance, or the optional heap-window mode. **AI use** OpenAI Codex (GPT-6 family, exact variant unavailable) adapted the temporary memory probe, ran the checks, and drafted the update.
Flyander commented 2026-11-24 19:11:24 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Flyander on 2026-11-24T19:11:24Z.

Review: CHANGES_REQUESTED


One correctness issue needs a fix; see the inline comment.

AI use: OpenAI Codex (GPT-6; exact variant unavailable).

<!-- greyfinch-sync:ivall/xcl:review:6045664017 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#pullrequestreview-6045664017). Originally posted by [Flyander](https://github.com/Flyander) on 2026-11-24T19:11:24Z. **Review:** CHANGES_REQUESTED --- One correctness issue needs a fix; see the inline comment. AI use: OpenAI Codex (GPT-6; exact variant unavailable).
MatyEjsr commented 2026-11-24 21:09:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by MatyEjsr on 2026-11-24T20:12:19Z.


Independent verification and code review of PR #1630 at commit 17c02330d8b5a78c938a1cc52f04874e1fb9087a.

Environment

  • OS: Windows 11 Pro for Workstations 10.0.26200 (Build 26200)
  • CPU: AMD Ryzen 7 7800X3D (8 cores)
  • GPU: NVIDIA GeForce RTX 3090 (24322 MiB VRAM, driver 617.42 / 32.0.16.1742, Wave32, hardware mesh shaders supported)
  • RAM: 31.4 GB
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09) / cargo 1.100.0 (3acc79c0c 2026-11-05) stable-x86_64-pc-windows-msvc, debug build, DXC dxcompiler 1.9.2602.17 (21d28f72) / dxil 1.9.2602.17

Tested

  • cargo build --workspace -j 8: exit 0 (12.25s; only the 2 pre-existing Atomic::fetch_update deprecation warnings).
  • cargo test --workspace -j 8 -- --test-threads=8: 795 passed, 0 failed, 41 ignored (exit 0).
    • Explicit SKIPPED tests (counted as passed by libtest, not coverage):
      • gpu::recomp::tests::gpu_geometry_wave32_prefix_count_over_a_mask: no wave64
      • gpu::recomp::tests::gpu_wave32_program_in_wave64_hardware: no wave64
      • heap_window_out_of_memory_falls_back_to_the_switch_form: no heap windows
      • test_title_draws_with_a_root_signature_under_the_debug_layer: no d3d12SDKLayers.dll
      • Sample-gated tests skipped with XCL_SAMPLE_* unset.
  • Hardware mesh-shader GPU verification (not covered on the PR's GTX 1070 run):
    • XCL_REQUIRE_GPU=mesh cargo test -p xcl --lib -- gpu_mesh_mode_two_passes gpu_geometry_mode_es_gs_strip gpu_bench_really_runs --nocapture --test-threads=1: 3 passed, 0 failed, 0 ignored, 0 SKIPPED (0.35s). Both gpu_mesh_mode_two_passes and gpu_geometry_mode_es_gs_strip ran on hardware and passed.
  • Full workspace suite under XCL_HEAP_WINDOWS=1:
    • XCL_HEAP_WINDOWS=1 cargo test --workspace -j 8 -- --test-threads=8: 795 passed, 0 failed, 41 ignored (exit 0), 3 explicit skips (no wave64 x2, no d3d12SDKLayers.dll x1). heap_window_out_of_memory_falls_back_to_the_switch_form, gpu_raw_window_view_reaches_its_top, gpu_heap_windows_reject_out_of_uma_aliasing, and all 4 gpu_compute_e2e tests ran and passed with no device removal.
  • Merge check against current origin/main (c160d86, after #1426): git merge-tree --write-tree origin/main 17c02330d8b5a78c938a1cc52f04874e1fb9087a exits 0 with no conflicts.

Review notes

  • PR size / split: At +7,293 / -206 lines across 5 files in one commit, several pieces are largely independent (branchless prelude helpers and img_cls, early s_endpgm direct return / emit_range continue/break, conditional globallycoherent, NonUniformResourceIndex elision, entry io.Load pruning) and would be much cheaper to review and bisect if split into stacked PRs.
  • Dynamic soff on known_zero_hi_sload / known_zero_hi_sbuf (opt.rs:3007-3020, emit.rs:1726, emit.rs:1815-1821): in non-Kernel modes, known_zero_hi_sload accepts dynamic soff != 125 when imm_off >= 0 (and known_zero_hi_sbuf accepts any soff) and lowers to 32-bit addition against Window 0. Because a runtime soff is unbounded, an overflowing base_lo + soff wraps within Window 0 rather than carrying into hi >= 1. Restricting the 32-bit Window-0 fast path to constant offsets (soff == 125), or adding a carry guard for dynamic soff, avoids 32-bit wrap aliasing.
  • GPU parity tests for new passes: All 19 new tests (opt::tests and emit::opt_helper_tests) check static analysis metadata or Rust-side helper math; adding small GPU execution tests for hoisted SMEM/SBUF groups (switch and heap_windows), intra-block SBUF subsumption with partial OOB bounds, lane-local bool mask chains (including EXEC widening), and early s_endpgm under safe_barrier would directly exercise the emitted HLSL on hardware.

Not tested

  • AMD RDNA / Intel GPUs and native hardware Wave64 (gpu_wave32_program_in_wave64_hardware, gpu_geometry_wave32_prefix_count_over_a_mask).
  • D3D12 debug-layer e2e (d3d12SDKLayers.dll not installed on this host).
  • Release-mode test run, cold-PSO compile timings, XCL_SAMPLE_* tests, and retail title / smoke runs.

AI use

  • agy with gemini-4-neon-high: checked out commit 17c02330d8b5a78c938a1cc52f04874e1fb9087a, ran the build and workspace test suites (default, XCL_REQUIRE_GPU=mesh, and XCL_HEAP_WINDOWS=1), reviewed the diff, and wrote this report from the captured logs.
<!-- greyfinch-sync:ivall/xcl:comment:7143187409 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7143187409). Originally posted by [MatyEjsr](https://github.com/MatyEjsr) on 2026-11-24T20:12:19Z. --- Independent verification and code review of PR #1630 at commit `17c02330d8b5a78c938a1cc52f04874e1fb9087a`. **Environment** - OS: Windows 11 Pro for Workstations 10.0.26200 (Build 26200) - CPU: AMD Ryzen 7 7800X3D (8 cores) - GPU: NVIDIA GeForce RTX 3090 (24322 MiB VRAM, driver 617.42 / 32.0.16.1742, Wave32, hardware mesh shaders supported) - RAM: 31.4 GB - Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09) / cargo 1.100.0 (3acc79c0c 2026-11-05) stable-x86_64-pc-windows-msvc, debug build, DXC dxcompiler 1.9.2602.17 (21d28f72) / dxil 1.9.2602.17 **Tested** - `cargo build --workspace -j 8`: exit 0 (12.25s; only the 2 pre-existing `Atomic::fetch_update` deprecation warnings). - `cargo test --workspace -j 8 -- --test-threads=8`: **795 passed, 0 failed, 41 ignored** (exit 0). - Explicit `SKIPPED` tests (counted as passed by libtest, not coverage): - `gpu::recomp::tests::gpu_geometry_wave32_prefix_count_over_a_mask: no wave64` - `gpu::recomp::tests::gpu_wave32_program_in_wave64_hardware: no wave64` - `heap_window_out_of_memory_falls_back_to_the_switch_form: no heap windows` - `test_title_draws_with_a_root_signature_under_the_debug_layer: no d3d12SDKLayers.dll` - Sample-gated tests skipped with `XCL_SAMPLE_*` unset. - Hardware mesh-shader GPU verification (not covered on the PR's GTX 1070 run): - `XCL_REQUIRE_GPU=mesh cargo test -p xcl --lib -- gpu_mesh_mode_two_passes gpu_geometry_mode_es_gs_strip gpu_bench_really_runs --nocapture --test-threads=1`: **3 passed, 0 failed, 0 ignored, 0 SKIPPED** (0.35s). Both `gpu_mesh_mode_two_passes` and `gpu_geometry_mode_es_gs_strip` ran on hardware and passed. - Full workspace suite under `XCL_HEAP_WINDOWS=1`: - `XCL_HEAP_WINDOWS=1 cargo test --workspace -j 8 -- --test-threads=8`: **795 passed, 0 failed, 41 ignored** (exit 0), 3 explicit skips (`no wave64` x2, `no d3d12SDKLayers.dll` x1). `heap_window_out_of_memory_falls_back_to_the_switch_form`, `gpu_raw_window_view_reaches_its_top`, `gpu_heap_windows_reject_out_of_uma_aliasing`, and all 4 `gpu_compute_e2e` tests ran and passed with no device removal. - Merge check against current `origin/main` (`c160d86`, after #1426): `git merge-tree --write-tree origin/main 17c02330d8b5a78c938a1cc52f04874e1fb9087a` exits 0 with no conflicts. **Review notes** - **PR size / split**: At +7,293 / -206 lines across 5 files in one commit, several pieces are largely independent (branchless prelude helpers and `img_cls`, early `s_endpgm` direct `return` / `emit_range` `continue`/`break`, conditional `globallycoherent`, `NonUniformResourceIndex` elision, entry `io.Load` pruning) and would be much cheaper to review and bisect if split into stacked PRs. - **Dynamic `soff` on `known_zero_hi_sload` / `known_zero_hi_sbuf`** (`opt.rs:3007-3020`, `emit.rs:1726`, `emit.rs:1815-1821`): in non-`Kernel` modes, `known_zero_hi_sload` accepts dynamic `soff != 125` when `imm_off >= 0` (and `known_zero_hi_sbuf` accepts any `soff`) and lowers to 32-bit addition against Window 0. Because a runtime `soff` is unbounded, an overflowing `base_lo + soff` wraps within Window 0 rather than carrying into `hi >= 1`. Restricting the 32-bit Window-0 fast path to constant offsets (`soff == 125`), or adding a carry guard for dynamic `soff`, avoids 32-bit wrap aliasing. - **GPU parity tests for new passes**: All 19 new tests (`opt::tests` and `emit::opt_helper_tests`) check static analysis metadata or Rust-side helper math; adding small GPU execution tests for hoisted SMEM/SBUF groups (switch and `heap_windows`), intra-block SBUF subsumption with partial OOB bounds, lane-local `bool` mask chains (including `EXEC` widening), and early `s_endpgm` under `safe_barrier` would directly exercise the emitted HLSL on hardware. **Not tested** - AMD RDNA / Intel GPUs and native hardware Wave64 (`gpu_wave32_program_in_wave64_hardware`, `gpu_geometry_wave32_prefix_count_over_a_mask`). - D3D12 debug-layer e2e (`d3d12SDKLayers.dll` not installed on this host). - Release-mode test run, cold-PSO compile timings, `XCL_SAMPLE_*` tests, and retail title / smoke runs. **AI use** - agy with gemini-4-neon-high: checked out commit `17c02330d8b5a78c938a1cc52f04874e1fb9087a`, ran the build and workspace test suites (default, `XCL_REQUIRE_GPU=mesh`, and `XCL_HEAP_WINDOWS=1`), reviewed the diff, and wrote this report from the captured logs.
DavidM1911 commented 2026-11-24 21:09:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-24T20:46:44Z.


Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, ~22 ignored. (Intermittent single-test flake under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified main.)

Thanks!

<!-- greyfinch-sync:ivall/xcl:comment:7144043317 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7144043317). Originally posted by [DavidM1911](https://github.com/DavidM1911) on 2026-11-24T20:46:44Z. --- Verification on RTX 3060 Ti (Windows 11), branch merged with current `main`: - `cargo test -p xcl --lib`: all passed, 0 failed, ~22 ignored. (Intermittent single-test flake under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified `main`.) Thanks!
milesah3ad commented 2026-11-24 21:09:43 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by milesah3ad on 2026-11-24T20:52:35Z.


Native Windows Blackwell numbers for this head, on synthetic programs. Driver time and DXC time don't change for them. In the switch form, DXIL grows 15–27 % for the programs the optimizer changes, without costing the driver anything. The suite passes.

Setup: RTX 5080 16 GB, driver 621.24, Ryzen 7 9800X3D (16 threads), 64 GB, Windows 11 Pro 26300, rustc 1.100.0, DXC 1.9.2609.5. Head 91ae2c6 against its base 9e3831e, release for the probe, debug for the suite.

Tested

  • cargo build --workspace then cargo test --workspace --no-fail-fast -- --test-threads=4 on 91ae2c6: 797 passed, 0 failed, 41 ignored. SKIPPED: the two wave64-only tests, and heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows).
  • The nv680 synthetic compute programs (#680's probe: 128 threads, wave64 + split wave64, 4 memory windows; 5 shapes × 250 / 1000 rounds × 2 seeds), translated on both trees through translate at the runtime's DXC level. Then a cold CreateComputePipelineState per program in its own process, base and head alternating which goes first. New seeds, so no driver-cache hits.
form programs DXIL, base → head driver, base → head
switch (default) 20 9,842 → 10,994 KB (+11.7 %) 1,020.8 → 1,014.8 s (−0.6 %)
heap (XCL_HEAP_WINDOWS=1) 20 6,678 → 6,678 KB 224.3 → 221.4 s (−1.3 %)
  • Per program, the driver time is within −8 % … +3 % (noise level on this machine), and no shape moves as a group.
  • Byte-identical DXIL for every program with a memory atomic (atomic, atomic64, both forms). I'd expect that from mem_coherent turning off for them.
  • Switch form, base / loop / wave: DXIL +15 to +27 % (e.g. base 1000 rounds 592 → 746 KB, wave 975 → 1,129 KB). The HLSL is about 1 % smaller (globallycoherent off the four window buffers, select helpers), so the growth comes from DXC. The driver time for these is unchanged (1000-round means: 55.4 → 55.7 s, 72.1 → 70.2 s, 80.7 → 79.3 s).
  • DXC time: no change measured. Three alternating runs of atomic / base / wave at 1000 rounds, switch form: 15.9 → 15.4 s, 9.5 → 9.3 s, 21.0 → 21.5 s. (A first, non-alternating pass showed +29 %. That was drift from running all base programs first, so I'm not counting it.)

Reading: these shapes have none of the scalar loads, buffer loads, carry-outs or SDWA helpers this optimizer works on, so "no change" here doesn't contradict the GTX 1070 retail numbers. What they do show: on Blackwell, the optimizer doesn't cost driver time on programs it barely touches, and dropping globallycoherent in the switch form makes DXC's output noticeably bigger without making the driver slower.

Not tested

  • Retail programs or a title run; Ada / Ampere / AMD; the heap form with retail programs.
  • Whether the bigger switch-form DXIL comes from globallycoherent alone (I didn't bisect the emitter changes).

AI use

  • Claude Code (Claude Opus 5.5) ran the builds, tests and measurements and wrote this report; I checked the numbers against the logs.
<!-- greyfinch-sync:ivall/xcl:comment:7144174099 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7144174099). Originally posted by [milesah3ad](https://github.com/milesah3ad) on 2026-11-24T20:52:35Z. --- Native Windows Blackwell numbers for this head, on synthetic programs. Driver time and DXC time don't change for them. In the switch form, DXIL grows 15–27 % for the programs the optimizer changes, without costing the driver anything. The suite passes. **Setup:** RTX 5080 16 GB, driver 621.24, Ryzen 7 9800X3D (16 threads), 64 GB, Windows 11 Pro 26300, rustc 1.100.0, DXC 1.9.2609.5. Head `91ae2c6` against its base `9e3831e`, release for the probe, debug for the suite. **Tested** - `cargo build --workspace` then `cargo test --workspace --no-fail-fast -- --test-threads=4` on `91ae2c6`: **797 passed, 0 failed, 41 ignored**. SKIPPED: the two wave64-only tests, and `heap_window_out_of_memory_falls_back_to_the_switch_form` (no heap windows). - The [`nv680`](https://github.com/milesah3ad/xcl/blob/nv680-probe/crates/xcl/examples/nv680.rs) synthetic compute programs (#680's probe: 128 threads, wave64 + split wave64, 4 memory windows; 5 shapes × 250 / 1000 rounds × 2 seeds), translated on both trees through `translate` at the runtime's DXC level. Then a cold `CreateComputePipelineState` per program in its own process, base and head alternating which goes first. New seeds, so no driver-cache hits. | form | programs | DXIL, base → head | driver, base → head | |---|---|---:|---:| | switch (default) | 20 | 9,842 → 10,994 KB (**+11.7 %**) | 1,020.8 → 1,014.8 s (−0.6 %) | | heap (`XCL_HEAP_WINDOWS=1`) | 20 | 6,678 → 6,678 KB | 224.3 → 221.4 s (−1.3 %) | - Per program, the driver time is within −8 % … +3 % (noise level on this machine), and no shape moves as a group. - **Byte-identical DXIL** for every program with a memory atomic (`atomic`, `atomic64`, both forms). I'd expect that from `mem_coherent` turning off for them. - **Switch form, base / loop / wave: DXIL +15 to +27 %** (e.g. `base` 1000 rounds 592 → 746 KB, `wave` 975 → 1,129 KB). The HLSL is about 1 % smaller (`globallycoherent` off the four window buffers, `select` helpers), so the growth comes from DXC. The driver time for these is unchanged (1000-round means: 55.4 → 55.7 s, 72.1 → 70.2 s, 80.7 → 79.3 s). - **DXC time:** no change measured. Three alternating runs of `atomic` / `base` / `wave` at 1000 rounds, switch form: 15.9 → 15.4 s, 9.5 → 9.3 s, 21.0 → 21.5 s. (A first, non-alternating pass showed +29 %. That was drift from running all base programs first, so I'm not counting it.) **Reading:** these shapes have none of the scalar loads, buffer loads, carry-outs or SDWA helpers this optimizer works on, so "no change" here doesn't contradict the GTX 1070 retail numbers. What they do show: on Blackwell, the optimizer doesn't cost driver time on programs it barely touches, and dropping `globallycoherent` in the switch form makes DXC's output noticeably bigger without making the driver slower. **Not tested** - Retail programs or a title run; Ada / Ampere / AMD; the heap form with retail programs. - Whether the bigger switch-form DXIL comes from `globallycoherent` alone (I didn't bisect the emitter changes). **AI use** - Claude Code (Claude Opus 5.5) ran the builds, tests and measurements and wrote this report; I checked the numbers against the logs.
Flyander commented 2026-11-24 21:09:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Flyander on 2026-11-24T19:11:24Z.

Code review location: crates/xcl/src/gpu/recomp/opt.rs; line 3021

@@ -0,0 +1,5691 @@
+//! Program-level static analysis and optimization metadata for the RDNA2 → HLSL recompiler.
+//!
+//! Computes PC-keyed liveness, dead-flag / dead-carry / dead-instruction facts, exact CFG
+//! dominators, CFG-wide SGPR reaching definitions & constant values, memory-hazard reachability,
+//! dominator-hoisted / CSE'd invariant `s_load_*` & `s_buffer_load_*` groups (with known-zero-hi
+//! Window-0 fast path), universal non-`Kernel` known-zero-hi `s_load_*` / `s_buffer_load_*` sets,
+//! non-consecutive intra-block `s_buffer_load_*` grouping, Wave32 & native-Wave64 lane-local
+//! `bool` mask scalarization, intra-block constant propagation, and conditional
+//! `globallycoherent` eligibility.
+//!
+//! Soundness invariants enforced throughout:
+//! 1. **VGPR backward liveness under divergent `EXEC`**: every VGPR write is modeled as a
+//!    read-modify-write (`kill_v = EMPTY`), so dual-mask `if/else` writes never lose liveness.
+//! 2. **Dominator-hoisted `s_load_*` (`HoistedSmemGroup`) & `s_buffer_load_*` (`HoistedSbufGroup`)**:
+//!    - Requires unique dominating reaching definitions (`(def_lo, def_hi)` for `s[b:b+1]`, or
+//!      `(def_d0, def_d1, def_d2)` for `s[b..b+3]`) and zero writes to those base SGPRs on ANY
+//!      CFG path (including `LOOP_GUARD` exits & loop cycles) from hoist point `H` to every use `U`.
+//!    - Requires zero memory hazards (stores, atomics, `s_barrier`, cache inv/wb, `s_sendmsg`,
+//!      calls/indirect branches, `unknown_succ`) on ANY CFG path from `H` to every use `U`,
+//!      including loop-carried paths re-entering `U`.
+//!    - Never hoists or CSEs `GLC`/`DLC` loads.
+//!    - `known_hi == Some(0)` ONLY when the high base bits are statically proven `0` on all
+//!      reaching paths (`s[b+1] == 0` for `s_load_*`, `(s[b+1] & 0xFFFF) == 0` for
+//!      `s_buffer_load_*`), AND obeying the 4 GiB wrap guard: in `Mode::Kernel`, ONLY `s_load_*`
+//!      with `min_off == 0 && max_end <= 4`; in non-`Kernel` modes, full 21-bit SMEM range
+//!      (`[-1_048_576, 1_048_576]`; valid UMA allocations never straddle 4 GiB).
+//!    - Sub-range subsumption on `s_load_*` only when `parent.offset >= 0` (preventing
+//!      negative-offset underflow mismatch).
+//! 3. **Intra-block `s_buffer_load_*` (`IntraBlockSbufGroup`)**: constant-offset (`soff == None`)
+//!    only, `max_end - min_off <= 1_048_576` (and `max_span == 0` in `Mode::Kernel`), disjoint
+//!    from `HoistedSbufGroup`, splitting epochs on any memory hazard, `GLC`/`DLC` SMEM op, or
+//!    write to `sbase..sbase+3`; never uses `[loop]` or wrap-fallback switch duplication.
+//! 4. **Lane-local `bool` masks (`lane_local_*`) — Convergence & Hazard Model**:
+//!    - **Strictly intra-block (zero ballot motion)**: never moves, hoists, sinks, or deduplicates
+//!      any `WaveActiveBallot` across basic-block boundaries, branches, merges, or loops; every
+//!      scalarized def-use DAG is contained inside one basic block and must be dead at block exit
+//!      (`!live_out_s[bi]`).
+//!    - **Zero cross-lane observation (convergence-free replacement)**: disabled in `Mode::Kernel`
+//!      and `split_wave64`; scalarizes `V_CMP_*` (non-`CMPX`), `V_ADD/SUB*_CO*_U32`, and dead-`scc`
+//!      bitwise SALU chains (`S_AND/OR/XOR/NOT/ANDN2/ORN2/NAND/NOR/XNOR/MOV`) only when every
+//!      consumer reads solely its own lane bit (`V_CNDMASK_B32` mask slot, `V_ADD/SUB*_CO_CI_U32`
+//!      carry-in slot, or another valid lane-local bitwise op). Any whole-mask consumer
+//!      (`S_CBRANCH_VCC*`, `S_BCNT*`, `S_FF*`, `EXEC` updates, scalar ALU data operands, memory
+//!      operands, or unknown/indirect ops) rejects the entire chain. Because lane `i` only ever
+//!      reads bit `i` of its own lane's ballot, `lanebit(WaveActiveBallot(and(act, cond)))` is
+//!      identically `and(act, cond)` per lane with zero cross-lane convergence semantics to preserve.
+//!    - **Divergent `EXEC` & widening guard (`needs_exec_mask`)**: if any `EXEC`-widening op
+//!      (`is_exec_widening`, e.g., `s_mov`/`s_or`/`s_xor`/`s_not`/`s_nand`/`s_nor`/`s_xnor` to
+//!      `exec`, `s_wqm`, `s_andn2_saveexec`) executes between a def and its last consumer in the
+//!      block, `needs_exec_mask = true` captures `and(act, cond)` at the def site so lanes disabled
+//!      at def remain `false` after `EXEC` is later restored.
+//! 5. **Dead `vcc`/carry `sdst`**: for `wave64`, both `n` and `n+1` must be dead; for wave32,
+//!    only `n` must be dead; `Null` (`125` or `> 127`) is always dead. Carry-in reads on
+//!    `v_add_co_ci*`/`v_sub*_co_ci*` are always preserved.
+//! 6. **`Mode::Kernel` epilogue**: all SGPRs, VGPRs, and `scc` are seeded live at `s_endpgm`.
+//! 7. **Unknown / indirect ops**: conservatively mark all registers live/read and restrict
+//!    hoisting to intra-block only.
+//! 8. **Conditional `mem_coherent`**: false only when zero `GLC`/`DLC`/`SLC`, zero memory
+//!    atomics, zero cache inv/wb ops, and `!(has_s_barrier && has_mem_store)`.
+
+use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
+
+use super::emit::ext_encoding;
+use super::{Mode, Options};
+use crate::gpu::rdna2::{self, Decoded, Operand, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR};
+
+/// SGPR bitset: bit `n` = `s<n>` (0..=105 plain, 106/107 VCC, 108..=123 ttmp, 124 M0, 126/127 EXEC).
+type SRegs = u128;
+
+const S_VCC_LO: SRegs = 1u128 << 106;
+const S_VCC: SRegs = 3u128 << 106;
+const S_M0: SRegs = 1u128 << 124;
+const S_EXEC: SRegs = 3u128 << 126;
+const S_ALL: SRegs = !0u128;
+const S_PLAIN_MASK: SRegs = (1u128 << 106) - 1;
+
+#[inline]
+fn sreg_range(first: u64, n: u64) -> SRegs {
+    if first >= 128 || n == 0 {
+        return 0;
+    }
+    let end = (first + n).min(128);
+    let mut m = 0u128;
+    for r in first..end {
+        if r != 125 {
+            m |= 1u128 << r;
+        }
+    }
+    m
+}
+
+/// 256-bit VGPR set (`v0..=v255`).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct VRegs([u64; 4]);
+
+impl VRegs {
+    const EMPTY: Self = Self([0; 4]);
+    const ALL: Self = Self([!0u64; 4]);
+
+    #[inline]
+    fn set(&mut self, r: u64) {
+        if r < 256 {
+            self.0[(r >> 6) as usize] |= 1u64 << (r & 63);
+        }
+    }
+
+    #[inline]
+    fn set_range(&mut self, first: u64, n: u64) {
+        let end = (first + n).min(256);
+        for r in first..end {
+            self.set(r);
+        }
+    }
+
+    #[inline]
+    fn union(self, other: Self) -> Self {
+        Self([
+            self.0[0] | other.0[0],
+            self.0[1] | other.0[1],
+            self.0[2] | other.0[2],
+            self.0[3] | other.0[3],
+        ])
+    }
+
+    #[inline]
+    fn intersect(self, other: Self) -> Self {
+        Self([
+            self.0[0] & other.0[0],
+            self.0[1] & other.0[1],
+            self.0[2] & other.0[2],
+            self.0[3] & other.0[3],
+        ])
+    }
+
+    #[inline]
+    fn is_empty(self) -> bool {
+        (self.0[0] | self.0[1] | self.0[2] | self.0[3]) == 0
+    }
+}
+
+/// One deduplicated load entry inside a `HoistedSmemGroup` or `IntraBlockSbufGroup`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct HoistedLoad {
+    /// Dword-aligned byte offset relative to `sbase` (signed 21-bit for `s_load_*`,
+    /// unsigned 21-bit for `s_buffer_load_*`).
+    pub offset: i64,
+    /// Number of dwords loaded (`1`, `2`, `4`, `8`, or `16`).
+    pub count: u8,
+}
+
+/// Dominator-hoisted / CSE'd group of invariant `s_load_dword*` ops sharing the exact same
+/// 64-bit base pointer `s[sbase:sbase+1]` in a memory-hazard-free dominated region.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct HoistedSmemGroup {
+    /// Unique group id (`0..N`) used for HLSL temp naming (`sm_g{id}_{uid}`).
+    pub id: u32,
+    /// Block `start_pc` of the dominator hoist block `H`.
+    #[allow(dead_code)]
+    pub hoist_block: u64,
+    /// Base SGPR pair start index (`s[sbase:sbase+1]`, always `< 105`).
+    pub sbase: u8,
+    /// Statically proven `Some(0)` ONLY when `s[sbase+1] == 0` on all reaching paths AND
+    /// wrap-safe (`Mode::Kernel`: `min_off == 0 && max_end <= 4`; non-`Kernel`: `[-1_048_576, 1_048_576]`).
+    /// Note: ONLY `hi == 0` maps unconditionally to Window 0 regardless of runtime `xcl_uma_base`.
+    pub known_hi: Option<u32>,
+    /// Minimum byte offset across all `loads`.
+    #[allow(dead_code)]
+    pub min_off: i64,
+    /// Maximum end byte offset (`offset + 4 * count`) across all `loads`.
+    #[allow(dead_code)]
+    pub max_end: i64,
+    /// Deduplicated loads in this group (`1..=96`), sorted by `(offset, count)`.
+    pub loads: Vec<HoistedLoad>,
+}
+
+/// Maps a dominated `s_load_dword*` PC to its pre-loaded temp inside a `HoistedSmemGroup`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct SmemUse {
+    /// `HoistedSmemGroup::id`.
+    pub group_id: u32,
+    /// Index into `HoistedSmemGroup::loads` (`0..loads.len()`).
+    pub load_idx: u16,
+    /// `HoistedSmemGroup::loads[load_idx].count` (`1`, `2`, `4`, `8`, or `16`).
+    pub parent_count: u8,
+    /// Sub-dword offset inside the parent load (`0` for exact match; `> 0` if subsumed).
+    pub dword_offset: u8,
+    /// Number of dwords to copy into `s[sdata..sdata+count]`.
+    pub count: u8,
+}
+
+/// Dominator-hoisted / CSE'd cross-block group of invariant constant-offset (`SOFFSET == 125`)
+/// `s_buffer_load_dword*` ops sharing the exact same V# descriptor dwords `s[sbase..sbase+3]`
+/// (`d0, d1, d2`) in a memory-hazard-free dominated region.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct HoistedSbufGroup {
+    /// Unique group id (`0..N`) used for HLSL temp naming (`sbh_g{id}_{uid}`).
+    pub id: u32,
+    /// Block `start_pc` of the dominator hoist block `H`.
+    #[allow(dead_code)]
+    pub hoist_block: u64,
+    /// Base 4-SGPR descriptor start index (`s[sbase..sbase+3]` read; always `sbase + 4 <= 106`).
+    pub sbase: u8,
+    /// Statically proven `Some(0)` ONLY when non-`Kernel` AND `(const_d1 & 0xFFFF) == 0`.
+    pub known_hi: Option<u32>,
+    /// Minimum unsigned byte offset across all `loads`.
+    #[allow(dead_code)]
+    pub min_off: i64,
+    /// Maximum end byte offset (`offset + 4 * count`) across all `loads`.
+    #[allow(dead_code)]
+    pub max_end: i64,
+    /// Deduplicated loads in this group (`1..=96`), sorted by `(offset, count)`.
+    pub loads: Vec<HoistedLoad>,
+}
+
+/// Non-consecutive intra-block group of constant-offset (`soff == None`) `s_buffer_load_dword*`
+/// ops sharing the same V# descriptor `s[sbase..sbase+3]` within a hazard-free, base-unmodified
+/// epoch of one basic block. Emitted at `first_pc` under ONE zero-loop switch (or 0 switches when
+/// `known_hi == Some(0)`).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct IntraBlockSbufGroup {
+    /// Unique group id (`0..N`) used for HLSL temp naming (`sb_g{id}_{uid}`).
+    pub id: u32,
+    /// PC of the first `s_buffer_load_*` instruction in this group (where the group executes).
+    pub first_pc: u64,
+    /// Base 4-SGPR descriptor start index (`s[sbase..sbase+4]`, always `<= 102`).
+    pub sbase: u8,
+    /// Shared dynamic SGPR offset (guaranteed `None` in `opt_v3` to avoid switch-doubling fallbacks).
+    pub soff: Option<u8>,
+    /// Statically proven `Some(0)` ONLY when non-`Kernel` AND `(const_d1 & 0xFFFF) == 0`.
+    pub known_hi: Option<u32>,
+    /// Minimum unsigned byte offset across all `loads`.
+    #[allow(dead_code)]
+    pub min_off: i64,
+    /// Maximum end byte offset (`offset + 4 * count`) across all `loads`.
+    #[allow(dead_code)]
+    pub max_end: i64,
+    /// Deduplicated loads in this group (`1..=96`), sorted by `(offset, count)`.
+    pub loads: Vec<HoistedLoad>,
+}
+
+/// Maps a member `s_buffer_load_dword*` PC to its pre-loaded temp inside a `HoistedSbufGroup`
+/// or `IntraBlockSbufGroup`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct SbufUse {
+    /// `IntraBlockSbufGroup::id`.
+    pub group_id: u32,
+    /// Index into `IntraBlockSbufGroup::loads` (`0..loads.len()`).
+    pub load_idx: u16,
+    /// `IntraBlockSbufGroup::loads[load_idx].count` (`1`, `2`, `4`, `8`, or `16`).
+    pub parent_count: u8,
+    /// Sub-dword offset inside the parent load (`0` for exact match; `> 0` if subsumed).
+    pub dword_offset: u8,
+    /// Number of dwords to copy into `s[sdata..sdata+count]`.
+    pub count: u8,
+}
+
+/// Kind of VALU/VOPC instruction defining a lane-local `bool` mask.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[allow(dead_code)]
+pub(crate) enum LaneLocalDefKind {
+    Cmp,
+    CarryOut,
+}
+
+/// Metadata for a `V_CMP_*` or `V_ADD/SUB*_CO*_U32` whose mask output is strictly lane-local.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct LaneLocalDef {
+    /// Unique `bool ml_{id}` variable identifier (declared inline at this def PC).
+    pub id: u32,
+    /// `true` iff an `EXEC`-widening op intervenes before a consumer (`and(act, (cond))`);
+    /// `false` => bare `(cond)` with zero `WaveActiveBallot` and zero `lanebit(exec)`.
+    pub needs_exec_mask: bool,
+    #[allow(dead_code)]
+    pub kind: LaneLocalDefKind,
+}
+
+/// Operand of a lane-local bitwise SALU instruction.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum LaneLocalOperand {
+    /// Another lane-local `bool ml_{id}` defined earlier in the same block.
+    Local(u32),
+    /// Current lane's `EXEC` bit (`act`).
+    Exec,
+    /// Constant `false` (`0`) or `true` (`-1` / all-1s).
+    Const(bool),
+    /// Plain SGPR or VCC mask register (`lanebit(s{r}, 0u)` in wave32, `lanebit(s{r}, s{r+1})` in wave64).
+    Sgpr(u8),
+}
+
+/// Logical operation for a lane-local bitwise SALU instruction.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum LaneLocalBitOp {
+    Mov,
+    Not,
+    And,
+    Or,
+    Xor,
+    Andn2,
+    Orn2,
+    Nand,
+    Nor,
+    Xnor,
+}
+
+/// Metadata for a dead-`scc` bitwise SALU instruction operating on lane-local `bool` masks.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct LaneLocalBitwise {
+    /// Unique `bool ml_{dst_id}` variable identifier defined by this instruction.
+    pub dst_id: u32,
+    pub op: LaneLocalBitOp,
+    pub src0: LaneLocalOperand,
+    /// `None` for `Mov` / `Not`, `Some` for binary bitwise ops.
+    pub src1: Option<LaneLocalOperand>,
+}
+
+/// Program-level analysis results consumed by `emit.rs` and `mod.rs`.
+#[derive(Debug)]
+pub(crate) struct ProgramOpt {
+    /// Guardrail #8: true iff Compute `mem..mem3` MUST keep `globallycoherent`.
+    /// False ONLY when ALL 4 hold: zero `GLC`/`DLC`/`SLC` ops, zero memory atomics,
+    /// zero cache-invalidate/writeback ops, and `!(has_s_barrier && has_mem_store)`.
+    pub mem_coherent: bool,
+    /// Weapon 1A: all dominator-hoisted / CSE'd invariant `s_load_*` groups.
+    hoisted_smem_groups: Vec<HoistedSmemGroup>,
+    hoisted_smem_at_entry: HashMap<u64, Vec<usize>>,
+    hoisted_smem_before: HashMap<u64, Vec<usize>>,
+    hoisted_smem_after: HashMap<u64, Vec<usize>>,
+    smem_uses: HashMap<u64, SmemUse>,
+    /// Weapon 1A-sbuf: cross-block dominator-hoisted / CSE'd invariant `s_buffer_load_*` groups.
+    hoisted_sbuf_groups: Vec<HoistedSbufGroup>,
+    hoisted_sbuf_at_entry: HashMap<u64, Vec<usize>>,
+    hoisted_sbuf_before: HashMap<u64, Vec<usize>>,
+    hoisted_sbuf_after: HashMap<u64, Vec<usize>>,
+    hoisted_sbuf_uses: HashMap<u64, SbufUse>,
+    /// Universal non-`Kernel` `s_load_dword*` PCs with statically proven `s[sbase+1] == 0`.
+    known_zero_hi_sload: HashSet<u64>,
+    /// Universal non-`Kernel` `s_buffer_load_dword*` PCs with statically proven `(s[sbase+1] & 0xFFFF) == 0`.
+    known_zero_hi_sbuf: HashSet<u64>,
+    /// Weapon 1B: non-consecutive intra-block `s_buffer_load_*` groups keyed by `first_pc`.
+    intra_block_sbuf_groups: HashMap<u64, IntraBlockSbufGroup>,
+    sbuf_uses: HashMap<u64, SbufUse>,
+    /// Weapon 3: Wave32 & native-Wave64 lane-local `bool` mask scalarization.
+    lane_local_defs: HashMap<u64, LaneLocalDef>,
+    lane_local_bitwise: HashMap<u64, LaneLocalBitwise>,
+    lane_local_uses: HashMap<u64, u32>,
+    dead_scc: HashSet<u64>,
+    dead_carry_sdst: HashSet<u64>,
+    dead_inst: HashSet<u64>,
+    const_srcs: HashMap<u64, [Option<u32>; 3]>,
+    const_sgprs: HashMap<(u64, u8), u32>,
+}
+
+impl Default for ProgramOpt {
+    fn default() -> Self {
+        Self {
+            mem_coherent: true,
+            hoisted_smem_groups: Vec::new(),
+            hoisted_smem_at_entry: HashMap::new(),
+            hoisted_smem_before: HashMap::new(),
+            hoisted_smem_after: HashMap::new(),
+            smem_uses: HashMap::new(),
+            hoisted_sbuf_groups: Vec::new(),
+            hoisted_sbuf_at_entry: HashMap::new(),
+            hoisted_sbuf_before: HashMap::new(),
+            hoisted_sbuf_after: HashMap::new(),
+            hoisted_sbuf_uses: HashMap::new(),
+            known_zero_hi_sload: HashSet::new(),
+            known_zero_hi_sbuf: HashSet::new(),
+            intra_block_sbuf_groups: HashMap::new(),
+            sbuf_uses: HashMap::new(),
+            lane_local_defs: HashMap::new(),
+            lane_local_bitwise: HashMap::new(),
+            lane_local_uses: HashMap::new(),
+            dead_scc: HashSet::new(),
+            dead_carry_sdst: HashSet::new(),
+            dead_inst: HashSet::new(),
+            const_srcs: HashMap::new(),
+            const_sgprs: HashMap::new(),
+        }
+    }
+}
+
+impl ProgramOpt {
+    /// True iff `scc` written by the instruction at `pc` is overwritten on all paths before any read.
+    pub(crate) fn is_dead_scc(&self, pc: u64) -> bool {
+        self.dead_scc.contains(&pc)
+    }
+
+    /// True iff carry/mask `sdst` of the instruction at `pc` is `Null` or provably dead before any read.
+    pub(crate) fn is_dead_carry_sdst(&self, pc: u64) -> bool {
+        self.dead_carry_sdst.contains(&pc)
+    }
+
+    /// True iff the instruction at `pc` is a pure register-only ALU/mov/cmp with no live outputs or side effects.
+    pub(crate) fn is_dead_inst(&self, pc: u64) -> bool {
+        self.dead_inst.contains(&pc)
+    }
+
+    /// Known 32-bit raw bit value of input operand `idx` (`0..3`, in `Em::ops` input order) at `pc`.
+    pub(crate) fn const_src(&self, pc: u64, idx: usize) -> Option<u32> {
+        if idx >= 3 {
+            return None;
+        }
+        self.const_srcs.get(&pc).and_then(|arr| arr[idx])
+    }
+
+    /// Known 32-bit raw bit value of SGPR `sgpr` (read by the instruction at `pc`) from constant propagation.
+    #[allow(dead_code)]
+    pub(crate) fn const_sgpr(&self, pc: u64, sgpr: u64) -> Option<u32> {
+        if sgpr >= 106 {
+            return None;
+        }
+        self.const_sgprs.get(&(pc, sgpr as u8)).copied()
+    }
+
+    /// All dominator-hoisted / CSE'd invariant `s_load_*` groups (for declaring `sm_g{id}_{uid}` at `main()` scope).
+    pub(crate) fn hoisted_smem_groups(&self) -> &[HoistedSmemGroup] {
+        &self.hoisted_smem_groups
+    }
+
+    /// Indices into `hoisted_smem_groups()` to emit at the entry of block `start_pc` (before block instructions).
+    pub(crate) fn hoisted_smem_at_block_entry(&self, start_pc: u64) -> &[usize] {
+        self.hoisted_smem_at_entry.get(&start_pc).map(Vec::as_slice).unwrap_or(&[])
+    }
+
+    /// Indices into `hoisted_smem_groups()` to emit immediately BEFORE instruction `pc` (even if `pc` is `dead_inst`).
+    pub(crate) fn hoisted_smem_before_pc(&self, pc: u64) -> &[usize] {
+        self.hoisted_smem_before.get(&pc).map(Vec::as_slice).unwrap_or(&[])
+    }
+
+    /// Indices into `hoisted_smem_groups()` to emit immediately AFTER instruction `pc` (never on a terminator).
+    pub(crate) fn hoisted_smem_after_pc(&self, pc: u64) -> &[usize] {
+        self.hoisted_smem_after.get(&pc).map(Vec::as_slice).unwrap_or(&[])
+    }
+
+    /// Dominated `s_load_*` instruction replaced by a copy from a hoisted `sm_g{group_id}_{load_idx}` temp.
+    pub(crate) fn smem_use(&self, pc: u64) -> Option<SmemUse> {
+        self.smem_uses.get(&pc).copied()
+    }
+
+    /// True iff `pc` is a non-`Kernel` `s_load_dword*` whose high base SGPR `s[sbase+1]` is
+    /// statically proven `0` (and offset is within the safe UMA Window-0 fast-path range).
+    pub(crate) fn is_known_zero_hi_sload(&self, pc: u64) -> bool {
+        self.known_zero_hi_sload.contains(&pc)
+    }
+
+    /// True iff `pc` is a non-`Kernel` `s_buffer_load_dword*` whose descriptor word 1 has
+    /// statically proven `(s[sbase+1] & 0xFFFF) == 0` (Window-0 fast path on UMA).
+    pub(crate) fn is_known_zero_hi_sbuf(&self, pc: u64) -> bool {
+        self.known_zero_hi_sbuf.contains(&pc)
+    }
+
+    /// All dominator-hoisted / CSE'd cross-block invariant `s_buffer_load_*` groups (for declaring
+    /// `sbh_g{id}_{uid}` at `main()` scope).
+    pub(crate) fn hoisted_sbuf_groups(&self) -> &[HoistedSbufGroup] {
+        &self.hoisted_sbuf_groups
+    }
+
+    /// Indices into `hoisted_sbuf_groups()` to emit at the entry of block `start_pc`.
+    pub(crate) fn hoisted_sbuf_at_block_entry(&self, start_pc: u64) -> &[usize] {
+        self.hoisted_sbuf_at_entry.get(&start_pc).map(Vec::as_slice).unwrap_or(&[])
+    }
+
+    /// Indices into `hoisted_sbuf_groups()` to emit immediately BEFORE instruction `pc`.
+    pub(crate) fn hoisted_sbuf_before_pc(&self, pc: u64) -> &[usize] {
+        self.hoisted_sbuf_before.get(&pc).map(Vec::as_slice).unwrap_or(&[])
+    }
+
+    /// Indices into `hoisted_sbuf_groups()` to emit immediately AFTER instruction `pc` (never on a terminator).
+    pub(crate) fn hoisted_sbuf_after_pc(&self, pc: u64) -> &[usize] {
+        self.hoisted_sbuf_after.get(&pc).map(Vec::as_slice).unwrap_or(&[])
+    }
+
+    /// Dominated `s_buffer_load_*` instruction replaced by a copy from a hoisted `sbh_g{group_id}_{load_idx}` temp.
+    pub(crate) fn hoisted_sbuf_use(&self, pc: u64) -> Option<SbufUse> {
+        self.hoisted_sbuf_uses.get(&pc).copied()
+    }
+
+    /// Non-consecutive intra-block `s_buffer_load_*` group starting at `first_pc`, if any.
+    pub(crate) fn intra_block_sbuf_group(&self, first_pc: u64) -> Option<&IntraBlockSbufGroup> {
+        self.intra_block_sbuf_groups.get(&first_pc)
+    }
+
+    /// Member `s_buffer_load_*` instruction replaced by a copy from `sb_g{group_id}_{load_idx}`.
+    pub(crate) fn sbuf_use(&self, pc: u64) -> Option<SbufUse> {
+        self.sbuf_uses.get(&pc).copied()
+    }
+
+    /// Lane-local `bool ml_{id}` definition for a `V_CMP_*` or `V_ADD/SUB*_CO*_U32` at `pc`.
+    pub(crate) fn lane_local_def(&self, pc: u64) -> Option<LaneLocalDef> {
+        self.lane_local_defs.get(&pc).copied()
+    }
+
+    /// Lane-local `bool ml_{dst_id}` bitwise SALU op at `pc`.
+    pub(crate) fn lane_local_bitwise(&self, pc: u64) -> Option<LaneLocalBitwise> {
+        self.lane_local_bitwise.get(&pc).copied()
+    }
+
+    /// Lane-local `bool ml_{id}` mask consumer (`V_CNDMASK_B32` or `V_ADD/SUB*_CO_CI_U32`) at `pc`.
+    pub(crate) fn lane_local_use(&self, pc: u64) -> Option<u32> {
+        self.lane_local_uses.get(&pc).copied()
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum CarryDst {
+    Null,
+    Sgpr(u64),
+}
+
+#[derive(Clone, Debug)]
+struct InstInfo {
+    s_read: SRegs,
+    s_kill: SRegs,
+    s_mod: SRegs,
+    scc_read: bool,
+    scc_write: bool,
+    v_read: VRegs,
+    v_mod: VRegs,
+    carry_sdst: Option<CarryDst>,
+    pure_eliminable: bool,
+    exec_widen: bool,
+    indirect_sgpr: bool,
+    indirect_vgpr: bool,
+}
+
+#[inline]
+fn fval(d: &Decoded, field: &str) -> u64 {
+    rdna2::field_value(d.enc, &d.words, field).unwrap_or(0)
+}
+
+#[inline]
+fn scaled_field(d: &Decoded, field: &str) -> u64 {
+    fval(d, field) * rdna2::register_scale(field)
+}
+
+/// Same explicit-operand partition as `Em::ops(d)` in `emit.rs`.
+fn explicit_ops(d: &Decoded) -> (Vec<&'static Operand>, Vec<&'static Operand>) {
+    let mut outs = Vec::new();
+    let mut ins = Vec::new();
+    for o in d.ienc.operands {
+        if o.implicit && !(o.field.is_none() && o.ty == "OPR_VCC") {
+            continue;
+        }
+        if o.output {
+            outs.push(o);
+        } else if o.input {
+            ins.push(o);
+        }
+    }
+    (outs, ins)
+}
+
+fn scalar_code_regs(code: u64, n: u64, wave64: bool) -> (SRegs, bool) {
+    match code {
+        251 => (if wave64 { S_VCC } else { S_VCC_LO }, false),
+        252 => (S_EXEC, false),
+        253 => (0, true),
+        125 => (0, false),
+        v if v <= 127 => (sreg_range(v, n), false),
+        _ => (0, false),
+    }
+}
+
+fn inline_const_bits(code: u64, literal: Option<u32>, f16: bool) -> Option<u32> {
+    Some(match code {
+        125 => 0,
+        128..=192 => (code - 128) as u32,
+        193..=208 => (-((code - 192) as i32)) as u32,
+        235..=238 => 0,
+        239 => 0x7FFF_FFFF,
+        240..=248 => {
+            if f16 {
+                match code {
+                    240 => 0x3800,
+                    241 => 0xB800,
+                    242 => 0x3C00,
+                    243 => 0xBC00,
+                    244 => 0x4000,
+                    245 => 0xC000,
+                    246 => 0x4400,
+                    247 => 0xC400,
+                    248 => 0x3118,
+                    _ => return None,
+                }
+            } else {
+                match code {
+                    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 => 0.159_154_94f32.to_bits(),
+                    _ => return None,
+                }
+            }
+        }
+        255 => literal?,
+        _ => return None,
+    })
+}
+
+fn is_valid_cmp_suffix(s: &str) -> bool {
+    matches!(
+        s,
+        "eq_i32"
+            | "lg_i32"
+            | "gt_i32"
+            | "ge_i32"
+            | "lt_i32"
+            | "le_i32"
+            | "eq_u32"
+            | "lg_u32"
+            | "gt_u32"
+            | "ge_u32"
+            | "lt_u32"
+            | "le_u32"
+    )
+}
+
+fn salu_writes_scc(enc: &str, name: &str) -> bool {
+    if enc == "ENC_SOPC" {
+        return true;
+    }
+    if enc == "ENC_SOPK" {
+        return name == "S_ADDK_I32" || name.starts_with("S_CMPK_");
+    }
+    if name.contains("SAVEEXEC") || name.contains("WREXEC") {
+        return true;
+    }
+    matches!(
+        name,
+        "S_NOT_B32"
+            | "S_BCNT0_I32_B32"
+            | "S_BCNT1_I32_B32"
+            | "S_ABS_I32"
+            | "S_AND_B32"
+            | "S_OR_B32"
+            | "S_XOR_B32"
+            | "S_ANDN2_B32"
+            | "S_ORN2_B32"
+            | "S_NAND_B32"
+            | "S_NOR_B32"
+            | "S_XNOR_B32"
+            | "S_ADD_U32"
+            | "S_SUB_U32"
+            | "S_ADDC_U32"
+            | "S_SUBB_U32"
+            | "S_ADD_I32"
+            | "S_SUB_I32"
+            | "S_LSHL_B32"
+            | "S_LSHR_B32"
+            | "S_ASHR_I32"
+            | "S_LSHL1_ADD_U32"
+            | "S_LSHL2_ADD_U32"
+            | "S_LSHL3_ADD_U32"
+            | "S_LSHL4_ADD_U32"
+            | "S_BFE_U32"
+            | "S_BFE_I32"
+            | "S_MIN_U32"
+            | "S_MAX_U32"
+            | "S_MIN_I32"
+            | "S_MAX_I32"
+            | "S_WQM_B32"
+            | "S_ABSDIFF_I32"
+            | "S_NOT_B64"
+            | "S_WQM_B64"
+            | "S_BCNT1_I32_B64"
+            | "S_BCNT0_I32_B64"
+            | "S_LSHL_B64"
+            | "S_LSHR_B64"
+            | "S_ASHR_I64"
+            | "S_BFE_U64"
+            | "S_BFE_I64"
+            | "S_AND_B64"
+            | "S_OR_B64"
+            | "S_XOR_B64"
+            | "S_ANDN2_B64"
+            | "S_ORN2_B64"
+            | "S_NAND_B64"
+            | "S_NOR_B64"
+            | "S_XNOR_B64"
+    )
+}
+
+fn is_supported_salu(enc: &str, name: &str) -> bool {
+    match enc {
+        "ENC_SOPK" => {
+            matches!(name, "S_MOVK_I32" | "S_CMOVK_I32" | "S_ADDK_I32" | "S_MULK_I32")
+                || name
+                    .strip_prefix("S_CMPK_")
+                    .is_some_and(|rest| is_valid_cmp_suffix(&rest.to_ascii_lowercase()))
+        }
+        "ENC_SOPC" => {
+            matches!(
+                name,
+                "S_BITCMP0_B64" | "S_BITCMP1_B64" | "S_BITCMP0_B32" | "S_BITCMP1_B32" | "S_CMP_EQ_U64" | "S_CMP_LG_U64"
+            ) || name
+                .strip_prefix("S_CMP_")
+                .is_some_and(|rest| is_valid_cmp_suffix(&rest.to_ascii_lowercase()))
+        }
+        "ENC_SOP1" | "ENC_SOP2" => matches!(
+            name,
+            "S_MOV_B32"
+                | "S_CMOV_B32"
+                | "S_NOT_B32"
+                | "S_BREV_B32"
+                | "S_BCNT0_I32_B32"
+                | "S_BCNT1_I32_B32"
+                | "S_FF0_I32_B32"
+                | "S_FF1_I32_B32"
+                | "S_FLBIT_I32_B32"
+                | "S_FLBIT_I32"
+                | "S_ABS_I32"
+                | "S_SEXT_I32_I8"
+                | "S_SEXT_I32_I16"
+                | "S_AND_B32"
+                | "S_OR_B32"
+                | "S_XOR_B32"
+                | "S_ANDN2_B32"
+                | "S_ORN2_B32"
+                | "S_NAND_B32"
+                | "S_NOR_B32"
+                | "S_XNOR_B32"
+                | "S_ADD_U32"
+                | "S_SUB_U32"
+                | "S_ADDC_U32"
+                | "S_SUBB_U32"
+                | "S_ADD_I32"
+                | "S_SUB_I32"
+                | "S_MUL_I32"
+                | "S_MUL_HI_U32"
+                | "S_MUL_HI_I32"
+                | "S_LSHL_B32"
+                | "S_LSHR_B32"
+                | "S_ASHR_I32"
+                | "S_LSHL1_ADD_U32"
+                | "S_LSHL2_ADD_U32"
+                | "S_LSHL3_ADD_U32"
+                | "S_LSHL4_ADD_U32"
+                | "S_BFM_B32"
+                | "S_BFE_U32"
+                | "S_BFE_I32"
+                | "S_MIN_U32"
+                | "S_MAX_U32"
+                | "S_MIN_I32"
+                | "S_MAX_I32"
+                | "S_CSELECT_B32"
+                | "S_WQM_B32"
+                | "S_BITSET0_B32"
+                | "S_BITSET1_B32"
+                | "S_ABSDIFF_I32"
+                | "S_PACK_LL_B32_B16"
+                | "S_PACK_LH_B32_B16"
+                | "S_PACK_HH_B32_B16"
+                | "S_GETPC_B64"
+                | "S_MOV_B64"
+                | "S_CMOV_B64"
+                | "S_NOT_B64"
+                | "S_CSELECT_B64"
+                | "S_WQM_B64"
+                | "S_BREV_B64"
+                | "S_BCNT1_I32_B64"
+                | "S_BCNT0_I32_B64"
+                | "S_FF1_I32_B64"
+                | "S_FF0_I32_B64"
+                | "S_FLBIT_I32_B64"
+                | "S_FLBIT_I32_I64"
+                | "S_LSHL_B64"
+                | "S_LSHR_B64"
+                | "S_ASHR_I64"
+                | "S_BFM_B64"
+                | "S_BFE_U64"
+                | "S_BFE_I64"
+                | "S_BITSET0_B64"
+                | "S_BITSET1_B64"
+                | "S_AND_B64"
+                | "S_OR_B64"
+                | "S_XOR_B64"
+                | "S_ANDN2_B64"
+                | "S_ORN2_B64"
+                | "S_NAND_B64"
+                | "S_NOR_B64"
+                | "S_XNOR_B64"
+        ),
+        _ => false,
+    }
+}
+
+fn is_supported_pure_valu(d: &Decoded) -> bool {
+    if d.variant != Variant::Plain {
+        return false;
+    }
+    let name = d.inst.name;
+    if name.starts_with("V_CMP_") {
+        return true;
+    }
+    if name.starts_with("V_CMPX_")
+        || name.starts_with("V_INTERP_")
+        || name.starts_with("V_MOVREL")
+        || name.starts_with("V_PERMLANE")
+        || matches!(
+            name,
+            "V_NOP"
+                | "V_READLANE_B32"
+                | "V_READFIRSTLANE_B32"
+                | "V_WRITELANE_B32"
+                | "V_SWAPREL_B32"
+                | "V_DIV_SCALE_F32"
+        )
+    {
+        return false;
+    }
+    matches!(
+        name,
+        "V_MOV_B32"
+            | "V_MOV_FED_B32"
+            | "V_NOT_B32"
+            | "V_BFREV_B32"
+            | "V_FFBH_U32"
+            | "V_FFBL_B32"
+            | "V_FFBH_I32"
+            | "V_CVT_F32_I32"
+            | "V_CVT_F32_U32"
+            | "V_CVT_U32_F32"
+            | "V_CVT_I32_F32"
+            | "V_CVT_RPI_I32_F32"
+            | "V_CVT_FLR_I32_F32"
+            | "V_CVT_F32_UBYTE0"
+            | "V_CVT_F32_UBYTE1"
+            | "V_CVT_F32_UBYTE2"
+            | "V_CVT_F32_UBYTE3"
+            | "V_CVT_F32_F16"
+            | "V_CVT_F16_F32"
+            | "V_CVT_PKRTZ_F16_F32"
+            | "V_PACK_B32_F16"
+            | "V_FMA_MIX_F32"
+            | "V_FMA_MIXLO_F16"
+            | "V_FMA_MIXHI_F16"
+            | "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_FRACT_F32"
+            | "V_TRUNC_F32"
+            | "V_FLOOR_F32"
+            | "V_CEIL_F32"
+            | "V_RNDNE_F32"
+            | "V_FREXP_MANT_F32"
+            | "V_FREXP_EXP_I32_F32"
+            | "V_LDEXP_F32"
+            | "V_ADD_F32"
+            | "V_SUB_F32"
+            | "V_SUBREV_F32"
+            | "V_MUL_F32"
+            | "V_MUL_LEGACY_F32"
+            | "V_MIN_F32"
+            | "V_MAX_F32"
+            | "V_FMAC_F32"
+            | "V_MAC_F32"
+            | "V_FMAC_LEGACY_F32"
+            | "V_FMA_F32"
+            | "V_MAD_F32"
+            | "V_FMA_LEGACY_F32"
+            | "V_FMAMK_F32"
+            | "V_FMAAK_F32"
+            | "V_MADMK_F32"
+            | "V_MADAK_F32"
+            | "V_MIN3_F32"
+            | "V_MAX3_F32"
+            | "V_MED3_F32"
+            | "V_CUBEID_F32"
+            | "V_CUBESC_F32"
+            | "V_CUBETC_F32"
+            | "V_CUBEMA_F32"
+            | "V_ADD_NC_U32"
+            | "V_SUB_NC_U32"
+            | "V_SUBREV_NC_U32"
+            | "V_ADD_NC_I32"
+            | "V_SUB_NC_I32"
+            | "V_MUL_LO_U32"
+            | "V_MUL_HI_U32"
+            | "V_MUL_HI_I32"
+            | "V_MUL_U32_U24"
+            | "V_MUL_HI_U32_U24"
+            | "V_MUL_I32_I24"
+            | "V_MUL_HI_I32_I24"
+            | "V_MAD_U32_U24"
+            | "V_MAD_I32_I24"
+            | "V_AND_B32"
+            | "V_OR_B32"
+            | "V_XOR_B32"
+            | "V_XNOR_B32"
+            | "V_LSHLREV_B32"
+            | "V_LSHRREV_B32"
+            | "V_ASHRREV_I32"
+            | "V_LSHL_ADD_U32"
+            | "V_ADD_LSHL_U32"
+            | "V_LSHL_OR_B32"
+            | "V_AND_OR_B32"
+            | "V_OR3_B32"
+            | "V_XOR3_B32"
+            | "V_ADD3_U32"
+            | "V_XAD_U32"
+            | "V_BFE_U32"
+            | "V_BFE_I32"
+            | "V_BFI_B32"
+            | "V_BFM_B32"
+            | "V_BCNT_U32_B32"
+            | "V_PERM_B32"
+            | "V_ALIGNBIT_B32"
+            | "V_ALIGNBYTE_B32"
+            | "V_MIN_U32"
+            | "V_MAX_U32"
+            | "V_MIN_I32"
+            | "V_MAX_I32"
+            | "V_MIN3_U32"
+            | "V_MAX3_U32"
+            | "V_MED3_U32"
+            | "V_MIN3_I32"
+            | "V_MAX3_I32"
+            | "V_MED3_I32"
+            | "V_SAD_U32"
+            | "V_SAD_U8"
+            | "V_SAD_HI_U8"
+            | "V_SAD_U16"
+            | "V_MSAD_U8"
+            | "V_LERP_U8"
+            | "V_MAD_U32_U16"
+            | "V_MAD_I32_I16"
+            | "V_CVT_PK_U16_U32"
+            | "V_CVT_PK_I16_I32"
+            | "V_CVT_PKNORM_I16_F32"
+            | "V_CVT_PKNORM_U16_F32"
+            | "V_CVT_PKNORM_I16_F16"
+            | "V_CVT_PKNORM_U16_F16"
+            | "V_SAT_PK_U8_I16"
+            | "V_DIV_FMAS_F32"
+            | "V_DIV_FIXUP_F32"
+            | "V_CVT_PK_U8_F32"
+            | "V_MBCNT_LO_U32_B32"
+            | "V_MBCNT_HI_U32_B32"
+            | "V_CNDMASK_B32"
+            | "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_SWAP_B32"
+            | "V_LSHLREV_B64"
+            | "V_LSHRREV_B64"
+            | "V_ASHRREV_I64"
+            | "V_MAD_U64_U32"
+            | "V_MAD_I64_I32"
+            | "V_ADD_F64"
+            | "V_MUL_F64"
+            | "V_FMA_F64"
+            | "V_MIN_F64"
+            | "V_MAX_F64"
+            | "V_RCP_F64"
+            | "V_CVT_F64_F32"
+            | "V_CVT_F64_I32"
+            | "V_CVT_F64_U32"
+            | "V_FLOOR_F64"
+            | "V_CEIL_F64"
+            | "V_FRACT_F64"
+            | "V_RNDNE_F64"
+            | "V_FREXP_MANT_F64"
+            | "V_SQRT_F64"
+            | "V_RSQ_F64"
+            | "V_TRUNC_F64"
+            | "V_LDEXP_F64"
+            | "V_CVT_F32_F64"
+            | "V_CVT_I32_F64"
+            | "V_CVT_U32_F64"
+            | "V_FREXP_EXP_I32_F64"
+            | "V_ADD_F16"
+            | "V_SUB_F16"
+            | "V_SUBREV_F16"
+            | "V_MUL_F16"
+            | "V_MIN_F16"
+            | "V_MAX_F16"
+            | "V_FMA_F16"
+            | "V_MED3_F16"
+            | "V_MIN3_F16"
+            | "V_MAX3_F16"
+            | "V_MED3_U16"
+            | "V_MIN3_U16"
+            | "V_MAX3_U16"
+            | "V_MED3_I16"
+            | "V_MIN3_I16"
+            | "V_MAX3_I16"
+            | "V_FREXP_MANT_F16"
+            | "V_FREXP_EXP_I16_F16"
+            | "V_MAD_F16"
+            | "V_FMAC_F16"
+            | "V_FMAMK_F16"
+            | "V_FMAAK_F16"
+            | "V_LDEXP_F16"
+            | "V_RCP_F16"
+            | "V_RSQ_F16"
+            | "V_SQRT_F16"
+            | "V_LOG_F16"
+            | "V_EXP_F16"
+            | "V_SIN_F16"
+            | "V_COS_F16"
+            | "V_FRACT_F16"
+            | "V_FLOOR_F16"
+            | "V_CEIL_F16"
+            | "V_TRUNC_F16"
+            | "V_RNDNE_F16"
+            | "V_CVT_F16_U16"
+            | "V_CVT_F16_I16"
+            | "V_CVT_U16_F16"
+            | "V_CVT_I16_F16"
+            | "V_CVT_NORM_U16_F16"
+            | "V_CVT_NORM_I16_F16"
+            | "V_ADD_NC_U16"
+            | "V_ADD_U16"
+            | "V_SUB_NC_U16"
+            | "V_SUB_U16"
+            | "V_SUBREV_NC_U16"
+            | "V_SUBREV_U16"
+            | "V_ADD_NC_I16"
+            | "V_SUB_NC_I16"
+            | "V_MUL_LO_U16"
+            | "V_LSHLREV_B16"
+            | "V_LSHRREV_B16"
+            | "V_ASHRREV_I16"
+            | "V_MAX_U16"
+            | "V_MIN_U16"
+            | "V_MAX_I16"
+            | "V_MIN_I16"
+            | "V_MAD_U16"
+            | "V_MAD_I16"
+            | "V_DOT2_F32_F16"
+            | "V_DOT2C_F32_F16"
+            | "V_DOT4C_I32_I8"
+            | "V_DOT2_I32_I16"
+            | "V_DOT2_U32_U16"
+            | "V_DOT4_U32_U8"
+            | "V_DOT4_I32_I8"
+            | "V_DOT8_U32_U4"
+            | "V_DOT8_I32_I4"
+            | "V_PK_ADD_F16"
+            | "V_PK_MUL_F16"
+            | "V_PK_FMA_F16"
+            | "V_PK_FMAC_F16"
+            | "V_PK_MIN_F16"
+            | "V_PK_MAX_F16"
+            | "V_PK_ADD_U16"
+            | "V_PK_SUB_U16"
+            | "V_PK_ADD_I16"
+            | "V_PK_SUB_I16"
+            | "V_PK_MUL_LO_U16"
+            | "V_PK_MAD_U16"
+            | "V_PK_MAD_I16"
+            | "V_PK_LSHLREV_B16"
+            | "V_PK_LSHRREV_B16"
+            | "V_PK_ASHRREV_I16"
+            | "V_PK_MAX_U16"
+            | "V_PK_MIN_U16"
+            | "V_PK_MAX_I16"
+            | "V_PK_MIN_I16"
+    )
+}
+
+fn is_rmw_or_partial_vgpr_write(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    if d.variant != Variant::Plain {
+        // SDWA preserves unused bytes/words; DPP16 row/bank mask or !bound_ctrl preserves lanes.
+        return true;
+    }
+    if matches!(
+        name,
+        "V_FMAC_F32"
+            | "V_MAC_F32"
+            | "V_FMAC_LEGACY_F32"
+            | "V_FMAC_F16"
+            | "V_PK_FMAC_F16"
+            | "V_DOT2C_F32_F16"
+            | "V_DOT4C_I32_I8"
+            | "V_FMA_MIXLO_F16"
+            | "V_FMA_MIXHI_F16"
+            | "V_CVT_F16_F32"
+            | "V_INTERP_P2_F16"
+            | "V_PERMLANE16_B32"
+            | "V_PERMLANEX16_B32"
+            | "V_WRITELANE_B32"
+            | "V_SWAP_B32"
+    ) {
+        return true;
+    }
+    // Plain 16-bit VALU (`valu16` in emit.rs) preserves the untouched 16-bit half of VDST.
+    const WIDE16: &[&str] = &[
+        "V_CVT_PKNORM_I16_F32",
+        "V_CVT_PKNORM_U16_F32",
+        "V_CVT_PKNORM_I16_F16",
+        "V_CVT_PKNORM_U16_F16",
+        "V_CVT_PK_U16_U32",
+        "V_CVT_PK_I16_I32",
+        "V_MAD_U32_U16",
+        "V_MAD_I32_I16",
+        "V_SAD_U16",
+        "V_SAT_PK_U8_I16",
+        "V_CVT_F32_F16",
+        "V_CVT_PKRTZ_F16_F32",
+        "V_PACK_B32_F16",
+    ];
+    if (name.contains("F16") || name.contains("_I16") || name.contains("_U16") || name.contains("_B16"))
+        && !name.starts_with("V_PK_")
+        && !name.starts_with("V_DOT")
+        && !name.starts_with("V_CMP")
+        && !name.starts_with("V_FMA_MIX")
+        && !WIDE16.contains(&name)
+        && (d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP"))
+    {
+        return true;
+    }
+    // D16 sub-dword loads preserve the untouched half of the destination VGPR.
+    if name.contains("_D16_") && (name.contains("_LOAD_") || name.contains("_READ_")) {
+        return true;
+    }
+    false
+}
+
+/// Returns true if an `EXEC`-modifying instruction can WIDEN `EXEC` (turn on previously inactive lanes).
+fn is_exec_widening(d: &Decoded, s_mod: SRegs) -> bool {
+    if (s_mod & S_EXEC) == 0 {
+        return false;
+    }
+    let name = d.inst.name;
+    // V_CMPX_* computes `ballot(act & cond)` — always a subset of current EXEC.
+    if name.starts_with("V_CMPX_") {
+        return false;
+    }
+    // `and_saveexec` / `and_wrexec` compute `src & exec`; `andn1_saveexec/wrexec` compute `~src & exec`.
+    // Note: `andn2_saveexec` computes `src & ~exec`, which WIDENS EXEC!
+    if matches!(
+        name,
+        "S_AND_SAVEEXEC_B32"
+            | "S_AND_SAVEEXEC_B64"
+            | "S_AND_WREXEC_B32"
+            | "S_AND_WREXEC_B64"
+            | "S_ANDN1_SAVEEXEC_B32"
+            | "S_ANDN1_SAVEEXEC_B64"
+            | "S_ANDN1_WREXEC_B32"
+            | "S_ANDN1_WREXEC_B64"
+    ) {
+        return false;
+    }
+    if matches!(name, "S_AND_B32" | "S_AND_B64") {
+        let s0 = fval(d, "SSRC0");
+        let s1 = fval(d, "SSRC1");
+        // Strictly narrowing iff one operand is EXEC (126).
+        return s0 != 126 && s1 != 126;
+    }
+    if matches!(name, "S_ANDN2_B32" | "S_ANDN2_B64") {
+        // `s_andn2` computes `SSRC0 & ~SSRC1`: narrowing iff SSRC0 == EXEC (126).
+        return fval(d, "SSRC0") != 126;
+    }
+    true
+}
+
+/// Extract carry/mask `sdst` for instructions that emit `write_mask(&sdst, ...)` in `emit.rs`.
+fn carry_sdst_of(d: &Decoded, outs: &[&Operand]) -> Option<CarryDst> {
+    let name = d.inst.name;
+    let is_carry_alu = 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"
+            | "V_DIV_SCALE_F32"
+    );
+    if is_carry_alu {
+        let Some(o) = outs.get(1) else {
+            return Some(if matches!(name, "V_MAD_U64_U32" | "V_MAD_I64_I32") {
+                CarryDst::Null
+            } else {
+                CarryDst::Sgpr(106)
+            });
+        };
+        return Some(match o.field {
+            Some(f) => {
+                let v = scaled_field(d, f);
+                if v == 125 || v > 127 {
+                    CarryDst::Null
+                } else {
+                    CarryDst::Sgpr(v)
+                }
+            }
+            None => match o.ty {
+                "OPR_VCC" => CarryDst::Sgpr(106),
+                "OPR_EXEC" => CarryDst::Sgpr(126),
+                _ => CarryDst::Null,
+            },
+        });
+    }
+    if name.starts_with("V_CMP_") {
+        if d.variant == Variant::Sdwa {
+            if let Some(e) = ext_encoding(d) {
+                if rdna2::field_value(e, &d.words, "SD") == Some(1) {
+                    let sd = rdna2::field_value(e, &d.words, "SDST").unwrap_or(106);
+                    return Some(if sd == 125 || sd > 127 {
+                        CarryDst::Null
+                    } else {
+                        CarryDst::Sgpr(sd)
+                    });
+                }
+            }
+            return Some(CarryDst::Sgpr(106));
+        }
+        let Some(o) = outs.first() else {
+            return Some(CarryDst::Sgpr(106));
+        };
+        return Some(match o.field {
+            Some(f) => {
+                let v = scaled_field(d, f);
+                if v == 125 || v > 127 {
+                    CarryDst::Null
+                } else {
+                    CarryDst::Sgpr(v)
+                }
+            }
+            None => match o.ty {
+                "OPR_VCC" => CarryDst::Sgpr(106),
+                "OPR_EXEC" => CarryDst::Sgpr(126),
+                _ => CarryDst::Null,
+            },
+        });
+    }
+    None
+}
+
+fn analyze_inst(d: &Decoded, opt: &Options) -> InstInfo {
+    let name = d.inst.name;
+    let enc = d.enc.name;
+    let wave64 = opt.wave64;
+    let mask_words: u64 = if wave64 { 2 } else { 1 };
+
+    let mut s_read: SRegs = 0;
+    let mut s_kill: SRegs = 0;
+    let mut s_mod: SRegs = 0;
+    let mut scc_read = false;
+    let mut scc_write = false;
+    let mut v_read = VRegs::EMPTY;
+    let mut v_mod = VRegs::EMPTY;
+
+    let (outs, _ins) = explicit_ops(d);
+    let carry_sdst = carry_sdst_of(d, &outs);
+
+    // 1. Indirect SGPR moves (`s_movrel*`): conservative all-SGPR read, zero kill.
+    if name.starts_with("S_MOVREL") {
+        let dst = fval(d, "SDST").min(123);
+        let mod_mask = if name.starts_with("S_MOVRELS_") {
+            sreg_range(dst, if name.ends_with("_B64") { 2 } else { 1 })
+        } else {
+            sreg_range(dst, 124u64.saturating_sub(dst))
+        };
+        return InstInfo {
+            s_read: S_ALL,
+            s_kill: 0,
+            s_mod: mod_mask,
+            scc_read: false,
+            scc_write: false,
+            v_read: VRegs::EMPTY,
+            v_mod: VRegs::EMPTY,
+            carry_sdst: None,
+            pure_eliminable: false,
+            exec_widen: false,
+            indirect_sgpr: true,
+            indirect_vgpr: false,
+        };
+    }
+
+    // 2. Indirect VGPR moves (`v_movrel*` / `v_swaprel*`): conservative all-VGPR read/mod.
+    if name.starts_with("V_MOVREL") || name == "V_SWAPREL_B32" {
+        s_read |= S_M0 | S_EXEC;
+        let src = fval(d, "SRC0");
+        if src < 256 {
+            let (sr, sc) = scalar_code_regs(src, 1, wave64);
+            s_read |= sr;
+            scc_read |= sc;
+        }
+        return InstInfo {
+            s_read,
+            s_kill: 0,
+            s_mod: 0,
+            scc_read,
+            scc_write: false,
+            v_read: VRegs::ALL,
+            v_mod: VRegs::ALL,
+            carry_sdst: None,
+            pure_eliminable: false,
+            exec_widen: false,
+            indirect_sgpr: false,
+            indirect_vgpr: true,
+        };
+    }
+
+    // 3. SOPP special instructions.
+    if enc == "ENC_SOPP" {
+        match name {
+            "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => scc_read = true,
+            "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => s_read |= if wave64 { S_VCC } else { S_VCC_LO },
+            "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => s_read |= S_EXEC,
+            "S_SENDMSG" if matches!(opt.mode, Mode::Mesh(_)) => s_read |= S_M0,
+            "S_SENDMSG" if matches!(opt.mode, Mode::Geometry(_)) => s_read |= S_EXEC,
+            _ => {}
+        }
+        return InstInfo {
+            s_read,
+            s_kill: 0,
+            s_mod: 0,
+            scc_read,
+            scc_write: false,
+            v_read: VRegs::EMPTY,
+            v_mod: VRegs::EMPTY,
+            carry_sdst: None,
+            pure_eliminable: false,
+            exec_widen: false,
+            indirect_sgpr: false,
+            indirect_vgpr: false,
+        };
+    }
+
+    // 4. `s_setreg_b32` reads `SDST` (field named SDST in SOPK is actually a source!).
+    if name == "S_SETREG_B32" {
+        let (sr, sc) = scalar_code_regs(fval(d, "SDST"), 1, wave64);
+        s_read |= sr;
+        scc_read |= sc;
+        return InstInfo {
+            s_read,
+            s_kill: 0,
+            s_mod: 0,
+            scc_read,
+            scc_write: false,
+            v_read: VRegs::EMPTY,
+            v_mod: VRegs::EMPTY,
+            carry_sdst: None,
+            pure_eliminable: false,
+            exec_widen: false,
+            indirect_sgpr: false,
+            indirect_vgpr: false,
+        };
+    }
+
+    // 5. Indirect branches / calls (Guardrail #7): conservatively read everything.
+    if (name == "S_SETPC_B64" && d.far_target.is_none() && !matches!(opt.mode, Mode::Geometry(_)))
+        || name.starts_with("S_CALL")
+        || (name == "S_SWAPPC_B64" && fval(d, "SDST") != fval(d, "SSRC0"))
+    {
+        return InstInfo {
+            s_read: S_ALL,
+            s_kill: 0,
+            s_mod: 0,
+            scc_read: true,
+            scc_write: false,
+            v_read: VRegs::ALL,
+            v_mod: VRegs::EMPTY,
+            carry_sdst: None,
+            pure_eliminable: false,
+            exec_widen: false,
+            indirect_sgpr: true,
+            indirect_vgpr: true,
+        };
+    }
+
+    // 6. Standard operand-table traversal for SGPRs & VGPRs.
+    let keeps_s_dst = name.starts_with("S_CMOV")
+        || matches!(
+            name,
+            "S_ADDK_I32" | "S_MULK_I32" | "S_BITSET0_B32" | "S_BITSET1_B32" | "S_BITSET0_B64" | "S_BITSET1_B64"
+        );
+    let is_mask_write_op = carry_sdst.is_some() || name.starts_with("V_CMPX_");
+    let is_per_lane_mask_read = matches!(
+        name,
+        "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32"
+    );
+
+    // SDWA extension dword handling (S0, S1, SD/SDST).
+    let mut sdwa_vopc_dst: Option<SRegs> = None;
+    if d.variant == Variant::Sdwa {
+        if let Some(e) = ext_encoding(d) {
+            let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0);
+            if fv("S0") == 1 {
+                let (sr, sc) = scalar_code_regs(fv("VSRC0"), 1, wave64);
+                s_read |= sr;
+                scc_read |= sc;
+            } else {
+                v_read.set(fv("VSRC0"));
+            }
+            if d.enc.field("VSRC1").is_some() {
+                if fv("S1") == 1 {
+                    let (sr, sc) = scalar_code_regs(fv("VSRC1"), 1, wave64);
+                    s_read |= sr;
+                    scc_read |= sc;
+                } else {
+                    v_read.set(fv("VSRC1"));
+                }
+            }
+            if enc == "ENC_VOPC" && !name.starts_with("V_CMPX") {
+                sdwa_vopc_dst = Some(if fv("SD") == 1 {
+                    scalar_code_regs(fv("SDST"), mask_words, wave64).0
+                } else {
+                    sreg_range(106, mask_words)
+                });
+            }
+        } else {
+            // Unknown SDWA encoding: conservative fallback.
+            return InstInfo {
+                s_read: S_ALL,
+                s_kill: 0,
+                s_mod: 0,
+                scc_read: true,
+                scc_write: false,
+                v_read: VRegs::ALL,
+                v_mod: VRegs::EMPTY,
+                carry_sdst: None,
+                pure_eliminable: false,
+                exec_widen: false,
+                indirect_sgpr: false,
+                indirect_vgpr: false,
+            };
+        }
+    } else if d.variant == Variant::Dpp16 || d.variant == Variant::Dpp8 {
+        if let Some(e) = ext_encoding(d) {
+            let v0 = rdna2::field_value(e, &d.words, "VSRC0").unwrap_or(0);
+            v_read.set(v0);
+        } else {
+            v_read = VRegs::ALL;
+        }
+        s_read |= S_EXEC;
+    }
+
+    // Iterate spec operands for SGPRs.
+    for o in d.ienc.operands {
+        if o.ty == "OPR_SSRC_SPECIAL_SCC" {
+            if o.input {
+                scc_read = true;
+            }
+            continue;
+        }
+        let n_base = (o.size as u64).div_ceil(32).max(1);
+        let (regs, reads_scc) = match (o.field, o.ty) {
+            (_, "OPR_VCC") => {
+                let n = if is_mask_write_op || is_per_lane_mask_read {
+                    mask_words
+                } else {
+                    n_base
+                };
+                (sreg_range(106, n), false)
+            }
+            (_, "OPR_EXEC" | "OPR_SDST_EXEC") => (S_EXEC, false),
+            (_, "OPR_SDST_M0") => (S_M0, false),
+            (None, _) | (Some("LITERAL"), _) => continue,
+            (Some(f), ty) => {
+                if o.implicit
+                    || !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"]
+                        .iter()
+                        .any(|k| ty.contains(k))
+                {
+                    continue;
+                }
+                if f == "SRC0" && d.variant != Variant::Plain {
+                    continue;
+                }
+                if f == "VSRC1" && d.variant == Variant::Sdwa {
+                    continue;
+                }
+                let raw = scaled_field(d, f);
+                let n = if o.output && is_mask_write_op && (f == "SDST" || (f == "VDST" && name.starts_with("V_CMP"))) {
+                    mask_words
+                } else if !o.output && is_per_lane_mask_read && f == "SRC2" {
+                    mask_words
+                } else {
+                    n_base
+                };
+                scalar_code_regs(raw, n, wave64)
+            }
+        };
+        if reads_scc && !o.output {
+            scc_read = true;
+        }
+        if o.output {
+            s_mod |= regs;
+            if keeps_s_dst {
+                s_read |= regs;
+            } else {
+                s_kill |= regs;
+            }
+        }
+        if o.input {
+            s_read |= regs;
+        }
+    }
+
+    if let Some(dst_regs) = sdwa_vopc_dst {
+        s_kill = (s_kill & !S_VCC) | dst_regs;
+        s_mod = (s_mod & !S_VCC) | dst_regs;
+    }
+
+    // SOPK: `SDST` is read by `s_cmovk`, `s_addk`, `s_mulk`, `s_cmpk_*`.
+    if enc == "ENC_SOPK" {
+        let sd = fval(d, "SDST");
+        let r = scalar_code_regs(sd, 1, wave64).0;
+        if name.starts_with("S_CMPK_") {
+            s_read |= r;
+            s_kill &= !r;
+            s_mod &= !r;
+        } else if name != "S_MOVK_I32" {
+            s_read |= r;
+            s_kill &= !r;
+            s_mod |= r;
+        }
+    }
+
+    // Saveexec / wrexec always read and write EXEC and write SCC.
+    if name.contains("SAVEEXEC") || name.contains("WREXEC") {
+        s_read |= S_EXEC;
+        s_kill |= S_EXEC;
+        s_mod |= S_EXEC;
+        scc_write = true;
+    }
+
+    // Explicit SCC reads/writes for SALU.
+    if matches!(enc, "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK") {
+        if matches!(
+            name,
+            "S_CMOV_B32" | "S_CMOV_B64" | "S_CMOVK_I32" | "S_CSELECT_B32" | "S_CSELECT_B64" | "S_ADDC_U32" | "S_SUBB_U32"
+        ) {
+            scc_read = true;
+        }
+        if salu_writes_scc(enc, name) {
+            scc_write = true;
+        } else if !is_supported_salu(enc, name) && !name.contains("SAVEEXEC") && !name.contains("WREXEC") {
+            // Unknown SALU op: conservatively assume it may read scc and all SGPRs.
+            scc_read = true;
+            s_read |= S_ALL;
+            s_kill = 0;
+        }
+    }
+
+    // Extra encoding-specific SGPR & VGPR uses (catching everything `rdna2::vgpr_uses` misses).
+    let (vr, vw) = rdna2::vgpr_uses(d);
+    for r in vr {
+        v_read.set(r);
+    }
+    for w in vw {
+        v_mod.set(w);
+    }
+    // Fix up SDWA VSRC1 if S1==1 (scalar, not VGPR — `rdna2::vgpr_uses` treats VSRC1 as VGPR).
+    if d.variant == Variant::Sdwa {
+        if let Some(e) = ext_encoding(d) {
+            if d.enc.field("VSRC1").is_some() && rdna2::field_value(e, &d.words, "S1") == Some(1) {
+                // Recompute v_read cleanly from SDWA fields only.
+                v_read = VRegs::EMPTY;
+                if rdna2::field_value(e, &d.words, "S0") != Some(1) {
+                    v_read.set(rdna2::field_value(e, &d.words, "VSRC0").unwrap_or(0));
+                }
+            }
+        }
+    }
+
+    match enc {
+        "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => {}
+        "ENC_SMEM" => {
+            if matches!(name, "S_MEMTIME" | "S_MEMREALTIME") {
+                let sdata = fval(d, "SDATA");
+                let r = sreg_range(sdata, 2);
+                s_kill |= r;
+                s_mod |= r;
+            } else if let Some(count) = smem_load_count(name) {
+                let sbase = scaled_field(d, "SBASE");
+                let base_n = if name.starts_with("S_BUFFER_LOAD_") { 4 } else { 2 };
+                s_read |= sreg_range(sbase, base_n);
+                let soff = fval(d, "SOFFSET");
+                if soff != 125 {
+                    let (sr, sc) = scalar_code_regs(soff, 1, wave64);
+                    s_read |= sr;
+                    scc_read |= sc;
+                }
+                let sdata = fval(d, "SDATA");
+                let dst = sreg_range(sdata, count as u64);
+                s_kill |= dst;
+                s_mod |= dst;
+            } else {
+                // Stores / atomics / cache ops: never kill.
+                s_kill = 0;
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            let srsrc = scaled_field(d, "SRSRC");
+            s_read |= sreg_range(srsrc, 4);
+            let (sr, sc) = scalar_code_regs(fval(d, "SOFFSET"), 1, wave64);
+            s_read |= sr;
+            scc_read |= sc;
+            s_read |= S_EXEC;
+            let vdata = fval(d, "VDATA");
+            if name.starts_with("BUFFER_ATOMIC_") {
+                let x2 = name.ends_with("_X2");
+                let cmpswap = name.contains("CMPSWAP");
+                let words = match (x2, cmpswap) {
+                    (false, false) => 1,
+                    (false, true) => 2,
+                    (true, false) => 2,
+                    (true, true) => 4,
+                };
+                v_read.set_range(vdata, words);
+                if fval(d, "GLC") == 1 {
+                    v_mod.set_range(vdata, if x2 { 2 } else { 1 });
+                } else {
+                    v_mod = VRegs::EMPTY;
+                }
+            }
+            if is_rmw_or_partial_vgpr_write(d) {
+                v_read = v_read.union(v_mod);
+            }
+        }
+        "ENC_MIMG" => {
+            let srsrc = scaled_field(d, "SRSRC");
+            let t_words = if fval(d, "R128") == 1 { 4 } else { 8 };
+            s_read |= sreg_range(srsrc, t_words);
+            let base = name.trim_start_matches("IMAGE_");
+            let sampling = base.starts_with("SAMPLE") || base.starts_with("GATHER4") || base == "GET_LOD";
+            if sampling {
+                let ssamp = scaled_field(d, "SSAMP");
+                s_read |= sreg_range(ssamp, 4);
+            }
+            s_read |= S_EXEC;
+            // Address VGPRs: sequential or NSA.
+            let nsa = fval(d, "NSA");
+            if nsa > 0 {
+                v_read.set(fval(d, "VADDR"));
+                if let Some(nsa_enc) = rdna2::encoding(&format!("MIMG_NSA{nsa}")) {
+                    for j in 0..(4 * nsa) {
+                        let letter = (b'A' + j.min(25) as u8) as char;
+                        if let Some(v) = rdna2::field_value(nsa_enc, &d.words, &format!("VADDR{letter}")) {
+                            v_read.set(v);
+                        }
+                    }
+                } else {
+                    v_read = VRegs::ALL;
+                }
+            } else {
+                // Sequential VADDR: conservatively cover up to 12 address VGPRs for BVH/grad samples.
+                let vaddr = fval(d, "VADDR");
+                let n_addr = if base.starts_with("BVH") {
+                    12
+                } else if sampling {
+                    10
+                } else {
+                    4
+                };
+                v_read.set_range(vaddr, n_addr);
+            }
+            // Data VGPRs.
+            let vdata = fval(d, "VDATA");
+            let dmask = fval(d, "DMASK");
+            let d16 = fval(d, "D16") == 1;
+            let comps = (dmask & 0xF).count_ones() as u64;
+            let n_data = if base.starts_with("GATHER4") || base.starts_with("BVH") {
+                if d16 { 2 } else { 4 }
+            } else if d16 {
+                comps.div_ceil(2).max(1)
+            } else {
+                comps.max(1)
+            };
+            if base.starts_with("STORE") {
+                v_read.set_range(vdata, n_data);
+                v_mod = VRegs::EMPTY;
+            } else if base.starts_with("ATOMIC_") {
+                let words = if base.contains("CMPSWAP") { 2 } else { 1 };
+                v_read.set_range(vdata, words);
+                if fval(d, "GLC") == 1 {
+                    v_mod.set_range(vdata, 1);
+                } else {
+                    v_mod = VRegs::EMPTY;
+                }
+            } else {
+                v_mod.set_range(vdata, n_data);
+            }
+        }
+        "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => {
+            s_read |= S_EXEC;
+            let saddr = fval(d, "SADDR");
+            let has_saddr = saddr != 0x7D && saddr != 0x7F && saddr < 128;
+            if has_saddr {
+                let n = if enc == "ENC_FLAT_SCRATCH" { 1 } else { 2 };
+                s_read |= sreg_range(saddr, n);
+            } else if !name.ends_with("_ADDTID") {
+                let addr = fval(d, "ADDR");
+                let n = if enc == "ENC_FLAT_SCRATCH" { 1 } else { 2 };
+                v_read.set_range(addr, n);
+            }
+            if name.contains("_ATOMIC_") {
+                let data = fval(d, "DATA");
+                let x2 = name.ends_with("_X2");
+                let cmpswap = name.contains("CMPSWAP");
+                let words = match (x2, cmpswap) {
+                    (false, false) => 1,
+                    (false, true) => 2,
+                    (true, false) => 2,
+                    (true, true) => 4,
+                };
+                v_read.set_range(data, words);
+                if fval(d, "GLC") == 1 {
+                    v_mod.set_range(fval(d, "VDST"), if x2 { 2 } else { 1 });
+                } else {
+                    v_mod = VRegs::EMPTY;
+                }
+            }
+            if is_rmw_or_partial_vgpr_write(d) {
+                v_read = v_read.union(v_mod);
+            }
+        }
+        "ENC_DS" => {
+            s_read |= S_EXEC;
+            if matches!(name, "DS_WRITE_ADDTID_B32" | "DS_READ_ADDTID_B32") {
+                s_read |= S_M0;
+                if name == "DS_WRITE_ADDTID_B32" {
+                    v_read.set(fval(d, "DATA0"));
+                } else {
+                    v_mod.set(fval(d, "VDST"));
+                }
+            } else if name == "DS_SWIZZLE_B32" {
+                v_read.set(fval(d, "ADDR"));
+                v_mod.set(fval(d, "VDST"));
+            } else if matches!(name, "DS_BPERMUTE_B32" | "DS_PERMUTE_B32") {
+                v_read.set(fval(d, "ADDR"));
+                v_read.set(fval(d, "DATA0"));
+                v_mod.set(fval(d, "VDST"));
+            } else {
+                v_read.set(fval(d, "ADDR"));
+                if name.starts_with("DS_READ2") {
+                    let n = if name.ends_with("_B64") { 4 } else { 2 };
+                    v_mod.set_range(fval(d, "VDST"), n);
+                } else if name.starts_with("DS_WRITE2") {
+                    let n = if name.ends_with("_B64") { 2 } else { 1 };
+                    v_read.set_range(fval(d, "DATA0"), n);
+                    v_read.set_range(fval(d, "DATA1"), n);
+                    v_mod = VRegs::EMPTY;
+                } else if name.contains("WRXCHG2") {
+                    v_read.set(fval(d, "DATA0"));
+                    v_read.set(fval(d, "DATA1"));
+                    if name.contains("_RTN_") {
+                        v_mod.set_range(fval(d, "VDST"), 2);
+                    }
+                } else if name.contains("_RTN_") {
+                    v_mod.set(fval(d, "VDST"));
+                }
+                if is_rmw_or_partial_vgpr_write(d) {
+                    v_read = v_read.union(v_mod);
+                }
+            }
+        }
+        "ENC_EXP" => {
+            s_read |= S_EXEC;
+            // `emit.rs:1840` unconditionally calls `self.vreg(VSRC0..3)`.
+            for f in ["VSRC0", "VSRC1", "VSRC2", "VSRC3"] {
+                v_read.set(fval(d, f));
+            }
+            v_mod = VRegs::EMPTY;
+        }
+        "ENC_VINTRP" => {
+            s_read |= S_EXEC;
+            if matches!(name, "V_INTERP_P1_F32" | "V_INTERP_P1LL_F16" | "V_INTERP_P1LV_F16") {
+                // `emit.rs:2009` emits only a comment for p1 (does not write VDST).
+                v_mod = VRegs::EMPTY;
+            } else if name == "V_INTERP_P2_F16" {
+                v_read = v_read.union(v_mod);
+            }
+        }
+        e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => {
+            s_read |= S_EXEC;
+            if name == "V_SWAP_B32" {
+                let s0 = fval(d, "SRC0");
+                let vd = fval(d, "VDST");
+                v_read.set(vd);
+                v_mod.set(vd);
+                if s0 >= 256 {
+                    v_read.set(s0 - 256);
+                    v_mod.set(s0 - 256);
+                }
+            } else if name.starts_with("V_INTERP_") {
+                if matches!(name, "V_INTERP_P1_F32" | "V_INTERP_P1LL_F16" | "V_INTERP_P1LV_F16") {
+                    v_mod = VRegs::EMPTY;
+                } else if name == "V_INTERP_P2_F16" {
+                    v_read = v_read.union(v_mod);
+                }
+            } else if is_rmw_or_partial_vgpr_write(d) {
+                v_read = v_read.union(v_mod);
+            }
+        }
+        _ => {
+            // Unknown encoding: conservative over-approximation.
+            s_read = S_ALL;
+            s_kill = 0;
+            scc_read = true;
+            v_read = VRegs::ALL;
+        }
+    }
+
+    let exec_widen = is_exec_widening(d, s_mod);
+
+    let has_any_output = s_mod != 0 || !v_mod.is_empty() || scc_write;
+    let pure_eliminable = has_any_output
+        && (s_mod & (S_EXEC | S_M0)) == 0
+        && match enc {
+            "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => {
+                is_supported_salu(enc, name) && !name.contains("SAVEEXEC") && !name.contains("WREXEC")
+            }
+            e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => is_supported_pure_valu(d),
+            _ => false,
+        };
+
+    InstInfo {
+        s_read,
+        s_kill,
+        s_mod,
+        scc_read,
+        scc_write,
+        v_read,
+        v_mod,
+        carry_sdst,
+        pure_eliminable,
+        exec_widen,
+        indirect_sgpr: false,
+        indirect_vgpr: false,
+    }
+}
+
+fn smem_load_count(name: &str) -> Option<usize> {
+    let rest = name
+        .strip_prefix("S_BUFFER_LOAD_")
+        .or_else(|| name.strip_prefix("S_LOAD_"))?;
+    Some(match rest {
+        "DWORD" => 1,
+        "DWORDX2" => 2,
+        "DWORDX4" => 4,
+        "DWORDX8" => 8,
+        "DWORDX16" => 16,
+        _ => return None,
+    })
+}
+
+/// Guardrail #8: check if Compute `mem..mem3` requires `globallycoherent`.
+fn compute_mem_coherent(insts: &[Decoded]) -> bool {
+    let mut has_s_barrier = false;
+    let mut has_mem_store = false;
+
+    for d in insts {
+        let name = d.inst.name;
+        let enc = d.enc.name;
+
+        // Condition 1: any GLC / DLC / SLC memory flag.
+        if matches!(
+            enc,
+            "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH"
+        ) {
+            if rdna2::field_value(d.enc, &d.words, "GLC") == Some(1)
+                || rdna2::field_value(d.enc, &d.words, "DLC") == Some(1)
+                || rdna2::field_value(d.enc, &d.words, "SLC") == Some(1)
+            {
+                return true;
+            }
+        }
+
+        // Condition 2: any memory atomic.
+        if name.starts_with("S_ATOMIC")
+            || name.starts_with("S_BUFFER_ATOMIC")
+            || name.starts_with("BUFFER_ATOMIC")
+            || name.starts_with("FLAT_ATOMIC")
+            || name.starts_with("GLOBAL_ATOMIC")
+        {
+            return true;
+        }
+
+        // Condition 3: any cache invalidate / writeback op (excluding instruction cache `S_ICACHE_INV`).
+        if name != "S_ICACHE_INV"
+            && (name.contains("DCACHE_INV")
+                || name.contains("DCACHE_WB")
+                || name.contains("DCACHE_DISCARD")
+                || name.contains("GL0_INV")
+                || name.contains("GL1_INV")
+                || name.contains("WBL2")
+                || (enc == "ENC_SMEM" && name.ends_with("_INV"))
+                || (enc == "ENC_MUBUF" && name.ends_with("_INV")))
+        {
+            return true;
+        }
+
+        // Condition 4: `s_barrier` combined with any `mem..mem3` store.
+        if name == "S_BARRIER" {
+            has_s_barrier = true;
+        }
+        match enc {
+            "ENC_MUBUF" | "ENC_MTBUF" => {
+                if name.starts_with("BUFFER_STORE") || name.starts_with("TBUFFER_STORE") {
+                    has_mem_store = true;
+                } else if !name.starts_with("BUFFER_LOAD")
+                    && !name.starts_with("TBUFFER_LOAD")
+                    && !name.ends_with("_INV")
+                    && !name.ends_with("WBL2")
+                {
+                    has_mem_store = true;
+                }
+            }
+            "ENC_FLAT" | "ENC_FLAT_GLBL" => {
+                if name.contains("_STORE_") || !name.contains("_LOAD_") {
+                    has_mem_store = true;
+                }
+            }
+            "ENC_SMEM" => {
+                if name.starts_with("S_STORE") || name.starts_with("S_BUFFER_STORE") {
+                    has_mem_store = true;
+                } else if smem_load_count(name).is_none()
+                    && !matches!(name, "S_MEMTIME" | "S_MEMREALTIME")
+                    && !name.contains("_INV")
+                {
+                    has_mem_store = true;
+                }
+            }
+            _ => {}
+        }
+    }
+
+    has_s_barrier && has_mem_store
+}
+
+/// Maximum byte span for a single hoisted SMEM or `s_buffer_load` group (full 21-bit SMEM range;
+/// valid non-`Kernel` UMA allocations never straddle 4 GiB, so zero wrap-fallback duplication!).
+const MAX_SMEM_GROUP_SPAN: i64 = 1_048_576;
+/// Maximum number of deduplicated loads per hoisted SMEM or `s_buffer_load` group.
+const MAX_SMEM_GROUP_LOADS: usize = 96;
+
+/// Returns true iff `d` can mutate global/UMA memory, synchronize memory visibility across
+/// lanes/workgroups, or transfer control to unknown code that may mutate memory.
+fn is_memory_hazard(d: &Decoded, opt: &Options) -> bool {
+    let name = d.inst.name;
+    let enc = d.enc.name;
+    match enc {
+        "ENC_SMEM" => {
+            smem_load_count(name).is_none()
+                && !matches!(name, "S_MEMTIME" | "S_MEMREALTIME" | "S_ICACHE_INV")
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            !name.starts_with("BUFFER_LOAD") && !name.starts_with("TBUFFER_LOAD")
+        }
+        "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => {
+            !name.contains("_LOAD_") || name.contains("_STORE_") || name.contains("_ATOMIC_")
+        }
+        "ENC_MIMG" => {
+            let base = name.trim_start_matches("IMAGE_");
+            base.starts_with("STORE") || base.starts_with("ATOMIC_")
+        }
+        "ENC_SOPP" => matches!(name, "S_BARRIER" | "S_SENDMSG"),
+        "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => {
+            name.starts_with("S_CALL")
+                || (name == "S_SETPC_B64"
+                    && d.far_target.is_none()
+                    && !matches!(opt.mode, Mode::Geometry(_)))
+                || (name == "S_SWAPPC_B64" && fval(d, "SDST") != fval(d, "SSRC0"))
+        }
+        "ENC_DS" | "ENC_EXP" | "ENC_VINTRP" => false,
+        e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => false,
+        _ => true,
+    }
+}
+
+fn is_terminator_inst(d: &Decoded) -> bool {
+    d.far_target.is_some()
+        || rdna2::branch_target(d).is_some()
+        || d.inst.flags & F_TERMINATOR != 0
+        || d.inst.flags & F_INDIRECT != 0
+        || matches!(
+            d.inst.name,
+            "S_ENDPGM" | "S_ENDPGM_SAVED" | "S_ENDPGM_ORDERED_PS_DONE" | "S_SETPC_B64"
+        )
+}
+
+/// Exact CFG dominator tree computed via iterative RPO + Cooper-Harvey-Kennedy algorithm.
+struct DomTree {
+    rpo_order: Vec<usize>,
+    rpo_num: Vec<usize>,
+    idom: Vec<Option<usize>>,
+}
+
+impl DomTree {
+    fn build(num_blocks: usize, succs: &[Vec<usize>], preds: &[Vec<usize>]) -> Self {
+        let mut visited = vec![false; num_blocks];
+        let mut postorder = Vec::with_capacity(num_blocks);
+
+        // Iterative DFS from entry block 0.
+        if num_blocks > 0 {
+            let mut stack: Vec<(usize, usize)> = vec![(0, 0)];
+            visited[0] = true;
+            while let Some((b, si)) = stack.last_mut() {
+                let b_val = *b;
+                if *si < succs[b_val].len() {
+                    let s = succs[b_val][*si];
+                    *si += 1;
+                    if !visited[s] {
+                        visited[s] = true;
+                        stack.push((s, 0));
+                    }
+                } else {
+                    postorder.push(b_val);
+                    stack.pop();
+                }
+            }
+        }
+
+        let mut rpo_order = postorder;
+        rpo_order.reverse();
+        let mut rpo_num = vec![usize::MAX; num_blocks];
+        for (idx, &b) in rpo_order.iter().enumerate() {
+            rpo_num[b] = idx;
+        }
+
+        let mut idom: Vec<Option<usize>> = vec![None; num_blocks];
+        if num_blocks > 0 {
+            idom[0] = Some(0);
+        }
+
+        let intersect = |mut f1: usize, mut f2: usize, idom: &[Option<usize>], rpo_num: &[usize]| -> usize {
+            while f1 != f2 {
+                while rpo_num[f1] > rpo_num[f2] {
+                    f1 = idom[f1].unwrap();
+                }
+                while rpo_num[f2] > rpo_num[f1] {
+                    f2 = idom[f2].unwrap();
+                }
+            }
+            f1
+        };
+
+        let mut changed = true;
+        while changed {
+            changed = false;
+            for &b in rpo_order.iter().skip(1) {
+                let mut new_idom: Option<usize> = None;
+                for &p in &preds[b] {
+                    if idom[p].is_some() {
+                        new_idom = Some(match new_idom {
+                            None => p,
+                            Some(cur) => intersect(p, cur, &idom, &rpo_num),
+                        });
+                    }
+                }
+                if new_idom.is_some() && idom[b] != new_idom {
+                    idom[b] = new_idom;
+                    changed = true;
+                }
+            }
+        }
+
+        Self {
+            rpo_order,
+            rpo_num,
+            idom,
+        }
+    }
+
+    #[inline]
+    fn is_reachable(&self, b: usize) -> bool {
+        b < self.rpo_num.len() && self.rpo_num[b] != usize::MAX
+    }
+
+    fn dominates(&self, a: usize, b: usize) -> bool {
+        if !self.is_reachable(a) || !self.is_reachable(b) || self.rpo_num[a] > self.rpo_num[b] {
+            return false;
+        }
+        let mut cur = b;
+        while cur != a {
+            if cur == 0 {
+                return false;
+            }
+            cur = match self.idom[cur] {
+                Some(p) => p,
+                None => return false,
+            };
+        }
+        true
+    }
+
+    fn lca(&self, mut f1: usize, mut f2: usize) -> Option<usize> {
+        if !self.is_reachable(f1) || !self.is_reachable(f2) {
+            return None;
+        }
+        while f1 != f2 {
+            while self.rpo_num[f1] > self.rpo_num[f2] {
+                f1 = self.idom[f1]?;
+            }
+            while self.rpo_num[f2] > self.rpo_num[f1] {
+                f2 = self.idom[f2]?;
+            }
+        }
+        Some(f1)
+    }
+}
+
+/// Unique reaching-definition identity for a plain SGPR `s0..s105`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+enum DefVal {
+    Bottom,
+    Entry,
+    Inst(usize),
+    Top,
+}
+
+#[inline]
+fn meet_def(a: DefVal, b: DefVal) -> DefVal {
+    match (a, b) {
+        (DefVal::Bottom, x) | (x, DefVal::Bottom) => x,
+        (x, y) if x == y => x,
+        _ => DefVal::Top,
+    }
+}
+
+/// Lattice value for CFG-wide plain SGPR constant propagation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ConstVal {
+    Bottom,
+    Known(u32),
+    Top,
+}
+
+#[inline]
+fn meet_const(a: ConstVal, b: ConstVal) -> ConstVal {
+    match (a, b) {
+        (ConstVal::Bottom, x) | (x, ConstVal::Bottom) => x,
+        (ConstVal::Known(x), ConstVal::Known(y)) if x == y => ConstVal::Known(x),
+        _ => ConstVal::Top,
+    }
+}
+
+#[inline]
+fn resolve_const_scalar(d: &Decoded, code: u64, state: &[ConstVal; 106]) -> Option<u32> {
+    if code < 106 {
+        match state[code as usize] {
+            ConstVal::Known(v) => Some(v),
+            _ => None,
+        }
+    } else {
+        inline_const_bits(code, d.literal, false)
+    }
+}
+
+/// Apply one instruction's effect to `(defs, consts)` for plain SGPRs `0..106`.
+fn step_sgpr_def_const(
+    inst_idx: usize,
+    d: &Decoded,
+    info: &InstInfo,
+    defs: &mut [DefVal; 106],
+    consts: &mut [ConstVal; 106],
+) {
+    let name = d.inst.name;
+    let mut new_c: [(usize, ConstVal); 2] = [(usize::MAX, ConstVal::Top); 2];
+    let mut new_c_len = 0usize;
+
+    match name {
+        "S_MOV_B32" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                if let Some(v) = resolve_const_scalar(d, fval(d, "SSRC0"), consts) {
+                    new_c[0] = (sd, ConstVal::Known(v));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_MOVK_I32" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                let v = fval(d, "SIMM16") as u16 as i16 as i32 as u32;
+                new_c[0] = (sd, ConstVal::Known(v));
+                new_c_len = 1;
+            }
+        }
+        "S_MOV_B64" => {
+            let sd = fval(d, "SDST") as usize;
+            let s0 = fval(d, "SSRC0");
+            if sd + 1 < 106 {
+                match s0 {
+                    0..=104 => {
+                        let lo = consts[s0 as usize];
+                        let hi = consts[s0 as usize + 1];
+                        if matches!(lo, ConstVal::Known(_)) {
+                            new_c[new_c_len] = (sd, lo);
+                            new_c_len += 1;
+                        }
+                        if matches!(hi, ConstVal::Known(_)) {
+                            new_c[new_c_len] = (sd + 1, hi);
+                            new_c_len += 1;
+                        }
+                    }
+                    128..=208 => {
+                        if let Some(v32) = inline_const_bits(s0, d.literal, false) {
+                            let v64 = v32 as i32 as i64;
+                            new_c[0] = (sd, ConstVal::Known(v64 as u32));
+                            new_c[1] = (sd + 1, ConstVal::Known((v64 >> 32) as u32));
+                            new_c_len = 2;
+                        }
+                    }
+                    255 => {
+                        if let Some(lit) = d.literal {
+                            new_c[0] = (sd, ConstVal::Known(lit));
+                            new_c[1] = (sd + 1, ConstVal::Known(0));
+                            new_c_len = 2;
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        }
+        "S_XOR_B32" => {
+            let sd = fval(d, "SDST") as usize;
+            let s0 = fval(d, "SSRC0");
+            let s1 = fval(d, "SSRC1");
+            if sd < 106 {
+                if s0 == s1 && s0 < 106 {
+                    new_c[0] = (sd, ConstVal::Known(0));
+                    new_c_len = 1;
+                } else if let (Some(a), Some(b)) = (
+                    resolve_const_scalar(d, s0, consts),
+                    resolve_const_scalar(d, s1, consts),
+                ) {
+                    new_c[0] = (sd, ConstVal::Known(a ^ b));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_XOR_B64" => {
+            let sd = fval(d, "SDST") as usize;
+            let s0 = fval(d, "SSRC0");
+            let s1 = fval(d, "SSRC1");
+            if sd + 1 < 106 && s0 == s1 && s0 < 105 {
+                new_c[0] = (sd, ConstVal::Known(0));
+                new_c[1] = (sd + 1, ConstVal::Known(0));
+                new_c_len = 2;
+            }
+        }
+        "S_AND_B32" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                let a = resolve_const_scalar(d, fval(d, "SSRC0"), consts);
+                let b = resolve_const_scalar(d, fval(d, "SSRC1"), consts);
+                if a == Some(0) || b == Some(0) {
+                    new_c[0] = (sd, ConstVal::Known(0));
+                    new_c_len = 1;
+                } else if let (Some(a), Some(b)) = (a, b) {
+                    new_c[0] = (sd, ConstVal::Known(a & b));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_AND_B64" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd + 1 < 106 {
+                let s0 = fval(d, "SSRC0");
+                let s1 = fval(d, "SSRC1");
+                let hi_of = |code: u64| -> Option<u32> {
+                    if code < 105 {
+                        match consts[code as usize + 1] {
+                            ConstVal::Known(v) => Some(v),
+                            _ => None,
+                        }
+                    } else if matches!(code, 128..=208) {
+                        inline_const_bits(code, d.literal, false).map(|v| ((v as i32 as i64) >> 32) as u32)
+                    } else if code == 255 && d.literal.is_some() {
+                        Some(0)
+                    } else {
+                        None
+                    }
+                };
+                let (h0, h1) = (hi_of(s0), hi_of(s1));
+                if h0 == Some(0) || h1 == Some(0) {
+                    new_c[0] = (sd + 1, ConstVal::Known(0));
+                    new_c_len = 1;
+                } else if let (Some(a), Some(b)) = (h0, h1) {
+                    new_c[0] = (sd + 1, ConstVal::Known(a & b));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_OR_B32" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                let a = resolve_const_scalar(d, fval(d, "SSRC0"), consts);
+                let b = resolve_const_scalar(d, fval(d, "SSRC1"), consts);
+                if a == Some(u32::MAX) || b == Some(u32::MAX) {
+                    new_c[0] = (sd, ConstVal::Known(u32::MAX));
+                    new_c_len = 1;
+                } else if let (Some(a), Some(b)) = (a, b) {
+                    new_c[0] = (sd, ConstVal::Known(a | b));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_SUB_U32" | "S_SUB_I32" => {
+            let sd = fval(d, "SDST") as usize;
+            let s0 = fval(d, "SSRC0");
+            let s1 = fval(d, "SSRC1");
+            if sd < 106 {
+                if s0 == s1 && s0 < 106 {
+                    new_c[0] = (sd, ConstVal::Known(0));
+                    new_c_len = 1;
+                } else if let (Some(a), Some(b)) = (
+                    resolve_const_scalar(d, s0, consts),
+                    resolve_const_scalar(d, s1, consts),
+                ) {
+                    new_c[0] = (sd, ConstVal::Known(a.wrapping_sub(b)));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_ADD_U32" | "S_ADD_I32" | "S_MUL_I32" | "S_LSHL_B32" | "S_LSHR_B32" | "S_ASHR_I32"
+        | "S_PACK_LL_B32_B16" | "S_PACK_LH_B32_B16" | "S_PACK_HH_B32_B16" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                if let (Some(a), Some(b)) = (
+                    resolve_const_scalar(d, fval(d, "SSRC0"), consts),
+                    resolve_const_scalar(d, fval(d, "SSRC1"), consts),
+                ) {
+                    let v = match name {
+                        "S_ADD_U32" | "S_ADD_I32" => a.wrapping_add(b),
+                        "S_MUL_I32" => a.wrapping_mul(b),
+                        "S_LSHL_B32" => a << (b & 31),
+                        "S_LSHR_B32" => a >> (b & 31),
+                        "S_ASHR_I32" => ((a as i32) >> (b & 31)) as u32,
+                        "S_PACK_LL_B32_B16" => (a & 0xFFFF) | (b << 16),
+                        "S_PACK_LH_B32_B16" => (a & 0xFFFF) | (b & 0xFFFF_0000),
+                        "S_PACK_HH_B32_B16" => (a >> 16) | (b & 0xFFFF_0000),
+                        _ => unreachable!(),
+                    };
+                    new_c[0] = (sd, ConstVal::Known(v));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_ADDK_I32" | "S_MULK_I32" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                if let ConstVal::Known(cur) = consts[sd] {
+                    let k = fval(d, "SIMM16") as u16 as i16 as i32 as u32;
+                    let v = if name == "S_ADDK_I32" {
+                        cur.wrapping_add(k)
+                    } else {
+                        cur.wrapping_mul(k)
+                    };
+                    new_c[0] = (sd, ConstVal::Known(v));
+                    new_c_len = 1;
+                }
+            }
+        }
+        "S_NOT_B32" => {
+            let sd = fval(d, "SDST") as usize;
+            if sd < 106 {
+                if let Some(a) = resolve_const_scalar(d, fval(d, "SSRC0"), consts) {
+                    new_c[0] = (sd, ConstVal::Known(!a));
+                    new_c_len = 1;
+                }
+            }
+        }
+        _ => {}
+    }
+
+    if info.indirect_sgpr {
+        *defs = [DefVal::Top; 106];
+        *consts = [ConstVal::Top; 106];
+        return;
+    }
+
+    let mut m = info.s_mod & S_PLAIN_MASK;
+    while m != 0 {
+        let r = m.trailing_zeros() as usize;
+        m &= m - 1;
+        defs[r] = DefVal::Inst(inst_idx);
+        consts[r] = ConstVal::Top;
+    }
+    for &(r, cv) in &new_c[..new_c_len] {
+        consts[r] = cv;
+    }
+}
+
+/// Forward CFG-wide fixpoint for SGPR reaching definitions and constant values.
+fn solve_cfg_sgpr_defs_and_consts(
+    num_blocks: usize,
+    dom: &DomTree,
+    cfg_preds: &[Vec<usize>],
+    block_ranges: &[(usize, usize)],
+    eff_end: &[usize],
+    insts: &[Decoded],
+    infos: &[InstInfo],
+    dead_inst: &HashSet<u64>,
+    has_unknown_cf: bool,
+) -> (Vec<[DefVal; 106]>, Vec<[ConstVal; 106]>) {
+    let mut def_in = vec![[DefVal::Bottom; 106]; num_blocks];
+    let mut def_out = vec![[DefVal::Bottom; 106]; num_blocks];
+    let mut const_in = vec![[ConstVal::Bottom; 106]; num_blocks];
+    let mut const_out = vec![[ConstVal::Bottom; 106]; num_blocks];
+
+    if num_blocks == 0 {
+        return (def_in, const_in);
+    }
+
+    if has_unknown_cf {
+        // Conservative under indirect branches: every block entry is Top.
+        for bi in 0..num_blocks {
+            def_in[bi] = [DefVal::Top; 106];
+            const_in[bi] = [ConstVal::Top; 106];
+        }
+        def_in[0] = [DefVal::Entry; 106];
+        return (def_in, const_in);
+    }
+
+    def_in[0] = [DefVal::Entry; 106];
+    const_in[0] = [ConstVal::Top; 106];
+
+    loop {
+        let mut changed = false;
+        for &bi in &dom.rpo_order {
+            let (in_d, in_c) = if bi == 0 {
+                let mut d0 = [DefVal::Entry; 106];
+                let mut c0 = [ConstVal::Top; 106];
+                for &p in &cfg_preds[0] {
+                    if dom.is_reachable(p) {
+                        for r in 0..106 {
+                            d0[r] = meet_def(d0[r], def_out[p][r]);
+                            c0[r] = meet_const(c0[r], const_out[p][r]);
+                        }
+                    }
+                }
+                (d0, c0)
+            } else {
+                let mut d_acc = [DefVal::Bottom; 106];
+                let mut c_acc = [ConstVal::Bottom; 106];
+                for &p in &cfg_preds[bi] {
+                    if dom.is_reachable(p) {
+                        for r in 0..106 {
+                            d_acc[r] = meet_def(d_acc[r], def_out[p][r]);
+                            c_acc[r] = meet_const(c_acc[r], const_out[p][r]);
+                        }
+                    }
+                }
+                (d_acc, c_acc)
+            };
+
+            let mut cur_d = in_d;
+            let mut cur_c = in_c;
+            let s_idx = block_ranges[bi].0;
+            let e_idx = eff_end[bi];
+            for k in s_idx..e_idx {
+                if dead_inst.contains(&insts[k].pc) {
+                    continue;
+                }
+                step_sgpr_def_const(k, &insts[k], &infos[k], &mut cur_d, &mut cur_c);
+            }
+
+            if in_d != def_in[bi]
+                || cur_d != def_out[bi]
+                || in_c != const_in[bi]
+                || cur_c != const_out[bi]
+            {
+                def_in[bi] = in_d;
+                def_out[bi] = cur_d;
+                const_in[bi] = in_c;
+                const_out[bi] = cur_c;
+                changed = true;
+            }
+        }
+        if !changed {
+            break;
+        }
+    }
+
+    (def_in, const_in)
+}
+
+/// Canonical reaching-def key for grouping `s_load_*` base pointer halves.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+enum DefKey {
+    Entry,
+    Inst(usize),
+    /// Block-entry identity for a `Top` reaching def (allows safe intra-block grouping &
+    /// `known_hi == Some(0)` without cross-block hoisting!).
+    LocalEntry(usize),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum HoistLoc {
+    BlockEntry(u64),
+    BeforePc(u64),
+    AfterPc(u64),
+}
+
+#[derive(Clone, Debug)]
+struct SmemCand {
+    bi: usize,
+    local_idx: usize,
+    pc: u64,
+    off: i64,
+    count: u8,
+    end: i64,
+}
+
+/// Deduplicate & subsume `(offset, count)` pairs into sorted `HoistedLoad`s.
+/// Sub-range subsumption (`parent` covers `child`) is applied only when `allow_subsume_neg || parent.offset >= 0`.
+fn dedup_and_subsume_loads(
+    pairs: &[(i64, u8)],
+    allow_subsume_neg: bool,
+) -> (Vec<HoistedLoad>, HashMap<(i64, u8), (u16, u8, u8)>) {
+    let mut uniq: Vec<(i64, u8)> = pairs.to_vec();
+    uniq.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| b.1.cmp(&a.1)));
+    uniq.dedup();
+
+    let mut loads: Vec<HoistedLoad> = Vec::with_capacity(uniq.len());
+    let mut map: HashMap<(i64, u8), (u16, u8, u8)> = HashMap::with_capacity(uniq.len());
+
+    for &(off, count) in &uniq {
+        let end = off + 4 * (count as i64);
+        let mut found: Option<(u16, u8, u8)> = None;
+        for (idx, parent) in loads.iter().enumerate() {
+            let p_end = parent.offset + 4 * (parent.count as i64);
+            if parent.offset == off && parent.count == count {
+                found = Some((idx as u16, 0, parent.count));
+                break;
+            }
+            if (allow_subsume_neg || parent.offset >= 0) && parent.offset <= off && end <= p_end {
+                let dw_off = ((off - parent.offset) / 4) as u8;
+                found = Some((idx as u16, dw_off, parent.count));
+                break;
+            }
+        }
+        if let Some(m) = found {
+            map.insert((off, count), m);
+        } else {
+            let idx = loads.len() as u16;
+            loads.push(HoistedLoad { offset: off, count });
+            map.insert((off, count), (idx, 0, count));
+        }
+    }
+
+    (loads, map)
+}
+
+struct HoistedSmemResult {
+    groups: Vec<HoistedSmemGroup>,
+    at_entry: HashMap<u64, Vec<usize>>,
+    before_pc: HashMap<u64, Vec<usize>>,
+    after_pc: HashMap<u64, Vec<usize>>,
+    uses: HashMap<u64, SmemUse>,
+}
+
+/// Weapon 1A: Dominator-hoisted & CSE'd invariant `s_load_dword*` groups + known-zero-hi Window-0 fast path.
+#[allow(clippy::too_many_arguments)]
+fn analyze_hoisted_smem(
+    insts: &[Decoded],
+    infos: &[InstInfo],
+    block_starts: &[u64],
+    block_ranges: &[(usize, usize)],
+    eff_end: &[usize],
+    dom: &DomTree,
+    cfg_preds: &[Vec<usize>],
+    unknown_succ: &[bool],
+    inst_hazard: &[bool],
+    dead_inst: &HashSet<u64>,
+    def_in: &[[DefVal; 106]],
+    const_in: &[[ConstVal; 106]],
+    opt: &Options,
+    has_unknown_cf: bool,
+) -> HoistedSmemResult {
+    let num_blocks = block_starts.len();
+    let kernel_mode = matches!(opt.mode, Mode::Kernel);
+
+    // Per-instruction block lookup and per-block hazard / SGPR-mod summaries.
+    let mut inst_block = vec![0usize; insts.len()];
+    let mut inst_local_idx = vec![0usize; insts.len()];
+    let mut block_has_hazard = vec![false; num_blocks];
+    let mut block_mod_s = vec![0u128; num_blocks];
+    let mut block_indirect_sgpr = vec![false; num_blocks];
+
+    for bi in 0..num_blocks {
+        let s_idx = block_ranges[bi].0;
+        let e_idx = eff_end[bi];
+        for (li, k) in (s_idx..e_idx).enumerate() {
+            inst_block[k] = bi;
+            inst_local_idx[k] = li;
+            if dead_inst.contains(&insts[k].pc) {
+                continue;
+            }
+            if inst_hazard[k] {
+                block_has_hazard[bi] = true;
+            }
+            block_mod_s[bi] |= infos[k].s_mod;
+            if infos[k].indirect_sgpr {
+                block_indirect_sgpr[bi] = true;
+            }
+        }
+    }
+
+    // Collect candidate `s_load_dword*` grouped by `(sbase, key_lo, key_hi)` in deterministic order.
+    let mut groups_by_key: BTreeMap<(u8, DefKey, DefKey), Vec<SmemCand>> = BTreeMap::new();
+    // Track per-block `(const_s_before_inst)` on demand by re-stepping block `H` when validating.
+    for &bi in &dom.rpo_order {
+        let s_idx = block_ranges[bi].0;
+        let e_idx = eff_end[bi];
+        let mut cur_d = def_in[bi];
+        let mut cur_c = const_in[bi];
+
+        for (li, k) in (s_idx..e_idx).enumerate() {
+            let d = &insts[k];
+            if dead_inst.contains(&d.pc) {
+                continue;
+            }
+            if d.enc.name == "ENC_SMEM" && d.inst.name.starts_with("S_LOAD_") {
+                if let Some(count) = smem_load_count(d.inst.name) {
+                    let is_glc_dlc = rdna2::field_value(d.enc, &d.words, "GLC") == Some(1)
+                        || rdna2::field_value(d.enc, &d.words, "DLC") == Some(1);
+                    let sbase = scaled_field(d, "SBASE");
+                    let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125);
+                    let raw_imm = fval(d, "OFFSET") as u32;
+                    let off = ((raw_imm << 11) as i32 >> 11) as i64;
+
+                    if !is_glc_dlc && sbase + 2 <= 106 && soff == 125 && (off & 3) == 0 {
+                        let to_key = |dv: DefVal| -> DefKey {
+                            if has_unknown_cf {
+                                return DefKey::LocalEntry(bi);
+                            }
+                            match dv {
+                                DefVal::Entry => DefKey::Entry,
+                                DefVal::Inst(di) => DefKey::Inst(di),
+                                DefVal::Top | DefVal::Bottom => DefKey::LocalEntry(bi),
+                            }
+                        };
+                        let key_lo = to_key(cur_d[sbase as usize]);
+                        let key_hi = to_key(cur_d[sbase as usize + 1]);
+                        groups_by_key
+                            .entry((sbase as u8, key_lo, key_hi))
+                            .or_default()
+                            .push(SmemCand {
+                                bi,
+                                local_idx: li,
+                                pc: d.pc,
+                                off,
+                                count: count as u8,
+                                end: off + 4 * (count as i64),
+                            });
+                    }
+                }
+            }
+            step_sgpr_def_const(k, d, &infos[k], &mut cur_d, &mut cur_c);
+        }
+    }
+
+    let def_block_of = |key: DefKey| -> usize {
+        match key {
+            DefKey::Entry => 0,
+            DefKey::Inst(di) => inst_block[di],
+            DefKey::LocalEntry(bi) => bi,
+        }
+    };
+
+    // Validate a candidate cluster: returns `Some((hoist_bi, h_idx, HoistLoc))` if 100% sound.
+    let validate_cluster = |sbase: u8,
+                            key_lo: DefKey,
+                            key_hi: DefKey,
+                            cluster: &[SmemCand]|
+     -> Option<(usize, usize, HoistLoc)> {
+        if cluster.is_empty() {
+            return None;
+        }
+        let mut min_off = i64::MAX;
+        let mut max_end = i64::MIN;
+        let mut h = cluster[0].bi;
+        for u in cluster {
+            min_off = min_off.min(u.off);
+            max_end = max_end.max(u.end);
+            h = dom.lca(h, u.bi)?;
+        }
+        if max_end - min_off > MAX_SMEM_GROUP_SPAN {
+            return None;
+        }
+        if !dom.dominates(def_block_of(key_lo), h) || !dom.dominates(def_block_of(key_hi), h) {
+            return None;
+        }
+
+        let hs_idx = block_ranges[h].0;
+        let he_idx = eff_end[h];
+        let h_len = he_idx - hs_idx;
+
+        let min_use_in_h = cluster
+            .iter()
+            .filter(|u| u.bi == h)
+            .map(|u| u.local_idx)
+            .min();
+
+        let (h_idx, hoist_loc) = if let Some(u_li) = min_use_in_h {
+            // Def inside H must strictly precede the hoist point.
+            if let DefKey::Inst(di) = key_lo {
+                if inst_block[di] == h && inst_local_idx[di] >= u_li {
+                    return None;
+                }
+            }
+            if let DefKey::Inst(di) = key_hi {
+                if inst_block[di] == h && inst_local_idx[di] >= u_li {
+                    return None;
+                }
+            }
+            (u_li, HoistLoc::BeforePc(insts[hs_idx + u_li].pc))
+        } else if h_len == 0 {
+            (0, HoistLoc::BlockEntry(block_starts[h]))
+        } else {
+            let last_k = he_idx - 1;
+            if is_terminator_inst(&insts[last_k]) {
+                let place_li = h_len - 1;
+                if let DefKey::Inst(di) = key_lo {
+                    if inst_block[di] == h && inst_local_idx[di] >= place_li {
+                        return None;
+                    }
+                }
+                if let DefKey::Inst(di) = key_hi {
+                    if inst_block[di] == h && inst_local_idx[di] >= place_li {
+                        return None;
+                    }
+                }
+                (place_li, HoistLoc::BeforePc(insts[last_k].pc))
+            } else {
+                // Fallthrough block: emit immediately after the last instruction of H.
+                (h_len, HoistLoc::AfterPc(insts[last_k].pc))
+            }
+        };
+
+        let base_mask = (1u128 << sbase) | (1u128 << (sbase + 1));
+
+        // Helper: check slice of instructions `lo..hi` inside block `bi` for hazard or base clobber.
+        let slice_is_clean = |bi: usize, lo: usize, hi: usize| -> bool {
+            let bs = block_ranges[bi].0;
+            for li in lo..hi {
+                let k = bs + li;
+                if dead_inst.contains(&insts[k].pc) {
+                    continue;
+                }
+                if inst_hazard[k]
+                    || infos[k].indirect_sgpr
+                    || (infos[k].s_mod & base_mask) != 0
+                {
+                    return false;
+                }
+            }
+            true
+        };
+
+        let mut checked_h_suffix = false;
+        let mut clean_interm_checked: HashSet<usize> = HashSet::new();
+
+        for u in cluster {
+            if u.bi == h {
+                if u.local_idx < h_idx || !slice_is_clean(h, h_idx, u.local_idx) {
+                    return None;
+                }
+            } else {
+                if !checked_h_suffix {
+                    if unknown_succ[h] || !slice_is_clean(h, h_idx, h_len) {
+                        return None;
+                    }
+                    checked_h_suffix = true;
+                }
+                if !slice_is_clean(u.bi, 0, u.local_idx) {
+                    return None;
+                }
+                // Backwards BFS from `cfg_preds[u.bi]` stopping at `h`.
+                // Note: `u.bi` itself is NOT pre-marked visited so cycles back to `u.bi`
+                // without passing through `h` DO visit `u.bi` and check `block_has_hazard[u.bi]`!
+                if !clean_interm_checked.contains(&u.bi) {
+                    let mut visited: HashSet<usize> = HashSet::new();
+                    let mut queue: VecDeque<usize> = VecDeque::new();
+                    for &p in &cfg_preds[u.bi] {
+                        if dom.is_reachable(p) && visited.insert(p) {
+                            queue.push_back(p);
+                        }
+                    }
+                    while let Some(m) = queue.pop_front() {
+                        if m == h {
+                            continue;
+                        }
+                        if m == 0 {
+                            // Reached entry without passing through H -> H does not dominate U!
+                            return None;
+                        }
+                        if block_has_hazard[m]
+                            || block_indirect_sgpr[m]
+                            || (block_mod_s[m] & base_mask) != 0
+                            || unknown_succ[m]
+                        {
+                            return None;
+                        }
+                        for &p in &cfg_preds[m] {
+                            if dom.is_reachable(p) && visited.insert(p) {
+                                queue.push_back(p);
+                            }
+                        }
+                    }
+                    clean_interm_checked.insert(u.bi);
+                }
+            }
+        }
+
+        Some((h, h_idx, hoist_loc))
+    };
+
+    // Compute `const_s[sbase + 1]` at exact point `(h, h_idx)`.
+    let const_hi_at = |h: usize, h_idx: usize, sbase: u8| -> Option<u32> {
+        let mut cur_d = def_in[h];
+        let mut cur_c = const_in[h];
+        let hs = block_ranges[h].0;
+        for li in 0..h_idx {
+            let k = hs + li;
+            if dead_inst.contains(&insts[k].pc) {
+                continue;
+            }
+            step_sgpr_def_const(k, &insts[k], &infos[k], &mut cur_d, &mut cur_c);
+        }
+        match cur_c[sbase as usize + 1] {
+            ConstVal::Known(v) => Some(v),
+            _ => None,
+        }
+    };
+
+    let mut out = HoistedSmemResult {
+        groups: Vec::new(),
+        at_entry: HashMap::new(),
+        before_pc: HashMap::new(),
+        after_pc: HashMap::new(),
+        uses: HashMap::new(),
+    };
+
+    for ((sbase, key_lo, key_hi), cands) in groups_by_key {
+        // Fast path: try the entire set as one cluster first!
+        let clusters: Vec<(Vec<SmemCand>, usize, usize, HoistLoc)> =
+            if let Some((h, h_idx, loc)) = validate_cluster(sbase, key_lo, key_hi, &cands) {
+                vec![(cands, h, h_idx, loc)]
+            } else {
+                // Partition greedily into maximal hazard-free clusters.
+                let mut open: Vec<(Vec<SmemCand>, usize, usize, HoistLoc)> = Vec::new();
+                for cand in cands {
+                    let mut placed = false;
+                    let start_try = open.len().saturating_sub(4);
+                    for entry in open[start_try..].iter_mut().rev() {
+                        entry.0.push(cand.clone());
+                        if let Some((h, h_idx, loc)) = validate_cluster(sbase, key_lo, key_hi, &entry.0) {
+                            entry.1 = h;
+                            entry.2 = h_idx;
+                            entry.3 = loc;
+                            placed = true;
+                            break;
+                        }
+                        entry.0.pop();
+                    }
+                    if !placed {
+                        let single = vec![cand];
+                        if let Some((h, h_idx, loc)) = validate_cluster(sbase, key_lo, key_hi, &single) {
+                            open.push((single, h, h_idx, loc));
+                        }
+                    }
+                }
+                open
+            };
+
+        for (cluster, h, h_idx, hoist_loc) in clusters {
+            let pairs: Vec<(i64, u8)> = cluster.iter().map(|u| (u.off, u.count)).collect();
+            let (all_loads, pair_map) = dedup_and_subsume_loads(&pairs, false);
+            let hi_const = const_hi_at(h, h_idx, sbase);
+
+            // Chunk into groups of `<= MAX_SMEM_GROUP_LOADS`.
+            let num_chunks = all_loads.len().div_ceil(MAX_SMEM_GROUP_LOADS);
+            for chunk_i in 0..num_chunks {
+                let lo_l = chunk_i * MAX_SMEM_GROUP_LOADS;
+                let hi_l = (lo_l + MAX_SMEM_GROUP_LOADS).min(all_loads.len());
+                let chunk_loads: Vec<HoistedLoad> = all_loads[lo_l..hi_l].to_vec();
+
+                let mut chunk_uses: Vec<(&SmemCand, u16, u8, u8)> = Vec::new();
+                for u in &cluster {
+                    let (global_li, dw_off, parent_cnt) = pair_map[&(u.off, u.count)];
+                    let gi = global_li as usize;
+                    if gi >= lo_l && gi < hi_l {
+                        chunk_uses.push((u, (gi - lo_l) as u16, dw_off, parent_cnt));
+                    }
+                }
+                if chunk_uses.is_empty() {
+                    continue;
+                }
+
+                let min_off = chunk_loads.iter().map(|l| l.offset).min().unwrap();
+                let max_end = chunk_loads
+                    .iter()
+                    .map(|l| l.offset + 4 * (l.count as i64))
+                    .max()
+                    .unwrap();
+
+                // CRITICAL: ONLY `hi == 0` unconditionally maps to Window 0 regardless of `xcl_uma_base`!
+                // Guardrail (`#326`): in `Mode::Kernel`, ONLY allow `known_hi = Some(0)` when
+                // `min_off == 0 && max_end <= 4` (cannot cross 4 GiB boundary!).
+                // In non-`Kernel` modes, valid UMA allocations never straddle 4 GiB, so the full
+                // 21-bit SMEM immediate range `[-1_048_576, 1_048_576]` is Window-0 safe.
+                let known_hi = if hi_const == Some(0) {
+                    if kernel_mode {
+                        (min_off == 0 && max_end <= 4).then_some(0)
+                    } else if min_off >= -1_048_576 && max_end <= 1_048_576 {
+                        Some(0)
+                    } else {
+                        None
+                    }
+                } else {
+                    None
+                };
+
+                let worth_emitting = if opt.mem_windows > 1 {
+                    chunk_uses.len() >= 2 || known_hi.is_some()
+                } else {
+                    chunk_uses.len() >= 2
+                };
+                if !worth_emitting {
+                    continue;
+                }
+
+                let gid = out.groups.len() as u32;
+                let gidx = out.groups.len();
+                out.groups.push(HoistedSmemGroup {
+                    id: gid,
+                    hoist_block: block_starts[h],
+                    sbase,
+                    known_hi,
+                    min_off,
+                    max_end,
+                    loads: chunk_loads,
+                });
+                match hoist_loc {
+                    HoistLoc::BlockEntry(bpc) => out.at_entry.entry(bpc).or_default().push(gidx),
+                    HoistLoc::BeforePc(pc) => out.before_pc.entry(pc).or_default().push(gidx),
+                    HoistLoc::AfterPc(pc) => out.after_pc.entry(pc).or_default().push(gidx),
+                }
+                for (u, load_idx, dword_offset, parent_count) in chunk_uses {
+                    out.uses.insert(
+                        u.pc,
+                        SmemUse {
+                            group_id: gid,
+                            load_idx,
+                            parent_count,
+                            dword_offset,
+                            count: u.count,
+                        },
+                    );
+                }
+            }
+        }
+    }
+
+    out
+}
+
+/// Universal non-`Kernel` Window-0 fast-path sets (`known_zero_hi_sload`, `known_zero_hi_sbuf`).
+///
+/// Covers EVERY non-`Kernel` `s_load_dword*` (including `soff != 125`, dynamic `s_lo`, and
+/// post-store loads) where `s[sbase+1] == 0` (and `imm_off >= 0` when `soff != 125`, or
+/// `-1_048_576 <= imm_off <= 1_048_576` when `soff == 125`), plus EVERY non-`Kernel`
+/// `s_buffer_load_dword*` where `(s[sbase+1] & 0xFFFF) == 0`.
+#[allow(clippy::too_many_arguments)]
+fn collect_known_zero_hi_smem(
+    insts: &[Decoded],
+    infos: &[InstInfo],
+    block_ranges: &[(usize, usize)],
+    eff_end: &[usize],
+    dom: &DomTree,
+    dead_inst: &HashSet<u64>,
+    def_in: &[[DefVal; 106]],
+    const_in: &[[ConstVal; 106]],
+    opt: &Options,
+    has_unknown_cf: bool,
+) -> (HashSet<u64>, HashSet<u64>) {
+    let mut known_zero_hi_sload = HashSet::new();
+    let mut known_zero_hi_sbuf = HashSet::new();
+    if matches!(opt.mode, Mode::Kernel) {
+        return (known_zero_hi_sload, known_zero_hi_sbuf);
+    }
+
+    for bi in 0..block_ranges.len() {
+        if !has_unknown_cf && !dom.is_reachable(bi) {
+            continue;
+        }
+        let s_idx = block_ranges[bi].0;
+        let e_idx = eff_end[bi];
+        let mut cur_d = def_in[bi];
+        let mut cur_c = const_in[bi];
+
+        for k in s_idx..e_idx {
+            let d = &insts[k];
+            if dead_inst.contains(&d.pc) {
+                continue;
+            }
+            if d.enc.name == "ENC_SMEM" && smem_load_count(d.inst.name).is_some() {
+                let sbase = scaled_field(d, "SBASE");
+                if d.inst.name.starts_with("S_LOAD_") {
+                    if sbase + 2 <= 106 && cur_c[sbase as usize + 1] == ConstVal::Known(0) {
+                        let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125);
+                        let raw_imm = fval(d, "OFFSET") as u32;
+                        let imm_off = ((raw_imm << 11) as i32 >> 11) as i64;
+                        let off_ok = if soff != 125 {

[P2] Preserve carry before selecting Window 0. This predicate proves only that the base high dword is zero. With dynamic SOFFSET, imm_off >= 0 does not prevent sbase_lo + imm + soff from carrying into the next 4-GiB window (for example, base 0x00000000_FFFFFFFC plus soff=4). The known_zero_hi emitter path then computes a 32-bit address and reads xcl_mem0, while the generic path forms a 64-bit effective address and selects the next window, so the loaded value differs when mem_windows > 1. The known_zero_hi_sbuf path has the same issue for d0 + off. Could both fast paths retain/select the carry or prove a bound, with parity coverage at the 4-GiB boundary?

<!-- greyfinch-sync:ivall/xcl:review-comment:4685179539 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#discussion_r4685179539). Originally posted by [Flyander](https://github.com/Flyander) on 2026-11-24T19:11:24Z. **Code review location:** `crates/xcl/src/gpu/recomp/opt.rs`; line 3021 ~~~~diff @@ -0,0 +1,5691 @@ +//! Program-level static analysis and optimization metadata for the RDNA2 → HLSL recompiler. +//! +//! Computes PC-keyed liveness, dead-flag / dead-carry / dead-instruction facts, exact CFG +//! dominators, CFG-wide SGPR reaching definitions & constant values, memory-hazard reachability, +//! dominator-hoisted / CSE'd invariant `s_load_*` & `s_buffer_load_*` groups (with known-zero-hi +//! Window-0 fast path), universal non-`Kernel` known-zero-hi `s_load_*` / `s_buffer_load_*` sets, +//! non-consecutive intra-block `s_buffer_load_*` grouping, Wave32 & native-Wave64 lane-local +//! `bool` mask scalarization, intra-block constant propagation, and conditional +//! `globallycoherent` eligibility. +//! +//! Soundness invariants enforced throughout: +//! 1. **VGPR backward liveness under divergent `EXEC`**: every VGPR write is modeled as a +//! read-modify-write (`kill_v = EMPTY`), so dual-mask `if/else` writes never lose liveness. +//! 2. **Dominator-hoisted `s_load_*` (`HoistedSmemGroup`) & `s_buffer_load_*` (`HoistedSbufGroup`)**: +//! - Requires unique dominating reaching definitions (`(def_lo, def_hi)` for `s[b:b+1]`, or +//! `(def_d0, def_d1, def_d2)` for `s[b..b+3]`) and zero writes to those base SGPRs on ANY +//! CFG path (including `LOOP_GUARD` exits & loop cycles) from hoist point `H` to every use `U`. +//! - Requires zero memory hazards (stores, atomics, `s_barrier`, cache inv/wb, `s_sendmsg`, +//! calls/indirect branches, `unknown_succ`) on ANY CFG path from `H` to every use `U`, +//! including loop-carried paths re-entering `U`. +//! - Never hoists or CSEs `GLC`/`DLC` loads. +//! - `known_hi == Some(0)` ONLY when the high base bits are statically proven `0` on all +//! reaching paths (`s[b+1] == 0` for `s_load_*`, `(s[b+1] & 0xFFFF) == 0` for +//! `s_buffer_load_*`), AND obeying the 4 GiB wrap guard: in `Mode::Kernel`, ONLY `s_load_*` +//! with `min_off == 0 && max_end <= 4`; in non-`Kernel` modes, full 21-bit SMEM range +//! (`[-1_048_576, 1_048_576]`; valid UMA allocations never straddle 4 GiB). +//! - Sub-range subsumption on `s_load_*` only when `parent.offset >= 0` (preventing +//! negative-offset underflow mismatch). +//! 3. **Intra-block `s_buffer_load_*` (`IntraBlockSbufGroup`)**: constant-offset (`soff == None`) +//! only, `max_end - min_off <= 1_048_576` (and `max_span == 0` in `Mode::Kernel`), disjoint +//! from `HoistedSbufGroup`, splitting epochs on any memory hazard, `GLC`/`DLC` SMEM op, or +//! write to `sbase..sbase+3`; never uses `[loop]` or wrap-fallback switch duplication. +//! 4. **Lane-local `bool` masks (`lane_local_*`) — Convergence & Hazard Model**: +//! - **Strictly intra-block (zero ballot motion)**: never moves, hoists, sinks, or deduplicates +//! any `WaveActiveBallot` across basic-block boundaries, branches, merges, or loops; every +//! scalarized def-use DAG is contained inside one basic block and must be dead at block exit +//! (`!live_out_s[bi]`). +//! - **Zero cross-lane observation (convergence-free replacement)**: disabled in `Mode::Kernel` +//! and `split_wave64`; scalarizes `V_CMP_*` (non-`CMPX`), `V_ADD/SUB*_CO*_U32`, and dead-`scc` +//! bitwise SALU chains (`S_AND/OR/XOR/NOT/ANDN2/ORN2/NAND/NOR/XNOR/MOV`) only when every +//! consumer reads solely its own lane bit (`V_CNDMASK_B32` mask slot, `V_ADD/SUB*_CO_CI_U32` +//! carry-in slot, or another valid lane-local bitwise op). Any whole-mask consumer +//! (`S_CBRANCH_VCC*`, `S_BCNT*`, `S_FF*`, `EXEC` updates, scalar ALU data operands, memory +//! operands, or unknown/indirect ops) rejects the entire chain. Because lane `i` only ever +//! reads bit `i` of its own lane's ballot, `lanebit(WaveActiveBallot(and(act, cond)))` is +//! identically `and(act, cond)` per lane with zero cross-lane convergence semantics to preserve. +//! - **Divergent `EXEC` & widening guard (`needs_exec_mask`)**: if any `EXEC`-widening op +//! (`is_exec_widening`, e.g., `s_mov`/`s_or`/`s_xor`/`s_not`/`s_nand`/`s_nor`/`s_xnor` to +//! `exec`, `s_wqm`, `s_andn2_saveexec`) executes between a def and its last consumer in the +//! block, `needs_exec_mask = true` captures `and(act, cond)` at the def site so lanes disabled +//! at def remain `false` after `EXEC` is later restored. +//! 5. **Dead `vcc`/carry `sdst`**: for `wave64`, both `n` and `n+1` must be dead; for wave32, +//! only `n` must be dead; `Null` (`125` or `> 127`) is always dead. Carry-in reads on +//! `v_add_co_ci*`/`v_sub*_co_ci*` are always preserved. +//! 6. **`Mode::Kernel` epilogue**: all SGPRs, VGPRs, and `scc` are seeded live at `s_endpgm`. +//! 7. **Unknown / indirect ops**: conservatively mark all registers live/read and restrict +//! hoisting to intra-block only. +//! 8. **Conditional `mem_coherent`**: false only when zero `GLC`/`DLC`/`SLC`, zero memory +//! atomics, zero cache inv/wb ops, and `!(has_s_barrier && has_mem_store)`. + +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; + +use super::emit::ext_encoding; +use super::{Mode, Options}; +use crate::gpu::rdna2::{self, Decoded, Operand, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; + +/// SGPR bitset: bit `n` = `s<n>` (0..=105 plain, 106/107 VCC, 108..=123 ttmp, 124 M0, 126/127 EXEC). +type SRegs = u128; + +const S_VCC_LO: SRegs = 1u128 << 106; +const S_VCC: SRegs = 3u128 << 106; +const S_M0: SRegs = 1u128 << 124; +const S_EXEC: SRegs = 3u128 << 126; +const S_ALL: SRegs = !0u128; +const S_PLAIN_MASK: SRegs = (1u128 << 106) - 1; + +#[inline] +fn sreg_range(first: u64, n: u64) -> SRegs { + if first >= 128 || n == 0 { + return 0; + } + let end = (first + n).min(128); + let mut m = 0u128; + for r in first..end { + if r != 125 { + m |= 1u128 << r; + } + } + m +} + +/// 256-bit VGPR set (`v0..=v255`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct VRegs([u64; 4]); + +impl VRegs { + const EMPTY: Self = Self([0; 4]); + const ALL: Self = Self([!0u64; 4]); + + #[inline] + fn set(&mut self, r: u64) { + if r < 256 { + self.0[(r >> 6) as usize] |= 1u64 << (r & 63); + } + } + + #[inline] + fn set_range(&mut self, first: u64, n: u64) { + let end = (first + n).min(256); + for r in first..end { + self.set(r); + } + } + + #[inline] + fn union(self, other: Self) -> Self { + Self([ + self.0[0] | other.0[0], + self.0[1] | other.0[1], + self.0[2] | other.0[2], + self.0[3] | other.0[3], + ]) + } + + #[inline] + fn intersect(self, other: Self) -> Self { + Self([ + self.0[0] & other.0[0], + self.0[1] & other.0[1], + self.0[2] & other.0[2], + self.0[3] & other.0[3], + ]) + } + + #[inline] + fn is_empty(self) -> bool { + (self.0[0] | self.0[1] | self.0[2] | self.0[3]) == 0 + } +} + +/// One deduplicated load entry inside a `HoistedSmemGroup` or `IntraBlockSbufGroup`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HoistedLoad { + /// Dword-aligned byte offset relative to `sbase` (signed 21-bit for `s_load_*`, + /// unsigned 21-bit for `s_buffer_load_*`). + pub offset: i64, + /// Number of dwords loaded (`1`, `2`, `4`, `8`, or `16`). + pub count: u8, +} + +/// Dominator-hoisted / CSE'd group of invariant `s_load_dword*` ops sharing the exact same +/// 64-bit base pointer `s[sbase:sbase+1]` in a memory-hazard-free dominated region. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HoistedSmemGroup { + /// Unique group id (`0..N`) used for HLSL temp naming (`sm_g{id}_{uid}`). + pub id: u32, + /// Block `start_pc` of the dominator hoist block `H`. + #[allow(dead_code)] + pub hoist_block: u64, + /// Base SGPR pair start index (`s[sbase:sbase+1]`, always `< 105`). + pub sbase: u8, + /// Statically proven `Some(0)` ONLY when `s[sbase+1] == 0` on all reaching paths AND + /// wrap-safe (`Mode::Kernel`: `min_off == 0 && max_end <= 4`; non-`Kernel`: `[-1_048_576, 1_048_576]`). + /// Note: ONLY `hi == 0` maps unconditionally to Window 0 regardless of runtime `xcl_uma_base`. + pub known_hi: Option<u32>, + /// Minimum byte offset across all `loads`. + #[allow(dead_code)] + pub min_off: i64, + /// Maximum end byte offset (`offset + 4 * count`) across all `loads`. + #[allow(dead_code)] + pub max_end: i64, + /// Deduplicated loads in this group (`1..=96`), sorted by `(offset, count)`. + pub loads: Vec<HoistedLoad>, +} + +/// Maps a dominated `s_load_dword*` PC to its pre-loaded temp inside a `HoistedSmemGroup`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct SmemUse { + /// `HoistedSmemGroup::id`. + pub group_id: u32, + /// Index into `HoistedSmemGroup::loads` (`0..loads.len()`). + pub load_idx: u16, + /// `HoistedSmemGroup::loads[load_idx].count` (`1`, `2`, `4`, `8`, or `16`). + pub parent_count: u8, + /// Sub-dword offset inside the parent load (`0` for exact match; `> 0` if subsumed). + pub dword_offset: u8, + /// Number of dwords to copy into `s[sdata..sdata+count]`. + pub count: u8, +} + +/// Dominator-hoisted / CSE'd cross-block group of invariant constant-offset (`SOFFSET == 125`) +/// `s_buffer_load_dword*` ops sharing the exact same V# descriptor dwords `s[sbase..sbase+3]` +/// (`d0, d1, d2`) in a memory-hazard-free dominated region. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HoistedSbufGroup { + /// Unique group id (`0..N`) used for HLSL temp naming (`sbh_g{id}_{uid}`). + pub id: u32, + /// Block `start_pc` of the dominator hoist block `H`. + #[allow(dead_code)] + pub hoist_block: u64, + /// Base 4-SGPR descriptor start index (`s[sbase..sbase+3]` read; always `sbase + 4 <= 106`). + pub sbase: u8, + /// Statically proven `Some(0)` ONLY when non-`Kernel` AND `(const_d1 & 0xFFFF) == 0`. + pub known_hi: Option<u32>, + /// Minimum unsigned byte offset across all `loads`. + #[allow(dead_code)] + pub min_off: i64, + /// Maximum end byte offset (`offset + 4 * count`) across all `loads`. + #[allow(dead_code)] + pub max_end: i64, + /// Deduplicated loads in this group (`1..=96`), sorted by `(offset, count)`. + pub loads: Vec<HoistedLoad>, +} + +/// Non-consecutive intra-block group of constant-offset (`soff == None`) `s_buffer_load_dword*` +/// ops sharing the same V# descriptor `s[sbase..sbase+3]` within a hazard-free, base-unmodified +/// epoch of one basic block. Emitted at `first_pc` under ONE zero-loop switch (or 0 switches when +/// `known_hi == Some(0)`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct IntraBlockSbufGroup { + /// Unique group id (`0..N`) used for HLSL temp naming (`sb_g{id}_{uid}`). + pub id: u32, + /// PC of the first `s_buffer_load_*` instruction in this group (where the group executes). + pub first_pc: u64, + /// Base 4-SGPR descriptor start index (`s[sbase..sbase+4]`, always `<= 102`). + pub sbase: u8, + /// Shared dynamic SGPR offset (guaranteed `None` in `opt_v3` to avoid switch-doubling fallbacks). + pub soff: Option<u8>, + /// Statically proven `Some(0)` ONLY when non-`Kernel` AND `(const_d1 & 0xFFFF) == 0`. + pub known_hi: Option<u32>, + /// Minimum unsigned byte offset across all `loads`. + #[allow(dead_code)] + pub min_off: i64, + /// Maximum end byte offset (`offset + 4 * count`) across all `loads`. + #[allow(dead_code)] + pub max_end: i64, + /// Deduplicated loads in this group (`1..=96`), sorted by `(offset, count)`. + pub loads: Vec<HoistedLoad>, +} + +/// Maps a member `s_buffer_load_dword*` PC to its pre-loaded temp inside a `HoistedSbufGroup` +/// or `IntraBlockSbufGroup`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct SbufUse { + /// `IntraBlockSbufGroup::id`. + pub group_id: u32, + /// Index into `IntraBlockSbufGroup::loads` (`0..loads.len()`). + pub load_idx: u16, + /// `IntraBlockSbufGroup::loads[load_idx].count` (`1`, `2`, `4`, `8`, or `16`). + pub parent_count: u8, + /// Sub-dword offset inside the parent load (`0` for exact match; `> 0` if subsumed). + pub dword_offset: u8, + /// Number of dwords to copy into `s[sdata..sdata+count]`. + pub count: u8, +} + +/// Kind of VALU/VOPC instruction defining a lane-local `bool` mask. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(dead_code)] +pub(crate) enum LaneLocalDefKind { + Cmp, + CarryOut, +} + +/// Metadata for a `V_CMP_*` or `V_ADD/SUB*_CO*_U32` whose mask output is strictly lane-local. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct LaneLocalDef { + /// Unique `bool ml_{id}` variable identifier (declared inline at this def PC). + pub id: u32, + /// `true` iff an `EXEC`-widening op intervenes before a consumer (`and(act, (cond))`); + /// `false` => bare `(cond)` with zero `WaveActiveBallot` and zero `lanebit(exec)`. + pub needs_exec_mask: bool, + #[allow(dead_code)] + pub kind: LaneLocalDefKind, +} + +/// Operand of a lane-local bitwise SALU instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum LaneLocalOperand { + /// Another lane-local `bool ml_{id}` defined earlier in the same block. + Local(u32), + /// Current lane's `EXEC` bit (`act`). + Exec, + /// Constant `false` (`0`) or `true` (`-1` / all-1s). + Const(bool), + /// Plain SGPR or VCC mask register (`lanebit(s{r}, 0u)` in wave32, `lanebit(s{r}, s{r+1})` in wave64). + Sgpr(u8), +} + +/// Logical operation for a lane-local bitwise SALU instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum LaneLocalBitOp { + Mov, + Not, + And, + Or, + Xor, + Andn2, + Orn2, + Nand, + Nor, + Xnor, +} + +/// Metadata for a dead-`scc` bitwise SALU instruction operating on lane-local `bool` masks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct LaneLocalBitwise { + /// Unique `bool ml_{dst_id}` variable identifier defined by this instruction. + pub dst_id: u32, + pub op: LaneLocalBitOp, + pub src0: LaneLocalOperand, + /// `None` for `Mov` / `Not`, `Some` for binary bitwise ops. + pub src1: Option<LaneLocalOperand>, +} + +/// Program-level analysis results consumed by `emit.rs` and `mod.rs`. +#[derive(Debug)] +pub(crate) struct ProgramOpt { + /// Guardrail #8: true iff Compute `mem..mem3` MUST keep `globallycoherent`. + /// False ONLY when ALL 4 hold: zero `GLC`/`DLC`/`SLC` ops, zero memory atomics, + /// zero cache-invalidate/writeback ops, and `!(has_s_barrier && has_mem_store)`. + pub mem_coherent: bool, + /// Weapon 1A: all dominator-hoisted / CSE'd invariant `s_load_*` groups. + hoisted_smem_groups: Vec<HoistedSmemGroup>, + hoisted_smem_at_entry: HashMap<u64, Vec<usize>>, + hoisted_smem_before: HashMap<u64, Vec<usize>>, + hoisted_smem_after: HashMap<u64, Vec<usize>>, + smem_uses: HashMap<u64, SmemUse>, + /// Weapon 1A-sbuf: cross-block dominator-hoisted / CSE'd invariant `s_buffer_load_*` groups. + hoisted_sbuf_groups: Vec<HoistedSbufGroup>, + hoisted_sbuf_at_entry: HashMap<u64, Vec<usize>>, + hoisted_sbuf_before: HashMap<u64, Vec<usize>>, + hoisted_sbuf_after: HashMap<u64, Vec<usize>>, + hoisted_sbuf_uses: HashMap<u64, SbufUse>, + /// Universal non-`Kernel` `s_load_dword*` PCs with statically proven `s[sbase+1] == 0`. + known_zero_hi_sload: HashSet<u64>, + /// Universal non-`Kernel` `s_buffer_load_dword*` PCs with statically proven `(s[sbase+1] & 0xFFFF) == 0`. + known_zero_hi_sbuf: HashSet<u64>, + /// Weapon 1B: non-consecutive intra-block `s_buffer_load_*` groups keyed by `first_pc`. + intra_block_sbuf_groups: HashMap<u64, IntraBlockSbufGroup>, + sbuf_uses: HashMap<u64, SbufUse>, + /// Weapon 3: Wave32 & native-Wave64 lane-local `bool` mask scalarization. + lane_local_defs: HashMap<u64, LaneLocalDef>, + lane_local_bitwise: HashMap<u64, LaneLocalBitwise>, + lane_local_uses: HashMap<u64, u32>, + dead_scc: HashSet<u64>, + dead_carry_sdst: HashSet<u64>, + dead_inst: HashSet<u64>, + const_srcs: HashMap<u64, [Option<u32>; 3]>, + const_sgprs: HashMap<(u64, u8), u32>, +} + +impl Default for ProgramOpt { + fn default() -> Self { + Self { + mem_coherent: true, + hoisted_smem_groups: Vec::new(), + hoisted_smem_at_entry: HashMap::new(), + hoisted_smem_before: HashMap::new(), + hoisted_smem_after: HashMap::new(), + smem_uses: HashMap::new(), + hoisted_sbuf_groups: Vec::new(), + hoisted_sbuf_at_entry: HashMap::new(), + hoisted_sbuf_before: HashMap::new(), + hoisted_sbuf_after: HashMap::new(), + hoisted_sbuf_uses: HashMap::new(), + known_zero_hi_sload: HashSet::new(), + known_zero_hi_sbuf: HashSet::new(), + intra_block_sbuf_groups: HashMap::new(), + sbuf_uses: HashMap::new(), + lane_local_defs: HashMap::new(), + lane_local_bitwise: HashMap::new(), + lane_local_uses: HashMap::new(), + dead_scc: HashSet::new(), + dead_carry_sdst: HashSet::new(), + dead_inst: HashSet::new(), + const_srcs: HashMap::new(), + const_sgprs: HashMap::new(), + } + } +} + +impl ProgramOpt { + /// True iff `scc` written by the instruction at `pc` is overwritten on all paths before any read. + pub(crate) fn is_dead_scc(&self, pc: u64) -> bool { + self.dead_scc.contains(&pc) + } + + /// True iff carry/mask `sdst` of the instruction at `pc` is `Null` or provably dead before any read. + pub(crate) fn is_dead_carry_sdst(&self, pc: u64) -> bool { + self.dead_carry_sdst.contains(&pc) + } + + /// True iff the instruction at `pc` is a pure register-only ALU/mov/cmp with no live outputs or side effects. + pub(crate) fn is_dead_inst(&self, pc: u64) -> bool { + self.dead_inst.contains(&pc) + } + + /// Known 32-bit raw bit value of input operand `idx` (`0..3`, in `Em::ops` input order) at `pc`. + pub(crate) fn const_src(&self, pc: u64, idx: usize) -> Option<u32> { + if idx >= 3 { + return None; + } + self.const_srcs.get(&pc).and_then(|arr| arr[idx]) + } + + /// Known 32-bit raw bit value of SGPR `sgpr` (read by the instruction at `pc`) from constant propagation. + #[allow(dead_code)] + pub(crate) fn const_sgpr(&self, pc: u64, sgpr: u64) -> Option<u32> { + if sgpr >= 106 { + return None; + } + self.const_sgprs.get(&(pc, sgpr as u8)).copied() + } + + /// All dominator-hoisted / CSE'd invariant `s_load_*` groups (for declaring `sm_g{id}_{uid}` at `main()` scope). + pub(crate) fn hoisted_smem_groups(&self) -> &[HoistedSmemGroup] { + &self.hoisted_smem_groups + } + + /// Indices into `hoisted_smem_groups()` to emit at the entry of block `start_pc` (before block instructions). + pub(crate) fn hoisted_smem_at_block_entry(&self, start_pc: u64) -> &[usize] { + self.hoisted_smem_at_entry.get(&start_pc).map(Vec::as_slice).unwrap_or(&[]) + } + + /// Indices into `hoisted_smem_groups()` to emit immediately BEFORE instruction `pc` (even if `pc` is `dead_inst`). + pub(crate) fn hoisted_smem_before_pc(&self, pc: u64) -> &[usize] { + self.hoisted_smem_before.get(&pc).map(Vec::as_slice).unwrap_or(&[]) + } + + /// Indices into `hoisted_smem_groups()` to emit immediately AFTER instruction `pc` (never on a terminator). + pub(crate) fn hoisted_smem_after_pc(&self, pc: u64) -> &[usize] { + self.hoisted_smem_after.get(&pc).map(Vec::as_slice).unwrap_or(&[]) + } + + /// Dominated `s_load_*` instruction replaced by a copy from a hoisted `sm_g{group_id}_{load_idx}` temp. + pub(crate) fn smem_use(&self, pc: u64) -> Option<SmemUse> { + self.smem_uses.get(&pc).copied() + } + + /// True iff `pc` is a non-`Kernel` `s_load_dword*` whose high base SGPR `s[sbase+1]` is + /// statically proven `0` (and offset is within the safe UMA Window-0 fast-path range). + pub(crate) fn is_known_zero_hi_sload(&self, pc: u64) -> bool { + self.known_zero_hi_sload.contains(&pc) + } + + /// True iff `pc` is a non-`Kernel` `s_buffer_load_dword*` whose descriptor word 1 has + /// statically proven `(s[sbase+1] & 0xFFFF) == 0` (Window-0 fast path on UMA). + pub(crate) fn is_known_zero_hi_sbuf(&self, pc: u64) -> bool { + self.known_zero_hi_sbuf.contains(&pc) + } + + /// All dominator-hoisted / CSE'd cross-block invariant `s_buffer_load_*` groups (for declaring + /// `sbh_g{id}_{uid}` at `main()` scope). + pub(crate) fn hoisted_sbuf_groups(&self) -> &[HoistedSbufGroup] { + &self.hoisted_sbuf_groups + } + + /// Indices into `hoisted_sbuf_groups()` to emit at the entry of block `start_pc`. + pub(crate) fn hoisted_sbuf_at_block_entry(&self, start_pc: u64) -> &[usize] { + self.hoisted_sbuf_at_entry.get(&start_pc).map(Vec::as_slice).unwrap_or(&[]) + } + + /// Indices into `hoisted_sbuf_groups()` to emit immediately BEFORE instruction `pc`. + pub(crate) fn hoisted_sbuf_before_pc(&self, pc: u64) -> &[usize] { + self.hoisted_sbuf_before.get(&pc).map(Vec::as_slice).unwrap_or(&[]) + } + + /// Indices into `hoisted_sbuf_groups()` to emit immediately AFTER instruction `pc` (never on a terminator). + pub(crate) fn hoisted_sbuf_after_pc(&self, pc: u64) -> &[usize] { + self.hoisted_sbuf_after.get(&pc).map(Vec::as_slice).unwrap_or(&[]) + } + + /// Dominated `s_buffer_load_*` instruction replaced by a copy from a hoisted `sbh_g{group_id}_{load_idx}` temp. + pub(crate) fn hoisted_sbuf_use(&self, pc: u64) -> Option<SbufUse> { + self.hoisted_sbuf_uses.get(&pc).copied() + } + + /// Non-consecutive intra-block `s_buffer_load_*` group starting at `first_pc`, if any. + pub(crate) fn intra_block_sbuf_group(&self, first_pc: u64) -> Option<&IntraBlockSbufGroup> { + self.intra_block_sbuf_groups.get(&first_pc) + } + + /// Member `s_buffer_load_*` instruction replaced by a copy from `sb_g{group_id}_{load_idx}`. + pub(crate) fn sbuf_use(&self, pc: u64) -> Option<SbufUse> { + self.sbuf_uses.get(&pc).copied() + } + + /// Lane-local `bool ml_{id}` definition for a `V_CMP_*` or `V_ADD/SUB*_CO*_U32` at `pc`. + pub(crate) fn lane_local_def(&self, pc: u64) -> Option<LaneLocalDef> { + self.lane_local_defs.get(&pc).copied() + } + + /// Lane-local `bool ml_{dst_id}` bitwise SALU op at `pc`. + pub(crate) fn lane_local_bitwise(&self, pc: u64) -> Option<LaneLocalBitwise> { + self.lane_local_bitwise.get(&pc).copied() + } + + /// Lane-local `bool ml_{id}` mask consumer (`V_CNDMASK_B32` or `V_ADD/SUB*_CO_CI_U32`) at `pc`. + pub(crate) fn lane_local_use(&self, pc: u64) -> Option<u32> { + self.lane_local_uses.get(&pc).copied() + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CarryDst { + Null, + Sgpr(u64), +} + +#[derive(Clone, Debug)] +struct InstInfo { + s_read: SRegs, + s_kill: SRegs, + s_mod: SRegs, + scc_read: bool, + scc_write: bool, + v_read: VRegs, + v_mod: VRegs, + carry_sdst: Option<CarryDst>, + pure_eliminable: bool, + exec_widen: bool, + indirect_sgpr: bool, + indirect_vgpr: bool, +} + +#[inline] +fn fval(d: &Decoded, field: &str) -> u64 { + rdna2::field_value(d.enc, &d.words, field).unwrap_or(0) +} + +#[inline] +fn scaled_field(d: &Decoded, field: &str) -> u64 { + fval(d, field) * rdna2::register_scale(field) +} + +/// Same explicit-operand partition as `Em::ops(d)` in `emit.rs`. +fn explicit_ops(d: &Decoded) -> (Vec<&'static Operand>, Vec<&'static Operand>) { + let mut outs = Vec::new(); + let mut ins = Vec::new(); + for o in d.ienc.operands { + if o.implicit && !(o.field.is_none() && o.ty == "OPR_VCC") { + continue; + } + if o.output { + outs.push(o); + } else if o.input { + ins.push(o); + } + } + (outs, ins) +} + +fn scalar_code_regs(code: u64, n: u64, wave64: bool) -> (SRegs, bool) { + match code { + 251 => (if wave64 { S_VCC } else { S_VCC_LO }, false), + 252 => (S_EXEC, false), + 253 => (0, true), + 125 => (0, false), + v if v <= 127 => (sreg_range(v, n), false), + _ => (0, false), + } +} + +fn inline_const_bits(code: u64, literal: Option<u32>, f16: bool) -> Option<u32> { + Some(match code { + 125 => 0, + 128..=192 => (code - 128) as u32, + 193..=208 => (-((code - 192) as i32)) as u32, + 235..=238 => 0, + 239 => 0x7FFF_FFFF, + 240..=248 => { + if f16 { + match code { + 240 => 0x3800, + 241 => 0xB800, + 242 => 0x3C00, + 243 => 0xBC00, + 244 => 0x4000, + 245 => 0xC000, + 246 => 0x4400, + 247 => 0xC400, + 248 => 0x3118, + _ => return None, + } + } else { + match code { + 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 => 0.159_154_94f32.to_bits(), + _ => return None, + } + } + } + 255 => literal?, + _ => return None, + }) +} + +fn is_valid_cmp_suffix(s: &str) -> bool { + matches!( + s, + "eq_i32" + | "lg_i32" + | "gt_i32" + | "ge_i32" + | "lt_i32" + | "le_i32" + | "eq_u32" + | "lg_u32" + | "gt_u32" + | "ge_u32" + | "lt_u32" + | "le_u32" + ) +} + +fn salu_writes_scc(enc: &str, name: &str) -> bool { + if enc == "ENC_SOPC" { + return true; + } + if enc == "ENC_SOPK" { + return name == "S_ADDK_I32" || name.starts_with("S_CMPK_"); + } + if name.contains("SAVEEXEC") || name.contains("WREXEC") { + return true; + } + matches!( + name, + "S_NOT_B32" + | "S_BCNT0_I32_B32" + | "S_BCNT1_I32_B32" + | "S_ABS_I32" + | "S_AND_B32" + | "S_OR_B32" + | "S_XOR_B32" + | "S_ANDN2_B32" + | "S_ORN2_B32" + | "S_NAND_B32" + | "S_NOR_B32" + | "S_XNOR_B32" + | "S_ADD_U32" + | "S_SUB_U32" + | "S_ADDC_U32" + | "S_SUBB_U32" + | "S_ADD_I32" + | "S_SUB_I32" + | "S_LSHL_B32" + | "S_LSHR_B32" + | "S_ASHR_I32" + | "S_LSHL1_ADD_U32" + | "S_LSHL2_ADD_U32" + | "S_LSHL3_ADD_U32" + | "S_LSHL4_ADD_U32" + | "S_BFE_U32" + | "S_BFE_I32" + | "S_MIN_U32" + | "S_MAX_U32" + | "S_MIN_I32" + | "S_MAX_I32" + | "S_WQM_B32" + | "S_ABSDIFF_I32" + | "S_NOT_B64" + | "S_WQM_B64" + | "S_BCNT1_I32_B64" + | "S_BCNT0_I32_B64" + | "S_LSHL_B64" + | "S_LSHR_B64" + | "S_ASHR_I64" + | "S_BFE_U64" + | "S_BFE_I64" + | "S_AND_B64" + | "S_OR_B64" + | "S_XOR_B64" + | "S_ANDN2_B64" + | "S_ORN2_B64" + | "S_NAND_B64" + | "S_NOR_B64" + | "S_XNOR_B64" + ) +} + +fn is_supported_salu(enc: &str, name: &str) -> bool { + match enc { + "ENC_SOPK" => { + matches!(name, "S_MOVK_I32" | "S_CMOVK_I32" | "S_ADDK_I32" | "S_MULK_I32") + || name + .strip_prefix("S_CMPK_") + .is_some_and(|rest| is_valid_cmp_suffix(&rest.to_ascii_lowercase())) + } + "ENC_SOPC" => { + matches!( + name, + "S_BITCMP0_B64" | "S_BITCMP1_B64" | "S_BITCMP0_B32" | "S_BITCMP1_B32" | "S_CMP_EQ_U64" | "S_CMP_LG_U64" + ) || name + .strip_prefix("S_CMP_") + .is_some_and(|rest| is_valid_cmp_suffix(&rest.to_ascii_lowercase())) + } + "ENC_SOP1" | "ENC_SOP2" => matches!( + name, + "S_MOV_B32" + | "S_CMOV_B32" + | "S_NOT_B32" + | "S_BREV_B32" + | "S_BCNT0_I32_B32" + | "S_BCNT1_I32_B32" + | "S_FF0_I32_B32" + | "S_FF1_I32_B32" + | "S_FLBIT_I32_B32" + | "S_FLBIT_I32" + | "S_ABS_I32" + | "S_SEXT_I32_I8" + | "S_SEXT_I32_I16" + | "S_AND_B32" + | "S_OR_B32" + | "S_XOR_B32" + | "S_ANDN2_B32" + | "S_ORN2_B32" + | "S_NAND_B32" + | "S_NOR_B32" + | "S_XNOR_B32" + | "S_ADD_U32" + | "S_SUB_U32" + | "S_ADDC_U32" + | "S_SUBB_U32" + | "S_ADD_I32" + | "S_SUB_I32" + | "S_MUL_I32" + | "S_MUL_HI_U32" + | "S_MUL_HI_I32" + | "S_LSHL_B32" + | "S_LSHR_B32" + | "S_ASHR_I32" + | "S_LSHL1_ADD_U32" + | "S_LSHL2_ADD_U32" + | "S_LSHL3_ADD_U32" + | "S_LSHL4_ADD_U32" + | "S_BFM_B32" + | "S_BFE_U32" + | "S_BFE_I32" + | "S_MIN_U32" + | "S_MAX_U32" + | "S_MIN_I32" + | "S_MAX_I32" + | "S_CSELECT_B32" + | "S_WQM_B32" + | "S_BITSET0_B32" + | "S_BITSET1_B32" + | "S_ABSDIFF_I32" + | "S_PACK_LL_B32_B16" + | "S_PACK_LH_B32_B16" + | "S_PACK_HH_B32_B16" + | "S_GETPC_B64" + | "S_MOV_B64" + | "S_CMOV_B64" + | "S_NOT_B64" + | "S_CSELECT_B64" + | "S_WQM_B64" + | "S_BREV_B64" + | "S_BCNT1_I32_B64" + | "S_BCNT0_I32_B64" + | "S_FF1_I32_B64" + | "S_FF0_I32_B64" + | "S_FLBIT_I32_B64" + | "S_FLBIT_I32_I64" + | "S_LSHL_B64" + | "S_LSHR_B64" + | "S_ASHR_I64" + | "S_BFM_B64" + | "S_BFE_U64" + | "S_BFE_I64" + | "S_BITSET0_B64" + | "S_BITSET1_B64" + | "S_AND_B64" + | "S_OR_B64" + | "S_XOR_B64" + | "S_ANDN2_B64" + | "S_ORN2_B64" + | "S_NAND_B64" + | "S_NOR_B64" + | "S_XNOR_B64" + ), + _ => false, + } +} + +fn is_supported_pure_valu(d: &Decoded) -> bool { + if d.variant != Variant::Plain { + return false; + } + let name = d.inst.name; + if name.starts_with("V_CMP_") { + return true; + } + if name.starts_with("V_CMPX_") + || name.starts_with("V_INTERP_") + || name.starts_with("V_MOVREL") + || name.starts_with("V_PERMLANE") + || matches!( + name, + "V_NOP" + | "V_READLANE_B32" + | "V_READFIRSTLANE_B32" + | "V_WRITELANE_B32" + | "V_SWAPREL_B32" + | "V_DIV_SCALE_F32" + ) + { + return false; + } + matches!( + name, + "V_MOV_B32" + | "V_MOV_FED_B32" + | "V_NOT_B32" + | "V_BFREV_B32" + | "V_FFBH_U32" + | "V_FFBL_B32" + | "V_FFBH_I32" + | "V_CVT_F32_I32" + | "V_CVT_F32_U32" + | "V_CVT_U32_F32" + | "V_CVT_I32_F32" + | "V_CVT_RPI_I32_F32" + | "V_CVT_FLR_I32_F32" + | "V_CVT_F32_UBYTE0" + | "V_CVT_F32_UBYTE1" + | "V_CVT_F32_UBYTE2" + | "V_CVT_F32_UBYTE3" + | "V_CVT_F32_F16" + | "V_CVT_F16_F32" + | "V_CVT_PKRTZ_F16_F32" + | "V_PACK_B32_F16" + | "V_FMA_MIX_F32" + | "V_FMA_MIXLO_F16" + | "V_FMA_MIXHI_F16" + | "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_FRACT_F32" + | "V_TRUNC_F32" + | "V_FLOOR_F32" + | "V_CEIL_F32" + | "V_RNDNE_F32" + | "V_FREXP_MANT_F32" + | "V_FREXP_EXP_I32_F32" + | "V_LDEXP_F32" + | "V_ADD_F32" + | "V_SUB_F32" + | "V_SUBREV_F32" + | "V_MUL_F32" + | "V_MUL_LEGACY_F32" + | "V_MIN_F32" + | "V_MAX_F32" + | "V_FMAC_F32" + | "V_MAC_F32" + | "V_FMAC_LEGACY_F32" + | "V_FMA_F32" + | "V_MAD_F32" + | "V_FMA_LEGACY_F32" + | "V_FMAMK_F32" + | "V_FMAAK_F32" + | "V_MADMK_F32" + | "V_MADAK_F32" + | "V_MIN3_F32" + | "V_MAX3_F32" + | "V_MED3_F32" + | "V_CUBEID_F32" + | "V_CUBESC_F32" + | "V_CUBETC_F32" + | "V_CUBEMA_F32" + | "V_ADD_NC_U32" + | "V_SUB_NC_U32" + | "V_SUBREV_NC_U32" + | "V_ADD_NC_I32" + | "V_SUB_NC_I32" + | "V_MUL_LO_U32" + | "V_MUL_HI_U32" + | "V_MUL_HI_I32" + | "V_MUL_U32_U24" + | "V_MUL_HI_U32_U24" + | "V_MUL_I32_I24" + | "V_MUL_HI_I32_I24" + | "V_MAD_U32_U24" + | "V_MAD_I32_I24" + | "V_AND_B32" + | "V_OR_B32" + | "V_XOR_B32" + | "V_XNOR_B32" + | "V_LSHLREV_B32" + | "V_LSHRREV_B32" + | "V_ASHRREV_I32" + | "V_LSHL_ADD_U32" + | "V_ADD_LSHL_U32" + | "V_LSHL_OR_B32" + | "V_AND_OR_B32" + | "V_OR3_B32" + | "V_XOR3_B32" + | "V_ADD3_U32" + | "V_XAD_U32" + | "V_BFE_U32" + | "V_BFE_I32" + | "V_BFI_B32" + | "V_BFM_B32" + | "V_BCNT_U32_B32" + | "V_PERM_B32" + | "V_ALIGNBIT_B32" + | "V_ALIGNBYTE_B32" + | "V_MIN_U32" + | "V_MAX_U32" + | "V_MIN_I32" + | "V_MAX_I32" + | "V_MIN3_U32" + | "V_MAX3_U32" + | "V_MED3_U32" + | "V_MIN3_I32" + | "V_MAX3_I32" + | "V_MED3_I32" + | "V_SAD_U32" + | "V_SAD_U8" + | "V_SAD_HI_U8" + | "V_SAD_U16" + | "V_MSAD_U8" + | "V_LERP_U8" + | "V_MAD_U32_U16" + | "V_MAD_I32_I16" + | "V_CVT_PK_U16_U32" + | "V_CVT_PK_I16_I32" + | "V_CVT_PKNORM_I16_F32" + | "V_CVT_PKNORM_U16_F32" + | "V_CVT_PKNORM_I16_F16" + | "V_CVT_PKNORM_U16_F16" + | "V_SAT_PK_U8_I16" + | "V_DIV_FMAS_F32" + | "V_DIV_FIXUP_F32" + | "V_CVT_PK_U8_F32" + | "V_MBCNT_LO_U32_B32" + | "V_MBCNT_HI_U32_B32" + | "V_CNDMASK_B32" + | "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_SWAP_B32" + | "V_LSHLREV_B64" + | "V_LSHRREV_B64" + | "V_ASHRREV_I64" + | "V_MAD_U64_U32" + | "V_MAD_I64_I32" + | "V_ADD_F64" + | "V_MUL_F64" + | "V_FMA_F64" + | "V_MIN_F64" + | "V_MAX_F64" + | "V_RCP_F64" + | "V_CVT_F64_F32" + | "V_CVT_F64_I32" + | "V_CVT_F64_U32" + | "V_FLOOR_F64" + | "V_CEIL_F64" + | "V_FRACT_F64" + | "V_RNDNE_F64" + | "V_FREXP_MANT_F64" + | "V_SQRT_F64" + | "V_RSQ_F64" + | "V_TRUNC_F64" + | "V_LDEXP_F64" + | "V_CVT_F32_F64" + | "V_CVT_I32_F64" + | "V_CVT_U32_F64" + | "V_FREXP_EXP_I32_F64" + | "V_ADD_F16" + | "V_SUB_F16" + | "V_SUBREV_F16" + | "V_MUL_F16" + | "V_MIN_F16" + | "V_MAX_F16" + | "V_FMA_F16" + | "V_MED3_F16" + | "V_MIN3_F16" + | "V_MAX3_F16" + | "V_MED3_U16" + | "V_MIN3_U16" + | "V_MAX3_U16" + | "V_MED3_I16" + | "V_MIN3_I16" + | "V_MAX3_I16" + | "V_FREXP_MANT_F16" + | "V_FREXP_EXP_I16_F16" + | "V_MAD_F16" + | "V_FMAC_F16" + | "V_FMAMK_F16" + | "V_FMAAK_F16" + | "V_LDEXP_F16" + | "V_RCP_F16" + | "V_RSQ_F16" + | "V_SQRT_F16" + | "V_LOG_F16" + | "V_EXP_F16" + | "V_SIN_F16" + | "V_COS_F16" + | "V_FRACT_F16" + | "V_FLOOR_F16" + | "V_CEIL_F16" + | "V_TRUNC_F16" + | "V_RNDNE_F16" + | "V_CVT_F16_U16" + | "V_CVT_F16_I16" + | "V_CVT_U16_F16" + | "V_CVT_I16_F16" + | "V_CVT_NORM_U16_F16" + | "V_CVT_NORM_I16_F16" + | "V_ADD_NC_U16" + | "V_ADD_U16" + | "V_SUB_NC_U16" + | "V_SUB_U16" + | "V_SUBREV_NC_U16" + | "V_SUBREV_U16" + | "V_ADD_NC_I16" + | "V_SUB_NC_I16" + | "V_MUL_LO_U16" + | "V_LSHLREV_B16" + | "V_LSHRREV_B16" + | "V_ASHRREV_I16" + | "V_MAX_U16" + | "V_MIN_U16" + | "V_MAX_I16" + | "V_MIN_I16" + | "V_MAD_U16" + | "V_MAD_I16" + | "V_DOT2_F32_F16" + | "V_DOT2C_F32_F16" + | "V_DOT4C_I32_I8" + | "V_DOT2_I32_I16" + | "V_DOT2_U32_U16" + | "V_DOT4_U32_U8" + | "V_DOT4_I32_I8" + | "V_DOT8_U32_U4" + | "V_DOT8_I32_I4" + | "V_PK_ADD_F16" + | "V_PK_MUL_F16" + | "V_PK_FMA_F16" + | "V_PK_FMAC_F16" + | "V_PK_MIN_F16" + | "V_PK_MAX_F16" + | "V_PK_ADD_U16" + | "V_PK_SUB_U16" + | "V_PK_ADD_I16" + | "V_PK_SUB_I16" + | "V_PK_MUL_LO_U16" + | "V_PK_MAD_U16" + | "V_PK_MAD_I16" + | "V_PK_LSHLREV_B16" + | "V_PK_LSHRREV_B16" + | "V_PK_ASHRREV_I16" + | "V_PK_MAX_U16" + | "V_PK_MIN_U16" + | "V_PK_MAX_I16" + | "V_PK_MIN_I16" + ) +} + +fn is_rmw_or_partial_vgpr_write(d: &Decoded) -> bool { + let name = d.inst.name; + if d.variant != Variant::Plain { + // SDWA preserves unused bytes/words; DPP16 row/bank mask or !bound_ctrl preserves lanes. + return true; + } + if matches!( + name, + "V_FMAC_F32" + | "V_MAC_F32" + | "V_FMAC_LEGACY_F32" + | "V_FMAC_F16" + | "V_PK_FMAC_F16" + | "V_DOT2C_F32_F16" + | "V_DOT4C_I32_I8" + | "V_FMA_MIXLO_F16" + | "V_FMA_MIXHI_F16" + | "V_CVT_F16_F32" + | "V_INTERP_P2_F16" + | "V_PERMLANE16_B32" + | "V_PERMLANEX16_B32" + | "V_WRITELANE_B32" + | "V_SWAP_B32" + ) { + return true; + } + // Plain 16-bit VALU (`valu16` in emit.rs) preserves the untouched 16-bit half of VDST. + const WIDE16: &[&str] = &[ + "V_CVT_PKNORM_I16_F32", + "V_CVT_PKNORM_U16_F32", + "V_CVT_PKNORM_I16_F16", + "V_CVT_PKNORM_U16_F16", + "V_CVT_PK_U16_U32", + "V_CVT_PK_I16_I32", + "V_MAD_U32_U16", + "V_MAD_I32_I16", + "V_SAD_U16", + "V_SAT_PK_U8_I16", + "V_CVT_F32_F16", + "V_CVT_PKRTZ_F16_F32", + "V_PACK_B32_F16", + ]; + if (name.contains("F16") || name.contains("_I16") || name.contains("_U16") || name.contains("_B16")) + && !name.starts_with("V_PK_") + && !name.starts_with("V_DOT") + && !name.starts_with("V_CMP") + && !name.starts_with("V_FMA_MIX") + && !WIDE16.contains(&name) + && (d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP")) + { + return true; + } + // D16 sub-dword loads preserve the untouched half of the destination VGPR. + if name.contains("_D16_") && (name.contains("_LOAD_") || name.contains("_READ_")) { + return true; + } + false +} + +/// Returns true if an `EXEC`-modifying instruction can WIDEN `EXEC` (turn on previously inactive lanes). +fn is_exec_widening(d: &Decoded, s_mod: SRegs) -> bool { + if (s_mod & S_EXEC) == 0 { + return false; + } + let name = d.inst.name; + // V_CMPX_* computes `ballot(act & cond)` — always a subset of current EXEC. + if name.starts_with("V_CMPX_") { + return false; + } + // `and_saveexec` / `and_wrexec` compute `src & exec`; `andn1_saveexec/wrexec` compute `~src & exec`. + // Note: `andn2_saveexec` computes `src & ~exec`, which WIDENS EXEC! + if matches!( + name, + "S_AND_SAVEEXEC_B32" + | "S_AND_SAVEEXEC_B64" + | "S_AND_WREXEC_B32" + | "S_AND_WREXEC_B64" + | "S_ANDN1_SAVEEXEC_B32" + | "S_ANDN1_SAVEEXEC_B64" + | "S_ANDN1_WREXEC_B32" + | "S_ANDN1_WREXEC_B64" + ) { + return false; + } + if matches!(name, "S_AND_B32" | "S_AND_B64") { + let s0 = fval(d, "SSRC0"); + let s1 = fval(d, "SSRC1"); + // Strictly narrowing iff one operand is EXEC (126). + return s0 != 126 && s1 != 126; + } + if matches!(name, "S_ANDN2_B32" | "S_ANDN2_B64") { + // `s_andn2` computes `SSRC0 & ~SSRC1`: narrowing iff SSRC0 == EXEC (126). + return fval(d, "SSRC0") != 126; + } + true +} + +/// Extract carry/mask `sdst` for instructions that emit `write_mask(&sdst, ...)` in `emit.rs`. +fn carry_sdst_of(d: &Decoded, outs: &[&Operand]) -> Option<CarryDst> { + let name = d.inst.name; + let is_carry_alu = 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" + | "V_DIV_SCALE_F32" + ); + if is_carry_alu { + let Some(o) = outs.get(1) else { + return Some(if matches!(name, "V_MAD_U64_U32" | "V_MAD_I64_I32") { + CarryDst::Null + } else { + CarryDst::Sgpr(106) + }); + }; + return Some(match o.field { + Some(f) => { + let v = scaled_field(d, f); + if v == 125 || v > 127 { + CarryDst::Null + } else { + CarryDst::Sgpr(v) + } + } + None => match o.ty { + "OPR_VCC" => CarryDst::Sgpr(106), + "OPR_EXEC" => CarryDst::Sgpr(126), + _ => CarryDst::Null, + }, + }); + } + if name.starts_with("V_CMP_") { + if d.variant == Variant::Sdwa { + if let Some(e) = ext_encoding(d) { + if rdna2::field_value(e, &d.words, "SD") == Some(1) { + let sd = rdna2::field_value(e, &d.words, "SDST").unwrap_or(106); + return Some(if sd == 125 || sd > 127 { + CarryDst::Null + } else { + CarryDst::Sgpr(sd) + }); + } + } + return Some(CarryDst::Sgpr(106)); + } + let Some(o) = outs.first() else { + return Some(CarryDst::Sgpr(106)); + }; + return Some(match o.field { + Some(f) => { + let v = scaled_field(d, f); + if v == 125 || v > 127 { + CarryDst::Null + } else { + CarryDst::Sgpr(v) + } + } + None => match o.ty { + "OPR_VCC" => CarryDst::Sgpr(106), + "OPR_EXEC" => CarryDst::Sgpr(126), + _ => CarryDst::Null, + }, + }); + } + None +} + +fn analyze_inst(d: &Decoded, opt: &Options) -> InstInfo { + let name = d.inst.name; + let enc = d.enc.name; + let wave64 = opt.wave64; + let mask_words: u64 = if wave64 { 2 } else { 1 }; + + let mut s_read: SRegs = 0; + let mut s_kill: SRegs = 0; + let mut s_mod: SRegs = 0; + let mut scc_read = false; + let mut scc_write = false; + let mut v_read = VRegs::EMPTY; + let mut v_mod = VRegs::EMPTY; + + let (outs, _ins) = explicit_ops(d); + let carry_sdst = carry_sdst_of(d, &outs); + + // 1. Indirect SGPR moves (`s_movrel*`): conservative all-SGPR read, zero kill. + if name.starts_with("S_MOVREL") { + let dst = fval(d, "SDST").min(123); + let mod_mask = if name.starts_with("S_MOVRELS_") { + sreg_range(dst, if name.ends_with("_B64") { 2 } else { 1 }) + } else { + sreg_range(dst, 124u64.saturating_sub(dst)) + }; + return InstInfo { + s_read: S_ALL, + s_kill: 0, + s_mod: mod_mask, + scc_read: false, + scc_write: false, + v_read: VRegs::EMPTY, + v_mod: VRegs::EMPTY, + carry_sdst: None, + pure_eliminable: false, + exec_widen: false, + indirect_sgpr: true, + indirect_vgpr: false, + }; + } + + // 2. Indirect VGPR moves (`v_movrel*` / `v_swaprel*`): conservative all-VGPR read/mod. + if name.starts_with("V_MOVREL") || name == "V_SWAPREL_B32" { + s_read |= S_M0 | S_EXEC; + let src = fval(d, "SRC0"); + if src < 256 { + let (sr, sc) = scalar_code_regs(src, 1, wave64); + s_read |= sr; + scc_read |= sc; + } + return InstInfo { + s_read, + s_kill: 0, + s_mod: 0, + scc_read, + scc_write: false, + v_read: VRegs::ALL, + v_mod: VRegs::ALL, + carry_sdst: None, + pure_eliminable: false, + exec_widen: false, + indirect_sgpr: false, + indirect_vgpr: true, + }; + } + + // 3. SOPP special instructions. + if enc == "ENC_SOPP" { + match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => scc_read = true, + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => s_read |= if wave64 { S_VCC } else { S_VCC_LO }, + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => s_read |= S_EXEC, + "S_SENDMSG" if matches!(opt.mode, Mode::Mesh(_)) => s_read |= S_M0, + "S_SENDMSG" if matches!(opt.mode, Mode::Geometry(_)) => s_read |= S_EXEC, + _ => {} + } + return InstInfo { + s_read, + s_kill: 0, + s_mod: 0, + scc_read, + scc_write: false, + v_read: VRegs::EMPTY, + v_mod: VRegs::EMPTY, + carry_sdst: None, + pure_eliminable: false, + exec_widen: false, + indirect_sgpr: false, + indirect_vgpr: false, + }; + } + + // 4. `s_setreg_b32` reads `SDST` (field named SDST in SOPK is actually a source!). + if name == "S_SETREG_B32" { + let (sr, sc) = scalar_code_regs(fval(d, "SDST"), 1, wave64); + s_read |= sr; + scc_read |= sc; + return InstInfo { + s_read, + s_kill: 0, + s_mod: 0, + scc_read, + scc_write: false, + v_read: VRegs::EMPTY, + v_mod: VRegs::EMPTY, + carry_sdst: None, + pure_eliminable: false, + exec_widen: false, + indirect_sgpr: false, + indirect_vgpr: false, + }; + } + + // 5. Indirect branches / calls (Guardrail #7): conservatively read everything. + if (name == "S_SETPC_B64" && d.far_target.is_none() && !matches!(opt.mode, Mode::Geometry(_))) + || name.starts_with("S_CALL") + || (name == "S_SWAPPC_B64" && fval(d, "SDST") != fval(d, "SSRC0")) + { + return InstInfo { + s_read: S_ALL, + s_kill: 0, + s_mod: 0, + scc_read: true, + scc_write: false, + v_read: VRegs::ALL, + v_mod: VRegs::EMPTY, + carry_sdst: None, + pure_eliminable: false, + exec_widen: false, + indirect_sgpr: true, + indirect_vgpr: true, + }; + } + + // 6. Standard operand-table traversal for SGPRs & VGPRs. + let keeps_s_dst = name.starts_with("S_CMOV") + || matches!( + name, + "S_ADDK_I32" | "S_MULK_I32" | "S_BITSET0_B32" | "S_BITSET1_B32" | "S_BITSET0_B64" | "S_BITSET1_B64" + ); + let is_mask_write_op = carry_sdst.is_some() || name.starts_with("V_CMPX_"); + let is_per_lane_mask_read = matches!( + name, + "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32" + ); + + // SDWA extension dword handling (S0, S1, SD/SDST). + let mut sdwa_vopc_dst: Option<SRegs> = None; + if d.variant == Variant::Sdwa { + if let Some(e) = ext_encoding(d) { + let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + if fv("S0") == 1 { + let (sr, sc) = scalar_code_regs(fv("VSRC0"), 1, wave64); + s_read |= sr; + scc_read |= sc; + } else { + v_read.set(fv("VSRC0")); + } + if d.enc.field("VSRC1").is_some() { + if fv("S1") == 1 { + let (sr, sc) = scalar_code_regs(fv("VSRC1"), 1, wave64); + s_read |= sr; + scc_read |= sc; + } else { + v_read.set(fv("VSRC1")); + } + } + if enc == "ENC_VOPC" && !name.starts_with("V_CMPX") { + sdwa_vopc_dst = Some(if fv("SD") == 1 { + scalar_code_regs(fv("SDST"), mask_words, wave64).0 + } else { + sreg_range(106, mask_words) + }); + } + } else { + // Unknown SDWA encoding: conservative fallback. + return InstInfo { + s_read: S_ALL, + s_kill: 0, + s_mod: 0, + scc_read: true, + scc_write: false, + v_read: VRegs::ALL, + v_mod: VRegs::EMPTY, + carry_sdst: None, + pure_eliminable: false, + exec_widen: false, + indirect_sgpr: false, + indirect_vgpr: false, + }; + } + } else if d.variant == Variant::Dpp16 || d.variant == Variant::Dpp8 { + if let Some(e) = ext_encoding(d) { + let v0 = rdna2::field_value(e, &d.words, "VSRC0").unwrap_or(0); + v_read.set(v0); + } else { + v_read = VRegs::ALL; + } + s_read |= S_EXEC; + } + + // Iterate spec operands for SGPRs. + for o in d.ienc.operands { + if o.ty == "OPR_SSRC_SPECIAL_SCC" { + if o.input { + scc_read = true; + } + continue; + } + let n_base = (o.size as u64).div_ceil(32).max(1); + let (regs, reads_scc) = match (o.field, o.ty) { + (_, "OPR_VCC") => { + let n = if is_mask_write_op || is_per_lane_mask_read { + mask_words + } else { + n_base + }; + (sreg_range(106, n), false) + } + (_, "OPR_EXEC" | "OPR_SDST_EXEC") => (S_EXEC, false), + (_, "OPR_SDST_M0") => (S_M0, false), + (None, _) | (Some("LITERAL"), _) => continue, + (Some(f), ty) => { + if o.implicit + || !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"] + .iter() + .any(|k| ty.contains(k)) + { + continue; + } + if f == "SRC0" && d.variant != Variant::Plain { + continue; + } + if f == "VSRC1" && d.variant == Variant::Sdwa { + continue; + } + let raw = scaled_field(d, f); + let n = if o.output && is_mask_write_op && (f == "SDST" || (f == "VDST" && name.starts_with("V_CMP"))) { + mask_words + } else if !o.output && is_per_lane_mask_read && f == "SRC2" { + mask_words + } else { + n_base + }; + scalar_code_regs(raw, n, wave64) + } + }; + if reads_scc && !o.output { + scc_read = true; + } + if o.output { + s_mod |= regs; + if keeps_s_dst { + s_read |= regs; + } else { + s_kill |= regs; + } + } + if o.input { + s_read |= regs; + } + } + + if let Some(dst_regs) = sdwa_vopc_dst { + s_kill = (s_kill & !S_VCC) | dst_regs; + s_mod = (s_mod & !S_VCC) | dst_regs; + } + + // SOPK: `SDST` is read by `s_cmovk`, `s_addk`, `s_mulk`, `s_cmpk_*`. + if enc == "ENC_SOPK" { + let sd = fval(d, "SDST"); + let r = scalar_code_regs(sd, 1, wave64).0; + if name.starts_with("S_CMPK_") { + s_read |= r; + s_kill &= !r; + s_mod &= !r; + } else if name != "S_MOVK_I32" { + s_read |= r; + s_kill &= !r; + s_mod |= r; + } + } + + // Saveexec / wrexec always read and write EXEC and write SCC. + if name.contains("SAVEEXEC") || name.contains("WREXEC") { + s_read |= S_EXEC; + s_kill |= S_EXEC; + s_mod |= S_EXEC; + scc_write = true; + } + + // Explicit SCC reads/writes for SALU. + if matches!(enc, "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK") { + if matches!( + name, + "S_CMOV_B32" | "S_CMOV_B64" | "S_CMOVK_I32" | "S_CSELECT_B32" | "S_CSELECT_B64" | "S_ADDC_U32" | "S_SUBB_U32" + ) { + scc_read = true; + } + if salu_writes_scc(enc, name) { + scc_write = true; + } else if !is_supported_salu(enc, name) && !name.contains("SAVEEXEC") && !name.contains("WREXEC") { + // Unknown SALU op: conservatively assume it may read scc and all SGPRs. + scc_read = true; + s_read |= S_ALL; + s_kill = 0; + } + } + + // Extra encoding-specific SGPR & VGPR uses (catching everything `rdna2::vgpr_uses` misses). + let (vr, vw) = rdna2::vgpr_uses(d); + for r in vr { + v_read.set(r); + } + for w in vw { + v_mod.set(w); + } + // Fix up SDWA VSRC1 if S1==1 (scalar, not VGPR — `rdna2::vgpr_uses` treats VSRC1 as VGPR). + if d.variant == Variant::Sdwa { + if let Some(e) = ext_encoding(d) { + if d.enc.field("VSRC1").is_some() && rdna2::field_value(e, &d.words, "S1") == Some(1) { + // Recompute v_read cleanly from SDWA fields only. + v_read = VRegs::EMPTY; + if rdna2::field_value(e, &d.words, "S0") != Some(1) { + v_read.set(rdna2::field_value(e, &d.words, "VSRC0").unwrap_or(0)); + } + } + } + } + + match enc { + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => {} + "ENC_SMEM" => { + if matches!(name, "S_MEMTIME" | "S_MEMREALTIME") { + let sdata = fval(d, "SDATA"); + let r = sreg_range(sdata, 2); + s_kill |= r; + s_mod |= r; + } else if let Some(count) = smem_load_count(name) { + let sbase = scaled_field(d, "SBASE"); + let base_n = if name.starts_with("S_BUFFER_LOAD_") { 4 } else { 2 }; + s_read |= sreg_range(sbase, base_n); + let soff = fval(d, "SOFFSET"); + if soff != 125 { + let (sr, sc) = scalar_code_regs(soff, 1, wave64); + s_read |= sr; + scc_read |= sc; + } + let sdata = fval(d, "SDATA"); + let dst = sreg_range(sdata, count as u64); + s_kill |= dst; + s_mod |= dst; + } else { + // Stores / atomics / cache ops: never kill. + s_kill = 0; + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + let srsrc = scaled_field(d, "SRSRC"); + s_read |= sreg_range(srsrc, 4); + let (sr, sc) = scalar_code_regs(fval(d, "SOFFSET"), 1, wave64); + s_read |= sr; + scc_read |= sc; + s_read |= S_EXEC; + let vdata = fval(d, "VDATA"); + if name.starts_with("BUFFER_ATOMIC_") { + let x2 = name.ends_with("_X2"); + let cmpswap = name.contains("CMPSWAP"); + let words = match (x2, cmpswap) { + (false, false) => 1, + (false, true) => 2, + (true, false) => 2, + (true, true) => 4, + }; + v_read.set_range(vdata, words); + if fval(d, "GLC") == 1 { + v_mod.set_range(vdata, if x2 { 2 } else { 1 }); + } else { + v_mod = VRegs::EMPTY; + } + } + if is_rmw_or_partial_vgpr_write(d) { + v_read = v_read.union(v_mod); + } + } + "ENC_MIMG" => { + let srsrc = scaled_field(d, "SRSRC"); + let t_words = if fval(d, "R128") == 1 { 4 } else { 8 }; + s_read |= sreg_range(srsrc, t_words); + let base = name.trim_start_matches("IMAGE_"); + let sampling = base.starts_with("SAMPLE") || base.starts_with("GATHER4") || base == "GET_LOD"; + if sampling { + let ssamp = scaled_field(d, "SSAMP"); + s_read |= sreg_range(ssamp, 4); + } + s_read |= S_EXEC; + // Address VGPRs: sequential or NSA. + let nsa = fval(d, "NSA"); + if nsa > 0 { + v_read.set(fval(d, "VADDR")); + if let Some(nsa_enc) = rdna2::encoding(&format!("MIMG_NSA{nsa}")) { + for j in 0..(4 * nsa) { + let letter = (b'A' + j.min(25) as u8) as char; + if let Some(v) = rdna2::field_value(nsa_enc, &d.words, &format!("VADDR{letter}")) { + v_read.set(v); + } + } + } else { + v_read = VRegs::ALL; + } + } else { + // Sequential VADDR: conservatively cover up to 12 address VGPRs for BVH/grad samples. + let vaddr = fval(d, "VADDR"); + let n_addr = if base.starts_with("BVH") { + 12 + } else if sampling { + 10 + } else { + 4 + }; + v_read.set_range(vaddr, n_addr); + } + // Data VGPRs. + let vdata = fval(d, "VDATA"); + let dmask = fval(d, "DMASK"); + let d16 = fval(d, "D16") == 1; + let comps = (dmask & 0xF).count_ones() as u64; + let n_data = if base.starts_with("GATHER4") || base.starts_with("BVH") { + if d16 { 2 } else { 4 } + } else if d16 { + comps.div_ceil(2).max(1) + } else { + comps.max(1) + }; + if base.starts_with("STORE") { + v_read.set_range(vdata, n_data); + v_mod = VRegs::EMPTY; + } else if base.starts_with("ATOMIC_") { + let words = if base.contains("CMPSWAP") { 2 } else { 1 }; + v_read.set_range(vdata, words); + if fval(d, "GLC") == 1 { + v_mod.set_range(vdata, 1); + } else { + v_mod = VRegs::EMPTY; + } + } else { + v_mod.set_range(vdata, n_data); + } + } + "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => { + s_read |= S_EXEC; + let saddr = fval(d, "SADDR"); + let has_saddr = saddr != 0x7D && saddr != 0x7F && saddr < 128; + if has_saddr { + let n = if enc == "ENC_FLAT_SCRATCH" { 1 } else { 2 }; + s_read |= sreg_range(saddr, n); + } else if !name.ends_with("_ADDTID") { + let addr = fval(d, "ADDR"); + let n = if enc == "ENC_FLAT_SCRATCH" { 1 } else { 2 }; + v_read.set_range(addr, n); + } + if name.contains("_ATOMIC_") { + let data = fval(d, "DATA"); + let x2 = name.ends_with("_X2"); + let cmpswap = name.contains("CMPSWAP"); + let words = match (x2, cmpswap) { + (false, false) => 1, + (false, true) => 2, + (true, false) => 2, + (true, true) => 4, + }; + v_read.set_range(data, words); + if fval(d, "GLC") == 1 { + v_mod.set_range(fval(d, "VDST"), if x2 { 2 } else { 1 }); + } else { + v_mod = VRegs::EMPTY; + } + } + if is_rmw_or_partial_vgpr_write(d) { + v_read = v_read.union(v_mod); + } + } + "ENC_DS" => { + s_read |= S_EXEC; + if matches!(name, "DS_WRITE_ADDTID_B32" | "DS_READ_ADDTID_B32") { + s_read |= S_M0; + if name == "DS_WRITE_ADDTID_B32" { + v_read.set(fval(d, "DATA0")); + } else { + v_mod.set(fval(d, "VDST")); + } + } else if name == "DS_SWIZZLE_B32" { + v_read.set(fval(d, "ADDR")); + v_mod.set(fval(d, "VDST")); + } else if matches!(name, "DS_BPERMUTE_B32" | "DS_PERMUTE_B32") { + v_read.set(fval(d, "ADDR")); + v_read.set(fval(d, "DATA0")); + v_mod.set(fval(d, "VDST")); + } else { + v_read.set(fval(d, "ADDR")); + if name.starts_with("DS_READ2") { + let n = if name.ends_with("_B64") { 4 } else { 2 }; + v_mod.set_range(fval(d, "VDST"), n); + } else if name.starts_with("DS_WRITE2") { + let n = if name.ends_with("_B64") { 2 } else { 1 }; + v_read.set_range(fval(d, "DATA0"), n); + v_read.set_range(fval(d, "DATA1"), n); + v_mod = VRegs::EMPTY; + } else if name.contains("WRXCHG2") { + v_read.set(fval(d, "DATA0")); + v_read.set(fval(d, "DATA1")); + if name.contains("_RTN_") { + v_mod.set_range(fval(d, "VDST"), 2); + } + } else if name.contains("_RTN_") { + v_mod.set(fval(d, "VDST")); + } + if is_rmw_or_partial_vgpr_write(d) { + v_read = v_read.union(v_mod); + } + } + } + "ENC_EXP" => { + s_read |= S_EXEC; + // `emit.rs:1840` unconditionally calls `self.vreg(VSRC0..3)`. + for f in ["VSRC0", "VSRC1", "VSRC2", "VSRC3"] { + v_read.set(fval(d, f)); + } + v_mod = VRegs::EMPTY; + } + "ENC_VINTRP" => { + s_read |= S_EXEC; + if matches!(name, "V_INTERP_P1_F32" | "V_INTERP_P1LL_F16" | "V_INTERP_P1LV_F16") { + // `emit.rs:2009` emits only a comment for p1 (does not write VDST). + v_mod = VRegs::EMPTY; + } else if name == "V_INTERP_P2_F16" { + v_read = v_read.union(v_mod); + } + } + e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => { + s_read |= S_EXEC; + if name == "V_SWAP_B32" { + let s0 = fval(d, "SRC0"); + let vd = fval(d, "VDST"); + v_read.set(vd); + v_mod.set(vd); + if s0 >= 256 { + v_read.set(s0 - 256); + v_mod.set(s0 - 256); + } + } else if name.starts_with("V_INTERP_") { + if matches!(name, "V_INTERP_P1_F32" | "V_INTERP_P1LL_F16" | "V_INTERP_P1LV_F16") { + v_mod = VRegs::EMPTY; + } else if name == "V_INTERP_P2_F16" { + v_read = v_read.union(v_mod); + } + } else if is_rmw_or_partial_vgpr_write(d) { + v_read = v_read.union(v_mod); + } + } + _ => { + // Unknown encoding: conservative over-approximation. + s_read = S_ALL; + s_kill = 0; + scc_read = true; + v_read = VRegs::ALL; + } + } + + let exec_widen = is_exec_widening(d, s_mod); + + let has_any_output = s_mod != 0 || !v_mod.is_empty() || scc_write; + let pure_eliminable = has_any_output + && (s_mod & (S_EXEC | S_M0)) == 0 + && match enc { + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => { + is_supported_salu(enc, name) && !name.contains("SAVEEXEC") && !name.contains("WREXEC") + } + e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => is_supported_pure_valu(d), + _ => false, + }; + + InstInfo { + s_read, + s_kill, + s_mod, + scc_read, + scc_write, + v_read, + v_mod, + carry_sdst, + pure_eliminable, + exec_widen, + indirect_sgpr: false, + indirect_vgpr: false, + } +} + +fn smem_load_count(name: &str) -> Option<usize> { + let rest = name + .strip_prefix("S_BUFFER_LOAD_") + .or_else(|| name.strip_prefix("S_LOAD_"))?; + Some(match rest { + "DWORD" => 1, + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => return None, + }) +} + +/// Guardrail #8: check if Compute `mem..mem3` requires `globallycoherent`. +fn compute_mem_coherent(insts: &[Decoded]) -> bool { + let mut has_s_barrier = false; + let mut has_mem_store = false; + + for d in insts { + let name = d.inst.name; + let enc = d.enc.name; + + // Condition 1: any GLC / DLC / SLC memory flag. + if matches!( + enc, + "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" + ) { + if rdna2::field_value(d.enc, &d.words, "GLC") == Some(1) + || rdna2::field_value(d.enc, &d.words, "DLC") == Some(1) + || rdna2::field_value(d.enc, &d.words, "SLC") == Some(1) + { + return true; + } + } + + // Condition 2: any memory atomic. + if name.starts_with("S_ATOMIC") + || name.starts_with("S_BUFFER_ATOMIC") + || name.starts_with("BUFFER_ATOMIC") + || name.starts_with("FLAT_ATOMIC") + || name.starts_with("GLOBAL_ATOMIC") + { + return true; + } + + // Condition 3: any cache invalidate / writeback op (excluding instruction cache `S_ICACHE_INV`). + if name != "S_ICACHE_INV" + && (name.contains("DCACHE_INV") + || name.contains("DCACHE_WB") + || name.contains("DCACHE_DISCARD") + || name.contains("GL0_INV") + || name.contains("GL1_INV") + || name.contains("WBL2") + || (enc == "ENC_SMEM" && name.ends_with("_INV")) + || (enc == "ENC_MUBUF" && name.ends_with("_INV"))) + { + return true; + } + + // Condition 4: `s_barrier` combined with any `mem..mem3` store. + if name == "S_BARRIER" { + has_s_barrier = true; + } + match enc { + "ENC_MUBUF" | "ENC_MTBUF" => { + if name.starts_with("BUFFER_STORE") || name.starts_with("TBUFFER_STORE") { + has_mem_store = true; + } else if !name.starts_with("BUFFER_LOAD") + && !name.starts_with("TBUFFER_LOAD") + && !name.ends_with("_INV") + && !name.ends_with("WBL2") + { + has_mem_store = true; + } + } + "ENC_FLAT" | "ENC_FLAT_GLBL" => { + if name.contains("_STORE_") || !name.contains("_LOAD_") { + has_mem_store = true; + } + } + "ENC_SMEM" => { + if name.starts_with("S_STORE") || name.starts_with("S_BUFFER_STORE") { + has_mem_store = true; + } else if smem_load_count(name).is_none() + && !matches!(name, "S_MEMTIME" | "S_MEMREALTIME") + && !name.contains("_INV") + { + has_mem_store = true; + } + } + _ => {} + } + } + + has_s_barrier && has_mem_store +} + +/// Maximum byte span for a single hoisted SMEM or `s_buffer_load` group (full 21-bit SMEM range; +/// valid non-`Kernel` UMA allocations never straddle 4 GiB, so zero wrap-fallback duplication!). +const MAX_SMEM_GROUP_SPAN: i64 = 1_048_576; +/// Maximum number of deduplicated loads per hoisted SMEM or `s_buffer_load` group. +const MAX_SMEM_GROUP_LOADS: usize = 96; + +/// Returns true iff `d` can mutate global/UMA memory, synchronize memory visibility across +/// lanes/workgroups, or transfer control to unknown code that may mutate memory. +fn is_memory_hazard(d: &Decoded, opt: &Options) -> bool { + let name = d.inst.name; + let enc = d.enc.name; + match enc { + "ENC_SMEM" => { + smem_load_count(name).is_none() + && !matches!(name, "S_MEMTIME" | "S_MEMREALTIME" | "S_ICACHE_INV") + } + "ENC_MUBUF" | "ENC_MTBUF" => { + !name.starts_with("BUFFER_LOAD") && !name.starts_with("TBUFFER_LOAD") + } + "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => { + !name.contains("_LOAD_") || name.contains("_STORE_") || name.contains("_ATOMIC_") + } + "ENC_MIMG" => { + let base = name.trim_start_matches("IMAGE_"); + base.starts_with("STORE") || base.starts_with("ATOMIC_") + } + "ENC_SOPP" => matches!(name, "S_BARRIER" | "S_SENDMSG"), + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => { + name.starts_with("S_CALL") + || (name == "S_SETPC_B64" + && d.far_target.is_none() + && !matches!(opt.mode, Mode::Geometry(_))) + || (name == "S_SWAPPC_B64" && fval(d, "SDST") != fval(d, "SSRC0")) + } + "ENC_DS" | "ENC_EXP" | "ENC_VINTRP" => false, + e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => false, + _ => true, + } +} + +fn is_terminator_inst(d: &Decoded) -> bool { + d.far_target.is_some() + || rdna2::branch_target(d).is_some() + || d.inst.flags & F_TERMINATOR != 0 + || d.inst.flags & F_INDIRECT != 0 + || matches!( + d.inst.name, + "S_ENDPGM" | "S_ENDPGM_SAVED" | "S_ENDPGM_ORDERED_PS_DONE" | "S_SETPC_B64" + ) +} + +/// Exact CFG dominator tree computed via iterative RPO + Cooper-Harvey-Kennedy algorithm. +struct DomTree { + rpo_order: Vec<usize>, + rpo_num: Vec<usize>, + idom: Vec<Option<usize>>, +} + +impl DomTree { + fn build(num_blocks: usize, succs: &[Vec<usize>], preds: &[Vec<usize>]) -> Self { + let mut visited = vec![false; num_blocks]; + let mut postorder = Vec::with_capacity(num_blocks); + + // Iterative DFS from entry block 0. + if num_blocks > 0 { + let mut stack: Vec<(usize, usize)> = vec![(0, 0)]; + visited[0] = true; + while let Some((b, si)) = stack.last_mut() { + let b_val = *b; + if *si < succs[b_val].len() { + let s = succs[b_val][*si]; + *si += 1; + if !visited[s] { + visited[s] = true; + stack.push((s, 0)); + } + } else { + postorder.push(b_val); + stack.pop(); + } + } + } + + let mut rpo_order = postorder; + rpo_order.reverse(); + let mut rpo_num = vec![usize::MAX; num_blocks]; + for (idx, &b) in rpo_order.iter().enumerate() { + rpo_num[b] = idx; + } + + let mut idom: Vec<Option<usize>> = vec![None; num_blocks]; + if num_blocks > 0 { + idom[0] = Some(0); + } + + let intersect = |mut f1: usize, mut f2: usize, idom: &[Option<usize>], rpo_num: &[usize]| -> usize { + while f1 != f2 { + while rpo_num[f1] > rpo_num[f2] { + f1 = idom[f1].unwrap(); + } + while rpo_num[f2] > rpo_num[f1] { + f2 = idom[f2].unwrap(); + } + } + f1 + }; + + let mut changed = true; + while changed { + changed = false; + for &b in rpo_order.iter().skip(1) { + let mut new_idom: Option<usize> = None; + for &p in &preds[b] { + if idom[p].is_some() { + new_idom = Some(match new_idom { + None => p, + Some(cur) => intersect(p, cur, &idom, &rpo_num), + }); + } + } + if new_idom.is_some() && idom[b] != new_idom { + idom[b] = new_idom; + changed = true; + } + } + } + + Self { + rpo_order, + rpo_num, + idom, + } + } + + #[inline] + fn is_reachable(&self, b: usize) -> bool { + b < self.rpo_num.len() && self.rpo_num[b] != usize::MAX + } + + fn dominates(&self, a: usize, b: usize) -> bool { + if !self.is_reachable(a) || !self.is_reachable(b) || self.rpo_num[a] > self.rpo_num[b] { + return false; + } + let mut cur = b; + while cur != a { + if cur == 0 { + return false; + } + cur = match self.idom[cur] { + Some(p) => p, + None => return false, + }; + } + true + } + + fn lca(&self, mut f1: usize, mut f2: usize) -> Option<usize> { + if !self.is_reachable(f1) || !self.is_reachable(f2) { + return None; + } + while f1 != f2 { + while self.rpo_num[f1] > self.rpo_num[f2] { + f1 = self.idom[f1]?; + } + while self.rpo_num[f2] > self.rpo_num[f1] { + f2 = self.idom[f2]?; + } + } + Some(f1) + } +} + +/// Unique reaching-definition identity for a plain SGPR `s0..s105`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +enum DefVal { + Bottom, + Entry, + Inst(usize), + Top, +} + +#[inline] +fn meet_def(a: DefVal, b: DefVal) -> DefVal { + match (a, b) { + (DefVal::Bottom, x) | (x, DefVal::Bottom) => x, + (x, y) if x == y => x, + _ => DefVal::Top, + } +} + +/// Lattice value for CFG-wide plain SGPR constant propagation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ConstVal { + Bottom, + Known(u32), + Top, +} + +#[inline] +fn meet_const(a: ConstVal, b: ConstVal) -> ConstVal { + match (a, b) { + (ConstVal::Bottom, x) | (x, ConstVal::Bottom) => x, + (ConstVal::Known(x), ConstVal::Known(y)) if x == y => ConstVal::Known(x), + _ => ConstVal::Top, + } +} + +#[inline] +fn resolve_const_scalar(d: &Decoded, code: u64, state: &[ConstVal; 106]) -> Option<u32> { + if code < 106 { + match state[code as usize] { + ConstVal::Known(v) => Some(v), + _ => None, + } + } else { + inline_const_bits(code, d.literal, false) + } +} + +/// Apply one instruction's effect to `(defs, consts)` for plain SGPRs `0..106`. +fn step_sgpr_def_const( + inst_idx: usize, + d: &Decoded, + info: &InstInfo, + defs: &mut [DefVal; 106], + consts: &mut [ConstVal; 106], +) { + let name = d.inst.name; + let mut new_c: [(usize, ConstVal); 2] = [(usize::MAX, ConstVal::Top); 2]; + let mut new_c_len = 0usize; + + match name { + "S_MOV_B32" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + if let Some(v) = resolve_const_scalar(d, fval(d, "SSRC0"), consts) { + new_c[0] = (sd, ConstVal::Known(v)); + new_c_len = 1; + } + } + } + "S_MOVK_I32" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + let v = fval(d, "SIMM16") as u16 as i16 as i32 as u32; + new_c[0] = (sd, ConstVal::Known(v)); + new_c_len = 1; + } + } + "S_MOV_B64" => { + let sd = fval(d, "SDST") as usize; + let s0 = fval(d, "SSRC0"); + if sd + 1 < 106 { + match s0 { + 0..=104 => { + let lo = consts[s0 as usize]; + let hi = consts[s0 as usize + 1]; + if matches!(lo, ConstVal::Known(_)) { + new_c[new_c_len] = (sd, lo); + new_c_len += 1; + } + if matches!(hi, ConstVal::Known(_)) { + new_c[new_c_len] = (sd + 1, hi); + new_c_len += 1; + } + } + 128..=208 => { + if let Some(v32) = inline_const_bits(s0, d.literal, false) { + let v64 = v32 as i32 as i64; + new_c[0] = (sd, ConstVal::Known(v64 as u32)); + new_c[1] = (sd + 1, ConstVal::Known((v64 >> 32) as u32)); + new_c_len = 2; + } + } + 255 => { + if let Some(lit) = d.literal { + new_c[0] = (sd, ConstVal::Known(lit)); + new_c[1] = (sd + 1, ConstVal::Known(0)); + new_c_len = 2; + } + } + _ => {} + } + } + } + "S_XOR_B32" => { + let sd = fval(d, "SDST") as usize; + let s0 = fval(d, "SSRC0"); + let s1 = fval(d, "SSRC1"); + if sd < 106 { + if s0 == s1 && s0 < 106 { + new_c[0] = (sd, ConstVal::Known(0)); + new_c_len = 1; + } else if let (Some(a), Some(b)) = ( + resolve_const_scalar(d, s0, consts), + resolve_const_scalar(d, s1, consts), + ) { + new_c[0] = (sd, ConstVal::Known(a ^ b)); + new_c_len = 1; + } + } + } + "S_XOR_B64" => { + let sd = fval(d, "SDST") as usize; + let s0 = fval(d, "SSRC0"); + let s1 = fval(d, "SSRC1"); + if sd + 1 < 106 && s0 == s1 && s0 < 105 { + new_c[0] = (sd, ConstVal::Known(0)); + new_c[1] = (sd + 1, ConstVal::Known(0)); + new_c_len = 2; + } + } + "S_AND_B32" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + let a = resolve_const_scalar(d, fval(d, "SSRC0"), consts); + let b = resolve_const_scalar(d, fval(d, "SSRC1"), consts); + if a == Some(0) || b == Some(0) { + new_c[0] = (sd, ConstVal::Known(0)); + new_c_len = 1; + } else if let (Some(a), Some(b)) = (a, b) { + new_c[0] = (sd, ConstVal::Known(a & b)); + new_c_len = 1; + } + } + } + "S_AND_B64" => { + let sd = fval(d, "SDST") as usize; + if sd + 1 < 106 { + let s0 = fval(d, "SSRC0"); + let s1 = fval(d, "SSRC1"); + let hi_of = |code: u64| -> Option<u32> { + if code < 105 { + match consts[code as usize + 1] { + ConstVal::Known(v) => Some(v), + _ => None, + } + } else if matches!(code, 128..=208) { + inline_const_bits(code, d.literal, false).map(|v| ((v as i32 as i64) >> 32) as u32) + } else if code == 255 && d.literal.is_some() { + Some(0) + } else { + None + } + }; + let (h0, h1) = (hi_of(s0), hi_of(s1)); + if h0 == Some(0) || h1 == Some(0) { + new_c[0] = (sd + 1, ConstVal::Known(0)); + new_c_len = 1; + } else if let (Some(a), Some(b)) = (h0, h1) { + new_c[0] = (sd + 1, ConstVal::Known(a & b)); + new_c_len = 1; + } + } + } + "S_OR_B32" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + let a = resolve_const_scalar(d, fval(d, "SSRC0"), consts); + let b = resolve_const_scalar(d, fval(d, "SSRC1"), consts); + if a == Some(u32::MAX) || b == Some(u32::MAX) { + new_c[0] = (sd, ConstVal::Known(u32::MAX)); + new_c_len = 1; + } else if let (Some(a), Some(b)) = (a, b) { + new_c[0] = (sd, ConstVal::Known(a | b)); + new_c_len = 1; + } + } + } + "S_SUB_U32" | "S_SUB_I32" => { + let sd = fval(d, "SDST") as usize; + let s0 = fval(d, "SSRC0"); + let s1 = fval(d, "SSRC1"); + if sd < 106 { + if s0 == s1 && s0 < 106 { + new_c[0] = (sd, ConstVal::Known(0)); + new_c_len = 1; + } else if let (Some(a), Some(b)) = ( + resolve_const_scalar(d, s0, consts), + resolve_const_scalar(d, s1, consts), + ) { + new_c[0] = (sd, ConstVal::Known(a.wrapping_sub(b))); + new_c_len = 1; + } + } + } + "S_ADD_U32" | "S_ADD_I32" | "S_MUL_I32" | "S_LSHL_B32" | "S_LSHR_B32" | "S_ASHR_I32" + | "S_PACK_LL_B32_B16" | "S_PACK_LH_B32_B16" | "S_PACK_HH_B32_B16" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + if let (Some(a), Some(b)) = ( + resolve_const_scalar(d, fval(d, "SSRC0"), consts), + resolve_const_scalar(d, fval(d, "SSRC1"), consts), + ) { + let v = match name { + "S_ADD_U32" | "S_ADD_I32" => a.wrapping_add(b), + "S_MUL_I32" => a.wrapping_mul(b), + "S_LSHL_B32" => a << (b & 31), + "S_LSHR_B32" => a >> (b & 31), + "S_ASHR_I32" => ((a as i32) >> (b & 31)) as u32, + "S_PACK_LL_B32_B16" => (a & 0xFFFF) | (b << 16), + "S_PACK_LH_B32_B16" => (a & 0xFFFF) | (b & 0xFFFF_0000), + "S_PACK_HH_B32_B16" => (a >> 16) | (b & 0xFFFF_0000), + _ => unreachable!(), + }; + new_c[0] = (sd, ConstVal::Known(v)); + new_c_len = 1; + } + } + } + "S_ADDK_I32" | "S_MULK_I32" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + if let ConstVal::Known(cur) = consts[sd] { + let k = fval(d, "SIMM16") as u16 as i16 as i32 as u32; + let v = if name == "S_ADDK_I32" { + cur.wrapping_add(k) + } else { + cur.wrapping_mul(k) + }; + new_c[0] = (sd, ConstVal::Known(v)); + new_c_len = 1; + } + } + } + "S_NOT_B32" => { + let sd = fval(d, "SDST") as usize; + if sd < 106 { + if let Some(a) = resolve_const_scalar(d, fval(d, "SSRC0"), consts) { + new_c[0] = (sd, ConstVal::Known(!a)); + new_c_len = 1; + } + } + } + _ => {} + } + + if info.indirect_sgpr { + *defs = [DefVal::Top; 106]; + *consts = [ConstVal::Top; 106]; + return; + } + + let mut m = info.s_mod & S_PLAIN_MASK; + while m != 0 { + let r = m.trailing_zeros() as usize; + m &= m - 1; + defs[r] = DefVal::Inst(inst_idx); + consts[r] = ConstVal::Top; + } + for &(r, cv) in &new_c[..new_c_len] { + consts[r] = cv; + } +} + +/// Forward CFG-wide fixpoint for SGPR reaching definitions and constant values. +fn solve_cfg_sgpr_defs_and_consts( + num_blocks: usize, + dom: &DomTree, + cfg_preds: &[Vec<usize>], + block_ranges: &[(usize, usize)], + eff_end: &[usize], + insts: &[Decoded], + infos: &[InstInfo], + dead_inst: &HashSet<u64>, + has_unknown_cf: bool, +) -> (Vec<[DefVal; 106]>, Vec<[ConstVal; 106]>) { + let mut def_in = vec![[DefVal::Bottom; 106]; num_blocks]; + let mut def_out = vec![[DefVal::Bottom; 106]; num_blocks]; + let mut const_in = vec![[ConstVal::Bottom; 106]; num_blocks]; + let mut const_out = vec![[ConstVal::Bottom; 106]; num_blocks]; + + if num_blocks == 0 { + return (def_in, const_in); + } + + if has_unknown_cf { + // Conservative under indirect branches: every block entry is Top. + for bi in 0..num_blocks { + def_in[bi] = [DefVal::Top; 106]; + const_in[bi] = [ConstVal::Top; 106]; + } + def_in[0] = [DefVal::Entry; 106]; + return (def_in, const_in); + } + + def_in[0] = [DefVal::Entry; 106]; + const_in[0] = [ConstVal::Top; 106]; + + loop { + let mut changed = false; + for &bi in &dom.rpo_order { + let (in_d, in_c) = if bi == 0 { + let mut d0 = [DefVal::Entry; 106]; + let mut c0 = [ConstVal::Top; 106]; + for &p in &cfg_preds[0] { + if dom.is_reachable(p) { + for r in 0..106 { + d0[r] = meet_def(d0[r], def_out[p][r]); + c0[r] = meet_const(c0[r], const_out[p][r]); + } + } + } + (d0, c0) + } else { + let mut d_acc = [DefVal::Bottom; 106]; + let mut c_acc = [ConstVal::Bottom; 106]; + for &p in &cfg_preds[bi] { + if dom.is_reachable(p) { + for r in 0..106 { + d_acc[r] = meet_def(d_acc[r], def_out[p][r]); + c_acc[r] = meet_const(c_acc[r], const_out[p][r]); + } + } + } + (d_acc, c_acc) + }; + + let mut cur_d = in_d; + let mut cur_c = in_c; + let s_idx = block_ranges[bi].0; + let e_idx = eff_end[bi]; + for k in s_idx..e_idx { + if dead_inst.contains(&insts[k].pc) { + continue; + } + step_sgpr_def_const(k, &insts[k], &infos[k], &mut cur_d, &mut cur_c); + } + + if in_d != def_in[bi] + || cur_d != def_out[bi] + || in_c != const_in[bi] + || cur_c != const_out[bi] + { + def_in[bi] = in_d; + def_out[bi] = cur_d; + const_in[bi] = in_c; + const_out[bi] = cur_c; + changed = true; + } + } + if !changed { + break; + } + } + + (def_in, const_in) +} + +/// Canonical reaching-def key for grouping `s_load_*` base pointer halves. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +enum DefKey { + Entry, + Inst(usize), + /// Block-entry identity for a `Top` reaching def (allows safe intra-block grouping & + /// `known_hi == Some(0)` without cross-block hoisting!). + LocalEntry(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HoistLoc { + BlockEntry(u64), + BeforePc(u64), + AfterPc(u64), +} + +#[derive(Clone, Debug)] +struct SmemCand { + bi: usize, + local_idx: usize, + pc: u64, + off: i64, + count: u8, + end: i64, +} + +/// Deduplicate & subsume `(offset, count)` pairs into sorted `HoistedLoad`s. +/// Sub-range subsumption (`parent` covers `child`) is applied only when `allow_subsume_neg || parent.offset >= 0`. +fn dedup_and_subsume_loads( + pairs: &[(i64, u8)], + allow_subsume_neg: bool, +) -> (Vec<HoistedLoad>, HashMap<(i64, u8), (u16, u8, u8)>) { + let mut uniq: Vec<(i64, u8)> = pairs.to_vec(); + uniq.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| b.1.cmp(&a.1))); + uniq.dedup(); + + let mut loads: Vec<HoistedLoad> = Vec::with_capacity(uniq.len()); + let mut map: HashMap<(i64, u8), (u16, u8, u8)> = HashMap::with_capacity(uniq.len()); + + for &(off, count) in &uniq { + let end = off + 4 * (count as i64); + let mut found: Option<(u16, u8, u8)> = None; + for (idx, parent) in loads.iter().enumerate() { + let p_end = parent.offset + 4 * (parent.count as i64); + if parent.offset == off && parent.count == count { + found = Some((idx as u16, 0, parent.count)); + break; + } + if (allow_subsume_neg || parent.offset >= 0) && parent.offset <= off && end <= p_end { + let dw_off = ((off - parent.offset) / 4) as u8; + found = Some((idx as u16, dw_off, parent.count)); + break; + } + } + if let Some(m) = found { + map.insert((off, count), m); + } else { + let idx = loads.len() as u16; + loads.push(HoistedLoad { offset: off, count }); + map.insert((off, count), (idx, 0, count)); + } + } + + (loads, map) +} + +struct HoistedSmemResult { + groups: Vec<HoistedSmemGroup>, + at_entry: HashMap<u64, Vec<usize>>, + before_pc: HashMap<u64, Vec<usize>>, + after_pc: HashMap<u64, Vec<usize>>, + uses: HashMap<u64, SmemUse>, +} + +/// Weapon 1A: Dominator-hoisted & CSE'd invariant `s_load_dword*` groups + known-zero-hi Window-0 fast path. +#[allow(clippy::too_many_arguments)] +fn analyze_hoisted_smem( + insts: &[Decoded], + infos: &[InstInfo], + block_starts: &[u64], + block_ranges: &[(usize, usize)], + eff_end: &[usize], + dom: &DomTree, + cfg_preds: &[Vec<usize>], + unknown_succ: &[bool], + inst_hazard: &[bool], + dead_inst: &HashSet<u64>, + def_in: &[[DefVal; 106]], + const_in: &[[ConstVal; 106]], + opt: &Options, + has_unknown_cf: bool, +) -> HoistedSmemResult { + let num_blocks = block_starts.len(); + let kernel_mode = matches!(opt.mode, Mode::Kernel); + + // Per-instruction block lookup and per-block hazard / SGPR-mod summaries. + let mut inst_block = vec![0usize; insts.len()]; + let mut inst_local_idx = vec![0usize; insts.len()]; + let mut block_has_hazard = vec![false; num_blocks]; + let mut block_mod_s = vec![0u128; num_blocks]; + let mut block_indirect_sgpr = vec![false; num_blocks]; + + for bi in 0..num_blocks { + let s_idx = block_ranges[bi].0; + let e_idx = eff_end[bi]; + for (li, k) in (s_idx..e_idx).enumerate() { + inst_block[k] = bi; + inst_local_idx[k] = li; + if dead_inst.contains(&insts[k].pc) { + continue; + } + if inst_hazard[k] { + block_has_hazard[bi] = true; + } + block_mod_s[bi] |= infos[k].s_mod; + if infos[k].indirect_sgpr { + block_indirect_sgpr[bi] = true; + } + } + } + + // Collect candidate `s_load_dword*` grouped by `(sbase, key_lo, key_hi)` in deterministic order. + let mut groups_by_key: BTreeMap<(u8, DefKey, DefKey), Vec<SmemCand>> = BTreeMap::new(); + // Track per-block `(const_s_before_inst)` on demand by re-stepping block `H` when validating. + for &bi in &dom.rpo_order { + let s_idx = block_ranges[bi].0; + let e_idx = eff_end[bi]; + let mut cur_d = def_in[bi]; + let mut cur_c = const_in[bi]; + + for (li, k) in (s_idx..e_idx).enumerate() { + let d = &insts[k]; + if dead_inst.contains(&d.pc) { + continue; + } + if d.enc.name == "ENC_SMEM" && d.inst.name.starts_with("S_LOAD_") { + if let Some(count) = smem_load_count(d.inst.name) { + let is_glc_dlc = rdna2::field_value(d.enc, &d.words, "GLC") == Some(1) + || rdna2::field_value(d.enc, &d.words, "DLC") == Some(1); + let sbase = scaled_field(d, "SBASE"); + let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); + let raw_imm = fval(d, "OFFSET") as u32; + let off = ((raw_imm << 11) as i32 >> 11) as i64; + + if !is_glc_dlc && sbase + 2 <= 106 && soff == 125 && (off & 3) == 0 { + let to_key = |dv: DefVal| -> DefKey { + if has_unknown_cf { + return DefKey::LocalEntry(bi); + } + match dv { + DefVal::Entry => DefKey::Entry, + DefVal::Inst(di) => DefKey::Inst(di), + DefVal::Top | DefVal::Bottom => DefKey::LocalEntry(bi), + } + }; + let key_lo = to_key(cur_d[sbase as usize]); + let key_hi = to_key(cur_d[sbase as usize + 1]); + groups_by_key + .entry((sbase as u8, key_lo, key_hi)) + .or_default() + .push(SmemCand { + bi, + local_idx: li, + pc: d.pc, + off, + count: count as u8, + end: off + 4 * (count as i64), + }); + } + } + } + step_sgpr_def_const(k, d, &infos[k], &mut cur_d, &mut cur_c); + } + } + + let def_block_of = |key: DefKey| -> usize { + match key { + DefKey::Entry => 0, + DefKey::Inst(di) => inst_block[di], + DefKey::LocalEntry(bi) => bi, + } + }; + + // Validate a candidate cluster: returns `Some((hoist_bi, h_idx, HoistLoc))` if 100% sound. + let validate_cluster = |sbase: u8, + key_lo: DefKey, + key_hi: DefKey, + cluster: &[SmemCand]| + -> Option<(usize, usize, HoistLoc)> { + if cluster.is_empty() { + return None; + } + let mut min_off = i64::MAX; + let mut max_end = i64::MIN; + let mut h = cluster[0].bi; + for u in cluster { + min_off = min_off.min(u.off); + max_end = max_end.max(u.end); + h = dom.lca(h, u.bi)?; + } + if max_end - min_off > MAX_SMEM_GROUP_SPAN { + return None; + } + if !dom.dominates(def_block_of(key_lo), h) || !dom.dominates(def_block_of(key_hi), h) { + return None; + } + + let hs_idx = block_ranges[h].0; + let he_idx = eff_end[h]; + let h_len = he_idx - hs_idx; + + let min_use_in_h = cluster + .iter() + .filter(|u| u.bi == h) + .map(|u| u.local_idx) + .min(); + + let (h_idx, hoist_loc) = if let Some(u_li) = min_use_in_h { + // Def inside H must strictly precede the hoist point. + if let DefKey::Inst(di) = key_lo { + if inst_block[di] == h && inst_local_idx[di] >= u_li { + return None; + } + } + if let DefKey::Inst(di) = key_hi { + if inst_block[di] == h && inst_local_idx[di] >= u_li { + return None; + } + } + (u_li, HoistLoc::BeforePc(insts[hs_idx + u_li].pc)) + } else if h_len == 0 { + (0, HoistLoc::BlockEntry(block_starts[h])) + } else { + let last_k = he_idx - 1; + if is_terminator_inst(&insts[last_k]) { + let place_li = h_len - 1; + if let DefKey::Inst(di) = key_lo { + if inst_block[di] == h && inst_local_idx[di] >= place_li { + return None; + } + } + if let DefKey::Inst(di) = key_hi { + if inst_block[di] == h && inst_local_idx[di] >= place_li { + return None; + } + } + (place_li, HoistLoc::BeforePc(insts[last_k].pc)) + } else { + // Fallthrough block: emit immediately after the last instruction of H. + (h_len, HoistLoc::AfterPc(insts[last_k].pc)) + } + }; + + let base_mask = (1u128 << sbase) | (1u128 << (sbase + 1)); + + // Helper: check slice of instructions `lo..hi` inside block `bi` for hazard or base clobber. + let slice_is_clean = |bi: usize, lo: usize, hi: usize| -> bool { + let bs = block_ranges[bi].0; + for li in lo..hi { + let k = bs + li; + if dead_inst.contains(&insts[k].pc) { + continue; + } + if inst_hazard[k] + || infos[k].indirect_sgpr + || (infos[k].s_mod & base_mask) != 0 + { + return false; + } + } + true + }; + + let mut checked_h_suffix = false; + let mut clean_interm_checked: HashSet<usize> = HashSet::new(); + + for u in cluster { + if u.bi == h { + if u.local_idx < h_idx || !slice_is_clean(h, h_idx, u.local_idx) { + return None; + } + } else { + if !checked_h_suffix { + if unknown_succ[h] || !slice_is_clean(h, h_idx, h_len) { + return None; + } + checked_h_suffix = true; + } + if !slice_is_clean(u.bi, 0, u.local_idx) { + return None; + } + // Backwards BFS from `cfg_preds[u.bi]` stopping at `h`. + // Note: `u.bi` itself is NOT pre-marked visited so cycles back to `u.bi` + // without passing through `h` DO visit `u.bi` and check `block_has_hazard[u.bi]`! + if !clean_interm_checked.contains(&u.bi) { + let mut visited: HashSet<usize> = HashSet::new(); + let mut queue: VecDeque<usize> = VecDeque::new(); + for &p in &cfg_preds[u.bi] { + if dom.is_reachable(p) && visited.insert(p) { + queue.push_back(p); + } + } + while let Some(m) = queue.pop_front() { + if m == h { + continue; + } + if m == 0 { + // Reached entry without passing through H -> H does not dominate U! + return None; + } + if block_has_hazard[m] + || block_indirect_sgpr[m] + || (block_mod_s[m] & base_mask) != 0 + || unknown_succ[m] + { + return None; + } + for &p in &cfg_preds[m] { + if dom.is_reachable(p) && visited.insert(p) { + queue.push_back(p); + } + } + } + clean_interm_checked.insert(u.bi); + } + } + } + + Some((h, h_idx, hoist_loc)) + }; + + // Compute `const_s[sbase + 1]` at exact point `(h, h_idx)`. + let const_hi_at = |h: usize, h_idx: usize, sbase: u8| -> Option<u32> { + let mut cur_d = def_in[h]; + let mut cur_c = const_in[h]; + let hs = block_ranges[h].0; + for li in 0..h_idx { + let k = hs + li; + if dead_inst.contains(&insts[k].pc) { + continue; + } + step_sgpr_def_const(k, &insts[k], &infos[k], &mut cur_d, &mut cur_c); + } + match cur_c[sbase as usize + 1] { + ConstVal::Known(v) => Some(v), + _ => None, + } + }; + + let mut out = HoistedSmemResult { + groups: Vec::new(), + at_entry: HashMap::new(), + before_pc: HashMap::new(), + after_pc: HashMap::new(), + uses: HashMap::new(), + }; + + for ((sbase, key_lo, key_hi), cands) in groups_by_key { + // Fast path: try the entire set as one cluster first! + let clusters: Vec<(Vec<SmemCand>, usize, usize, HoistLoc)> = + if let Some((h, h_idx, loc)) = validate_cluster(sbase, key_lo, key_hi, &cands) { + vec![(cands, h, h_idx, loc)] + } else { + // Partition greedily into maximal hazard-free clusters. + let mut open: Vec<(Vec<SmemCand>, usize, usize, HoistLoc)> = Vec::new(); + for cand in cands { + let mut placed = false; + let start_try = open.len().saturating_sub(4); + for entry in open[start_try..].iter_mut().rev() { + entry.0.push(cand.clone()); + if let Some((h, h_idx, loc)) = validate_cluster(sbase, key_lo, key_hi, &entry.0) { + entry.1 = h; + entry.2 = h_idx; + entry.3 = loc; + placed = true; + break; + } + entry.0.pop(); + } + if !placed { + let single = vec![cand]; + if let Some((h, h_idx, loc)) = validate_cluster(sbase, key_lo, key_hi, &single) { + open.push((single, h, h_idx, loc)); + } + } + } + open + }; + + for (cluster, h, h_idx, hoist_loc) in clusters { + let pairs: Vec<(i64, u8)> = cluster.iter().map(|u| (u.off, u.count)).collect(); + let (all_loads, pair_map) = dedup_and_subsume_loads(&pairs, false); + let hi_const = const_hi_at(h, h_idx, sbase); + + // Chunk into groups of `<= MAX_SMEM_GROUP_LOADS`. + let num_chunks = all_loads.len().div_ceil(MAX_SMEM_GROUP_LOADS); + for chunk_i in 0..num_chunks { + let lo_l = chunk_i * MAX_SMEM_GROUP_LOADS; + let hi_l = (lo_l + MAX_SMEM_GROUP_LOADS).min(all_loads.len()); + let chunk_loads: Vec<HoistedLoad> = all_loads[lo_l..hi_l].to_vec(); + + let mut chunk_uses: Vec<(&SmemCand, u16, u8, u8)> = Vec::new(); + for u in &cluster { + let (global_li, dw_off, parent_cnt) = pair_map[&(u.off, u.count)]; + let gi = global_li as usize; + if gi >= lo_l && gi < hi_l { + chunk_uses.push((u, (gi - lo_l) as u16, dw_off, parent_cnt)); + } + } + if chunk_uses.is_empty() { + continue; + } + + let min_off = chunk_loads.iter().map(|l| l.offset).min().unwrap(); + let max_end = chunk_loads + .iter() + .map(|l| l.offset + 4 * (l.count as i64)) + .max() + .unwrap(); + + // CRITICAL: ONLY `hi == 0` unconditionally maps to Window 0 regardless of `xcl_uma_base`! + // Guardrail (`#326`): in `Mode::Kernel`, ONLY allow `known_hi = Some(0)` when + // `min_off == 0 && max_end <= 4` (cannot cross 4 GiB boundary!). + // In non-`Kernel` modes, valid UMA allocations never straddle 4 GiB, so the full + // 21-bit SMEM immediate range `[-1_048_576, 1_048_576]` is Window-0 safe. + let known_hi = if hi_const == Some(0) { + if kernel_mode { + (min_off == 0 && max_end <= 4).then_some(0) + } else if min_off >= -1_048_576 && max_end <= 1_048_576 { + Some(0) + } else { + None + } + } else { + None + }; + + let worth_emitting = if opt.mem_windows > 1 { + chunk_uses.len() >= 2 || known_hi.is_some() + } else { + chunk_uses.len() >= 2 + }; + if !worth_emitting { + continue; + } + + let gid = out.groups.len() as u32; + let gidx = out.groups.len(); + out.groups.push(HoistedSmemGroup { + id: gid, + hoist_block: block_starts[h], + sbase, + known_hi, + min_off, + max_end, + loads: chunk_loads, + }); + match hoist_loc { + HoistLoc::BlockEntry(bpc) => out.at_entry.entry(bpc).or_default().push(gidx), + HoistLoc::BeforePc(pc) => out.before_pc.entry(pc).or_default().push(gidx), + HoistLoc::AfterPc(pc) => out.after_pc.entry(pc).or_default().push(gidx), + } + for (u, load_idx, dword_offset, parent_count) in chunk_uses { + out.uses.insert( + u.pc, + SmemUse { + group_id: gid, + load_idx, + parent_count, + dword_offset, + count: u.count, + }, + ); + } + } + } + } + + out +} + +/// Universal non-`Kernel` Window-0 fast-path sets (`known_zero_hi_sload`, `known_zero_hi_sbuf`). +/// +/// Covers EVERY non-`Kernel` `s_load_dword*` (including `soff != 125`, dynamic `s_lo`, and +/// post-store loads) where `s[sbase+1] == 0` (and `imm_off >= 0` when `soff != 125`, or +/// `-1_048_576 <= imm_off <= 1_048_576` when `soff == 125`), plus EVERY non-`Kernel` +/// `s_buffer_load_dword*` where `(s[sbase+1] & 0xFFFF) == 0`. +#[allow(clippy::too_many_arguments)] +fn collect_known_zero_hi_smem( + insts: &[Decoded], + infos: &[InstInfo], + block_ranges: &[(usize, usize)], + eff_end: &[usize], + dom: &DomTree, + dead_inst: &HashSet<u64>, + def_in: &[[DefVal; 106]], + const_in: &[[ConstVal; 106]], + opt: &Options, + has_unknown_cf: bool, +) -> (HashSet<u64>, HashSet<u64>) { + let mut known_zero_hi_sload = HashSet::new(); + let mut known_zero_hi_sbuf = HashSet::new(); + if matches!(opt.mode, Mode::Kernel) { + return (known_zero_hi_sload, known_zero_hi_sbuf); + } + + for bi in 0..block_ranges.len() { + if !has_unknown_cf && !dom.is_reachable(bi) { + continue; + } + let s_idx = block_ranges[bi].0; + let e_idx = eff_end[bi]; + let mut cur_d = def_in[bi]; + let mut cur_c = const_in[bi]; + + for k in s_idx..e_idx { + let d = &insts[k]; + if dead_inst.contains(&d.pc) { + continue; + } + if d.enc.name == "ENC_SMEM" && smem_load_count(d.inst.name).is_some() { + let sbase = scaled_field(d, "SBASE"); + if d.inst.name.starts_with("S_LOAD_") { + if sbase + 2 <= 106 && cur_c[sbase as usize + 1] == ConstVal::Known(0) { + let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); + let raw_imm = fval(d, "OFFSET") as u32; + let imm_off = ((raw_imm << 11) as i32 >> 11) as i64; + let off_ok = if soff != 125 { ~~~~ --- [P2] Preserve carry before selecting Window 0. This predicate proves only that the base high dword is zero. With dynamic SOFFSET, `imm_off >= 0` does not prevent `sbase_lo + imm + soff` from carrying into the next 4-GiB window (for example, base `0x00000000_FFFFFFFC` plus `soff=4`). The `known_zero_hi` emitter path then computes a 32-bit address and reads `xcl_mem0`, while the generic path forms a 64-bit effective address and selects the next window, so the loaded value differs when `mem_windows > 1`. The `known_zero_hi_sbuf` path has the same issue for `d0 + off`. Could both fast paths retain/select the carry or prove a bound, with parity coverage at the 4-GiB boundary?
bmjask commented 2026-11-29 14:50:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-11-29T14:50:13Z.


Current-main audit (2026-11-29): discard this PR as a merge unit; split any surviving ideas.

The measured corpus result is interesting, but this is 7,502 additions across a new ~5,700-line optimizer plus emitter/control-flow changes. It combines dead-code/liveness analysis, dominator/reaching-def logic, SMEM/SBUF hoisting, lane-local mask scalarization and lowering changes. That exceeds the repository's review-size rule by an order of magnitude, is stale/conflicted, and cannot be safely bisected or vendor-qualified as one change. The discussion also includes workloads where DXIL grew without a driver-time gain.

Each optimization needs its own preparation/analysis PR, transformation PR, GPU semantic tests, and current NVIDIA/AMD measurement. The present branch should not be rebased as one PR.

Cache impact: large intentional HLSL/DXIL changes, so affected PSOs recompile.

Review assisted by Codex; exact model name was not exposed in this session. I inspected the full diff structure and tests but did not execute the suite or retail corpus.

<!-- greyfinch-sync:ivall/xcl:comment:7257614227 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7257614227). Originally posted by [bmjask](https://github.com/bmjask) on 2026-11-29T14:50:13Z. --- **Current-main audit (2026-11-29): discard this PR as a merge unit; split any surviving ideas.** The measured corpus result is interesting, but this is 7,502 additions across a new ~5,700-line optimizer plus emitter/control-flow changes. It combines dead-code/liveness analysis, dominator/reaching-def logic, SMEM/SBUF hoisting, lane-local mask scalarization and lowering changes. That exceeds the repository's review-size rule by an order of magnitude, is stale/conflicted, and cannot be safely bisected or vendor-qualified as one change. The discussion also includes workloads where DXIL grew without a driver-time gain. Each optimization needs its own preparation/analysis PR, transformation PR, GPU semantic tests, and current NVIDIA/AMD measurement. The present branch should not be rebased as one PR. Cache impact: **large intentional HLSL/DXIL changes**, so affected PSOs recompile. Review assisted by Codex; exact model name was not exposed in this session. I inspected the full diff structure and tests but did not execute the suite or retail corpus.
Foniass commented 2026-12-01 06:20:14 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T06:20:14Z.


Triage (#1607) – head 91ae2c6

No open or merged PR makes the same change. The lines shared with #1575 are opcode name lists in the new opt.rs, not the same change.
Parts of it overlap work merged since: main now gates globallycoherent on compute memory with needs_coherent_mem (#2346), which does the same job as compute_mem_coherent / mem_coherent_prefix here, and #2203 added dead-SCC elision in split wave64. On rebase, keep main's coherence check and drop the duplicate. The PR conflicts with main and is +7502 lines in one PR. Splitting it (opt.rs analyses, then each emit.rs use of them) would make it reviewable.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7302756417 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1630#issuecomment-7302756417). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T06:20:14Z. --- **Triage (#1607)** – head 91ae2c6 No open or merged PR makes the same change. The lines shared with #1575 are opcode name lists in the new opt.rs, not the same change. Parts of it overlap work merged since: main now gates `globallycoherent` on compute memory with `needs_coherent_mem` (#2346), which does the same job as `compute_mem_coherent` / `mem_coherent_prefix` here, and #2203 added dead-SCC elision in split wave64. On rebase, keep main's coherence check and drop the duplicate. The PR conflicts with main and is +7502 lines in one PR. Splitting it (opt.rs analyses, then each emit.rs use of them) would make it reviewable. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
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/1630:upstream-pr/1630'
git switch 'upstream-pr/1630'

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/1630'
git switch 'upstream-pr/1630'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/1630'
git switch 'upstream-pr/1630'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/1630'
git switch 'main'
git merge --squash 'upstream-pr/1630'
git switch 'main'
git merge --ff-only 'upstream-pr/1630'
git switch 'main'
git merge 'upstream-pr/1630'
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!1620
No description provided.