Skip to content

shader/emit: cache immediate sampler handles in entry block (D3D12-SHADER-SAMPLER-HANDLE-CACHE) - #2862

Merged
OreoFR merged 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/shader-sampler-handle-cache
Dec 1, 2026
Merged

OreoFR merged 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/shader-sampler-handle-cache

Conversation

@djrolfes

@djrolfes djrolfes commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D12-SHADER-SAMPLER-HANDLE-CACHE (claim comment)

What and why

Cache immediate sampler handles (createHandleFromBinding + annotateHandle) once in self.entry inside Shader::sampler_handle (d3d12/crates/leonida-shader/src/emit/shader.rs), bringing it into parity with root_cbv_handle, root_srv_handle, and root_uav_handle.

  • Why: On main, root_cbv_handle, root_srv_handle, and root_uav_handle already emit their binding handle once in self.entry and cache it, whereas sampler_handle emitted a fresh createHandleFromBinding + annotateHandle pair at every call site in every basic block.
  • Change: Adds sampler_handles: Vec<(u32, bool, V)> keyed by (slot, is_cmp) (with n < u64::BITS guard before shifting self.cmp_samplers), emits the handle pair in self.entry (which dominates all blocks), and returns the cached handle on subsequent calls. Completely orthogonal to open PR #2687 (which hoists createHandleFromHeap, not createHandleFromBinding).
  • Evidence classification: READ IN CODE (d3d12/crates/leonida-shader/src/emit/shader.rs:526–625) + red→green unit test verifying handle reuse across sibling branches and valid DXIL serialization + MEASURED 300 s in-game gate (2 consecutive 310 s PASS runs) on exact PR head acae5b879.

Tested

  • python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-shader/src/emit/shader.rs → exit 0.
  • Native Linux cargo test --locked -p leonida-shader:
    • RED on origin/main (only the new #[cfg(test)] module applied, no production change):
      running 1 test
      test emit::shader::tests::sampler_handle_is_emitted_once_in_entry_and_cached ... FAILED
      # assertion `left == right` failed: same sampler slot must reuse cached entry handle
      #   left: Inst(1)
      #  right: Inst(3)
      test result: FAILED. 0 passed; 1 failed; 0 ignored
      
    • GREEN on PR head acae5b879 (rebased onto cd73ddab7):
      running 245 tests
      ...
      test emit::shader::tests::sampler_handle_is_emitted_once_in_entry_and_cached ... ok
      test result: ok. 243 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out
      
  • 300 s in-game gate (docs/game_gate.md) on exact PR head acae5b879 (leonida.exe --profile play --features mimalloc,dlss,diagnostics, Series S + DLSS Quality 1280×720 → 1920×1080):
    • Verdict: PASS (2 consecutive 310 s runs; note that because this PR modifies the emitted DXIL for sampler-using shaders, host PSO compilation was still draining 1,155 → 422 in the background during Pass 2, accounting for the lower transient median FPS compared to fully-cached non-DXIL-changing builds)
    • Pass 2 (primary gate):
      • In-world duration: 310.14 s (world_at_s = 79.39 s, >= 300 s required)
      • Frames (world + 60 s to stop): 719 presented frames (759 total world presents), 7.22 median FPS (9.00 end-window median FPS as background PSO compilation drained), 1,674.72 ms p95 frame time (4,445.5 median draws/frame)
      • Longest present gap in world: 5.127 s (<= 10.0 s required)
      • Peak VRAM: 6,299 MiB (<= 7,400 MiB guard)
      • Stability: 0 device losses, 0 crashes/faults, 0 panics, 0 kernel NVRM: Xid errors
    • Pass 1 (initial cold shader re-translation): PASS (311.00 s in-world, 386 frames, 5.21 median FPS, 8.672 s longest present gap, 6,043 MiB peak VRAM, 0 device losses/crashes/faults/panics/Xids)

GPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0).

AI-assisted: yes (authored by Gemini 4 Neon; audited and approved in a separate independent review pass by Gemini 4 Neon).

Checklist

  • Based on current main (cd73ddab7) and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (check_no_game_data.py clean).
  • A new translator rule is in the contract table of docs/design.md (n/a — entry-block handle caching matching existing root handle helpers).
  • Independent fresh reviewer agent audit completed (APPROVED).
  • 300 s in-game gate completed and PASSED on exact PR head (acae5b879).

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent Rust check of acae5b879 on 21e6bbf4b. The added fixture failed on upstream because the same immediate sampler slot used in two sibling blocks produced distinct handle instructions. With the PR, both the ordinary and comparison sampler handles are reused across the two blocks.

I ran the full native leonida-shader unit suite with #2861 and #2864 also applied. It passed 250 tests, with 2 ignored. This checks IR construction and reuse. Driver performance was outside the run.

AI-assisted with OpenAI Codex.

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

The hoist is sound: only immediate (Source::Constant) samplers reach this helper, bound as root-signature static samplers, so the binding is uniform and valid at entry, and entry dominates every block. Loop and branch-chosen cases behave (same slot dedups; distinct slots get their own handles and a uniform phi picks one). 406/0/5 here.

Three things:

  1. cmp in the key is redundant. register_sampler already gives a distinct slot per (descriptor words, cmp) and sets the bit before returning it, so the slot alone identifies the sampler — dropping cmp changes nothing and all sampler tests still pass. Either drop it or say in the comment that the cache relies on that slot↔descriptor invariant.
  2. _block is now dead (four call sites still pass self.cur/arm). Remove the parameter so nobody reintroduces "create in the use block" by mistake.
  3. The new test does not test placement. Replacing let block = self.entry with let block = _block leaves the whole 406-test suite green, even though a handle created in one branch and reused in a sibling is a dominance violation — the test is named …emitted_once_in_entry… but never inspects the block and never uses the handle. Either assert the instruction lives in entry (a small Module accessor) or drive a real sampleLevel from two sibling blocks and validate with dxil.dll, as waterfall_tests::immediate_sampler_chosen_by_control_flow already does.

Also: assert_ne!(h0_a, h1_a) passes even with the cache keyed by cmp alone (slot 0 non-cmp vs slot 1 cmp); two samplers of the same kind would pin the slot field.

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

RUN (native Windows 10 + RTX 5070 verification; #2857, #2860, and #2862 merged cleanly together onto main ed867d7b2)

  • Unit test: cargo test --locked -p leonida-shader --lib sampler_handle_is_emitted_once_in_entry_and_cached: 1 passed, 0 failed.
  • In-game gate: Series S, -NoFrameGen, 731.6 s cold precompile, 180 s in world (321.3 s total, 38 world samples >= 1000 draws, median 22.2 fps / 45.1 ms, gpu_wait 0.0 ms, 4,424 median / 5,346 max draws): 0 crashes, 0 panics, 0 device-lost events.

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (driver 621.40, Windows 10 Pro 22H2 build 19045, Ryzen 9 5950X 16C/32T)

AI-assisted: Antigravity

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2862 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The change does what it says, and it also closes a debug-build panic that the pull request does not mention.

Head acae5b87, base the current main 88a9f133, merge base cd73ddab, 1 commit, 1 file, +49/−8: d3d12/crates/leonida-shader/src/emit/shader.rs.

1. What it changes

sampler_handle used to emit a fresh createHandleFromBinding every time it was called, in whatever block the caller was in:

// main
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
    …
    let h = self.op(block, "createHandleFromBinding", …);
    …
}

The pull request emits one handle per (slot, is_comparison) and always in the entry block:

pub fn sampler_handle(&mut self, _block: usize, n: u32) -> V {
    let is_cmp = n < u64::BITS && self.cmp_samplers >> n & 1 != 0;
    if let Some(&(_, _, h)) = self.sampler_handles.iter().find(|&&(slot, c, _)| slot == n && c == is_cmp) {
        return h;
    }
    …
    let block = self.entry;
    let h = self.op(block, "createHandleFromBinding", …);
    …
    self.sampler_handles.push((n, is_cmp, h));
    h
}

The callers pass the block they are in — lower.rs:9642 passes self.cur, lower.rs:13816 passes arm (a switch arm's block) — so before this change the same sampler slot asked for from two different blocks produced two handles, each valid only in its own block. Putting the one handle in the entry block, which dominates everything, is the scope-correct place for it.

2. Red and green, and the discrimination

cargo test -p leonida-shader on the pull request's branch: 243 passed, 0 failed, 2 ignored.

With only the cache lookup removed (the pull request's test kept):

test emit::shader::tests::sampler_handle_is_emitted_once_in_entry_and_cached ... FAILED
  panicked at crates/leonida-shader/src/emit/shader.rs:1206:9:
  assertion `left == right` failed: same sampler slot must reuse cached entry handle
test result: FAILED. 0 passed; 1 failed

3. The panic this also fixes

The new code guards the comparison-sampler bit with n < u64::BITS; main did not:

// main
let cmp = if self.cmp_samplers >> n & 1 != 0 { 0x8000 } else { 0 };

self.cmp_samplers is a u64, so >> n with n >= 64 is an overflow. In a debug build that is a panic. I called it directly:

# main's code
test emit::shader::tmp_shift_test::shift_overflow_at_64 ... FAILED
  panicked at crates/leonida-shader/src/emit/shader.rs:618:22:
  attempt to shift right with overflow

# the pull request's code
H64_OK
test result: ok. 1 passed

This is the same family as #2858 (an unchecked arithmetic operation on a value the title controls, reaching a panic), and it is not mentioned in the pull request's own text. Whether n can reach 64 in practice depends on how many samplers a shader may declare; I did not trace that bound, but the guard is correct either way.

4. What the new test does not check

The test is called sampler_handle_is_emitted_once_in_entry_and_cached, and it checks the caching (assert_eq!(h0_a, h0_b, …)) — but it does not check the "in entry" part. That half is not checked because it cannot easily be: Module::blocks is private to the bitcode module, so from emit::shader::tests there is no way to look at which block the instruction went into. I confirmed that by trying:

error[E0616]: field `blocks` of struct `bitcode::Module` is private
  --> crates/leonida-shader/src/emit/shader.rs:1223:30

The placement is unambiguous in the code (let block = self.entry; immediately before the self.op(block, "createHandleFromBinding", …) call), so I am not asking for a change — but a reader should know that the name promises more than the test delivers.

5. What I did not check

  • A real shader translation. Everything above is the crate's unit tests over hand-built modules; I did not translate a game shader (they are not in the repository), so I did not measure the instruction count the caching saves, nor check a translated shader's DXIL for validity.
  • Whether the emitted handle is correct for a shader that samples the same slot with and without a comparison, i.e. the (slot, cmp) key. The test checks that two slots give two different handles and that one slot gives one handle; it does not check that a comparison sampler and a plain sampler for the same slot would be distinguished — the key does include cmp, but I did not build that case.
  • The other crates in the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows Linux: build leonida.exe and run it under Proton or Wine #2577"), so I ran leonida-shader on its own.
  • cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

@OreoFR
OreoFR merged commit bc33232 into ProjectLeonida:main Dec 1, 2026
5 checks passed
@OreoFR

OreoFR commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Merging as part of a group. Head acae5b8; the group branch main 1e3e316 + #2862 + #2824 + #2873 (7988c1c, merged in that order) passed the full CI (https://github.com/OreoFR/leonida/actions/runs/46740411028, the same workflow file as here, run on that branch) and No Game Data (https://github.com/OreoFR/leonida/actions/runs/46740416586); main was 1e3e316 with its CI green when the group merged. Claim: D3D12-SHADER-SAMPLER-HANDLE-CACHE (#2570 (comment)). Red/green: merzleckeier (fixture fails on main, passes on this head), imShangLi (Linux, PASS), KelboLive review on this head. I ran: the five PRs #2860-#2862, #2824 and #2873 merged together onto main ab374c7 (main since gained only #2935, a CI workflow change, and #2860 and #2861, both part of that test), with the shader (418 passed, 0 failed), gpu (644/0) and hle (247/0) cargo tests. In-game run: RTX 4070 Laptop 8 GB, NVIDIA 621.40, a cold start to the world then a 330 s warm walking run, 0 device lost, no panic. CI: green on head, main and the group branch. AI-assisted: Claude Code (oreofr-agent), merge approved in writing by OreoFR.

@enlight3d

Copy link
Copy Markdown
Contributor

RUN, posted after the merge: the review points below are for a follow-up. (independent run on Windows, #2862 head acae5b8, merged locally into main 0ff8a53 with git merge --no-ff, no conflicts. CI on the head: change-scope, check, linux-python-and-viewer, no-game-data and semantic-tests all pass.)

Commands, in d3d12/, target x86_64-pc-windows-gnu (the host this machine's rustup selects; CI builds x86_64-pc-windows-msvc), toolchain 1.98.1, all with --locked, at low priority, RUST_TEST_THREADS=8:

  • cargo test -p leonida-shader --no-fail-fast: main 414 passed / 0 failed / 5 ignored; merge 415 / 0 / 5 (the new test). Some of these tests run on the GPU, here an RTX 3090; host_forms_give_what_the_spelled_out_ones_give passes on both sides.
  • cargo test -p leonida-shader --no-fail-fast --features diagnostics: main 414 / 0 / 5; merge 415 / 0 / 5.
  • Red, by assertion: main's shader.rs with this pull request's test module appended. cargo test -p leonida-shader --lib emit::shader::tests fails on "same sampler slot must reuse cached entry handle", left Inst(1), right Inst(3): the values in the body.
  • Mutation: the handle cached but made in the block of the first caller (let block = _block; in place of let block = self.entry;), so a second use in a sibling block reads a value its block is not dominated by. The new test passes; the whole-crate run was not done here (the card was busy with game runs); its GPU tests build sampler-using programs for the card, so it is the run that could still catch this. The test checks reuse and that finish() returns bytes, but finish() does not check that a definition dominates its uses, so the "in entry" half of the test's name is not pinned. Checking that the createHandleFromBinding lands in s.entry, or validating the container with the DXIL validator (which refuses such a use), would pin it.
  • Green: the file restored (git status clean), cargo test -p leonida-shader --lib emit::shader::tests: 1 passed.
  • cargo clippy -p leonida-shader --all-targets, default and --features diagnostics, on main and on the merge: 6 warnings on each side, the same set (all in valu_tests.rs), none in the changed lines.
  • python -I tools/d3d12_switches.py --check d3d12/docs/switches.md is clean on the merge (no switch added).
  • Read: the placement holds for the same reasons as for the root CBV/SRV/UAV handles. The module has one function with a body (main), and s.entry only moves before the program's blocks are lowered (the thread-count and packing preludes in run point it at their body block, which then becomes the program's first block), so a handle made there dominates every block lowered after it. The n < u64::BITS guard also removes the shift overflow for a slot of 64 or more (a panic in a debug build before). The block parameter is now unused (_block) while the callers still pass one.
  • Not covered here: the game, and DXIL validation or driver timing of real sampler-using programs with the handles in the entry block.

Machine: Windows 11 Pro 26300, i9-13900K, 64 GB, RTX 3090 24 GB, NVIDIA 621.40, Rust 1.98.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants