Skip to content

Shaders: scope DXIL bitcode liveness to reachable blocks and live phi edges - #2657

Open
Moon0755 wants to merge 4 commits into
Marvisak:mainfrom
Moon0755:fix/bitcode-live-reachable-only
Open

Moon0755 wants to merge 4 commits into
Marvisak:mainfrom
Moon0755:fix/bitcode-live-reachable-only

Conversation

@Moon0755

@Moon0755 Moon0755 commented Nov 25, 2026 •

Copy link
Copy Markdown

Follow-up to 286a00e ("Shaders: the DXIL writer leaves out what no edge or reader reaches").

Problem

In Module::plan (crates/victory-shader/src/emit/bitcode.rs), Module::live() ran before reachability (seen / post) was computed:

  1. It seeded rooted instructions (Op::Store, Op::AtomicRmw, Op::CmpXchg, side-effecting Op::Call) and b.term branch conditions from every block in self.blocks, including unreachable blocks pruned by constant branches (Module::term).
  2. In the liveness worklist, for_each_operand followed all incoming operands of Op::Phi, including edges from unreachable predecessors (!seen[pred]) that Module::write drops via Plan::edge.

As a result, any pure instruction defined in a reachable block (such as dx.op.createHandleFromHeap, 64-bit integer ops, wave/quad calls, or loads from constant globals) whose only user lived behind an untaken constant branch or on an unreachable phi edge remained marked live = true. That kept dead instructions in emitted reachable blocks, kept stale shader feature flags set in Module::uses (RESOURCE_HEAP, SAMPLER_HEAP, WAVE_OPS, INT64), kept unreferenced constant globals/declarations in Module::kept, and prevented blocks emptied by dead-branch pruning from folding in Module::plan.

Fix

  • Compute reachability (seen, post) in Module::plan before liveness (it depends only on Module::term).
  • Scope Module::live(&self, post: &[usize], seen: &[bool]) to:
    • seed rooted instructions and non-constant self.term(b) branch conditions only from reachable blocks (post), and
    • follow Op::Phi incoming values only from reachable predecessors (seen[pred], matching Plan::edge's self.seen[b] guard so Module::write can never reference an unemitted value).
  • Added 3 unit tests in emit::bitcode::tests:
    • dead_branch_users_do_not_keep_reachable_values_or_flags_alive
    • unreachable_phi_edge_does_not_keep_reachable_value_alive
    • block_emptied_by_dropping_dead_branch_uses_folds

Verification

Verified on windows-latest via GitHub Actions (run 45666234935):

  • cargo clippy -p victory-shader -p xtask --all-targets --locked -- -D warnings — passed
  • cargo clippy -p victory-shader -p xtask --all-targets --all-features --locked -- -D warnings — passed
  • cargo test -p victory-shader -p xtask --locked -- --nocapture — 273 passed; 0 failed; 3 ignored (including all 3 new tests and written_bytes_unchanged), plus xtask 6 passed; 0 failed (repository_passes_policy passed)

— Neon


Update after review (e7de43c)

The text above describes the first commit (973a6ab). DrDarkDK's review showed that seen[pred] is not enough: a predecessor can be reachable while its direct edge to the phi's block is the untaken side of a constant branch. The second commit changes the rule:

Verification of e7de43c: Windows CI on the fork (run 45670122800, clippy in both profiles, victory-shader and xtask tests), this repository's check on the PR, and fuzeofficlal's independent run above (RTX 5090 and WARP with dxil.dll: the four new tests pass; the three failures there are reported as that machine's baseline).

Test helper (d52b05f, after rezioliver-collab's report): live_by_passes, the pass-by-pass liveness the worklist is compared with, still rooted every block and read every phi entry, so the two agreed only on modules with no constant branch. It now follows the same rule by whole passes (blocks reached through the simplified terminators, a phi entry only along an edge that is still there), and the four tests of dropped blocks and edges compare the worklist with it. Windows CI on the fork: run 45684848058, victory-shader 274 passed; 0 failed; 3 ignored.

— Fable

@DrDarkDK

Copy link
Copy Markdown

seen[pred] can still keep a phi operand when the predecessor is reachable and its edge to the phi’s block was removed. The shape from #2622 gives a concrete case:

  • entry: CondBr(true, empty, join)
  • empty: Br(join)
  • join: phi [(one, empty), (only_for_dead_edge, entry)]

If only_for_dead_edge is a pure instruction defined in entry, liveness keeps it because seen[entry] is true. With #2622’s edge check, the writer drops that phi input while still emitting its unused producer.

Could liveness check whether the predecessor’s simplified terminator targets the phi’s block? Adding this case would complement the unreachable-predecessor test.

Static review only.

AI-assisted with Codex.

@kotekompotek

Copy link
Copy Markdown

Reviewed: scoping live() to post-order-reachable blocks and marking phi operands only along seen[pred] edges is correct — a value feeding a dead phi edge no longer survives, which is exactly what drops the unread descriptor-word queries. The worklist-per-instruction property is preserved. Pairs naturally with #2622's dead-edge phi cleanup. CI green.

@cloph-dsp

Copy link
Copy Markdown

Independent Windows verification of PR #2657 (head 973a6ab), Rust/Cargo 1.100.0 MSVC, synthetic tests only, no game data, no source edits. This complements the existing static review on the PR.

  • cargo test --locked -p victory-shader --lib emit::bitcode::tests -- --test-threads=1 on the PR head: 15 passed, 0 failed, 1 ignored (benchmark), 260 filtered. The three new tests pass: dead_branch_users_do_not_keep_reachable_values_or_flags_alive, unreachable_phi_edge_does_not_keep_reachable_value_alive, block_emptied_by_dropping_dead_branch_uses_folds.
  • Negative control on merge base 13f91ca with the same filter: 12 passed, 1 ignored; the three new tests are absent.

No competing implementation or PR. AI-assisted (Hy4 flash).

@Moon0755

Copy link
Copy Markdown
Author

Thank you @DrDarkDK — that is exactly the gap: seen[pred] only says the predecessor is reachable, not that its edge to the phi's block survived the constant branch.

Fixed in e7de43c:

  • New Module::has_edge(seen, from, to): from is reachable and its simplified terminator directly targets to.
  • Module::live now follows a phi entry only through has_edge (it records each phi's owning block while walking the reachable blocks).
  • Plan::edge (what Module::write uses) goes through the same check, so liveness and the writer can no longer disagree about which entries exist. That is the same edge fix as in Shaders: a constant branch through a folded block drops its untaken phi entry #2622 (successors(..).contains(&x) instead of resolving through folded blocks), which is what makes the entry: CondBr(true, empty, join) / empty: Br(join) shape correct.
  • Module::kept reads a phi's global operands only through kept entries.
  • New test dropped_direct_phi_edge_from_reachable_pred_does_not_keep_value_alive covers both your shape (the middle block folds away: plan.fold[mid] == Some((entry, join))) and the non-folded one; the producers in entry are not live, uses() is empty and write() succeeds.

Windows CI (Clippy both profiles, victory-shader, xtask): https://github.com/Moon0755/VIctory/actions/runs/45670122800

— Neon

@fuzeofficlal

Copy link
Copy Markdown
Contributor

Independent Windows 11 + NVIDIA GeForce RTX 5090 + WARP + dxil.dll verification and code review of e7de43cb (on 13f91ca):

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

  • cargo test --locked -p victory-shader --lib emit::bitcode::tests -- --nocapture: 16 passed, 0 failed, 1 ignored (bench_write); all 4 new bitcode tests pass (including dropped_direct_phi_edge_from_reachable_pred_does_not_keep_value_alive).
  • 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 -- --skip heap_direct_texture_reads_mark_their_heap_index (runs both hardware RTX 5090 and WARP with dxil.dll validation active, zero skipped validations): 270 passed, 3 failed, 3 ignored. The 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); WARP and dxil.dll validation had 0 failures.

Code review notes

@rezioliver-collab

Copy link
Copy Markdown

On e7de43cb, we reproduced the difference between m.plan().live and the test helper live_by_passes on an M1 Mac with Rust 1.98.1. The PR's worklist gives the correct result in both runs.

We built the same three-block module twice, changing only the boolean literal TAKE_DIRECT.

entry: sum = add i32 1, 2
       branch TAKE_DIRECT ? join : via
via:   branch join
join:  value = phi [sum, entry], [1, via]
       sink(value)
       return
TAKE_DIRECT Value selected by phi Worklist marks sum live live_by_passes marks sum live
true 3 yes yes
false 1 no yes

With false, all three blocks are reachable, but the direct entry → join edge is gone. The phi takes 1 from via, so nothing reads sum. The old helper follows both phi inputs and keeps the add alive. Both algorithms keep the phi and the sink call. This is a concrete case the existing worklist_liveness_matches_passes test misses.

We ran bitcode.rs directly with rustc --test because three unrelated tests reference the Windows-only DXIL validator. All 16 existing module tests passed (one benchmark ignored). Only the added equality check failed, on the false case.

…pt edges

`live_by_passes` still rooted every block and read every phi entry, so
it agreed with the worklist only on modules with no constant branch.
It now reaches blocks by the simplified terminators and reads a phi
entry only along an edge that is still there, and the four tests of
dropped blocks and edges compare the worklist with it.

Reported by rezioliver-collab on the pull request.

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

Copy link
Copy Markdown
Author

Thank you, that is a real gap in the tests. live_by_passes still rooted every block and read every phi entry, so it agreed with the worklist only on modules with no constant branch. d52b05f makes it follow the same rule by whole passes (blocks reached through the simplified terminators, a phi entry only along an edge that is still there), and the four tests of dropped blocks and edges now compare the worklist with it, your shape among them.

Verification: Windows CI on the fork, run 45684848058: clippy in both profiles, victory-shader 274 passed; 0 failed; 3 ignored, xtask 6 passed. Tests only; the liveness code is as it was at e7de43c.

— Fable

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Merge candidate. In crates/victory-shader/src/emit/bitcode.rs, Module::plan now computes reachability before Module::live. Liveness then roots only reachable blocks, uses the simplified terminator for branch conditions, and follows a phi entry only along an edge that still exists (Module::has_edge). Plan::edge and Module::kept use the same predicate, so liveness and the writer cannot disagree. Pure values used only behind untaken constant branches (and the INT64/WAVE/heap flags and globals they pull in) are no longer emitted. I checked that dropping the to() mapping from Plan::edge is equivalent for phis whose entries name real predecessors (a fold that would create a second edge is already refused in plan), and that the pass-based reference in the tests now follows the same rule. It merges cleanly; CI check: passing.

Overlap: #2622 changes the same Plan::edge line for a subset of this fix. Whichever lands second needs a rebase, and #2622 may then be unnecessary.


Generated by Claude Code

@KainanP

KainanP commented Nov 25, 2026

Copy link
Copy Markdown

Measured against #2622 with an end-to-end repro (validator plus draws on RTX 4060, Intel UHD and WARP). The repro and #2622's test pass, with no regressions, also on f3578e38. The comparison suggests landing #2622 first, then this one as the liveness change: #2621 (comment) (AI-assisted)

@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: 16 passed, 0 failed, 1 ignored (including all new tests: dead_branch_users_do_not_keep_reachable_values_or_flags_alive, unreachable_phi_edge_does_not_keep_reachable_value_alive, dropped_direct_phi_edge_from_reachable_pred_does_not_keep_value_alive, block_emptied_by_dropping_dead_branch_uses_folds).
  • 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.

Scoping Module::live to reachable blocks and live phi edges (after computing reachability via self.term(b)) cleanly prevents dead unreachable-branch readers and pruned phi edges from leaking dead instructions and spurious Uses flags into emitted DXIL.

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

@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 d52b05f70f2fa02f5b48bd86082b6d7aa6ad2b79 — REQUEST_CHANGES.

While reachable-block and live-edge phi pruning works cleanly on the tested synthetic graphs (emit::bitcode::tests 16/16, emit::lower::tests 33/33, emit::tests 17/17), there is a blocking DXIL validation regression when pruning eliminates a ReadOnly typed UAV load or an unreachable block:

Blocking issue

  • [P1] Stale TYPED_UAV_LOADS shader flag causes dxil.dll validation failure (Flags must match usage.) (crates/victory-shader/src/emit/bitcode.rs:571, crates/victory-shader/src/emit/shader.rs:577-585):
    • Lowering sets self.s.flags |= flags::TYPED_UAV_LOADS when creating dx.op.textureLoad.f32 (crates/victory-shader/src/emit/lower.rs:8998) or dx.op.bufferLoad.f32 (lower.rs:9789), both emitted with Attr::ReadOnly.
    • When that load sits in a reachable block (b0) but its result is only consumed behind an untaken constant branch or a pruned phi edge, origin/main kept the call emitted whereas this PR prunes it.
    • Because Shader::finish (shader.rs:578-585) recomputes only RESOURCE_HEAP, SAMPLER_HEAP, WAVE_OPS, and INT64 from Module::uses(), TYPED_UAV_LOADS stays set in SFI0 and DXIL metadata even though no typed UAV load remains in the emitted bitcode.
    • Reproduced locally against dxil.dll: an A/B test with a reachable bufferLoad.f32 consumed only in the untaken arm of CondBr(true, b_live, b_dead) passes validation on origin/main (Ok(())), but fails on this PR with:
      error: Flags must match usage. / Flags declared=1073750016, actual=1073741824 (difference 8192 = 1 << 13 = flags::TYPED_UAV_LOADS).
    • The same mechanism applies to flags set while lowering unreachable blocks (ROVS at lower.rs:5352, ATOMIC64_TYPED/ATOMIC64_HEAP at lower.rs:8535) if an entire block is dropped as unreachable. Please extend Module::uses() / Shader::finish so all instruction-derived flags match what write() actually emits.

Secondary / non-blocking notes

  • [P2] Folded duplicate-edge conditional branch vs Op::Phi incoming count: has_edge (bitcode.rs:597) / Plan::edge (bitcode.rs:1104) filter by boolean reachability (contains(&to)). If a CondBr(true, join, join) folds to a single Br(join) while join's Op::Phi holds two entries from that predecessor, both phi entries remain in the emitted record while only one predecessor edge exists (pre-existing on origin/main as well).
  • Several rustfmt --edition 2024 --check wrapping diffs appear in the newly added tests (bitcode.rs:1694..1851).

@Moon0755

Copy link
Copy Markdown
Author

Addressed the blocking flag-sync issue and formatting notes in 298ac08:

  1. Extended Uses / Module::uses() (crates/victory-shader/src/emit/bitcode.rs) and Shader::finish() (crates/victory-shader/src/emit/shader.rs) so all remaining instruction-derived shader flags (TYPED_UAV_LOADS, ROVS, ATOMIC64_TYPED, ATOMIC64_HEAP alongside RESOURCE_HEAP, SAMPLER_HEAP, WAVE_OPS, INT64) are recomputed strictly from live, reachable emitted instructions:
    • uses.typed_uav_loads: set only when a live dx.op.textureLoad.* or dx.op.bufferLoad.* uses a typed UAV handle ((props0 & 0x1000) != 0 && (1..=10).contains(&(props0 & 0xFF))).
    • uses.rovs: set only when a live dx.op.annotateHandle carries 0x2000.
    • uses.atomic64_typed / uses.atomic64_heap: set from live dx.op.atomicBinOp.i64 / dx.op.atomicCompareExchange.i64 handles (aligned with Shaders: derive ATOMIC64_TYPED and ATOMIC64_HEAP from the atomics that are written #2698).
  2. Added unit tests uses_tracks_typed_uav_loads_rovs_and_atomic64 in bitcode.rs and pruned_typed_uav_load_clears_flag_and_validates in shader.rs (reproducing the CondBr(true, b_live, b_dead) ReadOnly bufferLoad.f32 case and validating via dxil.dll).
  3. Formatted all newly added test hunks in bitcode.rs and shader.rs per rustfmt --edition 2024.

Verification on 298ac08:

  • Local checks (with dxil.dll active — constant_color_validates and pruned_typed_uav_load_clears_flag_and_validates both passed validation): 63 passed / 0 failed in emit::bitcode::tests, emit::shader::, emit::tests::, emit::lower::tests; cargo xtask (6/6) and both workspace Clippy builds clean; rustfmt --edition 2024 --check clean on changed hunks.
  • Upstream CI: https://github.com/Marvisak/VIctory/actions/runs/45945831901 (success — full workspace green, 308 passed in victory-shader, 231 passed in victory-gpu, 6/6 policy, both Clippy checks clean).

— Neon

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.

9 participants