perf(shader): add DXIL pure LICM, canonical ptr-path LDS forwarding, and barrier dedup #41

Open
github-bot wants to merge 2 commits from github-bot/gh-41 into beta AGit
Owner

@⁠Vladimir-Human on GitHub · 2026-11-25 21:01 UTC · original
Vladimir-Human:shader/dxil-opt-licm-alloca → beta · +4645 −89 · 2 files · 2 commits · open

AI-assisted clean-room contribution (victory-shader, synthetic DXIL bitcode tests + hardware GPU parity only — no title files used).

Summary

Ports four sound DXIL bitcode optimization passes onto crates/victory-shader/src/emit/bitcode/opt.rs (and exposes pass-mask test control in crates/victory-shader/src/emit/mod.rs while preserving translation_fingerprint() and all upstream additions):

  1. Algebraic / select folds & canonical comparison tracking (FACTS): folds redundant compares/selects along dominating branches without emitting AMD fcmp one (NaN-safe).
  2. Pure loop-invariant code motion (LICM = 64): hoists loop-invariant pure value-only DXIL math calls, loads on non-escaping invariant slots, and bounded GEPs across split loop preheaders (split_preheader, keeping dominators/SSA/outer loops coherent), while strictly gating non-guaranteed blocks and tracking per-instruction WriteKind::All / dx.op.discard cutoffs.
  3. Canonical scalar-leaf GEP path LDS forwarding / DSE (LOADS = 16): unbounded trace_ptr / escaped_globals canonicalization with signed indices, strict per-level bounds, and scalar-leaf type matching, forwarding intra-block SharedGlobal loads/DSE across disjoint pointers.
  4. Adjacent redundant barrier elimination (BARRIERS = 128): eliminates provably redundant adjacent barriers via (prev & m) == m without accumulating hazard state across unrelated regions.
  • Disjoint scope: touches only crates/victory-shader/src/emit/bitcode/opt.rs and crates/victory-shader/src/emit/mod.rs (git merge-tree clean against beta).

Verification (beta e328c88, RTX 4070 SUPER / i5-13400F)

  • cargo clippy -p victory-shader --all-targets -- -D warnings (default & --all-features): 0 warnings.
  • cargo test -p victory-shader --lib: 235 passed, 0 failed (4 ignored).
  • VICTORY_D3D12_DEBUG=1 VICTORY_REQUIRE_HW_GPU=1 cargo test -p victory-shader --lib dxil_opt_hw_gpu_bit_exact_parity_and_validation: passed on hardware GPU (opt=0 vs old_bits vs ALL bit-exact).
  • Release bench_dxil_opt_hw_gpu (during parallel build load; uncontested benchmark follow-up planned): loop body -85.7% (42 -> 6 insts), GPU median 109.57 us -> 95.23 us (1.15x), LDS+barrier loop 164.86 us -> 111.62 us (1.48x), real GFX10 loop 99.33 us -> 83.97 us (1.18x).
**@⁠Vladimir-Human** on GitHub · 2026-11-25 21:01 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41) `Vladimir-Human:shader/dxil-opt-licm-alloca` → `beta` · +4645 −89 · 2 files · 2 commits · open AI-assisted clean-room contribution (`victory-shader`, synthetic DXIL bitcode tests + hardware GPU parity only — no title files used). ### Summary Ports four sound DXIL bitcode optimization passes onto `crates/victory-shader/src/emit/bitcode/opt.rs` (and exposes pass-mask test control in `crates/victory-shader/src/emit/mod.rs` while preserving `translation_fingerprint()` and all upstream additions): 1. **Algebraic / select folds & canonical comparison tracking (`FACTS`)**: folds redundant compares/selects along dominating branches without emitting AMD `fcmp one` (`NaN`-safe). 2. **Pure loop-invariant code motion (`LICM = 64`)**: hoists loop-invariant pure value-only DXIL math calls, loads on non-escaping invariant slots, and bounded GEPs across split loop preheaders (`split_preheader`, keeping dominators/SSA/outer loops coherent), while strictly gating non-guaranteed blocks and tracking per-instruction `WriteKind::All` / `dx.op.discard` cutoffs. 3. **Canonical scalar-leaf GEP path LDS forwarding / DSE (`LOADS = 16`)**: unbounded `trace_ptr` / `escaped_globals` canonicalization with signed indices, strict per-level bounds, and scalar-leaf type matching, forwarding intra-block `SharedGlobal` loads/DSE across disjoint pointers. 4. **Adjacent redundant barrier elimination (`BARRIERS = 128`)**: eliminates provably redundant adjacent barriers via `(prev & m) == m` without accumulating hazard state across unrelated regions. - **Disjoint scope**: touches only `crates/victory-shader/src/emit/bitcode/opt.rs` and `crates/victory-shader/src/emit/mod.rs` (`git merge-tree` clean against `beta`). ### Verification (`beta` `e328c88`, RTX 4070 SUPER / i5-13400F) - `cargo clippy -p victory-shader --all-targets -- -D warnings` (default & `--all-features`): **0 warnings**. - `cargo test -p victory-shader --lib`: **235 passed, 0 failed** (4 ignored). - `VICTORY_D3D12_DEBUG=1 VICTORY_REQUIRE_HW_GPU=1 cargo test -p victory-shader --lib dxil_opt_hw_gpu_bit_exact_parity_and_validation`: **passed** on hardware GPU (`opt=0` vs `old_bits` vs `ALL` bit-exact). - Release `bench_dxil_opt_hw_gpu` (during parallel build load; uncontested benchmark follow-up planned): loop body `-85.7%` (`42 -> 6` insts), GPU median `109.57 us -> 95.23 us` (`1.15x`), LDS+barrier loop `164.86 us -> 111.62 us` (`1.48x`), real GFX10 loop `99.33 us -> 83.97 us` (`1.18x`).
Extend bitcode::opt with four exact, bit-preserving DXIL optimization passes:
- Extended FOLD & canonical Cmp/FACTS: integer algebraic/bitwise/shift identities
  and constant reassociation, power-of-two strength reduction, compare negation
  (guarding against AMD fcmp one), boolean select/zext/compare-of-select folding,
  and canonicalized Key::Cmp/FACTS lookups preserving IEEE-754 NaN semantics.
- Pure LICM (bit 64, in MODULE/ALL): natural loop detection via dominator tree,
  innermost-first fixed-point hoisting to existing or lazily split dominating
  preheaders, strict unconditional single-pred Term::Br guaranteed-execution
  prefix with WriteKind::All (dx.op.discard) tracking, pure value-only math
  allowlist for speculative calls, and trace_ptr-validated constant-global loads.
- Pointer-root & non-aliasing memory forwarding/DSE (enhanced LOADS, bit 16):
  canonical signed/in-bounds scalar-leaf trace_ptr GEP paths and escape analysis
  for constant tables, thread-private space-0 globals, shared space-3 LDS, and
  DXIL resource memory; store-to-load forwarding, non-aliasing preservation
  across unrelated stores/barriers, and intra-block overwritten DSE.
- Adjacent redundant dx.op.barrier(mode) elimination (bit 128, in MODULE/ALL):
  drops redundant barriers covered by an earlier barrier's mode bits in the same
  block with no intervening memory or lane operations.
- Add test-only thread-local shader_opt override (with_shader_opt) in emit/mod.rs
  while preserving translation_fingerprint, plus unit, soundness-regression, and
  DXIL validation / hardware GPU parity tests.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 05:53:19 +00:00
Author
Owner

@⁠PastiiJay on GitHub · 2026-11-25 21:07 UTC · original

Thanks a lot @⁠Vladimir-Human! We test one change at a time on the RX 9070 XT (same save, same 7-minute run, fps and picture compared with our reference build), so this one goes into that queue on its own. Results will be posted here, then we merge or report back what we saw.

**@⁠PastiiJay** on GitHub · 2026-11-25 21:07 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7174654317) Thanks a lot @⁠Vladimir-Human! We test one change at a time on the RX 9070 XT (same save, same 7-minute run, fps and picture compared with our reference build), so this one goes into that queue on its own. Results will be posted here, then we merge or report back what we saw.
Author
Owner

@⁠HandshakeHackin on GitHub · 2026-11-25 21:09 UTC · original

On ba88ab0, the optimized and unoptimized shaders gave byte-identical output on Microsoft’s D3D12 software adapter (WARP) for the loop, shared-memory/barrier and translated GFX10 fixtures. The translated loop also matched the expected value for every output lane. I required WARP initialization and made a missing Windows SDK DXIL validator fail the test, so neither check could silently skip. Windows parity test and log

I also tested this revision with the eight queued beta fixes and the maintainer’s WARP test correction. Both strict workspace Clippy checks passed, the asset check passed for 190 files, and the Windows suite finished with 596 passed, 0 failed and 13 ignored. The RX 9070 XT run will give the in-game picture and frame-rate comparison. Integration run

**@⁠HandshakeHackin** on GitHub · 2026-11-25 21:09 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7174677602) On `ba88ab0`, the optimized and unoptimized shaders gave byte-identical output on Microsoft’s D3D12 software adapter (WARP) for the loop, shared-memory/barrier and translated GFX10 fixtures. The translated loop also matched the expected value for every output lane. I required WARP initialization and made a missing Windows SDK DXIL validator fail the test, so neither check could silently skip. [Windows parity test and log](https://github.com/HandshakeHackin/klbf-lab/actions/runs/45701094581/job/139511060222) I also tested this revision with the eight queued beta fixes and the maintainer’s WARP test correction. Both strict workspace Clippy checks passed, the asset check passed for 190 files, and the Windows suite finished with 596 passed, 0 failed and 13 ignored. The RX 9070 XT run will give the in-game picture and frame-rate comparison. [Integration run](https://github.com/HandshakeHackin/klbf-lab/actions/runs/45700719066/job/139509788742)
Author
Owner

@⁠PastiiJay on GitHub · 2026-11-25 21:10 UTC · original

Thank you @⁠HandshakeHackin, byte-identical output on WARP for all three fixtures, with WARP and the DXIL validator made mandatory so nothing can skip, is exactly the safety net a shader optimizer needs. And 596 passed / 0 failed with the eight queued beta fixes on top is great. The RX 9070 XT picture and frame-rate comparison is next on our side.

**@⁠PastiiJay** on GitHub · 2026-11-25 21:10 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7174715461) Thank you @⁠HandshakeHackin, byte-identical output on WARP for all three fixtures, with WARP and the DXIL validator made mandatory so nothing can skip, is exactly the safety net a shader optimizer needs. And 596 passed / 0 failed with the eight queued beta fixes on top is great. The RX 9070 XT picture and frame-rate comparison is next on our side.
Author
Owner

@⁠Proudnoob4 on GitHub · 2026-11-26 07:11 UTC · original

Live-tested this PR on an RTX 4080 16 GB / i5-13600K / Windows 10 (GTA 6 --console series-s, render_scale=0.6666667, RT off, release, ported onto VIctory-NVIDIA with LICM=128, BARRIERS=256, DEFAULT=447 preserving WIDE=64):

Results

  • Unit & hardware tests: 22/22 bitcode::opt tests pass on RTX 4080, including dxil_opt_hw_gpu_bit_exact_parity_and_validation and every_pass_leaves_what_random_programs_store.
  • Real in-world GTA 6 GPU speedup (10-min runs, same prison cell scene, ~4,500 draws/frame, warm cache, making==0):
    • Before (VICTORY_SHADER_OPT=63): median 25.40 fps (39.3 ms/frame), p90 27.0 fps, max 27.2 fps (n=40 5s intervals).
    • With #41 (+ LICM + BARRIERS + canonical ptr-path LOADS/DSE + FOLD/FACTS): median 27.20 fps (36.7 ms/frame), p90 27.8 fps, max 28.6 fps (35.0 ms) across n=96 settled 5s intervals (8 minutes continuous, 0 stutters >55 ms).
    • Net gain: +1.80 fps (-2.6 ms/frame) with native-looking visuals and zero artifacts!
    • GPU telemetry (steady n=50): P0, 2,805 MHz, 99.8 W, 99% GPU util, 7% VRAM util, max 12,809 MiB VRAM.

Two Practical Notes

  1. Cold-cache compile cost: On the initial uncached run, the ~300 heaviest compute shaders compiled noticeably slower (~2.5 s/pipeline). Running background compiler workers at VICTORY_PIPELINE_WORKERS=16 with VICTORY_PIPELINE_LOWEST=0 starved the submitting thread (that thread worked jumped 24 ms → 41 ms). Setting VICTORY_PIPELINE_WORKERS=6 + VICTORY_PIPELINE_LOWEST=1 completely avoided starvation once the cache populated.
  2. Follow-up opportunity for BARRIERS on Wave32 (NVIDIA): In lower.rs (split_lds), a dx.op.barrier is emitted before every ds_read and ds_write in all-lane blocks — so consecutive ds_reads have loads standing between the barriers, preventing #41's adjacent BARRIERS pass from dropping them. Coalescing Read-after-Read (or tracking read-only phase between barriers in lower.rs / opt.rs) looks like another big win on NVIDIA!
**@⁠Proudnoob4** on GitHub · 2026-11-26 07:11 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7185190923) Live-tested this PR on an **RTX 4080 16 GB / i5-13600K / Windows 10** (GTA 6 `--console series-s`, `render_scale=0.6666667`, RT off, `release`, ported onto `VIctory-NVIDIA` with `LICM=128`, `BARRIERS=256`, `DEFAULT=447` preserving `WIDE=64`): ### Results - **Unit & hardware tests:** 22/22 `bitcode::opt` tests pass on RTX 4080, including `dxil_opt_hw_gpu_bit_exact_parity_and_validation` and `every_pass_leaves_what_random_programs_store`. - **Real in-world GTA 6 GPU speedup (10-min runs, same prison cell scene, ~4,500 draws/frame, warm cache, `making==0`):** - **Before (`VICTORY_SHADER_OPT=63`):** median **25.40 fps** (`39.3 ms/frame`), p90 `27.0 fps`, max `27.2 fps` (`n=40` 5s intervals). - **With `#41` (`+ LICM + BARRIERS + canonical ptr-path LOADS/DSE + FOLD/FACTS`):** median **27.20 fps** (`36.7 ms/frame`), p90 `27.8 fps`, max **`28.6 fps` (`35.0 ms`)** across `n=96` settled 5s intervals (8 minutes continuous, **0 stutters >55 ms**). - **Net gain: `+1.80 fps` (`-2.6 ms/frame`)** with native-looking visuals and zero artifacts! - GPU telemetry (steady `n=50`): `P0`, 2,805 MHz, `99.8 W`, `99%` GPU util, `7%` VRAM util, max `12,809 MiB` VRAM. ### Two Practical Notes 1. **Cold-cache compile cost:** On the initial uncached run, the ~300 heaviest compute shaders compiled noticeably slower (~2.5 s/pipeline). Running background compiler workers at `VICTORY_PIPELINE_WORKERS=16` with `VICTORY_PIPELINE_LOWEST=0` starved the submitting thread (`that thread worked` jumped 24 ms → 41 ms). Setting `VICTORY_PIPELINE_WORKERS=6` + `VICTORY_PIPELINE_LOWEST=1` completely avoided starvation once the cache populated. 2. **Follow-up opportunity for `BARRIERS` on Wave32 (NVIDIA):** In `lower.rs` (`split_lds`), a `dx.op.barrier` is emitted before *every* `ds_read` and `ds_write` in all-lane blocks — so consecutive `ds_read`s have loads standing between the barriers, preventing `#41`'s adjacent `BARRIERS` pass from dropping them. Coalescing Read-after-Read (or tracking read-only phase between barriers in `lower.rs` / `opt.rs`) looks like another big win on NVIDIA!
Author
Owner

@⁠PastiiJay on GitHub · 2026-11-26 07:11 UTC · original

Thanks @⁠Proudnoob4, a 10-minute A/B in the same scene with frame-time percentiles is exactly what this PR needed. Noted: +1.8 fps median on the RTX 4080, the PIPELINE_WORKERS=6 / LOWEST=1 setting for cold caches, and the read-after-read barrier idea in split_lds as a follow-up.

**@⁠PastiiJay** on GitHub · 2026-11-26 07:11 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7185199627) Thanks @⁠Proudnoob4, a 10-minute A/B in the same scene with frame-time percentiles is exactly what this PR needed. Noted: +1.8 fps median on the RTX 4080, the `PIPELINE_WORKERS=6` / `LOWEST=1` setting for cold caches, and the read-after-read barrier idea in `split_lds` as a follow-up.
Author
Owner

@⁠HandshakeHackin on GitHub · 2026-11-26 08:35 UTC · original

I tried the read-after-read suggestion on top of ba88ab0. With the PR’s BARRIERS bit enabled, two adjacent, unguarded ds_read_b32 instructions in the same all-lane block share one group barrier. In the test shader (write, read, read, overwrite, read), the Wave32 DXIL went from five barriers to four. The barriers before and after the overwrite stayed in place. Inserting one instruction between the two reads kept all five barriers. The unmodified PR emitted five in both cases.

The Windows SDK validated the Wave32 binaries. For WARP execution, the harness omitted the wave-width declaration and checked that the entry-point instructions were identical to each validated version. Both fixtures matched all 192 expected output dwords with the pass off and on. Strict shader Clippy passed, and the Windows shader suite passed 236 tests with four ignored using the maintainer’s WARP runner correction. Physical Wave32 execution and frame timing are still open. Patch and runnable fixture · Windows comparison and readback

**@⁠HandshakeHackin** on GitHub · 2026-11-26 08:35 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7186777259) I tried the read-after-read suggestion on top of `ba88ab0`. With the PR’s `BARRIERS` bit enabled, two adjacent, unguarded `ds_read_b32` instructions in the same all-lane block share one group barrier. In the test shader (write, read, read, overwrite, read), the Wave32 DXIL went from five barriers to four. The barriers before and after the overwrite stayed in place. Inserting one instruction between the two reads kept all five barriers. The unmodified PR emitted five in both cases. The Windows SDK validated the Wave32 binaries. For WARP execution, the harness omitted the wave-width declaration and checked that the entry-point instructions were identical to each validated version. Both fixtures matched all 192 expected output dwords with the pass off and on. Strict shader Clippy passed, and the Windows shader suite passed 236 tests with four ignored using the maintainer’s WARP runner correction. Physical Wave32 execution and frame timing are still open. [Patch and runnable fixture](https://github.com/HandshakeHackin/klbf-lab/compare/ba88ab0607c7cc1b7fa83b3c6f3a4a9beb1093be...b08f25e206d063a1a61a1c84ea2745fd021dae34) · [Windows comparison and readback](https://github.com/HandshakeHackin/klbf-lab/actions/runs/45783469149/job/139784322856)
Drop intra-block middle dx.op.barrier(80, mode) calls between consecutive non-escaping LDS (addrspace 3) read phases when bounded on the left by a covering group+TGSM barrier and on the right by either a covering group+TGSM barrier or shader return, with no intervening stores, atomics, resource/wave calls, or branches.
Author
Owner

@⁠Vladimir-Human on GitHub · 2026-11-26 09:56 UTC · original

Thanks @⁠Proudnoob4 for the 10-minute RTX 4080 A/B run (+1.80 fps median / -2.6 ms/frame) and for spotting the Wave32 split_lds read-after-read barrier opportunity, @⁠HandshakeHackin for prototyping and validating the write -> read -> read -> overwrite -> read (5 -> 4 barriers) fixture, and @⁠PastiiJay!

Pushed 690b4b2 implementing bounded read-after-read LDS barrier coalescing directly in bitcode::opt under BARRIERS (128), keeping this PR confined to opt.rs and mod.rs:

  • Exact synchronization & WAR-hazard bounds (BarrierState / RarState): Drops an intra-block middle dx.op.barrier(80, mode) between consecutive non-escaping addrspace(3) (LDS) read phases only when bounded on both sides:
    1. Left bound: an intra-block covering group+TGSM barrier ((anchor_mode & 9) == 9 and (anchor_mode & mid_mode) == mid_mode), so every thread in the group has converged and fenced shared memory before the first read.
    2. Right bound: either a subsequent intra-block covering group+TGSM barrier (B_next, as split_lds emits before any ds_write / ds_atomic), or Term::Ret (for group/TGSM-only barrier modes followed only by non-atomic UAV/output sink stores). Requiring the right bound guarantees a read-to-write (WAR) barrier is never dropped before a branch into an un-barriered LDS store.
  • Intervening instructions:
    • Pure ALU / GEP address math, ReadNone intrinsics, and non-escaping space 0 / constant loads between ds_read* operations coalesce cleanly (N -> 1 barrier across N consecutive reads: BWBRBRBWBR -> BWBRRBWBR, and BWBRBR -> BWBRR before s_endpgm).
    • Any intervening Op::Store, LDS or UAV atomic (AtomicRmw, CmpXchg, atomicBinOp), resource load/store call (bufferLoad, rawBufferLoad, bufferStore), ReadOnly call, wave/quad/deriv op, fence-only barrier(8), or control-flow edge strictly resets tracking and preserves all barriers.
  • Verification on 690b4b2 (physical Wave32 RTX 4070 SUPER + D3D12 WARP + Windows SDK dxil.dll & dxc -dumpbin):
    • Added read_after_read_barrier_coalescing_and_soundness_negatives (IR unit suite) and hw_tests::split_lds_wave32_read_after_read_barrier_coalescing_and_parity (RDNA2 Wave32 split_lds positive + soundness-negative fixtures).
    • Verified BWBRBRBWBR -> BWBRRBWBR (5 -> 4) and BWBRBR -> BWBRR (3 -> 2), with all 192 output dwords matching analytically and bit-for-bit across opt=0, BARRIERS, and ALL on both physical Wave32 (RTX 4070 SUPER, VICTORY_REQUIRE_HW_GPU=1) and D3D12 WARP.
    • cargo test -p victory-shader --all-targets --locked: 237 passed; 0 failed; 4 ignored
    • cargo clippy -p victory-shader --all-targets --locked -- -D warnings: 0 warnings
    • cargo run --locked -p xtask -- policy --staged: asset policy: 2 files ok
**@⁠Vladimir-Human** on GitHub · 2026-11-26 09:56 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7188687331) Thanks @⁠Proudnoob4 for the 10-minute RTX 4080 A/B run (`+1.80 fps` median / `-2.6 ms/frame`) and for spotting the Wave32 `split_lds` read-after-read barrier opportunity, @⁠HandshakeHackin for prototyping and validating the `write -> read -> read -> overwrite -> read` (`5 -> 4` barriers) fixture, and @⁠PastiiJay! Pushed `690b4b2` implementing bounded read-after-read LDS barrier coalescing directly in `bitcode::opt` under `BARRIERS` (`128`), keeping this PR confined to `opt.rs` and `mod.rs`: - **Exact synchronization & WAR-hazard bounds (`BarrierState` / `RarState`):** Drops an intra-block middle `dx.op.barrier(80, mode)` between consecutive non-escaping `addrspace(3)` (LDS) read phases only when bounded on **both** sides: 1. **Left bound:** an intra-block covering group+TGSM barrier (`(anchor_mode & 9) == 9` and `(anchor_mode & mid_mode) == mid_mode`), so every thread in the group has converged and fenced shared memory before the first read. 2. **Right bound:** either a subsequent intra-block covering group+TGSM barrier (`B_next`, as `split_lds` emits before any `ds_write` / `ds_atomic`), or `Term::Ret` (for group/TGSM-only barrier modes followed only by non-atomic UAV/output sink stores). Requiring the right bound guarantees a read-to-write (WAR) barrier is never dropped before a branch into an un-barriered LDS store. - **Intervening instructions:** - Pure ALU / GEP address math, `ReadNone` intrinsics, and non-escaping `space 0` / constant loads between `ds_read*` operations coalesce cleanly (`N -> 1` barrier across `N` consecutive reads: `BWBRBRBWBR` -> `BWBRRBWBR`, and `BWBRBR` -> `BWBRR` before `s_endpgm`). - Any intervening `Op::Store`, LDS or UAV atomic (`AtomicRmw`, `CmpXchg`, `atomicBinOp`), resource load/store call (`bufferLoad`, `rawBufferLoad`, `bufferStore`), `ReadOnly` call, wave/quad/deriv op, fence-only `barrier(8)`, or control-flow edge strictly resets tracking and preserves all barriers. - **Verification on `690b4b2` (physical Wave32 RTX 4070 SUPER + D3D12 WARP + Windows SDK `dxil.dll` & `dxc -dumpbin`):** - Added `read_after_read_barrier_coalescing_and_soundness_negatives` (IR unit suite) and `hw_tests::split_lds_wave32_read_after_read_barrier_coalescing_and_parity` (RDNA2 Wave32 `split_lds` positive + soundness-negative fixtures). - Verified `BWBRBRBWBR -> BWBRRBWBR` (`5 -> 4`) and `BWBRBR -> BWBRR` (`3 -> 2`), with all 192 output dwords matching analytically and bit-for-bit across `opt=0`, `BARRIERS`, and `ALL` on both physical Wave32 (**RTX 4070 SUPER**, `VICTORY_REQUIRE_HW_GPU=1`) and **D3D12 WARP**. - `cargo test -p victory-shader --all-targets --locked`: **237 passed; 0 failed; 4 ignored** - `cargo clippy -p victory-shader --all-targets --locked -- -D warnings`: **0 warnings** - `cargo run --locked -p xtask -- policy --staged`: **asset policy: 2 files ok**
Author
Owner

@⁠PastiiJay on GitHub · 2026-11-26 10:42 UTC · original

Thanks, nice to see the read-after-read idea land so quickly. It's on our list for an in-game pass on AMD.

**@⁠PastiiJay** on GitHub · 2026-11-26 10:42 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7189715674) Thanks, nice to see the read-after-read idea land so quickly. It's on our list for an in-game pass on AMD.
Author
Owner

@⁠Kal0s-design on GitHub · 2026-11-26 15:47 UTC · original

Independent check of 690b4b2 on Windows (CPU only, no game files), focused on the memory passes and the new read-after-read barrier coalescing.

every_pass_leaves_what_random_programs_store is a good net for the scalar passes, but its generator never emits a load, a store or a barrier, and its interpreter panics on them. So LOADS, the load half of LICM and BARRIERS were only covered by the hand-written cases and the three WARP fixtures. I wrote a local harness (not pushed) to fill that in:

  • random structured programs in the same style as Gen (branches, short loops, joins), plus two private arrays and two LDS arrays, constant and masked dynamic indices, and dx.op.barrier at the top level only, so it stays uniform. Half the phases are straight-line, so several barriers land in one block, which is where the read-after-read rule works;
  • the LDS accesses are race-free by construction: in each phase every array is either written only at the thread's own slots (tid + 4k), touched only at own slots, or read anywhere;
  • an interpreter for a group of 4 threads that can stop after any instruction, run under 6 schedules (3 fixed orders, round robin, 2 random interleavings). A program whose result depends on the schedule is skipped; none were. The optimized program has to give the identical per-thread output stream and final LDS contents under every schedule, for 11 pass masks (DEAD, FOLD, REUSE, FACTS, LOADS, LICM, BARRIERS, the memory pairs, and ALL), and write() has to go through.

Result on 690b4b2: 30,000 programs, 5.94 million checks, no difference. ALL removed 24,899 barriers and 161,853 loads/stores across them, so the passes had real work.

To make sure the harness can fail, I planted three bugs one at a time and each was caught within the first few dozen seeds:

  • BarrierState::reset no longer clearing rar, so a middle barrier is dropped across an own-slot LDS store (caught under BARRIERS; a hand-built anchor / read / barrier / store / read / barrier case goes from 3 to 2 barriers and two threads then see different values);
  • a dynamic private store no longer invalidating the constant-index values of the same array (caught under LOADS);
  • can_hoist accepting any load (caught under LICM).

What this does not cover:

  • fence bits. The interpreter treats any barrier with the sync bit as full visibility, so a rule that keeps the sync but drops a TGSM or UAV fence bit would not show up here. The (prev & m) == m and (m & 9) == 9 checks read right to me, but this harness doesn't test them;
  • forwarding an LDS value across a barrier. In race-free code with no branching between the two loads every thread runs the same stores, and the dynamic own-slot store already clears the cache, so a missing clear at the barrier can't be observed this way;
  • barriers inside divergent control flow, float math, and anything past the bitcode (DXC validation, drivers). HandshakeHackin's WARP runs and the in-game A/B cover those.

AI-assisted: yes (Claude Code). The numbers are from runs on my machine.

