perf(shader): eliminate duplicate idoms, hash lookups, and BDD scratch allocations #402
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/lobomfz--VIctory-xmem!402
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-402"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@tommiehansen on GitHub · 2026-12-04 00:32 UTC · original
tommiehansen:perf/structure-flat-defs-bdd-scratch→main· +686 −251 · 1 files · 5 commits · openWhat this does
eliminate duplicate idoms, hash lookups, and BDD scratch allocations.
Checks
bdd_work_reuse_and_given_if_not_implied_match_referenceand wave/WQM regression tests; 299 previously passing. Pre-change comparison pending.cargo xtask policyon 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 = identicalacross allshaders/*anddescriptors/*workloads).Changes (
crates/victory-shader/src/structure.rs)ir::idomspass inLanes::new(): Reuses the immediate dominator tree computed bycrate::ir::idomsfor both the reducibility check (dominates/lca_idom) andcompute_active, eliminating the duplicatecompute_idomsfixed-point pass.DefLoctable (Lanes::locs): Replacesdefs: Map<Value, (usize, usize)>andphis: Map<Value, (usize, usize)>hash maps with a single denseValue-indexedVec<DefLoc>(Inst(u32, u32)/Phi(u32, u32)).Fx-hashed sets & dense block flags: Replaces internal SipHashHashSets (within,unresolved,derived_phis,phi_join_ids,scc_every,check_joins::seen_derived,finish::split) withSet<T>(BuildHasherDefault<Fx>), and stores densewide_flags/helped_flags: Vec<bool>onLanessoedge()andcompute_active()avoid repeated hash probes.BddWork): Carries reusablememo_pair,memo_node,assign, generation-stampedseen_nodes/seen_atoms, andvars/stackacrosspaths(forget_with),check_joins(implies_with/disjoint_with),join,helped_now(alone_with),step, andfinish(given_if_not_implied/given_with), eliminating per-callHashMapallocations and avoiding duplicateimpliesevaluation per guard transition infinish().EXECcache (masks_in_order) preserving exact semantics: Cacheslast_exec: Option<(Key, Bool)>within each block and deduplicates consecutive identicalrunsentries while keepinginst.read(Reg::S(EXEC)).is_some()as the outer gate (None => Bool::TRUEfor wave64 partialexec_loreads such ass_wqm_b32). Removesargs.clone()incheck_joins()andruns.clone()inhelped_now().structure_wide): Retains freshL = Lanes::new(program)reconstruction after WQM discovery completes (l.add_helped(&helped); l.whole = !helped.is_empty()), guaranteeing identical raw BDD tables andBoolIDs on kept-s_wqmshaders with empty or nonemptyhelpedsets.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, andkept_wqm_with_nonempty_helped_marks_whole_and_helped.Benchmarks (CPU-Only Synthetic Suite, Apple M5 macOS)
Paired A/B/B/A (
1152b9cvsb988f16,--offline --cpu-only --profile standard --blocks 4 --suite shaders,descriptors, 8 runs/side) viatools/benchmark-suite:1152b9c(ms)b988f16(ms)descriptors/shader_resource_trackingidenticalshaders/structurise_guard_runsidenticaldescriptors/copy_span_indexidenticalshaders/guest_load_clustersidenticalshaders/guest_load_clusters_extendedidenticalshaders/uniform_smem_and_wide_loadsidenticalshaders/node_probe_emitidenticalshaders/uniform_guest_loadsidenticalshaders/translate_corpusidenticaldescriptors/d3d12x_heap_and_copy,shaders/gpu_execute--cpu-onlyNote:
shaders/structurise_guard_runsmeasuresspill::build(ir::build) andstructure::structuretogether, soir::builddominates wall time on flat guard sequences.Verification & Reproducibility
victory-shader):299 passed; 0 failed; 2 ignored(on macOS; Windows D3D12 emit tests are Windows-only).1152b9c: Canonical dump comparison of rawbools.nodes,bools.atoms,BoolIDs (exits,guards,masks,highs,paired_masks,phi_masks,scc_some),active,wide,helped, andwave_anyacross wave64 partialexec_loreads, wave32/wave64 fullEXECreads, consecutive identicalEXECreads, and kepts_wqmwith empty and nonemptyhelpedsets matched byte-for-byte.Known Limitations
--cpu-onlyruns.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
b581f7e0a8086158953a64068ba29305d5450d68into the existing branch without rewriting history. New head:182e47869d0430cac3f3fb879693255eddbfc35b. Review split staged separately ata6ca7d39ce62871b8acaf7623b0eba989d9435c1(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.
@Kal0s-design on GitHub · 2026-12-04 01:53 UTC · original
Tested
80a1d6cnatively on Windows 11 (MSVC), against1152b9c.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.rsnext to the PR's as a test-only module and hookedstructure_wideso every call runs both and compares the results. One comparison uses rawBoolids and the full node table. The other expands every outputBoolinto its function over atoms, so node numbering doesn't matter. I ran that hook over the whole--libsuite plus about 18.5k random programs (wave32 and wave64; random SOP/VOPC/saveexec/wrexec/s_wqm mixes; forward and backward branches; randomwidesets), 23,855structurecalls in total. I also hashed the DXIL coming out of lowering on both sides. None of this is pushed.Behaviour change in
masks_in_order(structure.rs ~1420). Main gates oninst.read(Reg::S(EXEC)).is_some()and thenexec()givesBool::TRUEwhen there is no full key. The PR gates onself.key(..)beingSome. In wave64, an instruction that reads onlyexec_lo(e.g.s_wqm_b32 sN, exec_lo) gavenow = Some(TRUE)on main. With the PR it keeps the previous value (orNone).stepusesnowfor thewithincheck, soStructured::activecan come out different. The random run found 27 calls where the semantic dump differs, all in wave64 and all inactive(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.Extra BDD nodes on the
s_wqmpath (structure.rs ~1018-1024). When a program has a kepts_wqmbut ends up with no helped blocks, main threw away the discoveryLanesand redid everything from a freshBools. The PR finishes on the discoveryLanes, whichhelped_now()has already grown throughand/alone_with. SoStructured::boolshas a few extra nodes (1 to 18 in my cases), and someBoolids inexits/phi_masksshift. 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) hads_wqmin it andhelpedempty, 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 andMAX_NODES. Still, "byte-for-byte identical structured output" doesn't hold for this path.Everything else matched.
ir::idomsagreed with the oldcompute_idomson 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
seenbuffers 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*_withcall, as before. The Fx sets replace std sets whose order main couldn't have depended on. Andgiven_if_not_impliedmatches(!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:emit::size_tests::a_reused_descriptor_register_read_only_behind_its_flagon 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 theguard_runsbench 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
@tommiehansen on GitHub · 2026-12-04 11:50 UTC · original
Thanks @Kal0s-design for catching both divergences in the differential check! Pushed fix
b988f16addressing both findings and updated the PR description:EXECreads (masks_in_order): Restoredinst.read(Reg::S(EXEC)).is_some()as the outer condition withself.key(..., EXEC)returningNone => { last_exec = None; Bool::TRUE }inside, preservingmain's handling of wave64 partialexec_loreads (e.g.,s_wqm_b32 sN, exec_lo) and keeping thelast_execcache for fullEXECreads.structure_wide): Replaced the reuse/direct-finish shortcut on theneeds_wqm_checkpath with freshl = Lanes::new(program)?; l.add_helped(&helped); l.whole = !helped.is_empty(); break;so kepts_wqmprograms with either empty or nonemptyhelpedproduce identical raw BDD node tables andBoolIDs as1152b9c.Verification on
b988f16crates/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, andkept_wqm_with_nonempty_helped_marks_whole_and_helped(fullcargo test --offline -p victory-shader:299 passed; 0 failed; 2 ignoredon macOS).1152b9c: Compared canonicalized raw BDDnodes/atoms,BoolIDs,masks,active,guards,exits,phi_masks,wide, andhelpedagainst1152b9cacross those scenarios and consecutive identicalEXECreads —0differences (runsdeduplication needed no revert).1152b9cvsb988f16, 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 workloadsidenticalwith zero regressions. (UpdatedPROGRESS.mdon#322will be synced once#404finishes.)@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:
shaders/structurise_guard_runs, −5.19% ondescriptors/shader_resource_tracking, six of nine benchmarks "inconclusive" — against 854 changed lines in the pass that decides lane masks and guards. A wrongBoolout of a reused BDD memo does not crash; it emits a wrong guard.Lanes::newderiving reducibility fromcrate::ir::idomsinstead of its own fixed point,locs: Vec<DefLoc>, theFxsets and theVec<bool>flags are mechanical, checkable, and carry most of the line count for none of the risk. That half is a yes.BddWorkmemo reuse and thelast_execcache belong in a separate PR with a differential harness that comparesbools.nodeson captured shaders.Two things to fix on the way through:
last_exec(crates/victory-shader/src/structure.rs:1414-1448) is sound only becausemask(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 alast_exec = Nonenext to any future in-loop gc, is what keeps it true.locsis sized from phi/inst writes only (structure.rs:1189-1201) with every read throughlocs.get()(:1272-1296). Correct, but a read-but-never-written value degrades toDefLoc::Nonesilently instead of being diagnosable.debug_assertthe size againstp.inputstoo.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.rsuntouched onmainsince the merge base.@Kal0s-design on GitHub · 2026-12-04 13:54 UTC · original
Re-checked
b988f16natively on Windows 11 (MSVC, not Wine), against1152b9c. Both divergences are gone.Same local harness as before. Main's
structure.rssits next to the PR's as a test-only module, and everystructure_widecall runs both and compares a raw dump (node table, atoms, rawBoolids) and a semantic dump (every outputBoolexpanded over atoms). Same random generator and same seed as last time.structurecalls in total. 1,104 come from 249 tests of the--libsuite, one from a hand-written wave64exec_locase, and 23,855 from the random corpus (20k generated programs, wave32 and wave64).s_wqmwithhelpedempty and 82 withhelpednon-empty. 2,414 are wave64 with an instruction that readsexec_lobut notexec_hi.The fixes are at structure.rs:1416 (the
inst.read(Reg::S(EXEC)).is_some()gate is back, withNone => Bool::TRUE) and structure.rs:1021-1023 (freshLanes::newafter discovery).Negative control, same seed. I put each old hunk from
80a1d6cback on its own.masks_in_ordergate only gives 27 semantic differences, all wave64. That is the same count as my first run.s_wqmandhelpedempty. 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
structurecalls 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 onb988f16(raw words, little-endian).7D880081 BE840402 BF870005 8A8A0202 7E020303 878880C1 BF860003 BE86037E BF07817E BE84046A BF810000BE860A0A BF860002 4A000503 7DA40703 BF810000For 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 kepts_wqm, both with non-emptyhelped. None of them hits the empty-helpedcase or a partialexec_loread, 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.bdd_work_reuse_and_given_if_not_implied_match_referencefrom the earlier commits)1152b9c): 419 passed, 1 failed, 4 ignoredemit::size_tests::a_reused_descriptor_register_read_only_behind_its_flagon both sides (WARP rejects the compute pipeline). It already fails on main.None of the harness is pushed.
AI-assisted: yes
perf(shader): eliminate duplicate idoms, hash lookups, and BDD scratch allocations in structureto perf(shader): eliminate duplicate idoms, hash lookups, and BDD scratch allocations@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.
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.Merge
Merge the changes and update on Forgejo.