perf(shader): eliminate duplicate idoms, hash lookups, and BDD scratch allocations #402

Open
github-bot wants to merge 5 commits from github-bot/gh-402 into main AGit
Owner

@⁠tommiehansen on GitHub · 2026-12-04 00:32 UTC · original
tommiehansen:perf/structure-flat-defs-bdd-scratch → main · +686 −251 · 1 files · 5 commits · open

What this does

eliminate duplicate idoms, hash lookups, and BDD scratch allocations.

Checks

  • N/A: intended behavior-preserving compiler optimization, not new runtime behavior; keep parity checks explicit.
  • N/A: no new or changed switch.
  • No unrelated cleanup: Single structure/BDD optimization file.
  • A test must exercise the change: bdd_work_reuse_and_given_if_not_implied_match_reference and wave/WQM regression tests; 299 previously passing. Pre-change comparison pending.
  • Queue checked on 2026-12-04: #468 adds a structure module; #399/#404 optimize adjacent stages. Check rebase and parity.
  • Run cargo xtask policy on the final revision; no new game assets or build output intended.

Verified

Existing measurements and commands are retained below at their original revisions. No fresh compile, policy or hardware test is claimed by this metadata review.

Cost

CPU-only results below; no GPU or gameplay result.


Detailed implementation and historical validation

Summary

