Repository navigation
D3D12-SHADER-OPT-CHAINS-CANONICAL: a chain with its steps the other way round is in order (-8 % translate CPU, -0.34 % DXIL instructions) - #2800
Conversation
…ay round is in order `chains` rewrites a conjunction of lane conditions into `(((t1 & t2) & t3) & ...)` with the terms in the order they were made, and leaves a chain alone when it is that already (`canonical`). `canonical` only accepted a step written `and(lower, term)`. `key` has an integer `and` the same whichever way round its operands are, so a chain written `and(term, lower)` was never canonical: `chains` built `and(lower, term)` as new instructions, the reuse pass of `merge` put the instruction that was there back, and the next round did the same, until the limit of four rounds. Both passes said "changed" every round, so `optimise` never stopped early on those modules, and its last round ended on a `chains` rewrite that no `merge` followed, which left the rewrite's duplicates in the DXIL. `canonical` now accepts a step with its two operands either way round. Full-archive `leonida translate` (25,689 emitted programs): 10,291 programs ran all four rounds before (rounds 3 and 4 were 44 % of the optimiser's time); the DXIL of 10,089 programs changes, all of it in `arith` (-341,356 instructions, -0.84 % of arith, -0.34 % of all; every other kind of instruction and the block count are equal), 7,315 smaller, 2,767 of the same size, 7 larger by 4 bytes. The old code with one `merge` added after its last round gives the same arith count. The validator (`--validate`) reports the same table of reasons and the same counts before and after. Wall -7.8 %, user CPU -8.5 % over four alternating runs each. Tests: a chain with the term first at the root, below it, and both is left as it is (fails without the change), and a chain with its terms out of order is still rewritten. AI-assisted: Claude Sonnet 5.5 Co-authored-by: Cursor <cursoragent@cursor.com>
|
Verified by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), head MEASURED
READ IN CODE
ASSUMED
AI-assisted: Claude Code |
KelboLive
left a comment
There was a problem hiding this comment.
Verified the Rust arm (this is d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs, not the Python translator — so the semantic suite cannot discriminate it): cargo test --locked -p leonida-shader --lib is 402 passed / 0 failed / 5 ignored, and removing the new match arm makes a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is fail at opt.rs:1853, while the out-of-order control test still passes. So the new arm is pinned in both directions.
The change is semantically safe as far as I can tell: only i1 and nodes (plus pure xor) are replaced, leaves — including effectful loads/calls — keep their instructions and positions, and a store/atomic/barrier is not an i1 and step, so nothing with side effects is reordered. The term order is irrelevant to AND, and the terms are sorted by definition site and deduped, with a term-with-its-complement refused (:1242-1261); the only hash-ordered collection is the pre-existing by_block map, which does not decide which chains collapse.
One residual, performance only but worth closing: born[p] = (rank, 0) for every phi in a block (:1202) and a stable sort_by_key (:1249) mean same-block phis tie, so their order follows the DFS — which reverses when the chain is rebuilt. With three i1 phis from one block in a chain, canonical rejects the rebuilt chain and chains() rewrites again next call (temporary test: first call true, second call true; with three distinct comparisons the second is false). A total tie-break — (born, base) or a per-phi birth index — finishes the loop fix this PR is after.
(The Python semantic suite is irrelevant here: 553 files / 6,720 tests pass, but it never loads leonida-shader. The archive hash change is not reproducible here either — no work folder with disassembly on this machine — and the PR does not claim identical output anyway.)
VERIFY-2800 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game filesVerdict: PASS. The fix is one line and the pull request brings its own control: the out-of-order chain is still rewritten. Head 1. The change
match m.insts[i as usize].op {
Op::Bin(Bin::And, x, y) if y == want => cur = x,
_ => return false,
}That only accepts a step written as Op::Bin(Bin::And, x, y) if y == want => cur = x,
Op::Bin(Bin::And, x, y) if x == want => cur = y,The comment in the pull request describes the consequence: the reuse pass would put the instruction that is there back in place of the rewrite, and the next round would plan the same rewrite again, "up to the round limit". 2. Red and green, and the discrimination
With only that one line put back (the pull request's tests kept): So the new test looks at the code it is about. 3. The control is in the pull request
let low = m.bin(b, Bin::And, c2, a); // c2 & a — the terms are in the wrong order
let chain = m.bin(b, Bin::And, low, c1);
assert!(m.chains(), "`c2 & a` then `& c1` is not `(a & c1) & c2`");
assert!(!m.chains(), "and the rewrite is in order");The first assertion is that the pass finds work, the second that a second call finds none — so the fix cannot be "the pass stopped rewriting anything". With the fix reverted, the other test fails and this one still passes, which is what a control should do. 4. The claim about the reuse passThe pull request says the chain "would be rebuilt each round for the reuse pass to put back, and say that it had changed something every time, up to the limit of rounds". The new test checks the end of that: I did not measure the round count or the CPU saving on a real shader corpus — the pull request's title quotes "-8 % translate CPU, -0.34 % DXIL instructions", and that needs the game's shaders, which are not in the repository and which I do not have. 5. It does not collide with #2872Both pull requests change No conflict, and neither pull request's test breaks the other's. 6. What I did not check
AI-assisted: MiniMax M3.1 Flash. |
|
@KelboLive Addressed the same-block phi tie-break residual in
AI-assisted: Gemini 4 Neon (including an independent read-only reviewer pass). |
What
Module::optimise(leonida-shader/src/emit/bitcode/opt.rs) runsmerge,prune,guardsandchainsfor up to four rounds and stops early when none of them changes anything. In a full-archiveleonida translateon currentmain, 10,291 of 25,689 emitted programs (40 %) run all four rounds, and rounds 3 and 4 are 44 % of the time the optimiser takes. I traced those rounds (live instructions, dead instructions, blocks, and which pass said "changed") and they are a loop, not progress: from round 2 onmergeandchainsboth report a change every round while the counts do not move. With the limit raised to 16, 10,236 programs still say "changed" in the last round.The cause is in
chains. It rewrites a conjunction of lane conditions into(((t1 & t2) & t3) & ...), terms in the order they were made, and leaves a chain that is in that form (canonical).canonicalonly accepted a step writtenand(lower, term).key()treats an integerandas commutative, so a chain writtenand(term, lower)was never canonical:chainsbuiltand(lower, term)as new instructions, the reuse pass ofmergeput the instruction that was there back, and the next round did the same. I found it by printing the plans of a small program per round: the same root and the same terms every round, with the prefixandthere with its operands the other way round.canonicalnow accepts a step with its two operands either way round. That is one match arm.Claim: D3D12-SHADER-OPT-CHAINS-CANONICAL (coordination issue #2570, #2570 (comment)). No open pull request edits
chains(checked the diffs of the ones that touchopt.rs: #2750, #2698, #2687, #2681, #2569).The DXIL is not identical to
main's, and whyI claimed an identical-DXIL bar in the claim; this is not that, so here is what changes. Full archive, 25,689 programs, hash of the DXIL of each (a scratch patch writing the hashes; not in this pull request):
arith: -341,356 instructions (-0.84 % of arith, -0.34 % of all instructions). Every other kind (select, phi, calls, loads, stores, casts, extracts, handles) and the block count are equal, from the census (LEONIDA_SHADER_CENSUS) of both builds.mainhas those extra instructions: its last round ends on achainsrewrite and nomergefollows, so the rewrite's duplicates of existingands are written out. I checked that:mainwith onemergeadded after the last round gives the same arith count (40,370,778) as this branch and the same DXIL in 25,548 programs (total bytes within 8 of this branch's).Not rewriting a chain is always sound (it leaves the lowering's own form), so the new output is
main's with duplicateands absent and some operands in the other order; I did not run a GPU test on it.leonida translate --validate(Windows SDK 10.0.26100dxil.dll) on both builds: the same counts (14,220 of 14,247 vertex and pixel programs, 2,677 of 2,677 compute, 8,673 of 8,765 mesh) and the same table of reasons for the rest (compared line by line, counts included), so nothing new is refused.Measured
Full-archive
leonida translate, release build withmimalloc, 16 threads, Ryzen 7 7800X3D,mainat 2878a39 as the baseline (the same tree with the one arm taken out), four alternating runs of each:Means: wall 36.65 -> 33.78 s (-7.8 %), user CPU 477.2 -> 436.9 s (-8.5 %).
Tests
a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is: the term first at the root, below it, and both;chains()finds nothing to rewrite, still nothing afteroptimise(CHAINS | REUSE | DEAD)has merged them, and a second run leaves the instructions as they were. Negative control: taking the new arm out makes it fail on the first assertion.a_chain_with_its_terms_out_of_order_is_still_rewritten: the control for the other direction (it passes with and without the arm).cargo test -p leonida-shader(debug): 402 passed, 0 failed, 5 ignored.rustfmt --edition 2024 --check opt.rs: no diff in the lines this changes (the file's other diffs were there before).cargo clippy -p leonida-shader --no-deps --all-targets -- -D warningsreports errors in other files of the crate and two inopt.rs(lines 1318 and 1778, from the commit that addedchains), none in the lines this changes.check_no_game_data.pyon the changed file: clean.AI-assisted: Claude Sonnet 5.5