Skip to content

Shaders/Bitcode: cache Shader::op declarations, primitive types, scalar constants, and zero-copy bitcode Writer - #2665

Open
RVZO6 wants to merge 1 commit into
Marvisak:mainfrom
RVZO6:rvzo/bitcode-emit-fast
Open

RVZO6 wants to merge 1 commit into
Marvisak:mainfrom
RVZO6:rvzo/bitcode-emit-fast

Conversation

@RVZO6

@RVZO6 RVZO6 commented Nov 25, 2026

Copy link
Copy Markdown

Claimed in #1633: #1633 (comment)

Summary

Speeds up DXIL module construction and LLVM 3.7 bitcode emission (crates/victory-shader/src/emit/bitcode.rs, crates/victory-shader/src/emit/shader.rs, +451/-125) while emitting bit-for-bit identical bitcode (all written_bytes_unchanged FNV-1a hashes unchanged):

  1. Shader::op_funcs cache (shader.rs): caches dx.op.<name> declarations in an FxHash map, skipping per-call Vec<Ty> / format! / type_ids / func_ids lookups, and moves the arg Vec into Module::call when sampler_choices does not match.
  2. Fast Module interning (bitcode.rs): switches internal type/constant/func maps to FxHash, caches primitive Ty ids (void, f32, i1, i8, i32, i64), and splits scalar constant interning (int/float/undef/aggregate) to avoid cloning on lookup hits while preserving replace_const semantics.
  3. Zero-copy Writer & flat Pred (bitcode.rs): writes bitstream directly into a pre-sized Vec<u8>, caches active abbreviation width, specializes vbr6, streams variable-length records/strings directly without temp Vec<u64> allocations, and replaces vec![Vec::new(); blocks] predecessor lists in Module::plan with a flat Pred enum.

Measured on 13f91ca (--release emit::bitcode::tests::bench_write, median of 3×5 runs, bit-for-bit identical FNV-1a hashes)

Synthetic module Size & FNV-1a hash (unchanged) Before (13f91ca) After Speedup
64 regs × 64 stages (4,417 insts) 38,956 B, 0xf0d59e83b39da635 214.8 µs 161.3 µs 1.33×
128 regs × 256 stages (33,569 insts) 252,532 B, 0x59610d0b12c34414 2.811 ms 1.978 ms 1.42×
256 regs × 512 stages (132,865 insts) 1,232,736 B, 0x82d39ac2b67ccb9f 21.11 ms 19.32 ms 1.09×

(Note: bench_write isolates Module::write() only and does not include the Shader::op / primitive-type / scalar-constant caching wins during lowering.)

Not a duplicate of

Verification

  • Verified on windows-latest MSVC + WARP SM 6.6 CI (both clippy -D warnings profiles, xtask policy 6/6, victory-shader 281/281 including written_bytes_unchanged, vbr6_and_str_records_match_generic_vbr, cached_primitive_types_and_constants_intern_and_replace, and op_caches_declarations_and_handles_sampler_choices): https://github.com/RVZO6/VIctory/actions/runs/45666985023
  • Not run: the title; any hardware GPU.

AI-assisted: T3 Code (Antigravity, gemini-4-neon)

…ar constants, and zero-copy bitcode Writer

Speed up DXIL module construction and LLVM 3.7 bitcode emission while
producing bit-for-bit identical output (all written_bytes_unchanged FNV-1a
hashes unchanged):
- shader.rs: cache dx.op.<name> declarations in Shader::op_funcs (FxHash),
  skipping per-call Vec<Ty>/format!/type_ids/func_ids work, and move the
  arg Vec into Module::call when sampler_choices does not match.
- bitcode.rs: switch internal type/constant/func interning maps to FxHash,
  cache primitive Ty ids (void/f32/i1/i8/i32/i64), split scalar constant
  interning (int/float/undef/aggregate) to avoid cloning on lookup hits
  while preserving replace_const semantics.
- bitcode.rs: write bitstream directly into a pre-sized Vec<u8> (zero-copy
  Writer::finish), cache active abbreviation width, specialize vbr6, stream
  variable-length records/strings directly without temp Vec<u64> buffers,
  and replace vec![Vec::new(); blocks] predecessor lists in Module::plan
  with a flat Pred enum.

Measured on 13f91ca (--release emit::bitcode::tests::bench_write, median
of 3x5 runs, bit-for-bit identical FNV-1a hashes):
- 64x64   (  4,417 insts,   38,956 B, 0xf0d59e83b39da635): 214.8 -> 161.3 us (1.33x)
- 128x256 ( 33,569 insts,  252,532 B, 0x59610d0b12c34414): 2.811 -> 1.978 ms (1.42x)
- 256x512 (132,865 insts, 1,232,736 B, 0x82d39ac2b67ccb9f): 21.11 -> 19.32 ms (1.09x)

Assisted-by: T3 Code (Antigravity, gemini-4-neon)
@kotekompotek

Copy link
Copy Markdown

Reviewed: local FxHash (same multiply-rotate constant as structure::Fx) for the bitcode maps plus cached op declarations/types — straight perf work in the emit hot path. CI green.

@oni-swr

oni-swr commented Nov 25, 2026

Copy link
Copy Markdown

Independent verification of #2665 (bitcode: cached Shader::op declarations, primitive types/constants, zero-copy Writer)

PR head 8105fdcfb68ac99d79ea728847a0f555b7a41521, merges cleanly onto origin/main 13f91caee25f2fdf2c062be5f7a27f058e51cbca.

Environment: Windows 11 Pro 10.0.26200, rustc 1.98.1, VICTORY_WARP=1 + VICTORY_D3D12_WARP=1 on every run (WARP adapter only, no physical GPU created), DXC/dxil 1.8.2502.11 (Windows SDK 10.0.26100.0, via VICTORY_DXIL), cargo ... -j 4 --locked.

Tests/clippy vs baseline. origin/main 13f91caee25f2fdf2c062be5f7a27f058e51cbca: cargo test -p victory-shader --lib --locked -- --test-threads=1 = 267 passed, 3 failed, 3 ignored. The 3 failures are WARP limits and are the same 3 in every variant below: a_mask_joined_with_data_at_a_uniform_loop_is_its_number and permutes_read_the_lane_named_and_zero_from_lanes_left_out ("no pipeline for a wave of 32"), and gathers_at_a_level_match_the_hardware (WARP gather result differs). Clippy: cargo clippy -p victory-shader --all-targets --locked = 0 warnings.
With #2665: 270 passed, 3 failed (same 3), 4 ignored (+3 tests, +1 ignored benchmark). Clippy: 0 warnings.

Equivalence. Full diff read. is_void now compares against the cached ty_void; that is sound because void() is the only place that creates TypeDef::Void. Module::function already returns the existing declaration by name, so caching dx.op.<name> in op_funcs returns the same function (the only difference would be an unused function type no longer interned if one name were ever requested with different argument types). vbr6 / record_str / record_id_str are checked against the generic vbr path; the Writer block-length patching and abbrev-width stack are equivalent. All emit callers use widths <= 32, which the new debug_assert! (debug builds only) relies on. Output check with the throwaway hashing patch: the same 650 containers are byte-identical to origin/main; the only difference is one extra container from this PR's own new test (op_caches_declarations_and_handles_sampler_choices). bench_write also prints identical FNV hashes of the written bytes for 3 large synthetic modules on base and with the PRs.

Perf (release, combined run vs base). shader::op 4096 calls: 2837 / 2935 us -> 559 / 531 us; bench_write 64 regs x 64 stages: 309 / 306 us -> 228 / 177 us; 256 x 512: 9.8 / 8.9 ms -> 7.0 / 7.1 ms.

Findings: no bugs. Nit: the new Fx in bitcode.rs duplicates structure::Fx (its doc says "matching"); sharing one would avoid drift. The test module now compiles on non-Windows (#[cfg(test)]); the Windows-only helpers stay gated.

Limits: no physical GPU (WARP only), no game files; the 3 WARP-limited tests above are therefore not verified on hardware. Benchmarks are synthetic, release mode, one machine, two back-to-back rounds each for base and combined; they say nothing about real-title shaders.

AI-assisted: independent verification by Claude Code / Claude Sonnet 5.5, run on behalf of oni-swr. Claims for #1633.

@oni-swr

oni-swr commented Nov 25, 2026

Copy link
Copy Markdown

Composition check: #2662 + #2664 + #2665 together

Heads: #2662 95f56a53f8ff90f700d74d102ad79538bad68771, #2664 e6ab345e7b73be37a0741a54767e061aad35239c, #2665 8105fdcfb68ac99d79ea728847a0f555b7a41521, merged in that order onto origin/main 13f91caee25f2fdf2c062be5f7a27f058e51cbca as a local merge commit (31ed3543e4c18b978f7b0a699a71f8d18e52a81b, not pushed). No conflicts: the three touch disjoint files (structure.rs; gfx10/fields.rs + ir.rs; emit/bitcode.rs + emit/shader.rs).

Environment: Windows 11 Pro 10.0.26200, rustc 1.98.1, VICTORY_WARP=1 + VICTORY_D3D12_WARP=1 (WARP only), dxil 1.8.2502.11 (SDK 10.0.26100.0), -j 4 --locked.

  • cargo test -p victory-shader --lib --locked -- --test-threads=1: 276 passed, 3 failed, 5 ignored. That is exactly baseline 267 + 2 + 4 + 3 new tests; the 3 failures are the same WARP-limited ones as on origin/main (wave-of-32 x2, WARP gather).
  • cargo clippy -p victory-shader --all-targets --locked: 0 warnings.
  • Emitted containers over the lib test run: 650 byte-identical to origin/main, plus one extra from Shaders/Bitcode: cache Shader::op declarations, primitive types, scalar constants, and zero-copy bitcode Writer #2665's new test (throwaway hashing patch, not committed).
  • Perf (release, combined vs base, 2 rounds each): shader::op 4096 calls 2.84-2.94 ms -> 0.53-0.56 ms; ir::build 2048 insts 2.24-2.29 ms -> 1.80-1.84 ms; 64 movrel insts 426-456 us -> 88-103 us; bitcode writer, 256x512 synthetic module, 8.9-9.8 ms -> 7.0-7.1 ms; BDD given n=13 ~465 us -> ~0.45 us (synthetic).
  • No interaction bugs found. The merge order does not matter (disjoint files).

Limits: no physical GPU, no game files; synthetic benchmarks only.

AI-assisted: independent verification by Claude Code / Claude Sonnet 5.5, run on behalf of oni-swr. Claims for #1633.

@fuzeofficlal

Copy link
Copy Markdown
Contributor

Independent Windows 11 + NVIDIA GeForce RTX 5090 + WARP + dxil.dll verification, code review, and same-machine --release benchmark comparison of 8105fdcf (on 13f91ca):

Hardware + Validator Verification (rustc 1.98.1 MSVC, Windows SDK 10.0.26100.0 dxil.dll)

  • cargo clippy --locked -p victory-shader --all-targets -- -D warnings: 0 warnings.
  • cargo clippy --locked -p victory-shader --all-targets --features host -- -D warnings: 0 warnings.
  • cargo test --locked -p victory-shader --lib emit::bitcode::tests -- --nocapture: 14 passed, 0 failed, 1 ignored (bench_write), including vbr6_and_str_records_match_generic_vbr and cached_primitive_types_and_constants_intern_and_replace.
  • cargo test --locked -p victory-shader --lib -- --skip heap_direct_texture_reads_mark_their_heap_index (exercises both RTX 5090 hardware and WARP with dxil.dll active): 269 passed, 3 failed, 4 ignored. All 3 failures are the pre-existing RTX 5090 baseline mismatches (a_heap_buffer_read_by_element_takes_the_views_stride, a_heap_buffer_read_where_no_buffer_view_is_reads_zeros, gathers_at_a_level_match_the_hardware), and heap_direct_texture_reads_mark_their_heap_index is the pre-existing RTX 5090 0xc0000005 baseline crash (Shader tests: heap_direct_texture_reads_mark_their_heap_index kills the test process on a real GPU (RTX 5070, main 67e8ae1) #2571); all 3 new PR tests (including op_caches_declarations_and_handles_sampler_choices), WARP, and dxil.dll validation passed with 0 regressions.

Same-Machine --release Benchmark (13f91ca vs 8105fdcf, bit-identical output & FNV-1a checksums)

bench_write case Output size & FNV-1a 13f91ca 8105fdcf Speedup
64 regs x 64 stages (4,417 insts) 38,956 B, 0xf0d59e83b39da635 173.16 µs 116.58 µs 1.49x
128 regs x 256 stages (33,569 insts) 252,532 B, 0x59610d0b12c34414 1.5255 ms 888.86 µs 1.72x
256 regs x 512 stages (132,865 insts) 1,232,736 B, 0x82d39ac2b67ccb9f 10.2087 ms 8.2122 ms 1.24x

emit::shader::tests::bench_op_calls (4096x): 336.6 µs/run.

Code Review Notes

  • No bugs, cache-key collisions, or unsafe blocks found: int_consts keys on (Ty, i64), float_consts keys on raw u32 bits (preserving +0.0/-0.0 and distinct NaN payloads), and all caches are strictly per-instance (Shader/Module/Writer) with no shared static state.
  • Writer word-alignment, nested block length backpatching, emit (bits + width <= 63), and vbr6 (bits + 6 <= 37) match the prior Vec<u32> writer bit-for-bit.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Merge candidate (performance, same output). In crates/victory-shader/src/emit/shader.rs, Shader::op caches its dx.op.* declarations by name. That is equivalent, because Module::function already returns the existing declaration for a name. In crates/victory-shader/src/emit/bitcode.rs:

  • the type, constant and function maps use an Fx hasher;
  • primitive types are cached and constants are interned per kind; replace_const is unchanged;
  • Module::plan keeps one predecessor or "many" instead of lists, which is all plan reads;
  • Writer writes bytes directly, with a specialised vbr6 and string records.

I checked that every emit width stays at 32 or below, which the single-flush emit relies on, and that block lengths are still back-patched in words. Testers report the written_bytes_unchanged hashes and all lib-test containers byte-identical. It merges cleanly, including together with #2657 (same file); CI check: passing.

Nit, not blocking: the new Fx duplicates structure::Fx; sharing one would avoid drift.


Generated by Claude Code

Airamek added a commit to Airamek/VIctory that referenced this pull request Nov 25, 2026
…visak#2665)

Port of upstream Marvisak#2665's bitcode.rs: a local FxHash-based Map
replaces std HashMaps on the interning hot path; primitive types
(void/i1/i8/i32/i64/float) are cached in Option<Ty> slots; the
single (Ty, Const) const map splits per kind (int/float/undef/
aggregate) so lookups skip cloning and mismatched variants; the
bitstream Writer goes from Vec<u32> words to a Vec<u8> byte
buffer with a cached abbrev width and an inlined vbr6 fast path,
and every record/phi/call site streams operands through
record_header/record_str/record_id_str instead of building temp
Vecs (reused phi_ops scratch kept).

Adaptation: the PR's shader.rs op_funcs cache is NOT taken: this
tree already carries a fuller op_decls LRU (name+attr+ret+opcode+
arg types, move-to-front, 48 entries) which subsumes it. Took
instead the PR's test-module widening (cfg(test) with
windows-only items gated) plus its two cross-platform tests
adapted to op_decls (op_caches_declarations_and_handles_sampler_choices,
bench_op_calls). Behavior note: Module::function() already dedupes
by name ignoring later signatures, and func_ty/ptr interning is
value-deduped, so declaration caching cannot change which V or
type IDs are produced -- only how fast.

Correctness: op_caches test + full shader suite (293 passed,
incl. validator + byte-exact diff tests, which pin the emitted
bitcode).

Microbench (release, this machine, bench_op_calls 4096 ops:
1304.6 -> 777.3 us/run (-40%). Base measured with the same bench
on the parent commit.

@Dukestar69 Dukestar69 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.

Tested merged onto origin/main (63bcca4) on Windows 11 x64:

  • cargo test -p victory-shader --lib emit::bitcode::tests: 14 passed, 0 failed, 1 ignored (including new vbr6_and_str_records_match_generic_vbr and cached_primitive_types_and_constants_intern_and_replace).
  • cargo test -p victory-shader --lib emit::lower::tests: 33 passed, 0 failed.
  • cargo clippy -p victory-shader --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

BastienRodz added a commit to BastienRodz/VIctory that referenced this pull request Nov 26, 2026
…clarations, primitive types, scalar constants, and zero-copy bitcode Writer
Moon0755 pushed a commit to Moon0755/VIctory that referenced this pull request Nov 26, 2026
@rezioliver-collab

Copy link
Copy Markdown

Graph construction accounted for most of the gain in a synthetic compute shader that repeatedly used the same DXIL operation declaration. On Apple M1, building the largest graph went from 2.102 ms to 0.308 ms. Including Shader::finish(), the total went from 2.988 ms to 0.998 ms.

Branch-and-join stages Graph construction speedup Build + finish speedup
4 4.41× 2.44×
32 6.59× 2.98×
256 6.83× 2.98×

I built the same graphs on 13f91cae and 8105fdcf, with eight dependent integer operations per arm, a phi at each join and a final shared-memory store. The complete DXBC containers were byte-identical for all three sizes. These are median base/PR ratios from 12 alternating release pairs on macOS 14.7, Rust 1.98.1. The timed path starts at graph construction and ends with container emission.

@fuzeofficlal fuzeofficlal 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.

Reviewed at 8105fdcfb68ac99d79ea728847a0f555b7a41521 — APPROVE.

Verification

  • cargo xtask policy (191 files ok) and cargo clippy -p victory-shader --all-targets --all-features -- -D warnings passed cleanly.
  • Verified primitive type slots, scalar constant interning ((Ty, i64) separating i1/i8/i32/i64; raw u32 bits in float_consts preserving -0.0 vs +0.0 and distinct NaN payloads), and zero-copy Writer bit-packing, vbr6, record_str, align, and block-length backpatching against the generic Writer path (vbr6_and_str_records_match_generic_vbr and written_bytes_unchanged pass).
  • Targeted tests (emit::bitcode::tests 14/14, emit::shader::tests 2/2, emit::lower::tests 33/33) and full victory-shader runs under both VICTORY_WARP=1 and VICTORY_WARP=0 matched origin/main baseline parity with no regressions introduced.

Non-blocking notes

  • Shader::op (crates/victory-shader/src/emit/shader.rs:243) inherits Module::function's name-only keying (crates/victory-shader/src/emit/bitcode.rs:416), so adding a debug assertion that cached declarations match ret, parameter types, and attr would catch any accidental overload collision early.
  • Module::replace_const (crates/victory-shader/src/emit/bitcode.rs:409) continues to leave prior intern-map entries untouched (safe today because fix_user_data_size runs at finalization with no subsequent lookups of the placeholder constant).
  • Minor rustfmt wrapping difference in the new ignored benchmark shader.rs:1150, and op_caches_declarations_and_handles_sampler_choices (shader.rs:1125) only checks chosen != r1 rather than verifying the select emission directly.

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