**@⁠Kal0s-design** on GitHub · 2026-11-26 15:47 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7196759208) Independent check of 690b4b2 on Windows (CPU only, no game files), focused on the memory passes and the new read-after-read barrier coalescing. `every_pass_leaves_what_random_programs_store` is a good net for the scalar passes, but its generator never emits a load, a store or a barrier, and its interpreter panics on them. So `LOADS`, the load half of `LICM` and `BARRIERS` were only covered by the hand-written cases and the three WARP fixtures. I wrote a local harness (not pushed) to fill that in: - random structured programs in the same style as `Gen` (branches, short loops, joins), plus two private arrays and two LDS arrays, constant and masked dynamic indices, and `dx.op.barrier` at the top level only, so it stays uniform. Half the phases are straight-line, so several barriers land in one block, which is where the read-after-read rule works; - the LDS accesses are race-free by construction: in each phase every array is either written only at the thread's own slots (`tid + 4k`), touched only at own slots, or read anywhere; - an interpreter for a group of 4 threads that can stop after any instruction, run under 6 schedules (3 fixed orders, round robin, 2 random interleavings). A program whose result depends on the schedule is skipped; none were. The optimized program has to give the identical per-thread output stream and final LDS contents under every schedule, for 11 pass masks (`DEAD`, `FOLD`, `REUSE`, `FACTS`, `LOADS`, `LICM`, `BARRIERS`, the memory pairs, and `ALL`), and `write()` has to go through. Result on 690b4b2: 30,000 programs, 5.94 million checks, no difference. `ALL` removed 24,899 barriers and 161,853 loads/stores across them, so the passes had real work. To make sure the harness can fail, I planted three bugs one at a time and each was caught within the first few dozen seeds: - `BarrierState::reset` no longer clearing `rar`, so a middle barrier is dropped across an own-slot LDS store (caught under `BARRIERS`; a hand-built anchor / read / barrier / store / read / barrier case goes from 3 to 2 barriers and two threads then see different values); - a dynamic private store no longer invalidating the constant-index values of the same array (caught under `LOADS`); - `can_hoist` accepting any load (caught under `LICM`). What this does not cover: - fence bits. The interpreter treats any barrier with the sync bit as full visibility, so a rule that keeps the sync but drops a TGSM or UAV fence bit would not show up here. The `(prev & m) == m` and `(m & 9) == 9` checks read right to me, but this harness doesn't test them; - forwarding an LDS value across a barrier. In race-free code with no branching between the two loads every thread runs the same stores, and the dynamic own-slot store already clears the cache, so a missing clear at the barrier can't be observed this way; - barriers inside divergent control flow, float math, and anything past the bitcode (DXC validation, drivers). HandshakeHackin's WARP runs and the in-game A/B cover those. AI-assisted: yes (Claude Code). The numbers are from runs on my machine.
Author
Owner

@⁠PastiiJay on GitHub · 2026-11-26 15:56 UTC · original

Thanks @⁠Kal0s-design, a random-program harness that actually emits loads, stores and barriers is the coverage the existing net was missing. If you are willing to push it as a test-only PR on top of #41, it would keep guarding these passes after merge.

**@⁠PastiiJay** on GitHub · 2026-11-26 15:56 UTC · [original](https://github.com/PastiiJay/klbf-lab/pull/41#issuecomment-7196968234) Thanks @⁠Kal0s-design, a random-program harness that actually emits loads, stores and barriers is the coverage the existing net was missing. If you are willing to push it as a test-only PR on top of #41, it would keep guarding these passes after merge.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/41/head:github-bot/gh-41'
git switch 'github-bot/gh-41'

Merge

Merge the changes and update on Forgejo.
git switch 'beta'
git merge --no-ff 'github-bot/gh-41'
git switch 'github-bot/gh-41'
git rebase 'beta'
git switch 'beta'
git merge --ff-only 'github-bot/gh-41'
git switch 'github-bot/gh-41'
git rebase 'beta'
git switch 'beta'
git merge --no-ff 'github-bot/gh-41'
git switch 'beta'
git merge --squash 'github-bot/gh-41'
git switch 'beta'
git merge --ff-only 'github-bot/gh-41'
git switch 'beta'
git merge 'github-bot/gh-41'
git push origin 'beta'
This discussion has been locked. Commenting is limited to contributors.
No description provided.