Skip to content

Shaders: one instruction for one value (13.5 % fewer emitted instructions, no program lost) - #2150

Open
r4tedx wants to merge 3 commits into
Marvisak:mainfrom
r4tedx:shader/value-reuse
Open

r4tedx wants to merge 3 commits into
Marvisak:mainfrom
r4tedx:shader/value-reuse

Conversation

@r4tedx

@r4tedx r4tedx commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary: a pass over the finished DXIL module keeps one instruction for one value. On the title's shaders it takes out 10.5 % of the emitted instructions (on main 13f91ca) and loses no program. It makes a synthetic store-heavy program 19–27 % faster on WARP and changes nothing measurable on an AMD GPU, whose compiler already does this. So the gain shown is smaller modules, not GPU time.

What it does

The lowering writes code as the console instructions name it: a register read as a float is cast again at each read, a descriptor's handle is made and its index clamped again in each block, an address is shifted and masked again for each access. bitcode::reuse (new file emit/bitcode/reuse.rs, called from Shader::finish before the module is written) walks the dominator tree. An instruction that computes what an earlier one computed, where every path to it has run that earlier one, is left out, and its readers take the earlier result.

It takes part only where the result is a function of the operands:

  • integer arithmetic and compares, integer selects, width casts and bit casts, extractvalue, getelementptr
  • createHandleFromBinding, createHandleFromHeap, annotateHandle, and the integer dx.ops declared readnone
  • getDimensions: a resource's dimensions do not change while a shader runs
  • raw loads from the host's own tables (page table, view addresses, view marks, view strides). No shader writes them. The host does rewrite entries while the GPU runs, and the pass needs no promise about that: inside one invocation, the reads of one entry it merges give one value, the first read's.

It leaves these exactly as the lowering wrote them:

  • float arithmetic, float compares, conversions and float dx.ops: a driver may contract or reorder them by how they are used
  • every other load, samples, atomics, barriers, wave operations

Why it cannot break the flags

#1716 and #1646 each lose programs that validate on main ("Flags must match usage", "Internal declaration 'code' is unused"): removing the last use of an operation leaves the declared flags or a declaration stale. This pass removes only a copy of an instruction that stays, with the same operands. So no operation and no declaration loses its last use, no value loses its last reader, and nothing has to be recomputed. It does not do dead-code elimination or folding; those are #697, #1716 and #1646, and it composes with them.

Measured

Offline, the title's shaders.rpf (local title data, CPU only, translate --validate --list --count from #2115 b0f0b2e, dxil.dll 10.0.26100.0; counts only). Counted on main 13f91ca, which already has 850b66f (one handle per descriptor in the entry block) and 286a00e (dead code left out, constant branches folded):

main 13f91ca with this PR
instructions in emitted programs 164,909,025 147,551,134 −10.53 %
programs validated 24,846 24,846 none lost, none gained
programs smaller / same / larger 25,076 / 589 / 0

Every program has the same outcome as on main, compared program by program. What goes: bitcast −10,910,357, and −1,926,671, icmp −948,319, add −775,608, select −705,144, lshr −437,927, shl −406,785, or −390,609, annotateHandle −205,819, createHandleFromHeap −108,011, createHandleFromBinding −98,758, rawBufferLoad −84,623 (the table loads), getDimensions −925. Blocks are unchanged. (On 940d32f, before 850b66f and 286a00e, it was 190,954,569 -> 165,215,092, −13.48 %.)

GPU timestamps on a synthetic program (measured at 91d75b8 on 940d32f) (a compute program of 32 lanes that stores to an unordered buffer view 8 or 32 times, with write marks; least of 7 runs; the benchmark is not in this PR):

adapter stores main with this PR
WARP, 4,096 groups 8 6.13 ms 4.47 ms
WARP, 4,096 groups 32 23.08 ms 18.78 ms
AMD Radeon integrated (driver 32.0.21036.18), 65,536 groups 8 1.367 ms 1.367 ms
AMD Radeon integrated, 65,536 groups 32 5.198 ms 5.190 ms

WARP times do not predict a graphics card, and the Radeon rows show it: its compiler removes the copies itself. I did not measure pipeline compile time, and nothing was measured on NVIDIA or in the title.

Checks

  • cargo test -p victory-shader --lib at dcdb50e with VICTORY_WARP=1, one thread: 272 passed, 0 failed, 3 ignored, 3 skipped. Skipped: synthetic_tests::gathers_at_a_level_match_the_hardware, synthetic_tests::permutes_read_the_lane_named_and_zero_from_lanes_left_out, synthetic_tests::a_mask_joined_with_data_at_a_uniform_loop_is_its_number. They come from main, and their first leg asks for the hardware adapter, which VICTORY_WARP=1 turns into WARP (wave of 32 refused, WARP's gather rounding), so they fail there by design.
  • clippy -p victory-shader --all-targets -D warnings at dcdb50e: clean.
  • Five new unit tests, no device: a block keeps one of each value; a value serves only what it dominates (not a sibling branch, not the join from one side); floats, loads and atomics are left alone; a table entry is read once and the same load through another handle stays; a loop's phi and branch read the value kept.
  • cargo clippy -p victory-shader -p victory --all-targets: clean. rustfmt --check on the new file: clean. cargo xtask policy: ok.
  • Not run: the suite on a hardware GPU. A run on AMD and NVIDIA hardware by someone who has them would be welcome.

Credit

The fork fxceless/victory-fork has a clean-up pass with a "reuse" step; the idea of doing this on the finished module comes from reading it. No code is taken from it. This pass differs in what it admits (an explicit list and the declared readnone attribute, not name prefixes, and no floats).

AI-assisted.

🤖 Generated with Claude Code

The lowering writes code as the console instructions name it: a register
read as a float is cast again at each read, a descriptor's handle is made
and its index clamped again in each block, an address is shifted and
masked again for each access. `bitcode::reuse` runs on the finished
module: an instruction that computes what an earlier one computed, where
every path to it has run that earlier one, is left out and its readers
take the earlier result.

It takes integer arithmetic and compares, integer selects, width and bit
casts, extractvalue, getelementptr, handle creation and annotation, the
integer `readnone` operations, `getDimensions`, and raw loads from the
host's own tables (page table, view addresses, view marks, view
strides). Float arithmetic, float compares, conversions, every other
load, samples, atomics and wave operations stay as written.

What goes is always a copy of an instruction that stays, so no operation
and no declaration loses its last use: shader flags and declarations
stay valid without being recomputed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@DenRakEiw DenRakEiw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified locally merged onto origin/main (940d32f, Windows 11 x64, Rust 1.98.1 MSVC):

  • cargo test -p victory-shader --lib emit::bitcode:: — 11 passed, 0 failed (1 ignored)
  • cargo clippy -p victory-shader --all-targets — 0 warnings
  • cargo xtask policy — ok (184 files ok)

Clean dominator-tree GVN / value reuse pass (bitcode/reuse.rs) eliminating redundant emitted DXIL instructions. Looks great.

AI-assisted (Gemini 4 Neon).

r4tedx added a commit to r4tedx/VIctory that referenced this pull request Nov 25, 2026
…sak#2115 in; Marvisak#2150 left out for now

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Dathinel

Copy link
Copy Markdown
Contributor

Native NVIDIA run as requested: Windows, RTX 3050 Laptop, driver 32.0.16.1062, pinned Rust MSVC, adapter overrides unset. I ran cargo test --frozen -p victory-shader --no-fail-fast -- --nocapture --test-threads=1 on both unmodified revisions.

Revision Passed Failed Ignored
Parent 940d32f 244 3 3
PR 91d75b8 249 3 3

All five new reuse tests passed. The three failures had identical diagnostics on both runs: by-element stride read, missing buffer view, and gather (the three in #1835). All 467 printed arithmetic-model comparison lines also matched between runs. Six compiler-dependent checks skipped internally; the wave-32 permute test skipped its WARP path.

I also checked that the pass actually rewrote a shader exercised by the suite. In a separate run, logging the return value of self.m.reuse(&tables) in intersections_on_nodes_in_title_memory_equal_the_reference reported 58 instructions removed on each of its two emissions; the reference comparison passed. No game or performance measurement. AI-assisted.

@catminou4 catminou4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested locally: macOS arm64, rustc 1.98.1, PR head merged into main 940d32f, cargo test -p victory-shader --locked.

149 passed / 0 failed / 2 ignored. One instruction for one value (13.5% fewer emitted instructions, +5 tests) — emit-size optimization with measured improvement; nice perf win.

@sinan-cmyk

Copy link
Copy Markdown

Offline measurement on a retail dump

Result: no count change against main.

I merged head 91d75b8 onto main 940d32f (clean merge) and ran victory translate --validate --list on shaders.rpf (1.0.2.1), with dxil.dll 1.8.2502.11. I compared the result with main program by program (25,889 programs). Validated: 23,918 on main, 23,918 with this PR.

No program changes its failure reason. The count shows that the change rejects nothing on this data. It does not show whether the output is right.

No shader names or data are included, per the asset policy. AI-assisted (Claude Code).

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Merge candidate. Re-reviewed at dcdb50e, which now merges cleanly into main. Module::reuse (new crates/victory-shader/src/emit/bitcode/reuse.rs, called from Shader::finish) walks the dominator tree. It drops an instruction whose key (opcode and operands) matches one in a dominating block, and points readers at the earlier result, including phis and branch conditions.

I checked what it admits:

  • integer binaries, compares and selects, width and bit casts, extractvalue and getelementptr;
  • createHandleFromBinding/FromHeap, annotateHandle and getDimensions;
  • .i32 dx.ops declared ReadNone;
  • rawBufferLoad only through the host's own tables (page table, view addresses, view marks, view strides).

The lowering declares wave and lane ops NoUnwind or ReadOnly, not ReadNone, so a ballot or lane read in a narrower branch is not merged with one above it. Floats, other loads, samples, atomics and barriers are left alone. The pass removes only copies of an instruction that stays, so no declared operation loses its last use and the feature flags cannot go stale.

Evidence: on the title's archive, 10.5% fewer instructions on 13f91ca, and every program has the same outcome as on main. The suite passed on WARP, and on an RTX 3050 earlier.

On your reply: the corrected note in bitcode/reuse.rs and emit/mod.rs (reads of one entry inside an invocation take the first read's value, with no promise about the host) matches the code, and so does the updated figure. CI: check passing on this head.


Generated by Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@RomainKH RomainKH left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read reuse.rs against current main (13f91ca) and ran it merged there on macOS arm64 (CPU only). The pass looks correct to me. One sentence in the module notes states something the host does not guarantee.

What I checked

  • Lane-dependent calls stay out. integer admits any readnone call whose name ends in .i32, so I listed what the emitter declares readnone. On this head and on main: unaryBits.i32, unary.i32, flattenedThreadIdInGroup.i32, dot4AddPacked.i32 and loadInput.*, all functions of their operands. Every wave and quad op (waveReadLaneFirst, waveReadLaneAt, waveActiveOp, wavePrefixOp, waveActiveBallot, waveActiveBit, quadReadLaneAt) is declared NoUnwind, and waveGetLaneIndex is ReadOnly, so none of them is merged.
  • The four tables are read-only views. They are t0 (page table), t1 (view addresses), t2 (view marks) and the VIEW_STRIDES root SRV. The bitmaps shaders write are u views and are not in the list: memory_dirty, and u1 VIEW_WRITES, which main's new read marks (since this PR's base) also write.
  • Every terminator that reads a value is rewritten (only CondBr does). Blocks the entry does not reach are not visited, but main's writer now leaves them out (286a00e).
  • Merge with main: the only conflict is in emit/mod.rs, two notes added at the same place; keeping both resolves it. Merged there, together with #2558 and #2342: cargo test -p victory-shader --locked --lib gives 167 passed, 0 failed, 2 ignored. The hardware and WARP checks did not run here.

The module note

So the host does not change a table under a list that runs and reads it.

The host does change them. HostHeap writes the stride, mark and address entries into mapped upload buffers (write_stride, set_mark, note_address) whenever a slot is made, and descriptor/host.rs:531 says "Title threads rewrite slots while the GPU runs a submission".

The pass does not need that guarantee, though. Within one invocation, two reads of an entry the host is rewriting could each see either value, with or without the pass. With it, they agree. For example, buffer_guard's "no buffer view here" check and view_stride's stride then come from the same read of VIEW_STRIDES. I'd reword the note along those lines rather than state a host property.

One thing worth re-measuring

The 13.5 % was counted on 940d32f. Since then main makes one handle per descriptor at a fixed address in the entry block (850b66f), and the writer drops dead code and branches on constants (286a00e). Both overlap part of what this pass removes: createHandleFromHeap and annotateHandle were −2.4 M of the −25.7 M. A --count on the rebased head would show what is left.

AI-assisted (Claude Code); the results are from runs on my machine.

The host rewrites table entries while the GPU runs (the heap's
write_stride, set_mark and note_address), so the notes no longer say it
does not. The pass needs no such promise: inside one invocation the
reads of one entry it merges give the first read's value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@r4tedx

r4tedx commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking the pass. Both points are done at dcdb50e.

The note. You are right that the host rewrites the tables while the GPU runs (write_stride, set_mark and note_address write the mapped tables in place; descriptor/host.rs:531). The notes in bitcode/reuse.rs and emit/mod.rs no longer say otherwise. They now say that inside one invocation, the reads of one entry that the pass merges give one value, the first read's. So the pass needs no promise about the host.

One correction to the example: buffer_guard and view_stride do not share a read. buffer_guard reads VIEW_STRIDES at the clamped index (select(index > HEAP_VIEWS - 1, HEAP_VIEWS - 1, index), lower.rs:5313-5320). view_stride reads it at the unclamped index * 4 (lower.rs:5030-5033). The addresses differ, so the pass keeps both loads. What it does merge is a repeated read of the same entry at the same address, for example buffer_guard for one descriptor in several blocks. So I left that example out of the note.

The figure. Recounted on current main (13f91ca, whose code is that of 67e8ae1, so it includes 850b66f and 286a00e). The run was offline on the title's shaders.rpf (local title data, CPU only), with translate --validate --list --count from #2115 (b0f0b2e) and dxil.dll 10.0.26100.0:

  • instructions in emitted programs: 164,909,025 on main, 147,551,134 with this PR (−17,357,891, −10.53 %)
  • programs validated: 24,846 on both. Compared program by program, none was lost or gained, 25,076 are smaller, 589 are the same and none is larger. Blocks are unchanged.
  • handles: createHandleFromHeap −108,011 and annotateHandle −205,819, with createHandleFromBinding −98,758. That is −0.41 M together, against −2.4 M before 850b66f. Most of the reduction is still bitcast (−10.9 M), then and (−1.9 M), icmp, add and select.

So −13.5 % was stale; it is now −10.5 %. The PR text is updated.

AI-assisted.

Airamek added a commit to Airamek/VIctory that referenced this pull request Nov 26, 2026
…k#2150)

Port of upstream Marvisak#2150: new bitcode/reuse.rs implements a
dominator-tree-scoped GVN over pure integer ops/selects/casts,
readnone integer dx.ops, handle/DIMENSION calls and raw loads of
the host's own tables (page table, view addresses/marks/strides).
Shader::finish() runs it over the tables a shader reads, so the
reads of one entry inside an invocation agree on the first read's
value even where the host rewrites the entry mid-list (module
docs; the semantics are unchanged inside an invocation, where no
store or other thread can come between).

Floats, non-table memory, samples and wave ops are excluded, so
no contraction/reordering-sensitive computation changes meaning;
anything left out is a copy of an instruction that stays, so no
declaration loses its last use. Correctness: full shader suite
green (300 passed), including the validator (rewritten bitcode
validates), byte-sensitive diff tests and the hardware
differential tests on a D3D12 device.

Microbench (release, this machine): dominator GVN over a
600-inst synthetic module with 200x repeated pure ops folds 398
instructions (601 -> 203 insts, 5540 -> 2364 bytes, -57%) at
194 us pass cost. Upstream reports -13.5% emitted instructions on
their corpus; translate-time and GPU effects follow DXIL size.
github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 26, 2026
…ewer emitted instructions, no program lost)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants