Shaders: one instruction for one value (13.5 % fewer emitted instructions, no program lost) #2150
No reviewers
Labels
No labels
accessibility
area: build
area: formats
area: gpu
area: loader
area: runtime
area: shader
bug
documentation
duplicate
enhancement
good first issue
gpu: amd
gpu: intel
gpu: nvidia
help wanted
host: wine
invalid
out of scope
question
request
run report
triage: confirmed
triage: has patch
triage: merge candidate
triage: needs info
triage: needs rebase
triage: needs work
triage: proposed close
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/Marvisak--VIctory!2150
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2150"
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?
@r4tedx on GitHub · 2026-11-25 06:16 UTC · original
r4tedx:shader/value-reuse→main· +570 −0 · 4 files · 3 commits · openSummary: 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 fileemit/bitcode/reuse.rs, called fromShader::finishbefore 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:
extractvalue,getelementptrcreateHandleFromBinding,createHandleFromHeap,annotateHandle, and the integerdx.ops declaredreadnonegetDimensions: a resource's dimensions do not change while a shader runsIt leaves these exactly as the lowering wrote them:
dx.ops: a driver may contract or reorder them by how they are usedWhy 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 --countfrom #2115b0f0b2e, dxil.dll 10.0.26100.0; counts only). Counted onmain13f91ca, which already has850b66f(one handle per descriptor in the entry block) and286a00e(dead code left out, constant branches folded):main13f91caEvery 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. (On940d32f, before850b66fand286a00e, it was 190,954,569 -> 165,215,092, −13.48 %.)GPU timestamps on a synthetic program (measured at
91d75b8on940d32f) (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):mainWARP 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 --libatdcdb50ewithVICTORY_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, whichVICTORY_WARP=1turns into WARP (wave of 32 refused, WARP's gather rounding), so they fail there by design.-p victory-shader --all-targets -D warningsatdcdb50e: clean.cargo clippy -p victory-shader -p victory --all-targets: clean.rustfmt --checkon the new file: clean.cargo xtask policy: ok.Credit
The fork
fxceless/victory-forkhas 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 declaredreadnoneattribute, not name prefixes, and no floats).AI-assisted.
🤖 Generated with Claude Code
67e8ae1) into the value reuse branch b7e090c8a8@Dathinel on GitHub · 2026-11-25 06:34 UTC · original
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=1on both unmodified revisions.940d32f91d75b8All 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)inintersections_on_nodes_in_title_memory_equal_the_referencereported 58 instructions removed on each of its two emissions; the reference comparison passed. No game or performance measurement. AI-assisted.@sinan-cmyk on GitHub · 2026-11-25 08:18 UTC · original
Offline measurement on a retail dump
Result: no count change against
main.I merged head
91d75b82ontomain940d32f(clean merge) and ranvictory translate --validate --listonshaders.rpf(1.0.2.1), with dxil.dll 1.8.2502.11. I compared the result withmainprogram by program (25,889 programs). Validated: 23,918 onmain, 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 on GitHub · 2026-11-25 11:25 UTC · original · edited 2026-11-25 22:26 UTC
Automated triage for the maintainers.
Merge candidate. Re-reviewed at
dcdb50e, which now merges cleanly intomain.Module::reuse(newcrates/victory-shader/src/emit/bitcode/reuse.rs, called fromShader::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:
extractvalueandgetelementptr;createHandleFromBinding/FromHeap,annotateHandleandgetDimensions;.i32dx.ops declaredReadNone;rawBufferLoadonly through the host's own tables (page table, view addresses, view marks, view strides).The lowering declares wave and lane ops
NoUnwindorReadOnly, notReadNone, 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 onmain. The suite passed on WARP, and on an RTX 3050 earlier.On your reply: the corrected note in
bitcode/reuse.rsandemit/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:checkpassing on this head.Generated by Claude Code
@r4tedx on GitHub · 2026-11-25 21:15 UTC · original
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_markandnote_addresswrite the mapped tables in place; descriptor/host.rs:531). The notes inbitcode/reuse.rsandemit/mod.rsno 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_guardandview_stridedo not share a read.buffer_guardreadsVIEW_STRIDESat the clamped index (select(index > HEAP_VIEWS - 1, HEAP_VIEWS - 1, index), lower.rs:5313-5320).view_stridereads it at the unclampedindex * 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 examplebuffer_guardfor 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 of67e8ae1, so it includes850b66fand286a00e). The run was offline on the title'sshaders.rpf(local title data, CPU only), withtranslate --validate --list --countfrom #2115 (b0f0b2e) and dxil.dll 10.0.26100.0:main, 147,551,134 with this PR (−17,357,891, −10.53 %)createHandleFromHeap−108,011 andannotateHandle−205,819, withcreateHandleFromBinding−98,758. That is −0.41 M together, against −2.4 M before850b66f. Most of the reduction is stillbitcast(−10.9 M), thenand(−1.9 M),icmp,addandselect.So −13.5 % was stale; it is now −10.5 %. The PR text is updated.
AI-assisted.
@DenRakEiw on GitHub · 2026-11-25 06:23 UTC · original · approved these changes
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 warningscargo 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).
@catminou4 on GitHub · 2026-11-25 06:49 UTC · original · approved these changes
Tested locally: macOS arm64, rustc 1.98.1, PR head merged into main
940d32f69b,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.
@RomainKH on GitHub · 2026-11-25 19:15 UTC · original · reviewed
I read
reuse.rsagainst currentmain(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
integeradmits anyreadnonecall whose name ends in.i32, so I listed what the emitter declaresreadnone. On this head and onmain:unaryBits.i32,unary.i32,flattenedThreadIdInGroup.i32,dot4AddPacked.i32andloadInput.*, all functions of their operands. Every wave and quad op (waveReadLaneFirst,waveReadLaneAt,waveActiveOp,wavePrefixOp,waveActiveBallot,waveActiveBit,quadReadLaneAt) is declaredNoUnwind, andwaveGetLaneIndexisReadOnly, so none of them is merged.t0(page table),t1(view addresses),t2(view marks) and theVIEW_STRIDESroot SRV. The bitmaps shaders write areuviews and are not in the list:memory_dirty, andu1VIEW_WRITES, whichmain's new read marks (since this PR's base) also write.CondBrdoes). Blocks the entry does not reach are not visited, butmain's writer now leaves them out (286a00e).main: the only conflict is inemit/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 --libgives 167 passed, 0 failed, 2 ignored. The hardware and WARP checks did not run here.The module note
The host does change them.
HostHeapwrites the stride, mark and address entries into mapped upload buffers (write_stride,set_mark,note_address) whenever a slot is made, anddescriptor/host.rs:531says "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 andview_stride's stride then come from the same read ofVIEW_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 thenmainmakes 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:createHandleFromHeapandannotateHandlewere −2.4 M of the −25.7 M. A--counton the rebased head would show what is left.AI-assisted (Claude Code); the results are from runs on my machine.
@fuzeofficlal on GitHub · 2026-11-26 18:48 UTC · original · approved these changes
Reviewed
dcdb50e25ac4merged cleanly onto63bcca43.The dominator-tree GVN pass in
crates/victory-shader/src/emit/bitcode/reuse.rsis tightly scoped and preserves DXIL and memory semantics:reuse.rs:139-178): Only pure integer ops (Bin/SelectonTypeDef::Int(_), integerCmppredicates>= 32,Trunc/ZExt/SExt/Bitcast,Extract,Gep), the four resource-handle/dimension calls (CALLS),Attr::ReadNonedx.op.*.i32intrinsics (audited everyAttr::ReadNoneemission incrates/victory-shader/src/emit/— none are wave, quad, derivative, or side-effecting ops), anddx.op.rawBufferLoad.f32on the host's read-only SRV tables (shader.rs:921-925:memory,view_addresses,view_marks,VIEW_STRIDES, excluding shader-written dirty/write UAV bitmapsmemory_dirtyandview_writes) participate. Float arithmetic/comparisons/conversions, non-table loads, and atomics are untouched, andcreateHandleFromHeapkeys on the full argument list includingnonUniform.reuse.rs:72-136,182-253): The Cooper-Harvey-Kennedy dominator tree walks rawblocks[b].term(a conservative superset ofplan's constant-folded edges), scopesheldwithStep::Enter/Step::Leaveunwindingtakenso sibling branches never cross-reuse, and rewrites phis andTerm::CondBrafter the tree walk. Because every removed instruction is a duplicate of a dominating retained instruction with identical operands,Module::uses()shader-flag usage remains invariant.Hardware & validation verification (RTX 5090 + Microsoft WARP + Windows SDK
dxil.dll):cargo xtask policyandcargo clippy --locked -p victory-shader --all-targets -- -D warnings(default and--all-features) pass cleanly.emit::bitcode::(17/17, including all 5 newreuse::tests::),emit::flow_tests::(RTX 5090 + WARP),emit::crosslane_tests::(5/5),emit::waterfall_tests::(6/6),emit::bvh_tests::(14/14),emit::diff_tests::(5/5),emit::synthetic_tests::wave64(3/3),emit::valu_tests::{integer,cndmask},emit::memory_tests::(4/4;heap_direct_texture_reads_mark_their_heap_indexcrashes identically on cleanmain63bcca43on this adapter), andemit::stride_tests::(6/6; the two heap-element tests fail identically on cleanmain63bcca43).bitcode::reuseedge-case probe covering: (1) an unreachable block referencing a deduplicated entry instruction (writes valid bitcode without panicking), (2) non-dominating sibling branches (reuse == 0), (3) constantCondBrdiamond consistency, (4)Module::uses()flag invariance when an earlier deadi64/heap op replaces a later live one, and (5)createHandleFromHeapstaying distinct whennonUniformdiffers.LGTM.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.