Shaders: a folded program reads the joins of its lane masks (the particle light atlas ran to the loop limit) #2853

Closed
wutzebaer wants to merge 2 commits from upstream-pr/2853 into main
wutzebaer commented 2026-11-29 18:08:51 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by wutzebaer on 2026-11-29T18:08:51Z.


What it changes

A folded wave64 compute program reads its EXEC pair as a number wherever the console reads a first lane (s_cmp_lg_u32 E.lo, 0: which half holds the first lane). Where that pair came through a join that only a loop header's join reads, the join was not marked as read, and its incoming masks became zero without a word. That is the shortcut VICTORY_STRICT_JOINS names in fill_phis.

From the second iteration on, the read then said "no lane in the lower half". It took the upper half's first lane, and with no lane there a stale value.

In ptfx_CS_lightAtlas_Sprite (2561af9577c47289) the counter of the loop over the light mask's words is read that way. In every wave of 32 sprites or fewer:

  • the counter never moved, and the loop ran to the iteration limit (4,096) with a light's whole body in each round: 60-80 ms of the card for one dispatch of one group;
  • the lanes then left as killed, without their store, so the title asked for the same sprites again in every frame.

The host code showed it directly: the loop header's join of that mask had the ballot on the entry edge and the constant 0 on the back edge.

The change: in folded programs the joins of lane masks are read too, whatever the switch. A mask has a DXIL form, the ballot of its lanes. Other joins keep the shortcut, so nothing else changes.

Of the title's 26,084 programs, 18 come out otherwise, all folded:

Programs Count
ptx_prerender:ptfx_CS_lightAtlas_Sprite, _Trail 2
shadowmask:CS_GenerateShadowMasks*, CS_TraceShadowRays_Full 6
water_shading:CS_TransmissionVolumetrics* 4
scattering_transmittance_system:CS_Gather, _Reference 2
GpuParticleUpdate:CS_Update*Particles 4

All 26,084 still translate (victory translate --list before and after, compared by the emitted hashes).

How it was tested

  • GPU and profile: RTX 5090, Series X, 2560x1440, DLSS Quality, frame generation off in the measured runs, ray tracing off.
  • Scene: on a deck at night, facing a house, about 10,000 draws a frame, diagnostics build.
  • Before: the card's time in the title's lists 40-77 ms a frame (VICTORY_GPU_TIMES: 45-68 ms of it in 2561af9577c47289, the longest command about 80 ms); frame 78-112 ms.
  • After: the card's time 22.5 ms a frame, the program at 0.1-0.3 ms; frame 65-75 ms.
  • With VICTORY_STRICT_JOINS=1 on that one program the result is the same; the switch itself stays as it is.
  • Stills before and after in two scenes show no difference and no artefacts. Not looked at: water, heavy smoke, the city, motion.
  • For shader changes, the wave sizes tested: 32 lanes. Not tested on a 64-lane host (folding does not run there).
  • cargo test passed for the crates it touches: yes (cargo test -p victory-shader --lib: 462 passed, 9 ignored, on the RTX 5090).
  • cargo clippy -p victory-shader --all-targets -- -D warnings stops at four findings that are on main already and in lines this does not touch (lower/analysis.rs:6, lower/analysis.rs:467, lower.rs:594, native.rs:1655).

No regression test is in this change. A folded program with a first-lane read in a loop whose EXEC pair passes a join before the back edge, run with lanes in the lower half only, would be one; I can add it if wanted.

Checked for overlap

  • I searched the open pull requests for the same issue and for the files this touches. Related: none found for this join; #2833, #2801 and #2702 touch emit/lower.rs elsewhere.
<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:issue:5553586032 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853). Originally posted by [wutzebaer](https://github.com/wutzebaer) on 2026-11-29T18:08:51Z. --- ## What it changes A folded wave64 compute program reads its EXEC pair as a number wherever the console reads a first lane (`s_cmp_lg_u32 E.lo, 0`: which half holds the first lane). Where that pair came through a join that only a loop header's join reads, the join was not marked as read, and its incoming masks became zero without a word. That is the shortcut `VICTORY_STRICT_JOINS` names in `fill_phis`. From the second iteration on, the read then said "no lane in the lower half". It took the upper half's first lane, and with no lane there a stale value. In `ptfx_CS_lightAtlas_Sprite` (`2561af9577c47289`) the counter of the loop over the light mask's words is read that way. In every wave of 32 sprites or fewer: - the counter never moved, and the loop ran to the iteration limit (4,096) with a light's whole body in each round: 60-80 ms of the card for one dispatch of one group; - the lanes then left as killed, without their store, so the title asked for the same sprites again in every frame. The host code showed it directly: the loop header's join of that mask had the ballot on the entry edge and the constant 0 on the back edge. The change: in folded programs the joins of lane masks are read too, whatever the switch. A mask has a DXIL form, the ballot of its lanes. Other joins keep the shortcut, so nothing else changes. Of the title's 26,084 programs, 18 come out otherwise, all folded: | Programs | Count | |---|---| | `ptx_prerender:ptfx_CS_lightAtlas_Sprite`, `_Trail` | 2 | | `shadowmask:CS_GenerateShadowMasks*`, `CS_TraceShadowRays_Full` | 6 | | `water_shading:CS_TransmissionVolumetrics*` | 4 | | `scattering_transmittance_system:CS_Gather`, `_Reference` | 2 | | `GpuParticleUpdate:CS_Update*Particles` | 4 | All 26,084 still translate (`victory translate --list` before and after, compared by the emitted hashes). ## How it was tested - GPU and profile: RTX 5090, Series X, 2560x1440, DLSS Quality, frame generation off in the measured runs, ray tracing off. - Scene: on a deck at night, facing a house, about 10,000 draws a frame, diagnostics build. - Before: the card's time in the title's lists 40-77 ms a frame (`VICTORY_GPU_TIMES`: 45-68 ms of it in `2561af9577c47289`, the longest command about 80 ms); frame 78-112 ms. - After: the card's time 22.5 ms a frame, the program at 0.1-0.3 ms; frame 65-75 ms. - With `VICTORY_STRICT_JOINS=1` on that one program the result is the same; the switch itself stays as it is. - Stills before and after in two scenes show no difference and no artefacts. Not looked at: water, heavy smoke, the city, motion. - For shader changes, the wave sizes tested: 32 lanes. Not tested on a 64-lane host (folding does not run there). - `cargo test` passed for the crates it touches: yes (`cargo test -p victory-shader --lib`: 462 passed, 9 ignored, on the RTX 5090). - `cargo clippy -p victory-shader --all-targets -- -D warnings` stops at four findings that are on `main` already and in lines this does not touch (`lower/analysis.rs:6`, `lower/analysis.rs:467`, `lower.rs:594`, `native.rs:1655`). No regression test is in this change. A folded program with a first-lane read in a loop whose EXEC pair passes a join before the back edge, run with lanes in the lower half only, would be one; I can add it if wanted. ## Checked for overlap - [x] I searched the open pull requests for the same issue and for the files this touches. Related: none found for this join; #2833, #2801 and #2702 touch `emit/lower.rs` elsewhere.
cadfan commented 2026-11-30 05:57:23 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by cadfan on 2026-11-30T05:57:23Z.


Tested on an RTX 5080: this fixes the strip-club hang in the Delight robbery mission (#3623) here.

Setup: RTX 5080 16 GB (driver 621.24), Ryzen 7 7800X3D, 64 GB RAM, Windows 11 26200. 41adb551 plus #3043 and #3487, Series X, DLSS Performance, DLSS frame generation 2x. Diagnostics build with VICTORY_D3D12_DRED=light and VICTORY_CARD_METER_PIPELINES=1, same save both times.

Before (without this PR): the card hung (0x887A0006) after 6.5 minutes in the club, before the stage. The card meter showed the light atlas growing until it did:

time compute 2561af9577c47289 compute cabb87599722e59a card time per frame, title's lists
+4:45 6 ms 3.6 ms 35 ms
+5:26 13 ms 6.9 ms 48 ms
+5:52 31 ms 9.4 ms 67 ms
+6:27 57 ms 29 ms 112 ms
+6:47 device hung

Each was one dispatch a frame. DRED put the stop in another list (command 599 of 998, with compute 0452fc2d2e2fc4c3 and 9146291b38ea9ce1 in flight between the same barriers), so the atlas looks like what drove the frame into the hang rather than the command that hung.

After (this PR merged, nothing else changed): 24 minutes, the whole club scene including the dance, closed normally. Across 262 card-meter readings (256 frames each), neither 2561af9577c47289 nor cabb87599722e59a was ever among the largest pipelines. The card's time in the title's lists peaked at 58 ms. In the club it was 18-27 fps with "on the GPU" at 1-5 ms (median per minute), where the earlier release run sat at 4 fps with 185-234 ms.

Release build too: same merge, release profile, translates and prepares cleanly (5,344 pipelines, 1 without a host pipeline, as before).

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7270164188 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7270164188). Originally posted by [cadfan](https://github.com/cadfan) on 2026-11-30T05:57:23Z. --- Tested on an RTX 5080: this fixes the strip-club hang in the Delight robbery mission (#3623) here. **Setup:** RTX 5080 16 GB (driver 621.24), Ryzen 7 7800X3D, 64 GB RAM, Windows 11 26200. `41adb551` plus #3043 and #3487, Series X, DLSS Performance, DLSS frame generation 2x. Diagnostics build with `VICTORY_D3D12_DRED=light` and `VICTORY_CARD_METER_PIPELINES=1`, same save both times. **Before (without this PR):** the card hung (0x887A0006) after 6.5 minutes in the club, before the stage. The card meter showed the light atlas growing until it did: | time | `compute 2561af9577c47289` | `compute cabb87599722e59a` | card time per frame, title's lists | |---|---:|---:|---:| | +4:45 | 6 ms | 3.6 ms | 35 ms | | +5:26 | 13 ms | 6.9 ms | 48 ms | | +5:52 | 31 ms | 9.4 ms | 67 ms | | +6:27 | 57 ms | 29 ms | 112 ms | | +6:47 | device hung | | | Each was one dispatch a frame. DRED put the stop in another list (command 599 of 998, with `compute 0452fc2d2e2fc4c3` and `9146291b38ea9ce1` in flight between the same barriers), so the atlas looks like what drove the frame into the hang rather than the command that hung. **After (this PR merged, nothing else changed):** 24 minutes, the whole club scene including the dance, closed normally. Across 262 card-meter readings (256 frames each), neither `2561af9577c47289` nor `cabb87599722e59a` was ever among the largest pipelines. The card's time in the title's lists peaked at 58 ms. In the club it was 18-27 fps with "on the GPU" at 1-5 ms (median per minute), where the earlier release run sat at 4 fps with 185-234 ms. Release build too: same merge, `release` profile, translates and prepares cleanly (5,344 pipelines, 1 without a host pipeline, as before).
Lyrnc commented 2026-11-30 06:11:31 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Lyrnc on 2026-11-30T06:11:31Z.


Checked this against a Radeon gfx1036 (RDNA 2) running the same kernels natively in wave64, and ran the folded form for main and for this PR on an RTX 5080 and on that Radeon through D3D12.

Setup

  • main at 41adb551 with this PR's head (bd9ffc5) merged locally, no conflict. The victory-shader test binary was built from that merged tree (own tree and target directory).
  • Kernels: hand-written GFX10 code, nothing from a title. One 64-thread group as one wave64; per-lane inputs from tables on the thread id; outputs v10.. stored per lane.
  • Hardware rows: the same machine code dispatched natively on the gfx1036 as one wave64.
  • Host runs: super::folded (the two-lanes-per-host-lane rewrite), dxil.dll validation, dispatched on the 5080 and on the Radeon (VICTORY_ADAPTER=radeon). Also super::emit with 32 host lanes (both cards) and 64 (Radeon).

Cases

  • counter_loop/<lo20|all|up40> and counter_loop2/*: a loop whose exit reads a VGPR counter through v_readfirstlane_b32 (s_cmp_lt_u32 s40, 7), with an s_and_saveexec_b64 / s_cbranch_execz / s_or_b64 exec if inside the loop (EXEC written in the loop, so the header joins the EXEC pair) and another if before the loop (the pair's entry value comes through a join). Lanes taking part: below 20 (lower half only, "32 or fewer"), all 64, or 40..51 (upper half only). An iteration guard stops it at 40 rounds. v10 = per-lane hits (1 in each lane taking part), v11 = rounds (7), v12 = the last counter read (7), v13 = the value from the if before the loop. counter_loop2 restores EXEC inside both arms of each if (so the merges join two different EXEC values) and has no vector instruction between the loop's inner merge and its back edge, so that merge's EXEC reaches only the loop header's join (9 rounds, last counter 8).
  • waterfall/<mixed|upper_only|sparse>: a v_readfirstlane_b32 waterfall (v_cmp_eq_u32, s_and_saveexec_b64, s_xor_b64 exec, s_cbranch_execnz) with a scalar counter read after the loop (5, 3, 5 rounds on the hardware).
  • Also run: restore_exec/*, join_leader*/*, permute*, saveexec_forms.

Results (values that differ from the gfx1036, out of 64 lanes x outputs)

case main, folded, 5080 this PR, folded, 5080 main, folded, Radeon this PR, folded, Radeon
counter_loop/lo20, /all, /up40 exact exact exact exact
counter_loop2/lo20, /all, /up40 exact exact exact exact
waterfall/mixed 32 (v11) 32 (the same values) 32 32
waterfall/sparse 40 (v11) 40 40 40
waterfall/upper_only 44 (v11) 44 44 44

Over 30 wave64 cases (27 in all five host forms, the three counter_loop2 in four) and the 24 wave32 cases (two host forms), this PR changed no value anywhere compared with main. The waterfall difference is the counter after the loop (the gfx1036 has 5 / 5 / 3 in every lane; the folded form gives each lane the round it left in, e.g. 4 in the even lanes of mixed); #2265 makes those three exact in the folded form.

Verdict: not reproduced, no regression. None of my loops shows the zeroed join on main: the folded form already gets the counter loops right on both cards, with the lanes in the lower half only (lanes 0..19, the "32 or fewer" case), in the upper half only, or all 64, and with or without a join of two EXEC values feeding the loop header. This PR changes no value in any case, so it is safe on this set, but I cannot confirm the fix from hand-written code. A loop shape that does fail on main (written by hand, not taken from a title) would let me measure it against the gfx1036.

Outside this PR: with super::emit (both cards, 32 and 64 host lanes) counter_loop/lo20 and /up40 give v11 = 40 (the iteration guard) and v12 = 0 in the half with no lane taking part, where the hardware has 7 and 7 in every lane; main and this PR alike.

AI use: Claude Code (Claude Opus 5.5) ran the oracle and host cases and wrote this comment.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7270396358 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7270396358). Originally posted by [Lyrnc](https://github.com/Lyrnc) on 2026-11-30T06:11:31Z. --- Checked this against a Radeon gfx1036 (RDNA 2) running the same kernels natively in wave64, and ran the folded form for main and for this PR on an RTX 5080 and on that Radeon through D3D12. **Setup** - `main` at 41adb551 with this PR's head (bd9ffc5) merged locally, no conflict. The victory-shader test binary was built from that merged tree (own tree and target directory). - Kernels: hand-written GFX10 code, nothing from a title. One 64-thread group as one wave64; per-lane inputs from tables on the thread id; outputs v10.. stored per lane. - Hardware rows: the same machine code dispatched natively on the gfx1036 as one wave64. - Host runs: `super::folded` (the two-lanes-per-host-lane rewrite), `dxil.dll` validation, dispatched on the 5080 and on the Radeon (`VICTORY_ADAPTER=radeon`). Also `super::emit` with 32 host lanes (both cards) and 64 (Radeon). **Cases** - `counter_loop/<lo20|all|up40>` and `counter_loop2/*`: a loop whose exit reads a VGPR counter through `v_readfirstlane_b32` (`s_cmp_lt_u32 s40, 7`), with an `s_and_saveexec_b64` / `s_cbranch_execz` / `s_or_b64 exec` if inside the loop (EXEC written in the loop, so the header joins the EXEC pair) and another if before the loop (the pair's entry value comes through a join). Lanes taking part: below 20 (lower half only, "32 or fewer"), all 64, or 40..51 (upper half only). An iteration guard stops it at 40 rounds. v10 = per-lane hits (1 in each lane taking part), v11 = rounds (7), v12 = the last counter read (7), v13 = the value from the if before the loop. `counter_loop2` restores EXEC inside both arms of each if (so the merges join two different EXEC values) and has no vector instruction between the loop's inner merge and its back edge, so that merge's EXEC reaches only the loop header's join (9 rounds, last counter 8). - `waterfall/<mixed|upper_only|sparse>`: a `v_readfirstlane_b32` waterfall (`v_cmp_eq_u32`, `s_and_saveexec_b64`, `s_xor_b64 exec`, `s_cbranch_execnz`) with a scalar counter read after the loop (5, 3, 5 rounds on the hardware). - Also run: `restore_exec/*`, `join_leader*/*`, `permute*`, `saveexec_forms`. **Results** (values that differ from the gfx1036, out of 64 lanes x outputs) | case | main, folded, 5080 | this PR, folded, 5080 | main, folded, Radeon | this PR, folded, Radeon | |---|---|---|---|---| | `counter_loop/lo20`, `/all`, `/up40` | exact | exact | exact | exact | | `counter_loop2/lo20`, `/all`, `/up40` | exact | exact | exact | exact | | `waterfall/mixed` | 32 (v11) | 32 (the same values) | 32 | 32 | | `waterfall/sparse` | 40 (v11) | 40 | 40 | 40 | | `waterfall/upper_only` | 44 (v11) | 44 | 44 | 44 | Over 30 wave64 cases (27 in all five host forms, the three `counter_loop2` in four) and the 24 wave32 cases (two host forms), this PR changed no value anywhere compared with main. The waterfall difference is the counter after the loop (the gfx1036 has 5 / 5 / 3 in every lane; the folded form gives each lane the round it left in, e.g. 4 in the even lanes of `mixed`); #2265 makes those three exact in the folded form. **Verdict: not reproduced, no regression.** None of my loops shows the zeroed join on main: the folded form already gets the counter loops right on both cards, with the lanes in the lower half only (lanes 0..19, the "32 or fewer" case), in the upper half only, or all 64, and with or without a join of two EXEC values feeding the loop header. This PR changes no value in any case, so it is safe on this set, but I cannot confirm the fix from hand-written code. A loop shape that does fail on main (written by hand, not taken from a title) would let me measure it against the gfx1036. Outside this PR: with `super::emit` (both cards, 32 and 64 host lanes) `counter_loop/lo20` and `/up40` give v11 = 40 (the iteration guard) and v12 = 0 in the half with no lane taking part, where the hardware has 7 and 7 in every lane; main and this PR alike. AI use: Claude Code (Claude Opus 5.5) ran the oracle and host cases and wrote this comment.
SergDi commented 2026-11-30 06:32:33 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by SergDi on 2026-11-30T06:32:33Z.


@Lyrnc, I have a synthetic loop that does reproduce the zeroed join on an RTX 4080. The test patch below contains no title data and no production fix.

The distinguishing shape keeps SCC live across the back edge: the loop header reads an EXEC-mask phi whose incoming value is another mask phi, read only by that header. Bounding initial EXEC with both a lower and an upper limit prevents upper-half lanes from accidentally making the broken version pass. The CPU test asserts that the intended phi chain survives folding.

Windows evidence: RTX 4080 16 GB, driver 610.88, pinned Rust 1.98.1. Actual test base was f72cec7714aa6d6e274b761fb6fa40bfcf44243b plus this test; GREEN adds this PR's bd9ffc513c7479393119abb816ebb133b46952db diff. These are not runs on current main or on the exact PR head.

  • GPU RED without the fix: lane 0, first active lane's count, left 0 / right 4; hardware execution was recorded.
  • GREEN: five masks through both folding paths, 10 hardware executions. Full shader library suite: 465 passed, 0 failed, 9 ignored.
  • Mutation check: removing only the production fix makes the CPU test fail with [(32, 0)] on the back edge; restoring it passes.
cargo test --locked --release -p victory-shader --lib folded_join -- --test-threads=1 --nocapture
cargo test --locked --release -p victory-shader --lib a_folded_first_lane_loop_counts_through -- --test-threads=1 --nocapture

The GPU helper can return early without an adapter; check for ran on the hardware device, not just a passing test. Strict Clippy still fails the same four baseline findings; no new diagnostics from this patch. I have not measured an in-game FPS benefit from this fix.

AI assistance: Codex and Claude prepared/reviewed the synthetic tests; the reported Windows results were collected on the physical machine.

pr2853-test.patch
diff --git a/crates/victory-shader/src/emit/bitcode/census.rs b/crates/victory-shader/src/emit/bitcode/census.rs
index 9c0efb17..f336c5da 100644
--- a/crates/victory-shader/src/emit/bitcode/census.rs
+++ b/crates/victory-shader/src/emit/bitcode/census.rs
@@ -49,9 +49,10 @@ thread_local! {
     /// a hash of each one's bitcode, with its counts (a program may be
     /// emitted in several forms before one is kept).
     static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) };
-    /// Under tests, the live `dx.op.barrier` modes of each module written on this thread.
+    /// Under tests, the live `dx.op.barrier` modes of each module written on this thread,
+    /// and the integer constants its joins take over back edges.
     #[cfg(test)]
-    static BARRIERS: RefCell<Vec<(usize, u64, Vec<u32>)>> = const { RefCell::new(Vec::new()) };
+    static BARRIERS: RefCell<Vec<(usize, u64, Vec<u32>, Vec<(u32, i64)>)>> = const { RefCell::new(Vec::new()) };
 }
 
 fn fnv(bytes: &[u8]) -> u64 {
@@ -107,7 +108,7 @@ pub(crate) fn note(m: &Module, bitcode: &[u8]) {
         if b.len() >= 32 {
             b.drain(..16);
         }
-        b.push((bitcode.len(), fnv(bitcode), m.barrier_modes()));
+        b.push((bitcode.len(), fnv(bitcode), m.barrier_modes(), m.back_edge_constants()));
     });
     if !enabled() {
         return;
@@ -125,11 +126,26 @@ pub(crate) fn barrier_modes(dxil: &[u8]) -> Option<Vec<u32>> {
         l.borrow()
             .iter()
             .rev()
-            .find(|(len, hash, _)| dxil.get(at..at + *len).is_some_and(|b| fnv(b) == *hash))
+            .find(|(len, hash, ..)| dxil.get(at..at + *len).is_some_and(|b| fnv(b) == *hash))
             .map(|w| w.2.clone())
     })
 }
 
+/// The integer constants (width, value) that live joins of the module whose bitcode `dxil`
+/// holds take over a back edge (from a block that a path from the entry reaches through
+/// the join's block).
+#[cfg(test)]
+pub(crate) fn back_edge_constants(dxil: &[u8]) -> Option<Vec<(u32, i64)>> {
+    let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?;
+    BARRIERS.with(|l| {
+        l.borrow()
+            .iter()
+            .rev()
+            .find(|(len, hash, ..)| dxil.get(at..at + *len).is_some_and(|b| fnv(b) == *hash))
+            .map(|w| w.3.clone())
+    })
+}
+
 fn kind(name: &str) -> usize {
     let n = name.strip_prefix("dx.op.").unwrap_or(name);
     let n = n.split('.').next().unwrap_or(n);
@@ -249,4 +265,59 @@ impl Module {
         }
         modes
     }
+
+    #[cfg(test)]
+    fn back_edge_constants(&self) -> Vec<(u32, i64)> {
+        let n = self.blocks.len();
+        if n == 0 {
+            return Vec::new();
+        }
+        let mut back = std::collections::HashSet::new();
+        let mut on_path = vec![false; n];
+        let mut seen = vec![false; n];
+        let mut stack = vec![(0usize, 0usize)];
+        seen[0] = true;
+        on_path[0] = true;
+        while let Some(&(b, k)) = stack.last() {
+            let succs = super::successors(self.blocks[b].term);
+            let Some(&s) = succs.get(k) else {
+                on_path[b] = false;
+                stack.pop();
+                continue;
+            };
+            stack.last_mut().expect("a block").1 += 1;
+            if on_path[s] {
+                back.insert((b, s));
+            } else if !seen[s] {
+                seen[s] = true;
+                on_path[s] = true;
+                stack.push((s, 0));
+            }
+        }
+        let live = self.live();
+        let mut found = Vec::new();
+        for (b, blk) in self.blocks.iter().enumerate() {
+            for &i in blk.phis.iter().filter(|&&i| seen[b] && live[i as usize]) {
+                let Op::Phi(incoming) = &self.insts[i as usize].op else { continue };
+                for &(v, from) in incoming {
+                    if let (true, V::Const(c), Some(x)) = (back.contains(&(from, b)), v, self.int_value(v))
+                        && let super::TypeDef::Int(bits) = self.types[self.consts[c as usize].0.0 as usize]
+                    {
+                        found.push((bits, x));
+                    }
+                }
+            }
+        }
+        found
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::Module;
+
+    #[test]
+    fn an_empty_module_takes_no_constants_over_back_edges() {
+        assert!(Module::default().back_edge_constants().is_empty());
+    }
 }
diff --git a/crates/victory-shader/src/emit/folded_join_tests.rs b/crates/victory-shader/src/emit/folded_join_tests.rs
new file mode 100644
index 00000000..5afc114b
--- /dev/null
+++ b/crates/victory-shader/src/emit/folded_join_tests.rs
@@ -0,0 +1,194 @@
+//! A folded wave64 program ([`crate::fold`]) whose loop header joins EXEC from a join of
+//! EXEC, and reads it as a number.
+
+use super::lower;
+use crate::fold::{Asm, Src, int, sgpr, vgpr};
+use crate::gfx10::{self, Encoding};
+use crate::native::{
+    ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
+};
+use crate::{io, resource, structure};
+
+const VCC: u8 = 106;
+const EXEC: u8 = 126;
+
+fn op(e: Encoding, name: &str) -> u32 {
+    u32::from(gfx10::opcode(e, name).unwrap_or_else(|| panic!("no opcode {name}")))
+}
+
+#[derive(Default)]
+struct Code {
+    a: Asm,
+    labels: std::collections::HashMap<&'static str, usize>,
+    jumps: Vec<(usize, &'static str)>,
+}
+
+impl Code {
+    fn vop2(&mut self, name: &str, d: u8, s0: Src, s1: u8) {
+        let (c, lit) = match s0 {
+            Src::Code(c) => (u32::from(c), None),
+            Src::Lit(l) => (255, Some(l)),
+        };
+        self.a.words.push(op(Encoding::Vop2, name) << 25 | u32::from(d) << 17 | u32::from(s1) << 9 | c);
+        self.a.words.extend(lit);
+    }
+
+    fn vopc(&mut self, name: &str, s0: Src, s1: u8) {
+        let Src::Code(c) = s0 else { panic!("literal") };
+        self.a.words.push(0b011_1110 << 25 | op(Encoding::Vopc, name) << 17 | u32::from(s1) << 9 | u32::from(c));
+    }
+
+    /// `buffer_store_dword v<data>, v<addr>, s[8:11], 0 offen`
+    fn store(&mut self, data: u8, addr: u8) {
+        self.a.words.push(0x38 << 26 | op(Encoding::Mubuf, "buffer_store_dword") << 18 | 1 << 12);
+        self.a.words.push(0x80 << 24 | 2 << 16 | u32::from(data) << 8 | u32::from(addr));
+    }
+
+    fn label(&mut self, name: &'static str) {
+        self.labels.insert(name, self.a.words.len());
+    }
+
+    fn branch(&mut self, name: &str, to: &'static str) {
+        self.jumps.push((self.a.words.len(), to));
+        self.a.sopp(name, 0);
+    }
+
+    fn words(mut self) -> Vec<u32> {
+        for (at, to) in self.jumps {
+            let d = self.labels[to] as i64 - at as i64 - 1;
+            self.a.words[at] |= u32::from(d as i16 as u16);
+        }
+        self.a.words
+    }
+}
+
+/// A wave64 compute program of 64 threads (thread index in v0), 4 root constants in
+/// s0..s3 and a raw UAV's descriptor in s[8:11], then `body`.
+fn native(body: &[u32]) -> NativeProgram {
+    let mut words = vec![
+        0xBE85_0380, // s_mov_b32 s5, 0
+        0x3D << 26 | 0x02 << 18 | 8 << 6 | 2,
+        125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0
+    ];
+    words.extend_from_slice(body);
+    words.push(0xBF81_0000); // s_endpgm
+    let param = |root, sgprs, user_data, slot| RootParam {
+        root,
+        table_offset_dwords: 0,
+        sgprs,
+        base_register: 0,
+        user_data,
+        slot,
+    };
+    NativeProgram {
+        stage: HwStage::Cs,
+        wave64: true,
+        vgprs: 16,
+        layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)],
+        used: vec![UsedResource {
+            kind: ResourceType::Uav,
+            root: RootType::Table,
+            table_offset_dwords: 0,
+            lower_bound: 0,
+            stride: 0,
+            dwords: 4,
+            user_data: 4,
+            slot: 1,
+        }],
+        io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [64, 1, 1] }),
+        code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
+    }
+}
+
+/// A loop over the first active lane's counter (v1) of the lanes from s0 below s1: an
+/// iteration whose count is odd narrows EXEC to those below s3, an even one keeps them all
+/// (with s1 at most 32 the upper half never has a lane, as a wave of 32 sprites). The two ways
+/// meet in a block of their own that only takes the back edge (SCC, live across it, keeps
+/// the fold from settling EXEC there), so the loop header's EXEC join reads a join of EXEC
+/// and nothing else reads that one. The first lane's count is s2 when the loop leaves; every
+/// lane stores it.
+pub(super) fn first_lane_loop() -> NativeProgram {
+    let mut c = Code::default();
+    c.a.vop1("v_mov_b32", 1, int(0));
+    c.vop2("v_lshlrev_b32", 5, int(2), 0);
+    c.vopc("v_cmp_le_u32", sgpr(0), 0); // s0 <= t
+    c.a.sop1("s_mov_b64", EXEC, sgpr(VCC));
+    c.vopc("v_cmp_gt_u32", sgpr(1), 0); // s1 > t
+    c.a.sop2("s_and_b64", EXEC, sgpr(EXEC), sgpr(VCC));
+    c.a.sop1("s_mov_b64", 12, sgpr(EXEC));
+    c.label("header");
+    c.a.vop1("v_readfirstlane_b32", 16, vgpr(1));
+    c.vop2("v_add_nc_u32", 1, int(1), 1);
+    c.a.sop2("s_and_b32", 17, sgpr(16), int(1));
+    c.a.sopc("s_cmp_eq_u32", sgpr(17), int(0));
+    c.branch("s_cbranch_scc1", "wide");
+    c.vopc("v_cmp_gt_u32", sgpr(3), 0); // s3 > t
+    c.a.sop2("s_and_b64", EXEC, sgpr(12), sgpr(VCC));
+    c.a.sopc("s_cmp_lt_u32", sgpr(16), sgpr(2));
+    c.branch("s_branch", "join");
+    c.label("wide");
+    c.a.sop1("s_mov_b64", EXEC, sgpr(12));
+    c.a.sopc("s_cmp_lt_u32", sgpr(16), sgpr(2));
+    c.label("join");
+    c.branch("s_cbranch_scc1", "header");
+    c.a.sop1("s_mov_b64", EXEC, int(-1));
+    c.a.vop1("v_mov_b32", 3, sgpr(16));
+    c.store(3, 5);
+    native(&c.words())
+}
+
+/// The fold reads EXEC as a number at the first-lane read, so the header's EXEC join is
+/// read; the join of EXEC it takes over the back edge must be read with it. Left unread,
+/// that join came out as zero in DXIL ("no lane in the lower half" from the second
+/// iteration on: the read took a lane that does not count, and the loop ran to its limit).
+#[test]
+fn a_folded_loop_header_reads_the_mask_join_on_its_back_edge() {
+    let native = first_lane_loop();
+    let (f, _) = crate::fold::fold(&native).unwrap_or_else(|(at, why)| panic!("fold at {at:#x}: {why}"));
+    let p = crate::spill::build(&f).expect("ir::build");
+    let st = structure::structure(&p).expect("structure");
+
+    let is_mask = |v: &crate::ir::Value| st.masks.contains_key(v) || st.highs.contains_key(v);
+    let phi_of = |v: crate::ir::Value| {
+        p.blocks.iter().enumerate().find_map(|(b, block)| block.phis.iter().any(|phi| phi.value == v).then_some(b))
+    };
+    let readers = |v: crate::ir::Value| {
+        let by_phis = p.blocks.iter().flat_map(|b| &b.phis).filter(|phi| phi.args.contains(&v)).count();
+        let by_insts = p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.reads.iter().any(|r| r.1 == v)).count();
+        by_phis + by_insts
+    };
+    let chain = p.blocks.iter().enumerate().any(|(h, header)| {
+        header.preds.iter().enumerate().any(|(n, &latch)| {
+            latch >= h
+                && header.phis.iter().any(|phi| {
+                    let arg = phi.args[n];
+                    is_mask(&phi.value) && is_mask(&arg) && phi_of(arg) == Some(latch) && readers(arg) == 1
+                })
+        })
+    });
+    assert!(chain, "a loop header's mask join whose back edge brings a mask join only it reads");
+
+    let res = resource::track(&p, &f.layout, f.stage, Some(&st)).expect("resource::track");
+    let io = io::raise(&p, &f).expect("io::raise");
+    let was = lower::TEST_HOST_WAVE.replace(Some(32));
+    let lowered = lower::with_folded(|| {
+        lower::lower(&lower::Parts {
+            native: &f,
+            p: &p,
+            st: &st,
+            io: &io,
+            res: &res,
+            inputs: Vec::new(),
+            outputs: Vec::new(),
+            prims: Vec::new(),
+            mesh_stride: 0,
+        })
+    });
+    lower::TEST_HOST_WAVE.set(was);
+    let lowered = lowered.expect("lower");
+    let constants = super::bitcode::census::back_edge_constants(&lowered.dxil).expect("the module written");
+    assert!(
+        !constants.contains(&(32, 0)),
+        "a 32-bit join takes zero over the back edge (the mask join left unread): {constants:?}"
+    );
+}
diff --git a/crates/victory-shader/src/emit/folded_tests.rs b/crates/victory-shader/src/emit/folded_tests.rs
index 9a246aec..a5e28871 100644
--- a/crates/victory-shader/src/emit/folded_tests.rs
+++ b/crates/victory-shader/src/emit/folded_tests.rs
@@ -1072,3 +1072,19 @@ fn a_folded_program_using_all_32_kib_of_lds_fits_without_the_wave_counter() {
     let Some(out) = run(&shader, &[], 128 * 2) else { return };
     check(&out, 128, 2, |t, j| if j == 0 { t as u32 % 64 } else { 127 - t as u32 }, &["console lane", "LDS of thread 127 - t"]);
 }
+
+/// The loop of [`super::folded_join_tests::first_lane_loop`] on the host: the header's EXEC
+/// join takes a join of EXEC over the back edge, and the first lane's count must reach s2
+/// (s3 above s0 keeps that lane in every iteration). With s1 at most 32 no lane of the upper
+/// half ever runs: read as zero there, the lower half's EXEC dword sends the first-lane read
+/// to the upper half's counters, which stay 0, and the loop runs to its limit without a store.
+#[test]
+fn a_folded_first_lane_loop_counts_through_a_mask_join_on_its_back_edge() {
+    let native = super::folded_join_tests::first_lane_loop();
+    for shader in [folded(&native), folded_as_translated(&native)] {
+        for constants in [[0, 16, 4, 8], [0, 32, 7, 16], [8, 32, 6, 20], [32, 64, 4, 48], [0, 64, 5, 64]] {
+            let Some(out) = run(&shader, &constants, 64) else { return };
+            check(&out, 64, 1, |_, _| constants[2], &["first active lane's count"]);
+        }
+    }
+}
diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs
index cc37a0fc..c0dad4dc 100644
--- a/crates/victory-shader/src/emit/mod.rs
+++ b/crates/victory-shader/src/emit/mod.rs
@@ -83,6 +83,8 @@
 mod bitcode;
 #[cfg(test)]
 mod census_tests;
+#[cfg(test)]
+mod folded_join_tests;
 mod container;
 mod cost;
 #[cfg(all(test, windows))]
<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7270755614 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7270755614). Originally posted by [SergDi](https://github.com/SergDi) on 2026-11-30T06:32:33Z. --- @Lyrnc, I have a synthetic loop that does reproduce the zeroed join on an RTX 4080. The test patch below contains no title data and no production fix. The distinguishing shape keeps SCC live across the back edge: the loop header reads an EXEC-mask phi whose incoming value is another mask phi, read only by that header. Bounding initial EXEC with both a lower and an upper limit prevents upper-half lanes from accidentally making the broken version pass. The CPU test asserts that the intended phi chain survives folding. **Windows evidence:** RTX 4080 16 GB, driver 610.88, pinned Rust 1.98.1. Actual test base was `f72cec7714aa6d6e274b761fb6fa40bfcf44243b` plus this test; GREEN adds this PR's `bd9ffc513c7479393119abb816ebb133b46952db` diff. These are not runs on current main or on the exact PR head. - GPU RED without the fix: `lane 0, first active lane's count`, **left 0 / right 4**; hardware execution was recorded. - GREEN: five masks through both folding paths, **10 hardware executions**. Full shader library suite: **465 passed, 0 failed, 9 ignored**. - Mutation check: removing only the production fix makes the CPU test fail with `[(32, 0)]` on the back edge; restoring it passes. ```powershell cargo test --locked --release -p victory-shader --lib folded_join -- --test-threads=1 --nocapture cargo test --locked --release -p victory-shader --lib a_folded_first_lane_loop_counts_through -- --test-threads=1 --nocapture ``` The GPU helper can return early without an adapter; check for `ran on the hardware device`, not just a passing test. Strict Clippy still fails the same four baseline findings; no new diagnostics from this patch. I have not measured an in-game FPS benefit from this fix. AI assistance: Codex and Claude prepared/reviewed the synthetic tests; the reported Windows results were collected on the physical machine. <details> <summary>pr2853-test.patch</summary> ```diff diff --git a/crates/victory-shader/src/emit/bitcode/census.rs b/crates/victory-shader/src/emit/bitcode/census.rs index 9c0efb17..f336c5da 100644 --- a/crates/victory-shader/src/emit/bitcode/census.rs +++ b/crates/victory-shader/src/emit/bitcode/census.rs @@ -49,9 +49,10 @@ thread_local! { /// a hash of each one's bitcode, with its counts (a program may be /// emitted in several forms before one is kept). static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) }; - /// Under tests, the live `dx.op.barrier` modes of each module written on this thread. + /// Under tests, the live `dx.op.barrier` modes of each module written on this thread, + /// and the integer constants its joins take over back edges. #[cfg(test)] - static BARRIERS: RefCell<Vec<(usize, u64, Vec<u32>)>> = const { RefCell::new(Vec::new()) }; + static BARRIERS: RefCell<Vec<(usize, u64, Vec<u32>, Vec<(u32, i64)>)>> = const { RefCell::new(Vec::new()) }; } fn fnv(bytes: &[u8]) -> u64 { @@ -107,7 +108,7 @@ pub(crate) fn note(m: &Module, bitcode: &[u8]) { if b.len() >= 32 { b.drain(..16); } - b.push((bitcode.len(), fnv(bitcode), m.barrier_modes())); + b.push((bitcode.len(), fnv(bitcode), m.barrier_modes(), m.back_edge_constants())); }); if !enabled() { return; @@ -125,11 +126,26 @@ pub(crate) fn barrier_modes(dxil: &[u8]) -> Option<Vec<u32>> { l.borrow() .iter() .rev() - .find(|(len, hash, _)| dxil.get(at..at + *len).is_some_and(|b| fnv(b) == *hash)) + .find(|(len, hash, ..)| dxil.get(at..at + *len).is_some_and(|b| fnv(b) == *hash)) .map(|w| w.2.clone()) }) } +/// The integer constants (width, value) that live joins of the module whose bitcode `dxil` +/// holds take over a back edge (from a block that a path from the entry reaches through +/// the join's block). +#[cfg(test)] +pub(crate) fn back_edge_constants(dxil: &[u8]) -> Option<Vec<(u32, i64)>> { + let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?; + BARRIERS.with(|l| { + l.borrow() + .iter() + .rev() + .find(|(len, hash, ..)| dxil.get(at..at + *len).is_some_and(|b| fnv(b) == *hash)) + .map(|w| w.3.clone()) + }) +} + fn kind(name: &str) -> usize { let n = name.strip_prefix("dx.op.").unwrap_or(name); let n = n.split('.').next().unwrap_or(n); @@ -249,4 +265,59 @@ impl Module { } modes } + + #[cfg(test)] + fn back_edge_constants(&self) -> Vec<(u32, i64)> { + let n = self.blocks.len(); + if n == 0 { + return Vec::new(); + } + let mut back = std::collections::HashSet::new(); + let mut on_path = vec![false; n]; + let mut seen = vec![false; n]; + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + on_path[0] = true; + while let Some(&(b, k)) = stack.last() { + let succs = super::successors(self.blocks[b].term); + let Some(&s) = succs.get(k) else { + on_path[b] = false; + stack.pop(); + continue; + }; + stack.last_mut().expect("a block").1 += 1; + if on_path[s] { + back.insert((b, s)); + } else if !seen[s] { + seen[s] = true; + on_path[s] = true; + stack.push((s, 0)); + } + } + let live = self.live(); + let mut found = Vec::new(); + for (b, blk) in self.blocks.iter().enumerate() { + for &i in blk.phis.iter().filter(|&&i| seen[b] && live[i as usize]) { + let Op::Phi(incoming) = &self.insts[i as usize].op else { continue }; + for &(v, from) in incoming { + if let (true, V::Const(c), Some(x)) = (back.contains(&(from, b)), v, self.int_value(v)) + && let super::TypeDef::Int(bits) = self.types[self.consts[c as usize].0.0 as usize] + { + found.push((bits, x)); + } + } + } + } + found + } +} + +#[cfg(test)] +mod tests { + use super::Module; + + #[test] + fn an_empty_module_takes_no_constants_over_back_edges() { + assert!(Module::default().back_edge_constants().is_empty()); + } } diff --git a/crates/victory-shader/src/emit/folded_join_tests.rs b/crates/victory-shader/src/emit/folded_join_tests.rs new file mode 100644 index 00000000..5afc114b --- /dev/null +++ b/crates/victory-shader/src/emit/folded_join_tests.rs @@ -0,0 +1,194 @@ +//! A folded wave64 program ([`crate::fold`]) whose loop header joins EXEC from a join of +//! EXEC, and reads it as a number. + +use super::lower; +use crate::fold::{Asm, Src, int, sgpr, vgpr}; +use crate::gfx10::{self, Encoding}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, resource, structure}; + +const VCC: u8 = 106; +const EXEC: u8 = 126; + +fn op(e: Encoding, name: &str) -> u32 { + u32::from(gfx10::opcode(e, name).unwrap_or_else(|| panic!("no opcode {name}"))) +} + +#[derive(Default)] +struct Code { + a: Asm, + labels: std::collections::HashMap<&'static str, usize>, + jumps: Vec<(usize, &'static str)>, +} + +impl Code { + fn vop2(&mut self, name: &str, d: u8, s0: Src, s1: u8) { + let (c, lit) = match s0 { + Src::Code(c) => (u32::from(c), None), + Src::Lit(l) => (255, Some(l)), + }; + self.a.words.push(op(Encoding::Vop2, name) << 25 | u32::from(d) << 17 | u32::from(s1) << 9 | c); + self.a.words.extend(lit); + } + + fn vopc(&mut self, name: &str, s0: Src, s1: u8) { + let Src::Code(c) = s0 else { panic!("literal") }; + self.a.words.push(0b011_1110 << 25 | op(Encoding::Vopc, name) << 17 | u32::from(s1) << 9 | u32::from(c)); + } + + /// `buffer_store_dword v<data>, v<addr>, s[8:11], 0 offen` + fn store(&mut self, data: u8, addr: u8) { + self.a.words.push(0x38 << 26 | op(Encoding::Mubuf, "buffer_store_dword") << 18 | 1 << 12); + self.a.words.push(0x80 << 24 | 2 << 16 | u32::from(data) << 8 | u32::from(addr)); + } + + fn label(&mut self, name: &'static str) { + self.labels.insert(name, self.a.words.len()); + } + + fn branch(&mut self, name: &str, to: &'static str) { + self.jumps.push((self.a.words.len(), to)); + self.a.sopp(name, 0); + } + + fn words(mut self) -> Vec<u32> { + for (at, to) in self.jumps { + let d = self.labels[to] as i64 - at as i64 - 1; + self.a.words[at] |= u32::from(d as i16 as u16); + } + self.a.words + } +} + +/// A wave64 compute program of 64 threads (thread index in v0), 4 root constants in +/// s0..s3 and a raw UAV's descriptor in s[8:11], then `body`. +fn native(body: &[u32]) -> NativeProgram { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + ]; + words.extend_from_slice(body); + words.push(0xBF81_0000); // s_endpgm + let param = |root, sgprs, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 16, + layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [64, 1, 1] }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// A loop over the first active lane's counter (v1) of the lanes from s0 below s1: an +/// iteration whose count is odd narrows EXEC to those below s3, an even one keeps them all +/// (with s1 at most 32 the upper half never has a lane, as a wave of 32 sprites). The two ways +/// meet in a block of their own that only takes the back edge (SCC, live across it, keeps +/// the fold from settling EXEC there), so the loop header's EXEC join reads a join of EXEC +/// and nothing else reads that one. The first lane's count is s2 when the loop leaves; every +/// lane stores it. +pub(super) fn first_lane_loop() -> NativeProgram { + let mut c = Code::default(); + c.a.vop1("v_mov_b32", 1, int(0)); + c.vop2("v_lshlrev_b32", 5, int(2), 0); + c.vopc("v_cmp_le_u32", sgpr(0), 0); // s0 <= t + c.a.sop1("s_mov_b64", EXEC, sgpr(VCC)); + c.vopc("v_cmp_gt_u32", sgpr(1), 0); // s1 > t + c.a.sop2("s_and_b64", EXEC, sgpr(EXEC), sgpr(VCC)); + c.a.sop1("s_mov_b64", 12, sgpr(EXEC)); + c.label("header"); + c.a.vop1("v_readfirstlane_b32", 16, vgpr(1)); + c.vop2("v_add_nc_u32", 1, int(1), 1); + c.a.sop2("s_and_b32", 17, sgpr(16), int(1)); + c.a.sopc("s_cmp_eq_u32", sgpr(17), int(0)); + c.branch("s_cbranch_scc1", "wide"); + c.vopc("v_cmp_gt_u32", sgpr(3), 0); // s3 > t + c.a.sop2("s_and_b64", EXEC, sgpr(12), sgpr(VCC)); + c.a.sopc("s_cmp_lt_u32", sgpr(16), sgpr(2)); + c.branch("s_branch", "join"); + c.label("wide"); + c.a.sop1("s_mov_b64", EXEC, sgpr(12)); + c.a.sopc("s_cmp_lt_u32", sgpr(16), sgpr(2)); + c.label("join"); + c.branch("s_cbranch_scc1", "header"); + c.a.sop1("s_mov_b64", EXEC, int(-1)); + c.a.vop1("v_mov_b32", 3, sgpr(16)); + c.store(3, 5); + native(&c.words()) +} + +/// The fold reads EXEC as a number at the first-lane read, so the header's EXEC join is +/// read; the join of EXEC it takes over the back edge must be read with it. Left unread, +/// that join came out as zero in DXIL ("no lane in the lower half" from the second +/// iteration on: the read took a lane that does not count, and the loop ran to its limit). +#[test] +fn a_folded_loop_header_reads_the_mask_join_on_its_back_edge() { + let native = first_lane_loop(); + let (f, _) = crate::fold::fold(&native).unwrap_or_else(|(at, why)| panic!("fold at {at:#x}: {why}")); + let p = crate::spill::build(&f).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + + let is_mask = |v: &crate::ir::Value| st.masks.contains_key(v) || st.highs.contains_key(v); + let phi_of = |v: crate::ir::Value| { + p.blocks.iter().enumerate().find_map(|(b, block)| block.phis.iter().any(|phi| phi.value == v).then_some(b)) + }; + let readers = |v: crate::ir::Value| { + let by_phis = p.blocks.iter().flat_map(|b| &b.phis).filter(|phi| phi.args.contains(&v)).count(); + let by_insts = p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.reads.iter().any(|r| r.1 == v)).count(); + by_phis + by_insts + }; + let chain = p.blocks.iter().enumerate().any(|(h, header)| { + header.preds.iter().enumerate().any(|(n, &latch)| { + latch >= h + && header.phis.iter().any(|phi| { + let arg = phi.args[n]; + is_mask(&phi.value) && is_mask(&arg) && phi_of(arg) == Some(latch) && readers(arg) == 1 + }) + }) + }); + assert!(chain, "a loop header's mask join whose back edge brings a mask join only it reads"); + + let res = resource::track(&p, &f.layout, f.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &f).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let lowered = lower::with_folded(|| { + lower::lower(&lower::Parts { + native: &f, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered.expect("lower"); + let constants = super::bitcode::census::back_edge_constants(&lowered.dxil).expect("the module written"); + assert!( + !constants.contains(&(32, 0)), + "a 32-bit join takes zero over the back edge (the mask join left unread): {constants:?}" + ); +} diff --git a/crates/victory-shader/src/emit/folded_tests.rs b/crates/victory-shader/src/emit/folded_tests.rs index 9a246aec..a5e28871 100644 --- a/crates/victory-shader/src/emit/folded_tests.rs +++ b/crates/victory-shader/src/emit/folded_tests.rs @@ -1072,3 +1072,19 @@ fn a_folded_program_using_all_32_kib_of_lds_fits_without_the_wave_counter() { let Some(out) = run(&shader, &[], 128 * 2) else { return }; check(&out, 128, 2, |t, j| if j == 0 { t as u32 % 64 } else { 127 - t as u32 }, &["console lane", "LDS of thread 127 - t"]); } + +/// The loop of [`super::folded_join_tests::first_lane_loop`] on the host: the header's EXEC +/// join takes a join of EXEC over the back edge, and the first lane's count must reach s2 +/// (s3 above s0 keeps that lane in every iteration). With s1 at most 32 no lane of the upper +/// half ever runs: read as zero there, the lower half's EXEC dword sends the first-lane read +/// to the upper half's counters, which stay 0, and the loop runs to its limit without a store. +#[test] +fn a_folded_first_lane_loop_counts_through_a_mask_join_on_its_back_edge() { + let native = super::folded_join_tests::first_lane_loop(); + for shader in [folded(&native), folded_as_translated(&native)] { + for constants in [[0, 16, 4, 8], [0, 32, 7, 16], [8, 32, 6, 20], [32, 64, 4, 48], [0, 64, 5, 64]] { + let Some(out) = run(&shader, &constants, 64) else { return }; + check(&out, 64, 1, |_, _| constants[2], &["first active lane's count"]); + } + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index cc37a0fc..c0dad4dc 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -83,6 +83,8 @@ mod bitcode; #[cfg(test)] mod census_tests; +#[cfg(test)] +mod folded_join_tests; mod container; mod cost; #[cfg(all(test, windows))] ``` </details>
wutzebaer commented 2026-11-30 07:07:34 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by wutzebaer on 2026-11-30T07:07:34Z.


Thanks for testing, all three.

@SergDi, I added your synthetic loop to this PR as f080d07a (both tests, unchanged). Here on an RTX 5090 (driver 621.40), on the PR branch:

  • Without the fix (lower.rs as before this PR) the CPU test fails with a 32-bit join takes zero over the back edge (the mask join left unread): [(32, 0)]; with the fix it passes.
  • a_folded_first_lane_loop_counts_through_a_mask_join_on_its_back_edge ran on the hardware device and passes for all five masks in both folded forms.
  • cargo test --locked --release -p victory-shader --lib: 465 passed, 0 failed, 9 ignored.

@cadfan, good to know it also takes the light atlas out of the picture in the club; here it was the same pair of pipelines outdoors at night (2561af9577c47289 at 60-80 ms a dispatch before, gone from the card meter after).

@Lyrnc, that matches what I saw: the zero only appears when the mask join on the back edge is read by nothing but the header's join, which is the shape SergDi's loop builds.

The CI run on the first commit failed without starting a job ("workflow file issue"); ci.yml on this branch is the same as on main, and no run has started for f080d07a yet.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7271383444 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7271383444). Originally posted by [wutzebaer](https://github.com/wutzebaer) on 2026-11-30T07:07:34Z. --- Thanks for testing, all three. @SergDi, I added your synthetic loop to this PR as f080d07a (both tests, unchanged). Here on an RTX 5090 (driver 621.40), on the PR branch: - Without the fix (`lower.rs` as before this PR) the CPU test fails with `a 32-bit join takes zero over the back edge (the mask join left unread): [(32, 0)]`; with the fix it passes. - `a_folded_first_lane_loop_counts_through_a_mask_join_on_its_back_edge` ran on the hardware device and passes for all five masks in both folded forms. - `cargo test --locked --release -p victory-shader --lib`: 465 passed, 0 failed, 9 ignored. @cadfan, good to know it also takes the light atlas out of the picture in the club; here it was the same pair of pipelines outdoors at night (`2561af9577c47289` at 60-80 ms a dispatch before, gone from the card meter after). @Lyrnc, that matches what I saw: the zero only appears when the mask join on the back edge is read by nothing but the header's join, which is the shape SergDi's loop builds. The CI run on the first commit failed without starting a job ("workflow file issue"); `ci.yml` on this branch is the same as on main, and no run has started for f080d07a yet.
Ramsody commented 2026-11-30 12:05:26 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Ramsody on 2026-11-30T12:05:26Z.


Tested on another RTX 5090, this time on Windows 10. With this PR, 2561af9577c47289 no longer appears in the card meter rows, and neither of my two runs had a log line below 8 fps. The full report and three before/after logs are in #3933.

Setup: RTX 5090 (driver 617.42), Core Ultra 7 270K Plus, 64 GB, Windows 10 22H2. v2026.11.29.05 (41adb551) + f080d07a, merged with no conflicts. Series X, 2560x1440, frame generation and ray tracing off.

v2026.11.29.05, no DLSS + this PR, no DLSS + this PR, DLSS Quality M
Lines below 8 fps 56 of 135 0 of 84 0 of 122
FPS median, all world lines 13.5 20.6 20.6
FPS median at 4,000-6,999 draws (lines) 7.8 (88) 25.1 (28) 22.3 (20)
Wait for the GPU at 4,000-6,999 draws, median 74.1 ms 4.6 ms 5.2 ms
Card meter rows naming 2561af9577c47289 38, up to 164.6 ms 0 0

Tests on this card: your new loop test passed with 10 runs on the hardware device. All 19 folded_ tests passed, with none skipped.

Windows 10 note: a plain cargo test printed no SM 6.6 hardware device; not run for the GPU tests, but still reported them as ok. To really run them, I used a copy of the test exe with the D3D12 SDK 614 exports added and D3D12\D3D12Core.dll beside it.

Limits: this was not a controlled route. I have not confirmed that the "after" runs include the same spot at the petrol station at night, so the whole FPS difference should not be credited to this PR. The game was stable, with no crashes or device-removed errors in the logs. I did not specifically check shadows, water, smoke or particles for visual changes, and I did not compare this PR with the other proposed fixes.

Thank you for finding and fixing this. I would like to see it, or another verified fix for this problem, in the next release.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7277929997 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7277929997). Originally posted by [Ramsody](https://github.com/Ramsody) on 2026-11-30T12:05:26Z. --- Tested on another RTX 5090, this time on Windows 10. With this PR, `2561af9577c47289` no longer appears in the card meter rows, and neither of my two runs had a log line below 8 fps. **The full report and three before/after logs are in #3933.** **Setup:** RTX 5090 (driver 617.42), Core Ultra 7 270K Plus, 64 GB, Windows 10 22H2. v2026.11.29.05 (`41adb551`) + `f080d07a`, merged with no conflicts. Series X, 2560x1440, frame generation and ray tracing off. | | v2026.11.29.05, no DLSS | + this PR, no DLSS | + this PR, DLSS Quality M | |---|---|---|---| | Lines below 8 fps | **56 of 135** | **0 of 84** | **0 of 122** | | FPS median, all world lines | 13.5 | 20.6 | 20.6 | | FPS median at 4,000-6,999 draws (lines) | 7.8 (88) | 25.1 (28) | 22.3 (20) | | Wait for the GPU at 4,000-6,999 draws, median | 74.1 ms | 4.6 ms | 5.2 ms | | Card meter rows naming `2561af9577c47289` | 38, up to 164.6 ms | 0 | 0 | **Tests on this card:** your new loop test passed with 10 runs on the hardware device. All 19 `folded_` tests passed, with none skipped. **Windows 10 note:** a plain `cargo test` printed `no SM 6.6 hardware device; not run` for the GPU tests, but still reported them as `ok`. To really run them, I used a copy of the test exe with the D3D12 SDK 614 exports added and `D3D12\D3D12Core.dll` beside it. **Limits:** this was not a controlled route. I have not confirmed that the "after" runs include the same spot at the petrol station at night, so the whole FPS difference should not be credited to this PR. The game was stable, with no crashes or device-removed errors in the logs. I did not specifically check shadows, water, smoke or particles for visual changes, and I did not compare this PR with the other proposed fixes. Thank you for finding and fixing this. I would like to see it, or another verified fix for this problem, in the next release.
andrewpozdnakov7-jpg commented 2026-11-30 12:23:09 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by andrewpozdnakov7-jpg on 2026-11-30T12:23:09Z.


I reran the checked-in mask-join regressions, using the same Windows WARP 1.0.22 runtime and DXIL validator on both sides. The baseline is current 41adb551 with only the test commit f080d07a applied as e40f1b8. The fixed build is GitHub's exact merge of this PR into 41adb551, 7ae8b24.

Check Baseline plus test commit With this PR
Mask phi on the loop back edge Fails with the unwanted constant zero [(32, 0)] Passes
First active lane's count after dispatch Lane 0 reads 0, expected 4 All five masks pass in both folded forms

I counted ten completed WARP dispatch confirmations on the fixed run and zero adapter skips. All 19 folded_ tests also passed. The harness prints ran on the hardware device for the forced software adapter too. I set VICTORY_WARP=1, which selects DXGI's software adapter in this harness.

@Ramsody, your Windows 10 results in #3933 complement the synthetic check. If you can repeat the same petrol-station checkpoint at night with identical DLSS settings on .05 and this PR, that would give a route-matched measure of the FPS and GPU-wait changes.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7278359295 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7278359295). Originally posted by [andrewpozdnakov7-jpg](https://github.com/andrewpozdnakov7-jpg) on 2026-11-30T12:23:09Z. --- I reran the checked-in mask-join regressions, using the same Windows WARP 1.0.22 runtime and DXIL validator on both sides. The baseline is current `41adb551` with only the test commit `f080d07a` applied as `e40f1b8`. The fixed build is GitHub's exact merge of this PR into `41adb551`, `7ae8b24`. | Check | Baseline plus test commit | With this PR | | --- | --- | --- | | Mask phi on the loop back edge | Fails with the unwanted constant zero `[(32, 0)]` | Passes | | First active lane's count after dispatch | Lane 0 reads 0, expected 4 | All five masks pass in both folded forms | I counted ten completed WARP dispatch confirmations on the fixed run and zero adapter skips. All 19 `folded_` tests also passed. The harness prints `ran on the hardware device` for the forced software adapter too. I set `VICTORY_WARP=1`, which selects DXGI's software adapter in this harness. @Ramsody, your Windows 10 results in #3933 complement the synthetic check. If you can repeat the same petrol-station checkpoint at night with identical DLSS settings on .05 and this PR, that would give a route-matched measure of the FPS and GPU-wait changes. AI-assisted with OpenAI Codex.
wutzebaer commented 2026-12-01 10:09:59 +00:00 (Migrated from github.com)

Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by wutzebaer on 2026-12-01T10:09:59Z.


Closing this: both commits are in main now, unchanged, through #3871 (b8f365ad and f1e2a0cd), so there is nothing left for this PR to add. The conflict it shows is only the test file, which already holds the same tests.

Thanks to everyone who tested it: cadfan for the club run, Lyrnc for the comparison against the Radeon running the kernels natively, SergDi for the synthetic loop, Ramsody for the Windows 10 runs and andrewpozdnakov7-jpg for the WARP check.

<!-- greyfinch-sync:trustno1-coder/VIctory-NVIDIA:comment:7307771030 --> Imported from [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2853#issuecomment-7307771030). Originally posted by [wutzebaer](https://github.com/wutzebaer) on 2026-12-01T10:09:59Z. --- Closing this: both commits are in `main` now, unchanged, through #3871 (`b8f365ad` and `f1e2a0cd`), so there is nothing left for this PR to add. The conflict it shows is only the test file, which already holds the same tests. Thanks to everyone who tested it: cadfan for the club run, Lyrnc for the comparison against the Radeon running the kernels natively, SergDi for the synthetic loop, Ramsody for the Windows 10 runs and andrewpozdnakov7-jpg for the WARP check.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
trustno1-coder/VIctory-NVIDIA!2853
No description provided.