Eliminates redundant dominator recomputation, hash lookups, and per-call BDD scratch allocations in victory_shader::structure (crates/victory-shader/src/structure.rs) while producing byte-for-byte identical structured output, raw BDD node tables, and DXIL (equivalence = identical across all shaders/* and descriptors/* workloads).

Changes (crates/victory-shader/src/structure.rs)

  • Single ir::idoms pass in Lanes::new(): Reuses the immediate dominator tree computed by crate::ir::idoms for both the reducibility check (dominates / lca_idom) and compute_active, eliminating the duplicate compute_idoms fixed-point pass.
  • Direct-indexed DefLoc table (Lanes::locs): Replaces defs: Map<Value, (usize, usize)> and phis: Map<Value, (usize, usize)> hash maps with a single dense Value-indexed Vec<DefLoc> (Inst(u32, u32) / Phi(u32, u32)).
  • Fx-hashed sets & dense block flags: Replaces internal SipHash HashSets (within, unresolved, derived_phis, phi_join_ids, scc_every, check_joins::seen_derived, finish::split) with Set<T> (BuildHasherDefault<Fx>), and stores dense wide_flags/helped_flags: Vec<bool> on Lanes so edge() and compute_active() avoid repeated hash probes.
  • Reusable BDD scratch buffers (BddWork): Carries reusable memo_pair, memo_node, assign, generation-stamped seen_nodes/seen_atoms, and vars/stack across paths (forget_with), check_joins (implies_with/disjoint_with), join, helped_now (alone_with), step, and finish (given_if_not_implied/given_with), eliminating per-call HashMap allocations and avoiding duplicate implies evaluation per guard transition in finish().
  • Consecutive EXEC cache (masks_in_order) preserving exact semantics: Caches last_exec: Option<(Key, Bool)> within each block and deduplicates consecutive identical runs entries while keeping inst.read(Reg::S(EXEC)).is_some() as the outer gate (None => Bool::TRUE for wave64 partial exec_lo reads such as s_wqm_b32). Removes args.clone() in check_joins() and runs.clone() in helped_now().
  • Fresh BDD state after WQM discovery (structure_wide): Retains fresh L = Lanes::new(program) reconstruction after WQM discovery completes (l.add_helped(&helped); l.whole = !helped.is_empty()), guaranteeing identical raw BDD tables and Bool IDs on kept-s_wqm shaders with empty or nonempty helped sets.
  • Unit & regression tests: Added bdd_work_reuse_and_given_if_not_implied_match_reference, wave64_partial_exec_read_after_non_true_mask_tracks_active, wave32_and_full_wave64_exec_reads_track_masks_and_guards, kept_wqm_with_empty_helped_uses_fresh_bdd_state, and kept_wqm_with_nonempty_helped_marks_whole_and_helped.

Benchmarks (CPU-Only Synthetic Suite, Apple M5 macOS)

Paired A/B/B/A (1152b9c vs b988f16, --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors, 8 runs/side) via tools/benchmark-suite:

Benchmark 1152b9c (ms) b988f16 (ms) Change p-value 95% CI Equivalence Classification
descriptors/shader_resource_tracking 1.137 1.079 −5.19% 0.0010 [−6.42%, −3.95%] identical Improvement
shaders/structurise_guard_runs 9.496 9.223 −3.06% 0.0171 [−5.04%, −1.05%] identical Improvement
descriptors/copy_span_index 0.022 0.022 −1.19% 0.0125 [−1.89%, −0.49%] identical No significant difference
shaders/guest_load_clusters 6.966 6.885 −1.19% 0.0110 [−1.85%, −0.52%] identical No significant difference
shaders/guest_load_clusters_extended 5.175 5.096 −1.48% 0.0013 [−1.88%, −1.08%] identical No significant difference
shaders/uniform_smem_and_wide_loads 4.155 4.110 −1.19% 0.0001 [−1.33%, −1.06%] identical No significant difference
shaders/node_probe_emit 1.086 1.084 −0.18% 0.5736 [−1.07%, +0.72%] identical No significant difference
shaders/uniform_guest_loads 1.445 1.430 −1.13% 0.0319 [−2.06%, −0.19%] identical Inconclusive
shaders/translate_corpus 2.640 2.564 −0.73% 0.7060 [−6.17%, +5.02%] identical Inconclusive
descriptors/d3d12x_heap_and_copy, shaders/gpu_execute - - - - - n/a Unsupported in --cpu-only

Note: shaders/structurise_guard_runs measures spill::build (ir::build) and structure::structure together, so ir::build dominates wall time on flat guard sequences.

Verification & Reproducibility

  • Unit & regression tests (victory-shader):
    cargo test --offline -p victory-shader
    
    299 passed; 0 failed; 2 ignored (on macOS; Windows D3D12 emit tests are Windows-only).
  • Differential verification vs 1152b9c: Canonical dump comparison of raw bools.nodes, bools.atoms, Bool IDs (exits, guards, masks, highs, paired_masks, phi_masks, scc_some), active, wide, helped, and wave_any across wave64 partial exec_lo reads, wave32/wave64 full EXEC reads, consecutive identical EXEC reads, and kept s_wqm with empty and nonempty helped sets matched byte-for-byte.
  • Benchmark Suite command:
    ./tools/benchmark-suite/run compare 1152b9c b988f16 --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors
    

Known Limitations

  • CPU-only benchmarks on Apple M5 macOS measure shader translation/structuring and descriptor tracking; native Windows D3D12 shader translation and GPU execution are not exercised by --cpu-only runs.
  • Structured output and DXIL are unchanged relative to 1152b9c, so steady-state GPU runtime of cached shaders is unchanged.

Follow-up review fixes (2026-12-04)

Head: 4b33fe65beecbc75f378b71f4888a7d994a788f2.

Include live-in SSA values in the definition table's domain and document the block-local lifetime of the last EXEC memo relative to BDD garbage collection. The requested mechanical/memo split and differential real-shader evidence remain separate review work.

Pinned CI audit started for this revision. Final-head compilation, tests and policy results are pending; historical measurements have not been relabelled.

Queue refresh — 2026-12-05

Merged upstream main b581f7e0a8086158953a64068ba29305d5450d68 into the existing branch without rewriting history. New head: 182e47869d0430cac3f3fb879693255eddbfc35b. Review split staged separately at a6ca7d39ce62871b8acaf7623b0eba989d9435c1 (mechanical-only). The original PR remains intact until the isolated candidate is validated.

Fresh pinned CI audit is the verification record for this revision; previous tests apply to the previously stated heads. #528 remains a separate policy prerequisite, not a runtime dependency. No new gameplay or GPU timing claim.

Review follow-up

The mechanical split is now open as #545. It passed 298 shader tests; two were ignored. The audit’s inherited launcher documentation failure is tracked in #528.

Post-review follow-up — 2026-12-05

Head: e4391d3a3c2238e6c074910755b58f537f2eec22.

The sparse SSA fallback from the mechanical split #545 is now also applied here: unreachable blocks and the NONE sentinel use separate instruction/phi maps, with two targeted regressions. Ordinary SSA retains dense lookup. Historical timings and DXIL comparisons do not describe this new head.

Fresh pinned debug/release CI started. The isolated review alternatives remain #545–547; do not merge overlapping original and split changes blindly.

**@⁠tommiehansen** on GitHub · 2026-12-04 00:32 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/402) `tommiehansen:perf/structure-flat-defs-bdd-scratch` → `main` · +686 −251 · 1 files · 5 commits · open ## What this does eliminate duplicate idoms, hash lookups, and BDD scratch allocations. ## Checks - N/A: intended behavior-preserving compiler optimization, not new runtime behavior; keep parity checks explicit. - N/A: no new or changed switch. - [x] No unrelated cleanup: Single structure/BDD optimization file. - [ ] A test must exercise the change: `bdd_work_reuse_and_given_if_not_implied_match_reference` and wave/WQM regression tests; 299 previously passing. Pre-change comparison pending. - [x] Queue checked on 2026-12-04: #468 adds a structure module; #399/#404 optimize adjacent stages. Check rebase and parity. - [ ] Run `cargo xtask policy` on the final revision; no new game assets or build output intended. ## Verified Existing measurements and commands are retained below at their original revisions. No fresh compile, policy or hardware test is claimed by this metadata review. ## Cost CPU-only results below; no GPU or gameplay result. --- ## Detailed implementation and historical validation ## Summary Eliminates redundant dominator recomputation, hash lookups, and per-call BDD scratch allocations in `victory_shader::structure` (`crates/victory-shader/src/structure.rs`) while producing **byte-for-byte identical structured output, raw BDD node tables, and DXIL** (`equivalence = identical` across all `shaders/*` and `descriptors/*` workloads). ### Changes (`crates/victory-shader/src/structure.rs`) - **Single `ir::idoms` pass in `Lanes::new()`:** Reuses the immediate dominator tree computed by `crate::ir::idoms` for both the reducibility check (`dominates` / `lca_idom`) and `compute_active`, eliminating the duplicate `compute_idoms` fixed-point pass. - **Direct-indexed `DefLoc` table (`Lanes::locs`):** Replaces `defs: Map<Value, (usize, usize)>` and `phis: Map<Value, (usize, usize)>` hash maps with a single dense `Value`-indexed `Vec<DefLoc>` (`Inst(u32, u32)` / `Phi(u32, u32)`). - **`Fx`-hashed sets & dense block flags:** Replaces internal SipHash `HashSet`s (`within`, `unresolved`, `derived_phis`, `phi_join_ids`, `scc_every`, `check_joins::seen_derived`, `finish::split`) with `Set<T>` (`BuildHasherDefault<Fx>`), and stores dense `wide_flags`/`helped_flags: Vec<bool>` on `Lanes` so `edge()` and `compute_active()` avoid repeated hash probes. - **Reusable BDD scratch buffers (`BddWork`):** Carries reusable `memo_pair`, `memo_node`, `assign`, generation-stamped `seen_nodes`/`seen_atoms`, and `vars`/`stack` across `paths` (`forget_with`), `check_joins` (`implies_with`/`disjoint_with`), `join`, `helped_now` (`alone_with`), `step`, and `finish` (`given_if_not_implied`/`given_with`), eliminating per-call `HashMap` allocations and avoiding duplicate `implies` evaluation per guard transition in `finish()`. - **Consecutive `EXEC` cache (`masks_in_order`) preserving exact semantics:** Caches `last_exec: Option<(Key, Bool)>` within each block and deduplicates consecutive identical `runs` entries while keeping `inst.read(Reg::S(EXEC)).is_some()` as the outer gate (`None => Bool::TRUE` for wave64 partial `exec_lo` reads such as `s_wqm_b32`). Removes `args.clone()` in `check_joins()` and `runs.clone()` in `helped_now()`. - **Fresh BDD state after WQM discovery (`structure_wide`):** Retains fresh `L = Lanes::new(program)` reconstruction after WQM discovery completes (`l.add_helped(&helped); l.whole = !helped.is_empty()`), guaranteeing identical raw BDD tables and `Bool` IDs on kept-`s_wqm` shaders with empty or nonempty `helped` sets. - **Unit & regression tests:** Added `bdd_work_reuse_and_given_if_not_implied_match_reference`, `wave64_partial_exec_read_after_non_true_mask_tracks_active`, `wave32_and_full_wave64_exec_reads_track_masks_and_guards`, `kept_wqm_with_empty_helped_uses_fresh_bdd_state`, and `kept_wqm_with_nonempty_helped_marks_whole_and_helped`. ## Benchmarks (CPU-Only Synthetic Suite, Apple M5 macOS) Paired A/B/B/A (`1152b9c` vs `b988f16`, `--offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors`, 8 runs/side) via `tools/benchmark-suite`: | Benchmark | `1152b9c` (ms) | `b988f16` (ms) | Change | p-value | 95% CI | Equivalence | Classification | |---|---:|---:|---:|---:|---|---|---| | `descriptors/shader_resource_tracking` | 1.137 | 1.079 | **−5.19%** | 0.0010 | [−6.42%, −3.95%] | `identical` | Improvement | | `shaders/structurise_guard_runs` | 9.496 | 9.223 | **−3.06%** | 0.0171 | [−5.04%, −1.05%] | `identical` | Improvement | | `descriptors/copy_span_index` | 0.022 | 0.022 | −1.19% | 0.0125 | [−1.89%, −0.49%] | `identical` | No significant difference | | `shaders/guest_load_clusters` | 6.966 | 6.885 | −1.19% | 0.0110 | [−1.85%, −0.52%] | `identical` | No significant difference | | `shaders/guest_load_clusters_extended` | 5.175 | 5.096 | −1.48% | 0.0013 | [−1.88%, −1.08%] | `identical` | No significant difference | | `shaders/uniform_smem_and_wide_loads` | 4.155 | 4.110 | −1.19% | 0.0001 | [−1.33%, −1.06%] | `identical` | No significant difference | | `shaders/node_probe_emit` | 1.086 | 1.084 | −0.18% | 0.5736 | [−1.07%, +0.72%] | `identical` | No significant difference | | `shaders/uniform_guest_loads` | 1.445 | 1.430 | −1.13% | 0.0319 | [−2.06%, −0.19%] | `identical` | Inconclusive | | `shaders/translate_corpus` | 2.640 | 2.564 | −0.73% | 0.7060 | [−6.17%, +5.02%] | `identical` | Inconclusive | | `descriptors/d3d12x_heap_and_copy`, `shaders/gpu_execute` | - | - | - | - | - | n/a | Unsupported in `--cpu-only` | *Note:* `shaders/structurise_guard_runs` measures `spill::build` (`ir::build`) and `structure::structure` together, so `ir::build` dominates wall time on flat guard sequences. ## Verification & Reproducibility - **Unit & regression tests (`victory-shader`):** ```sh cargo test --offline -p victory-shader ``` `299 passed; 0 failed; 2 ignored` (on macOS; Windows D3D12 emit tests are Windows-only). - **Differential verification vs `1152b9c`:** Canonical dump comparison of raw `bools.nodes`, `bools.atoms`, `Bool` IDs (`exits`, `guards`, `masks`, `highs`, `paired_masks`, `phi_masks`, `scc_some`), `active`, `wide`, `helped`, and `wave_any` across wave64 partial `exec_lo` reads, wave32/wave64 full `EXEC` reads, consecutive identical `EXEC` reads, and kept `s_wqm` with empty and nonempty `helped` sets matched **byte-for-byte**. - **Benchmark Suite command:** ```sh ./tools/benchmark-suite/run compare 1152b9c b988f16 --offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors ``` ## Known Limitations - CPU-only benchmarks on Apple M5 macOS measure shader translation/structuring and descriptor tracking; native Windows D3D12 shader translation and GPU execution are not exercised by `--cpu-only` runs. - Structured output and DXIL are unchanged relative to `1152b9c`, so steady-state GPU runtime of cached shaders is unchanged. ### Follow-up review fixes (2026-12-04) Head: `4b33fe65beecbc75f378b71f4888a7d994a788f2`. Include live-in SSA values in the definition table's domain and document the block-local lifetime of the last EXEC memo relative to BDD garbage collection. The requested mechanical/memo split and differential real-shader evidence remain separate review work. Pinned [CI audit](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47438443784) started for this revision. Final-head compilation, tests and policy results are pending; historical measurements have not been relabelled. ### Queue refresh — 2026-12-05 Merged upstream main `b581f7e0a8086158953a64068ba29305d5450d68` into the existing branch without rewriting history. New head: `182e47869d0430cac3f3fb879693255eddbfc35b`. Review split staged separately at `a6ca7d39ce62871b8acaf7623b0eba989d9435c1` (mechanical-only). The original PR remains intact until the isolated candidate is validated. [Fresh pinned CI audit](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47466412636) is the verification record for this revision; previous tests apply to the previously stated heads. #528 remains a separate policy prerequisite, not a runtime dependency. No new gameplay or GPU timing claim. ### Review follow-up The mechanical split is now open as #545. It passed 298 shader tests; two were ignored. The audit’s inherited launcher documentation failure is tracked in #528. ### Post-review follow-up — 2026-12-05 Head: `e4391d3a3c2238e6c074910755b58f537f2eec22`. The sparse SSA fallback from the mechanical split #545 is now also applied here: unreachable blocks and the NONE sentinel use separate instruction/phi maps, with two targeted regressions. Ordinary SSA retains dense lookup. Historical timings and DXIL comparisons do not describe this new head. [Fresh pinned debug/release CI](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47499397549) started. The isolated review alternatives remain #545–547; do not merge overlapping original and split changes blindly.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-04 00:34:28 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 01:53 UTC · original

Tested 80a1d6c natively on Windows 11 (MSVC), against 1152b9c.

The speedup looks real, but the output is not identical to main in two cases. One of them changes behaviour.

How I checked: locally I put main's structure.rs next to the PR's as a test-only module and hooked structure_wide so every call runs both and compares the results. One comparison uses raw Bool ids and the full node table. The other expands every output Bool into its function over atoms, so node numbering doesn't matter. I ran that hook over the whole --lib suite plus about 18.5k random programs (wave32 and wave64; random SOP/VOPC/saveexec/wrexec/s_wqm mixes; forward and backward branches; random wide sets), 23,855 structure calls in total. I also hashed the DXIL coming out of lowering on both sides. None of this is pushed.

  1. Behaviour change in masks_in_order (structure.rs ~1420). Main gates on inst.read(Reg::S(EXEC)).is_some() and then exec() gives Bool::TRUE when there is no full key. The PR gates on self.key(..) being Some. In wave64, an instruction that reads only exec_lo (e.g. s_wqm_b32 sN, exec_lo) gave now = Some(TRUE) on main. With the PR it keeps the previous value (or None). step uses now for the within check, so Structured::active can come out different. The random run found 27 calls where the semantic dump differs, all in wave64 and all in active (one mask missing). With main's gate put back (key lookup and cache kept inside it) I got 0 semantic differences over 4,841 calls. It's an odd pattern and the PR's result may even be the more sensible one, but either way it isn't a pure refactor. I'd restore the old gate here, or call the change out explicitly.

  2. Extra BDD nodes on the s_wqm path (structure.rs ~1018-1024). When a program has a kept s_wqm but ends up with no helped blocks, main threw away the discovery Lanes and redid everything from a fresh Bools. The PR finishes on the discovery Lanes, which helped_now() has already grown through and/alone_with. So Structured::bools has a few extra nodes (1 to 18 in my cases), and some Bool ids in exits/phi_masks shift. Semantically identical every time: in the random set, 4,061 calls differ only in raw ids. Every one I dumped (824 from a separate 4k run) had s_wqm in it and helped empty, with the new node table longer. Probably harmless. The one thing I can think of is that the extra nodes count toward the gc threshold and MAX_NODES. Still, "byte-for-byte identical structured output" doesn't hold for this path.

Everything else matched. ir::idoms agreed with the old compute_idoms on every program (I asserted it inside the old copy). On the suite's own programs (1,098 calls from 245 tests) the raw and semantic dumps were all identical. For DXIL I logged a hash of every lowered module on both sides: 830 modules from 165 tests, same multiset of hashes. None of those suite programs hit either of the two paths above, though, so the DXIL match doesn't cover them.

The rest of the diff reads fine to me. The generation-stamped seen buffers can't hand back stale state, because every query takes a fresh stamp and the buffers get zeroed on wrap. The memos are cleared at the start of every *_with call, as before. The Fx sets replace std sets whose order main couldn't have depended on. And given_if_not_implied matches (!implies).then(given) on every constant case I went through.

Tests, cargo test -p victory-shader --lib, D3D12 tests on one NVIDIA desktop card plus WARP:

  • PR: 420 passed, 1 failed, 4 ignored
  • main: 419 passed, 1 failed, 4 ignored (the PR adds one test)
  • The one failure is emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag on both sides (WARP rejects the compute pipeline). It already fails on main and has nothing to do with this PR.

Clippy (-p victory-shader --all-targets): no new warnings, same set as main (the existing E0603 in the guard_runs bench is there on both).

Timing, release build, same random corpus, both versions back to back per call: 802 ms vs 972 ms total (about 17% less), per-call median about 0.96. That's synthetic CFGs on a busy machine, so treat it as a rough number. It points the same way as your benchmarks.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 01:53 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/402#issuecomment-7398354215) Tested 80a1d6c natively on Windows 11 (MSVC), against 1152b9c. The speedup looks real, but the output is not identical to main in two cases. One of them changes behaviour. How I checked: locally I put main's `structure.rs` next to the PR's as a test-only module and hooked `structure_wide` so every call runs both and compares the results. One comparison uses raw `Bool` ids and the full node table. The other expands every output `Bool` into its function over atoms, so node numbering doesn't matter. I ran that hook over the whole `--lib` suite plus about 18.5k random programs (wave32 and wave64; random SOP/VOPC/saveexec/wrexec/s_wqm mixes; forward and backward branches; random `wide` sets), 23,855 `structure` calls in total. I also hashed the DXIL coming out of lowering on both sides. None of this is pushed. 1. Behaviour change in `masks_in_order` (structure.rs ~1420). Main gates on `inst.read(Reg::S(EXEC)).is_some()` and then `exec()` gives `Bool::TRUE` when there is no full key. The PR gates on `self.key(..)` being `Some`. In wave64, an instruction that reads only `exec_lo` (e.g. `s_wqm_b32 sN, exec_lo`) gave `now = Some(TRUE)` on main. With the PR it keeps the previous value (or `None`). `step` uses `now` for the `within` check, so `Structured::active` can come out different. The random run found 27 calls where the semantic dump differs, all in wave64 and all in `active` (one mask missing). With main's gate put back (key lookup and cache kept inside it) I got 0 semantic differences over 4,841 calls. It's an odd pattern and the PR's result may even be the more sensible one, but either way it isn't a pure refactor. I'd restore the old gate here, or call the change out explicitly. 2. Extra BDD nodes on the `s_wqm` path (structure.rs ~1018-1024). When a program has a kept `s_wqm` but ends up with no helped blocks, main threw away the discovery `Lanes` and redid everything from a fresh `Bools`. The PR finishes on the discovery `Lanes`, which `helped_now()` has already grown through `and`/`alone_with`. So `Structured::bools` has a few extra nodes (1 to 18 in my cases), and some `Bool` ids in `exits`/`phi_masks` shift. Semantically identical every time: in the random set, 4,061 calls differ only in raw ids. Every one I dumped (824 from a separate 4k run) had `s_wqm` in it and `helped` empty, with the new node table longer. Probably harmless. The one thing I can think of is that the extra nodes count toward the gc threshold and `MAX_NODES`. Still, "byte-for-byte identical structured output" doesn't hold for this path. Everything else matched. `ir::idoms` agreed with the old `compute_idoms` on every program (I asserted it inside the old copy). On the suite's own programs (1,098 calls from 245 tests) the raw and semantic dumps were all identical. For DXIL I logged a hash of every lowered module on both sides: 830 modules from 165 tests, same multiset of hashes. None of those suite programs hit either of the two paths above, though, so the DXIL match doesn't cover them. The rest of the diff reads fine to me. The generation-stamped `seen` buffers can't hand back stale state, because every query takes a fresh stamp and the buffers get zeroed on wrap. The memos are cleared at the start of every `*_with` call, as before. The Fx sets replace std sets whose order main couldn't have depended on. And `given_if_not_implied` matches `(!implies).then(given)` on every constant case I went through. Tests, `cargo test -p victory-shader --lib`, D3D12 tests on one NVIDIA desktop card plus WARP: - PR: 420 passed, 1 failed, 4 ignored - main: 419 passed, 1 failed, 4 ignored (the PR adds one test) - The one failure is `emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag` on both sides (WARP rejects the compute pipeline). It already fails on main and has nothing to do with this PR. Clippy (`-p victory-shader --all-targets`): no new warnings, same set as main (the existing E0603 in the `guard_runs` bench is there on both). Timing, release build, same random corpus, both versions back to back per call: 802 ms vs 972 ms total (about 17% less), per-call median about 0.96. That's synthetic CFGs on a busy machine, so treat it as a rough number. It points the same way as your benchmarks. AI-assisted: yes
Author
Owner

@⁠tommiehansen on GitHub · 2026-12-04 11:50 UTC · original

Thanks @⁠Kal0s-design for catching both divergences in the differential check! Pushed fix b988f16 addressing both findings and updated the PR description:

  1. Wave64 partial EXEC reads (masks_in_order): Restored inst.read(Reg::S(EXEC)).is_some() as the outer condition with self.key(..., EXEC) returning None => { last_exec = None; Bool::TRUE } inside, preserving main's handling of wave64 partial exec_lo reads (e.g., s_wqm_b32 sN, exec_lo) and keeping the last_exec cache for full EXEC reads.
  2. Fresh BDD state after WQM discovery (structure_wide): Replaced the reuse/direct-finish shortcut on the needs_wqm_check path with fresh l = Lanes::new(program)?; l.add_helped(&helped); l.whole = !helped.is_empty(); break; so kept s_wqm programs with either empty or nonempty helped produce identical raw BDD node tables and Bool IDs as 1152b9c.

Verification on b988f16

  • New regression tests in crates/victory-shader/src/structure.rs: wave64_partial_exec_read_after_non_true_mask_tracks_active, wave32_and_full_wave64_exec_reads_track_masks_and_guards, kept_wqm_with_empty_helped_uses_fresh_bdd_state, and kept_wqm_with_nonempty_helped_marks_whole_and_helped (full cargo test --offline -p victory-shader: 299 passed; 0 failed; 2 ignored on macOS).
  • Differential check vs 1152b9c: Compared canonicalized raw BDD nodes/atoms, Bool IDs, masks, active, guards, exits, phi_masks, wide, and helped against 1152b9c across those scenarios and consecutive identical EXEC reads — 0 differences (runs deduplication needed no revert).
  • Standard paired benchmark (1152b9c vs b988f16, Apple M5 CPU-only, 4 A/B/B/A blocks): descriptors/shader_resource_tracking −5.19% (p = 0.0010), shaders/structurise_guard_runs −3.06% (p = 0.0171), all 9 comparable workloads identical with zero regressions. (Updated PROGRESS.md on #322 will be synced once #404 finishes.)
**@⁠tommiehansen** on GitHub · 2026-12-04 11:50 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/402#issuecomment-7410622179) Thanks @⁠Kal0s-design for catching both divergences in the differential check! Pushed fix [`b988f16`](https://github.com/tommiehansen/VIctory-xmem/commit/b988f16) addressing both findings and updated the PR description: 1. **Wave64 partial `EXEC` reads (`masks_in_order`):** Restored `inst.read(Reg::S(EXEC)).is_some()` as the outer condition with `self.key(..., EXEC)` returning `None => { last_exec = None; Bool::TRUE }` inside, preserving `main`'s handling of wave64 partial `exec_lo` reads (e.g., `s_wqm_b32 sN, exec_lo`) and keeping the `last_exec` cache for full `EXEC` reads. 2. **Fresh BDD state after WQM discovery (`structure_wide`):** Replaced the reuse/direct-finish shortcut on the `needs_wqm_check` path with fresh `l = Lanes::new(program)?; l.add_helped(&helped); l.whole = !helped.is_empty(); break;` so kept `s_wqm` programs with either empty or nonempty `helped` produce identical raw BDD node tables and `Bool` IDs as `1152b9c`. ### Verification on `b988f16` - **New regression tests in `crates/victory-shader/src/structure.rs`:** `wave64_partial_exec_read_after_non_true_mask_tracks_active`, `wave32_and_full_wave64_exec_reads_track_masks_and_guards`, `kept_wqm_with_empty_helped_uses_fresh_bdd_state`, and `kept_wqm_with_nonempty_helped_marks_whole_and_helped` (full `cargo test --offline -p victory-shader`: `299 passed; 0 failed; 2 ignored` on macOS). - **Differential check vs `1152b9c`:** Compared canonicalized raw BDD `nodes`/`atoms`, `Bool` IDs, `masks`, `active`, `guards`, `exits`, `phi_masks`, `wide`, and `helped` against `1152b9c` across those scenarios and consecutive identical `EXEC` reads — `0` differences (`runs` deduplication needed no revert). - **Standard paired benchmark (`1152b9c` vs `b988f16`, Apple M5 CPU-only, 4 A/B/B/A blocks):** `descriptors/shader_resource_tracking` **−5.19%** (`p = 0.0010`), `shaders/structurise_guard_runs` **−3.06%** (`p = 0.0171`), all 9 comparable workloads `identical` with zero regressions. (Updated `PROGRESS.md` on `#322` will be synced once `#404` finishes.)
Author
Owner

@⁠Luxuride on GitHub · 2026-12-04 12:20 UTC · original

Split this. The mechanical half is worth taking today; the memo reuse is not worth 3% and a wrong guard.

Why the split:

  • Your own numbers: −3.06% on shaders/structurise_guard_runs, −5.19% on descriptors/shader_resource_tracking, six of nine benchmarks "inconclusive" — against 854 changed lines in the pass that decides lane masks and guards. A wrong Bool out of a reused BDD memo does not crash; it emits a wrong guard.
  • Lanes::new deriving reducibility from crate::ir::idoms instead of its own fixed point, locs: Vec<DefLoc>, the Fx sets and the Vec<bool> flags are mechanical, checkable, and carry most of the line count for none of the risk. That half is a yes.
  • BddWork memo reuse and the last_exec cache belong in a separate PR with a differential harness that compares bools.nodes on captured shaders.

Two things to fix on the way through:

  1. last_exec (crates/victory-shader/src/structure.rs:1414-1448) is sound only because mask(k) is memoised and the BDD store is append-only within a block, gc'd only at block end after the cache is dropped. Nothing in the type says that — one comment, or a last_exec = None next to any future in-loop gc, is what keeps it true.
  2. locs is sized from phi/inst writes only (structure.rs:1189-1201) with every read through locs.get() (:1272-1296). Correct, but a read-but-never-written value degrades to DefLoc::None silently instead of being diagnosable. debug_assert the size against p.inputs too.

Your own history here is the argument for caution: three rounds of self-inflicted regressions, head commit "restore wave64 partial EXEC read and fresh WQM discovery BDD state".

42 behind, structure.rs untouched on main since the merge base.

**@⁠Luxuride** on GitHub · 2026-12-04 12:20 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/402#issuecomment-7411296521) Split this. The mechanical half is worth taking today; the memo reuse is not worth 3% and a wrong guard. Why the split: - Your own numbers: −3.06% on `shaders/structurise_guard_runs`, −5.19% on `descriptors/shader_resource_tracking`, six of nine benchmarks "inconclusive" — against 854 changed lines in the pass that decides lane masks and guards. A wrong `Bool` out of a reused BDD memo does not crash; it emits a wrong guard. - `Lanes::new` deriving reducibility from `crate::ir::idoms` instead of its own fixed point, `locs: Vec<DefLoc>`, the `Fx` sets and the `Vec<bool>` flags are mechanical, checkable, and carry most of the line count for none of the risk. That half is a yes. - `BddWork` memo reuse and the `last_exec` cache belong in a separate PR with a differential harness that compares `bools.nodes` on captured shaders. Two things to fix on the way through: 1. `last_exec` (`crates/victory-shader/src/structure.rs:1414-1448`) is sound only because `mask(k)` is memoised and the BDD store is append-only within a block, gc'd only at block end after the cache is dropped. Nothing in the type says that — one comment, or a `last_exec = None` next to any future in-loop gc, is what keeps it true. 2. `locs` is sized from phi/inst writes only (`structure.rs:1189-1201`) with every read through `locs.get()` (`:1272-1296`). Correct, but a read-but-never-written value degrades to `DefLoc::None` silently instead of being diagnosable. `debug_assert` the size against `p.inputs` too. Your own history here is the argument for caution: three rounds of self-inflicted regressions, head commit "restore wave64 partial EXEC read and fresh WQM discovery BDD state". 42 behind, `structure.rs` untouched on `main` since the merge base.
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-04 13:54 UTC · original

Re-checked b988f16 natively on Windows 11 (MSVC, not Wine), against 1152b9c. Both divergences are gone.

Same local harness as before. Main's structure.rs sits next to the PR's as a test-only module, and every structure_wide call runs both and compares a raw dump (node table, atoms, raw Bool ids) and a semantic dump (every output Bool expanded over atoms). Same random generator and same seed as last time.

  • 24,960 structure calls in total. 1,104 come from 249 tests of the --lib suite, one from a hand-written wave64 exec_lo case, and 23,855 from the random corpus (20k generated programs, wave32 and wave64).
  • 0 raw differences and 0 semantic differences.
  • Both paths get real traffic. Across all calls, 10,485 go through a kept s_wqm with helped empty and 82 with helped non-empty. 2,414 are wave64 with an instruction that reads exec_lo but not exec_hi.

The fixes are at structure.rs:1416 (the inst.read(Reg::S(EXEC)).is_some() gate is back, with None => Bool::TRUE) and structure.rs:1021-1023 (fresh Lanes::new after discovery).

Negative control, same seed. I put each old hunk from 80a1d6c back on its own.

  • Old masks_in_order gate only gives 27 semantic differences, all wave64. That is the same count as my first run.
  • Old WQM shortcut only gives 4,066 raw-only differences and 0 semantic, all with a kept s_wqm and helped empty. Last time I reported 4,061 because 5 programs hit both old paths and got counted with the 27.

So the harness still catches both. The four new tests pass under both controls, and their own structure calls come out identical to main there too. They don't pin either regression. If you want tests that do, the two random programs below differ from main under the old code and match it on b988f16 (raw words, little-endian).

  • wave64, old gate: 7D880081 BE840402 BF870005 8A8A0202 7E020303 878880C1 BF860003 BE86037E BF07817E BE84046A BF810000
  • wave64, old WQM path: BE860A0A BF860002 4A000503 7DA40703 BF810000

For DXIL I hashed every module out of lowering on both sides over the whole suite. 830 modules from 165 tests, same multiset of hashes. Only two of those tests (a_killed_pixel_is_read_by_its_quad, a_killed_pixel_stays_in_its_quad) go through a kept s_wqm, both with non-empty helped. None of them hits the empty-helped case or a partial exec_lo read, so DXIL covers those two paths only through the structure comparison above.

Tests were run with cargo test -p victory-shader --lib -- --test-threads=2, D3D12 tests on one NVIDIA desktop card plus WARP.

  • PR: 424 passed, 1 failed, 4 ignored (5 more than main, the 4 new ones plus bdd_work_reuse_and_given_if_not_implied_match_reference from the earlier commits)
  • main (1152b9c): 419 passed, 1 failed, 4 ignored
  • The failure is emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag on both sides (WARP rejects the compute pipeline). It already fails on main.

None of the harness is pushed.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-04 13:54 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/402#issuecomment-7413533683) Re-checked b988f16 natively on Windows 11 (MSVC, not Wine), against 1152b9c. Both divergences are gone. Same local harness as before. Main's `structure.rs` sits next to the PR's as a test-only module, and every `structure_wide` call runs both and compares a raw dump (node table, atoms, raw `Bool` ids) and a semantic dump (every output `Bool` expanded over atoms). Same random generator and same seed as last time. - 24,960 `structure` calls in total. 1,104 come from 249 tests of the `--lib` suite, one from a hand-written wave64 `exec_lo` case, and 23,855 from the random corpus (20k generated programs, wave32 and wave64). - 0 raw differences and 0 semantic differences. - Both paths get real traffic. Across all calls, 10,485 go through a kept `s_wqm` with `helped` empty and 82 with `helped` non-empty. 2,414 are wave64 with an instruction that reads `exec_lo` but not `exec_hi`. The fixes are at structure.rs:1416 (the `inst.read(Reg::S(EXEC)).is_some()` gate is back, with `None => Bool::TRUE`) and structure.rs:1021-1023 (fresh `Lanes::new` after discovery). Negative control, same seed. I put each old hunk from 80a1d6c back on its own. - Old `masks_in_order` gate only gives 27 semantic differences, all wave64. That is the same count as my first run. - Old WQM shortcut only gives 4,066 raw-only differences and 0 semantic, all with a kept `s_wqm` and `helped` empty. Last time I reported 4,061 because 5 programs hit both old paths and got counted with the 27. So the harness still catches both. The four new tests pass under both controls, and their own `structure` calls come out identical to main there too. They don't pin either regression. If you want tests that do, the two random programs below differ from main under the old code and match it on b988f16 (raw words, little-endian). - wave64, old gate: `7D880081 BE840402 BF870005 8A8A0202 7E020303 878880C1 BF860003 BE86037E BF07817E BE84046A BF810000` - wave64, old WQM path: `BE860A0A BF860002 4A000503 7DA40703 BF810000` For DXIL I hashed every module out of lowering on both sides over the whole suite. 830 modules from 165 tests, same multiset of hashes. Only two of those tests (`a_killed_pixel_is_read_by_its_quad`, `a_killed_pixel_stays_in_its_quad`) go through a kept `s_wqm`, both with non-empty `helped`. None of them hits the empty-`helped` case or a partial `exec_lo` read, so DXIL covers those two paths only through the structure comparison above. Tests were run with `cargo test -p victory-shader --lib -- --test-threads=2`, D3D12 tests on one NVIDIA desktop card plus WARP. - PR: 424 passed, 1 failed, 4 ignored (5 more than main, the 4 new ones plus `bdd_work_reuse_and_given_if_not_implied_match_reference` from the earlier commits) - main (1152b9c): 419 passed, 1 failed, 4 ignored - The failure is `emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flag` on both sides (WARP rejects the compute pipeline). It already fails on main. None of the harness is pushed. AI-assisted: yes
github-bot changed title from perf(shader): eliminate duplicate idoms, hash lookups, and BDD scratch allocations in structure to perf(shader): eliminate duplicate idoms, hash lookups, and BDD scratch allocations 2026-12-04 22:19:58 +00:00
Author
Owner

@⁠tommiehansen on GitHub · 2026-12-05 10:18 UTC · original

Thanks for the split and differential-review suggestions. The smaller mechanical alternative is now #545. The combined head e4391d3 also preserves separate SSA namespaces for dead blocks/NONE, with regression tests. Debug/release tests passed. The earlier BDD equivalence and timing results remain scoped to their tested revisions.

**@⁠tommiehansen** on GitHub · 2026-12-05 10:18 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/402#issuecomment-7436354387) Thanks for the split and differential-review suggestions. The smaller mechanical alternative is now #545. The combined head [e4391d3](https://github.com/tommiehansen/VIctory-xmem/commit/e4391d3a3c2238e6c074910755b58f537f2eec22) also preserves separate SSA namespaces for dead blocks/NONE, with regression tests. [Debug/release tests passed](https://github.com/tommiehansen/VIctory-xmem/actions/runs/47499397549). The earlier BDD equivalence and timing results remain scoped to their tested revisions.
This pull request has changes conflicting with the target branch.
  • crates/victory-shader/src/structure.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

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

Merge

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