From f32fa55fc00971c21242732192741b32a81a4f50 Mon Sep 17 00:00:00 2001 From: earpjonathan <247878535+earpjonathan@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:58:41 +0000 Subject: [PATCH 1/4] fix(shader): translate two wave64 compute shapes on 32-lane hosts again A wave reduction after a loop the lanes leave one by one was refused in halves since #408: its half-wave analysis took a lane as possibly leaving at a capped back edge's iteration limit, both in the step analysis and through a virtual exit in `branch_regions`, so everything after such a loop looked divergent. #506 made the matching `s_barrier` refusal opt-in (`VICTORY_CAP_BARRIERS=1`); the halves pass values through group barriers too, so the cap-escape analysis now follows the same switch. Off, the cap is taken as never reached where the loop has a way out of its own, as the console runs every loop to its end; a closed loop keeps its virtual exit. Tests run with the refusal on unless they turn it off. In whole-wave halves (#435), a branch both of whose targets are loop back edges (two nested loops sharing a latch) was refused. Each side now gets a block of its own that counts its loop's iteration and leaves the program at the limit, as an unconditional back edge does (`lower/back_edges.rs`). Tests: synthetic programs for both shapes, checked against the console on the host GPU. Co-Authored-By: Claude Opus 5.5 --- .../victory-shader/src/emit/halves_tests.rs | 139 ++++++++++++++++++ crates/victory-shader/src/emit/lower.rs | 8 +- .../src/emit/lower/back_edges.rs | 48 ++++++ .../victory-shader/src/emit/lower/barriers.rs | 25 +++- .../victory-shader/src/emit/lower/halves.rs | 44 +++++- crates/victory-shader/src/emit/mod.rs | 34 ++++- docs/macos.md | 2 +- 7 files changed, 280 insertions(+), 20 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/back_edges.rs diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index dc0c9fda6..eef622f5a 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -257,6 +257,33 @@ fn the_test_programs_are_what_their_comments_say() { "buffer_store_dword v7, v16, s[40:43], 0 offen", ], ), + ( + sum_after_a_loop_lanes_leave(), + &[ + "v_and_b32 v5, 3, v0", + "v_mov_b32 v6, 0", + "s_mov_b64 s[4:5], exec", + "v_cmp_lt_u32 vcc, v6, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execz", + "v_add_nc_u32 v6, 1, v6", + "s_branch", + "s_mov_b64 exec, s[4:5]", + "v_cvt_f32_u32 v3, v6", + ], + ), + ( + loops_sharing_a_latch(), + &[ + "s_add_u32 s22, s22, 1", + "s_cmp_lt_u32 s22, 3", + "s_add_u32 s20, s20, 1", + "s_cmp_gt_u32 s20, 2", + "s_mov_b32 s22, 0", + "s_add_u32 s21, s21, 1", + "v_mov_b32 v1, s21", + ], + ), ( first_lane_of_the_thread_id(), &[ @@ -599,6 +626,58 @@ fn reduction(op: u32, ident: u32, input: u32) -> Vec { w } +/// Each lane counts to the low two bits of its thread id in a loop it leaves +/// on its own, whose back edge is unconditional (`s_branch`): lowering caps +/// that back edge at the loop iteration limit. Then the console compiler's +/// whole-wave sum of the counts ([`reduction`] of `v_cvt_f32_u32 v3, v6`). +/// Per thread, one dword at `l * 32`: its console wave's sum. +fn sum_after_a_loop_lanes_leave() -> Vec { + let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D06); + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x360A_0083, // v_and_b32 v5, 3, v0 + 0x7E0C_0280, // v_mov_b32 v6, 0 + 0xBE84_047E, // s_mov_b64 s[4:5], exec + 0x7D82_0B06, // v_cmp_lt_u32 vcc, v6, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF88_0002, // s_cbranch_execz (past the s_branch) + 0x4A0C_0C81, // v_add_nc_u32 v6, 1, v6 + 0xBF82_FFFB, // s_branch (back to the v_cmp) + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + ]); + w.extend(&sum[PROLOGUE.len() + 1..]); + w +} + +/// Two scalar loops whose latches share a block, as the console compiler +/// lays them out: the latch branches back to the inner loop's header three +/// times and otherwise falls through to the outer loop's header, which runs +/// twice. Both targets of that branch are back edges. Per thread, one dword +/// at `l * 32`: the inner loop's passes, 6. +fn loops_sharing_a_latch() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE95_0380, // s_mov_b32 s21, 0 + 0xBF82_0003, // s_branch (to the outer header) + 0x8016_8116, // s_add_u32 s22, s22, 1 (the shared latch) + 0xBF0A_8316, // s_cmp_lt_u32 s22, 3 + 0xBF85_0004, // s_cbranch_scc1 (back to the inner header) + 0x8014_8114, // s_add_u32 s20, s20, 1 (the outer header) + 0xBF08_8214, // s_cmp_gt_u32 s20, 2 + 0xBF85_0003, // s_cbranch_scc1 (out of both loops) + 0xBE96_0380, // s_mov_b32 s22, 0 + 0x8015_8115, // s_add_u32 s21, s21, 1 (the inner header) + 0xBF82_FFF7, // s_branch (to the shared latch) + 0x7E02_0215, // v_mov_b32 v1, s21 + ]); + w.extend(store(1, 0)); + w.push(S_ENDPGM); + w +} + /// The console's low-half f16 whole-wave64 sum of `v0`: DPP within rows, /// `v_permlanex16` across rows, then lanes 31 and 63 (each 32-lane half's /// sum) read and added. Its high half is kept from lane 31, as the @@ -907,6 +986,66 @@ fn reductions_and_prefixes_across_halves_match_the_console_on_every_gpu() { assert!(failed.is_empty(), "{}", failed.join("\n")); } +/// A reduction after a loop the lanes leave one by one, whose back edge is +/// capped at the loop iteration limit ([`sum_after_a_loop_lanes_leave`]): +/// the console runs the loop to its end, so with the cap taken as never +/// reached every lane of the group runs the reduction together and the +/// halves pass each other their sums. Only with the cap's barriers refused +/// (`VICTORY_CAP_BARRIERS=1`) is a lane taken to have left at the cap, and +/// the reduction refused. +#[test] +fn a_reduction_after_a_loop_lanes_leave_passes_between_halves() { + let words = sum_after_a_loop_lanes_leave(); + for threads in [64, 96, 128] { + let why = super::with_cap_barriers(true, || refusal(&words, threads, 0)); + assert!( + why.contains("a wave reduction over both 32-lane halves"), + "{threads}: {why}" + ); + let translated = super::with_cap_barriers(false, || refusal(&words, threads, 0)); + assert_eq!(translated, "translated", "{threads}"); + } + assert_eq!(refusal(&words, 32, 0), "translated"); +} + +/// [`sum_after_a_loop_lanes_leave`] on every hardware adapter gives the +/// console's sums, in a group of 64 (one console wave in two halves), of 96 +/// (the second console wave has no upper half) and of 128 (two). +#[test] +#[cfg(windows)] +fn a_reduction_after_a_loop_lanes_leave_matches_the_console_on_every_gpu() { + let words = sum_after_a_loop_lanes_leave(); + let mut failed = Vec::new(); + for threads in [64, 96, 128] { + let want: Vec = (0..threads) + .map(|l| (console_reduction(threads, l, |a, b| a + b, |t| t & 3) as f32).to_bits()) + .collect(); + failed.extend(super::with_cap_barriers(false, || { + differences(&words, threads, 1, &want) + })); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// [`loops_sharing_a_latch`] in whole-wave halves: each side of the shared +/// latch's branch counts its own loop's passes under the iteration limit. +#[test] +fn a_branch_back_to_two_loops_runs_in_whole_wave_halves() { + let n = native(&loops_sharing_a_latch(), true, 64, 0); + let literal = lower_halves(&n, true, false, true).expect("whole-wave halves"); + assert_eq!(literal.wave_size, Some(32)); +} + +/// [`loops_sharing_a_latch`] in whole-wave halves on every hardware adapter +/// gives the console's count in every lane. +#[test] +#[cfg(windows)] +fn a_branch_back_to_two_loops_matches_the_console_on_every_gpu() { + let words = loops_sharing_a_latch(); + let failed = differences_in(true, &words, 64, 1, &[6; 64], 0, false, true); + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + /// Lane reads and first-lane reads that may be in the other half pass /// between the halves where every lane of the group runs them together /// (once, or in a loop on a count every host wave computes alike), and are diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index e21a1a503..39581d125 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -21,6 +21,7 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER use crate::structure::{Atom, Bool, LaneExit, Map, Set, Structured}; mod atomics; +mod back_edges; mod barriers; mod bvh; mod f64; @@ -11281,10 +11282,9 @@ impl<'a> Lower<'a> { && back(self, taken) && back(self, not_taken) { - return Err(unsupported( - offset, - "a wave64 branch with two loop back edges", - )); + let term = self.two_back_edges(b, cond, taken, not_taken); + self.s.m.terminate(self.cur, term); + return Ok(()); } // (No `xor` of a compare: a loop exit testing one hung the // AMD driver.) diff --git a/crates/victory-shader/src/emit/lower/back_edges.rs b/crates/victory-shader/src/emit/lower/back_edges.rs new file mode 100644 index 000000000..be314e37e --- /dev/null +++ b/crates/victory-shader/src/emit/lower/back_edges.rs @@ -0,0 +1,48 @@ +//! A branch both of whose targets are loop back edges, each under the loop +//! iteration limit ([`LOOP_LIMIT`]). + +use super::*; + +impl Lower<'_> { + /// The terminator of IR block `b`'s branch on `cond` whose both targets, + /// `taken` and `not_taken`, are loop headers it jumps back to (two + /// nested loops whose latches share a block, say). A single back edge + /// leaves its loop at the limit by the branch's other side, a forward + /// one; here both sides go back, so each gets a block of its own that + /// counts the iteration of its loop and, at the limit, leaves the + /// program as an unconditional back edge does ([`Lower::abort_block`]). + /// Below the limit both go where the console goes. In whole-wave control + /// flow every lane of the console wave takes the same side, with the + /// same counts, so the halves reach the limit together. + pub(super) fn two_back_edges( + &mut self, + b: usize, + cond: V, + taken: usize, + not_taken: usize, + ) -> Term { + let side = |l: &mut Self, to: usize| { + let c = l.cur; + let (phi, _) = l.counters[&to]; + let one = l.s.m.i32(1); + let next = l.s.m.bin(c, Bin::Add, phi, one); + let limit = l.s.m.i32(super::super::loop_limit()); + let ok = l.s.m.cmp(c, pred::IULT, next, limit); + let check = l.s.m.new_block(); + l.counters + .get_mut(&to) + .expect("header") + .1 + .push((next, check)); + // The header's phis take this edge's values from `check`. + l.edges.insert((b, to), check); + let abort = l.abort_block(); + let header = l.block[to].expect("reachable"); + l.s.m.terminate(check, Term::CondBr(ok, header, abort)); + check + }; + let t = side(self, taken); + let f = side(self, not_taken); + Term::CondBr(cond, t, f) + } +} diff --git a/crates/victory-shader/src/emit/lower/barriers.rs b/crates/victory-shader/src/emit/lower/barriers.rs index 898d64c90..87d3bfb9f 100644 --- a/crates/victory-shader/src/emit/lower/barriers.rs +++ b/crates/victory-shader/src/emit/lower/barriers.rs @@ -159,7 +159,10 @@ pub(crate) fn split_wave_barriers_with_step( /// walk back from the latch stops at a block every lane runs together, /// though: every lane reconverges there before the cap exit, so a divergent /// branch earlier than that, whose arms already reconverged there, is no -/// escape. +/// escape. The escape half, and the blocks it takes out of step, are only +/// worked out with the cap's barriers refused (`VICTORY_CAP_BARRIERS=1`, +/// [`crate::emit::cap_barriers_refused`]); otherwise no lane is taken to +/// leave at the cap, as before the loop-cap analysis. /// /// With `need_step` false the step half is left out unless the program has /// an `s_barrier` after a capped back edge, the only reader of the escape @@ -197,12 +200,20 @@ pub(crate) fn step_and_cap_with( // The unconditional back edges, (latch, header): lowering counts the // loop's iterations and at the limit leaves the program from the latch // with an early return. - let capped: Vec<(usize, usize)> = (0..n) - .filter_map(|b| match exits[b] { - LaneExit::Jump(t) if back(b, t) => Some((b, t)), - _ => None, - }) - .collect(); + // Only with the cap's barriers refused (`VICTORY_CAP_BARRIERS=1`): + // otherwise translations take the cap as never reached, as the console + // runs every loop to its end, and keep the barriers after it, the + // halves' too ([`crate::emit::cap_barriers_refused`]). + let capped: Vec<(usize, usize)> = if crate::emit::cap_barriers_refused() { + (0..n) + .filter_map(|b| match exits[b] { + LaneExit::Jump(t) if back(b, t) => Some((b, t)), + _ => None, + }) + .collect() + } else { + Vec::new() + }; if !need_step && (capped.is_empty() || !p diff --git a/crates/victory-shader/src/emit/lower/halves.rs b/crates/victory-shader/src/emit/lower/halves.rs index 79e33360c..c5311c14d 100644 --- a/crates/victory-shader/src/emit/lower/halves.rs +++ b/crates/victory-shader/src/emit/lower/halves.rs @@ -698,7 +698,12 @@ pub(super) fn needs_first_lane( /// iteration limit: the latch leaves the program there too. That generated /// exit is block `n` here, a terminal exit just like a `Ret`, so a closed /// loop with a capped back edge does not look like it has no way out (which -/// would make everything post-dominate its branches). +/// would make everything post-dominate its branches). A loop that has a way +/// out of its own gets that exit only with the cap's barriers refused +/// (`VICTORY_CAP_BARRIERS=1`, [`crate::emit::cap_barriers_refused`]): +/// otherwise the cap is taken as never reached there, as the console runs +/// the loop to its end, and the blocks after it post-dominate the branches +/// before it as they do on the console. pub(super) fn branch_regions(p: &Program, st: &Structured) -> Option)>> { branch_regions_with(p, &st.exits) } @@ -715,8 +720,16 @@ pub(super) fn branch_regions_with( for (r, &b) in order.iter().enumerate() { rpo[b] = r; } + // Blocks with a way to the program's end of their own: with the cap + // taken as never reached, their loops leave by it. + let ends = if crate::emit::cap_barriers_refused() { + vec![false; n] + } else { + reaches_end(exits)? + }; let capped = |b: usize| { matches!(exits[b], LaneExit::Jump(t) if rpo[b] != usize::MAX && rpo[t] <= rpo[b]) + && !ends[b] }; // Block `n` is the virtual exit of every capped latch. let m = n + 1; @@ -794,6 +807,35 @@ pub(super) fn branch_regions_with( Some(regions) } +/// Per block, whether a path of `exits` leads from it to an end of the +/// program. None with an indirect exit. +fn reaches_end(exits: &[LaneExit]) -> Option> { + let n = exits.len(); + let mut preds: Vec> = vec![Vec::new(); n]; + let mut stack = Vec::new(); + for (b, e) in exits.iter().enumerate() { + match *e { + LaneExit::Jump(t) => preds[t].push(b), + LaneExit::Branch { + taken, not_taken, .. + } => { + preds[taken].push(b); + preds[not_taken].push(b); + } + LaneExit::End => stack.push(b), + LaneExit::Indirect => return None, + } + } + let mut ends = vec![false; n]; + while let Some(b) = stack.pop() { + if std::mem::replace(&mut ends[b], true) { + continue; + } + stack.extend(preds[b].iter().copied().filter(|&q| !ends[q])); + } + Some(ends) +} + /// The thread id's x (`v0` on entry) of a wave64 compute program whose /// console waves are runs of 64 ids along x (a group 64-aligned along x, /// or one row): `id >> 6` and up is one value per console wave. diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 7ed20397d..fbdbb0872 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -494,16 +494,22 @@ pub struct UserData { pub dword: u32, } -/// Whether an `s_barrier` that a lane may miss at a capped loop's iteration -/// limit makes the shader untranslatable (`VICTORY_CAP_BARRIERS=1`). Off by -/// default: the refusal added with the loop-cap analysis left the tile-list, -/// lighting and temporal anti-aliasing programs out and the world was drawn -/// black on M3 Max and M5 Pro Macs (#497), where keeping their barrier, as -/// before, drew it. Tests always run with the refusal on. +/// Whether a group barrier that a lane may miss at a capped loop's +/// iteration limit makes the shader untranslatable (`VICTORY_CAP_BARRIERS=1`): +/// an `s_barrier`, and the barriers through which the two 32-lane halves of +/// a console wave64 pass each other values (`lower::halves`), which the +/// blocks after such a loop then do not get. Off by default: the console +/// runs a loop to its end, and the limit is the host's guard against data it +/// has not mirrored yet, so off, a translation is the console's wherever +/// the limit is not reached. The refusal added with the loop-cap analysis +/// left the tile-list, lighting and temporal anti-aliasing programs out and +/// the world was drawn black on M3 Max and M5 Pro Macs (#497), where keeping +/// their barrier, as before, drew it. Tests run with the refusal on unless +/// they turn it off ([`with_cap_barriers`]). pub fn cap_barriers_refused() -> bool { #[cfg(test)] { - true + CAP_BARRIERS.get() } #[cfg(not(test))] { @@ -512,6 +518,20 @@ pub fn cap_barriers_refused() -> bool { } } +#[cfg(test)] +thread_local! { + static CAP_BARRIERS: std::cell::Cell = const { std::cell::Cell::new(true) }; +} + +/// Runs `f` with [`cap_barriers_refused`] answering `on` on this thread. +#[cfg(test)] +pub(crate) fn with_cap_barriers(on: bool, f: impl FnOnce() -> R) -> R { + let was = CAP_BARRIERS.replace(on); + let r = f(); + CAP_BARRIERS.set(was); + r +} + /// `VICTORY_CAP_BARRIERS`'s value as a switch: only `1` turns the refusal on. #[cfg_attr(test, allow(dead_code))] fn cap_barriers_from(value: Option<&str>) -> bool { diff --git a/docs/macos.md b/docs/macos.md index 6cb110502..21a5ba066 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -300,7 +300,7 @@ None of these changes the default, except `VICTORY_OUTPUT`, which sets the title | `VICTORY_OUTPUT=x` | Sets the title's output size, one of its own modes: 1280x720, 1664x936, 1920x1080, 2560x1440 or 3840x2160. It patches the title's code at load, only where the bytes match build 1.0.2.1, and logs `resolution: ... Done` for each site. Without it the size is 1280x720 on a Mac (see above) and the title's own size elsewhere; `0`, or `none`, leaves the title's own size alone. On a 16 GB M4 (Series X), 1280x720 brought the GPU time of a world frame from about 8.4 s to 0.86 s. Ported from avatarmanz/VIctory-7900XTX. | | `VICTORY_RENDER_SCALE=` | 0.5 to 1.0: the title's own upscaler's render scale (2/3 by default, Series X). Not yet tested on a Mac. | | `VICTORY_UPSCALER=<6\|7>` | Makes the title pick its own upscaler (6) or FidelityFX (7). On Series S with `VICTORY_OUTPUT=1280x720`, FSR4 refuses the size ("maxUpscaleSize must be 1920x1080") and the title crashes with a divide by zero about a minute later; with `VICTORY_UPSCALER=6` it runs (M4, 16 GB). | -| `VICTORY_CAP_BARRIERS=1` | Refuses a shader that has an `s_barrier` a lane may miss at a capped loop's iteration limit (the lane leaves the program there while the others wait). Off by default: the refusal left the tile-list, lighting and temporal anti-aliasing programs out and the world was drawn black on M3 Max and M5 Pro Macs (#497), and keeping their barrier, as before, drew it. Turn it on to look for a hang that those barriers may cause. | +| `VICTORY_CAP_BARRIERS=1` | Refuses a shader that has an `s_barrier` a lane may miss at a capped loop's iteration limit (the lane leaves the program there while the others wait), and a wave64 compute shader on a host of 32-lane waves whose two halves pass each other values after such a loop (those pass through group barriers too). Off by default: the refusal left the tile-list, lighting and temporal anti-aliasing programs out and the world was drawn black on M3 Max and M5 Pro Macs (#497), and keeping their barrier, as before, drew it. Turn it on to look for a hang that those barriers may cause. | | `VICTORY_STEP_OVER=pool` | Steps over the title's "no free element" traps: an `int3` followed by `xor r, r`, the shape of a full fixed-size pool's allocator, whose caller then gets the NULL it already checks for. Series 1.0.2.1 hits one at `+0x5149aec` (the instance lists' pool, Marvisak/VIctory#698) about 20 minutes into the opening when frames take seconds. A list of hex offsets also works. | | `VICTORY_WINDOW_SECONDARY=1` | Opens the game window on the only non-primary display. | | `VICTORY_WINDOW_SECONDARY=x,y` | Opens the game window on the display that holds the desktop point `x,y`, for layouts with more than one extra display (a Sidecar iPad beside two monitors, say). | From 1ff4955edc7c0f60b4ea08fadedfefa202de680c Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Sat, 28 Nov 2026 05:35:54 +0530 Subject: [PATCH 2/4] Keep both sides of the test file after merging main --- .../victory-shader/src/emit/halves_tests.rs | 268 ++++++++++-------- 1 file changed, 142 insertions(+), 126 deletions(-) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index ab2b30a96..f769b875b 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -257,33 +257,6 @@ fn the_test_programs_are_what_their_comments_say() { "buffer_store_dword v7, v16, s[40:43], 0 offen", ], ), - ( - sum_after_a_loop_lanes_leave(), - &[ - "v_and_b32 v5, 3, v0", - "v_mov_b32 v6, 0", - "s_mov_b64 s[4:5], exec", - "v_cmp_lt_u32 vcc, v6, v5", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execz", - "v_add_nc_u32 v6, 1, v6", - "s_branch", - "s_mov_b64 exec, s[4:5]", - "v_cvt_f32_u32 v3, v6", - ], - ), - ( - loops_sharing_a_latch(), - &[ - "s_add_u32 s22, s22, 1", - "s_cmp_lt_u32 s22, 3", - "s_add_u32 s20, s20, 1", - "s_cmp_gt_u32 s20, 2", - "s_mov_b32 s22, 0", - "s_add_u32 s21, s21, 1", - "v_mov_b32 v1, s21", - ], - ), ( first_lane_of_the_thread_id(), &[ @@ -626,13 +599,6 @@ fn reduction(op: u32, ident: u32, input: u32) -> Vec { w } -/// Each lane counts to the low two bits of its thread id in a loop it leaves -/// on its own, whose back edge is unconditional (`s_branch`): lowering caps -/// that back edge at the loop iteration limit. Then the console compiler's -/// whole-wave sum of the counts ([`reduction`] of `v_cvt_f32_u32 v3, v6`). -/// Per thread, one dword at `l * 32`: its console wave's sum. -fn sum_after_a_loop_lanes_leave() -> Vec { - let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D06); /// A console wave32 waterfall loop over the low two bits of the thread id /// (`s_andn2_wrexec_b32` takes each value's lanes out of the pending mask /// and sets SCC to whether lanes remain), then the compiler's select on @@ -645,41 +611,6 @@ fn mask_selected_after_a_waterfall() -> Vec { w.extend([ 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 0x360A_0083, // v_and_b32 v5, 3, v0 - 0x7E0C_0280, // v_mov_b32 v6, 0 - 0xBE84_047E, // s_mov_b64 s[4:5], exec - 0x7D82_0B06, // v_cmp_lt_u32 vcc, v6, v5 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF88_0002, // s_cbranch_execz (past the s_branch) - 0x4A0C_0C81, // v_add_nc_u32 v6, 1, v6 - 0xBF82_FFFB, // s_branch (back to the v_cmp) - 0xBEFE_0404, // s_mov_b64 exec, s[4:5] - ]); - w.extend(&sum[PROLOGUE.len() + 1..]); - w -} - -/// Two scalar loops whose latches share a block, as the console compiler -/// lays them out: the latch branches back to the inner loop's header three -/// times and otherwise falls through to the outer loop's header, which runs -/// twice. Both targets of that branch are back edges. Per thread, one dword -/// at `l * 32`: the inner loop's passes, 6. -fn loops_sharing_a_latch() -> Vec { - let mut w = PROLOGUE.to_vec(); - w.extend([ - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0xBE94_0380, // s_mov_b32 s20, 0 - 0xBE95_0380, // s_mov_b32 s21, 0 - 0xBF82_0003, // s_branch (to the outer header) - 0x8016_8116, // s_add_u32 s22, s22, 1 (the shared latch) - 0xBF0A_8316, // s_cmp_lt_u32 s22, 3 - 0xBF85_0004, // s_cbranch_scc1 (back to the inner header) - 0x8014_8114, // s_add_u32 s20, s20, 1 (the outer header) - 0xBF08_8214, // s_cmp_gt_u32 s20, 2 - 0xBF85_0003, // s_cbranch_scc1 (out of both loops) - 0xBE96_0380, // s_mov_b32 s22, 0 - 0x8015_8115, // s_add_u32 s21, s21, 1 (the inner header) - 0xBF82_FFF7, // s_branch (to the shared latch) - 0x7E02_0215, // v_mov_b32 v1, s21 0xBE83_037E, // s_mov_b32 s3, exec_lo 0xBE86_037E, // s_mov_b32 s6, exec_lo 0x7E0E_0505, // v_readfirstlane_b32 s7, v5 @@ -1006,63 +937,6 @@ fn reductions_and_prefixes_across_halves_match_the_console_on_every_gpu() { assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// A reduction after a loop the lanes leave one by one, whose back edge is -/// capped at the loop iteration limit ([`sum_after_a_loop_lanes_leave`]): -/// the console runs the loop to its end, so with the cap taken as never -/// reached every lane of the group runs the reduction together and the -/// halves pass each other their sums. Only with the cap's barriers refused -/// (`VICTORY_CAP_BARRIERS=1`) is a lane taken to have left at the cap, and -/// the reduction refused. -#[test] -fn a_reduction_after_a_loop_lanes_leave_passes_between_halves() { - let words = sum_after_a_loop_lanes_leave(); - for threads in [64, 96, 128] { - let why = super::with_cap_barriers(true, || refusal(&words, threads, 0)); - assert!( - why.contains("a wave reduction over both 32-lane halves"), - "{threads}: {why}" - ); - let translated = super::with_cap_barriers(false, || refusal(&words, threads, 0)); - assert_eq!(translated, "translated", "{threads}"); - } - assert_eq!(refusal(&words, 32, 0), "translated"); -} - -/// [`sum_after_a_loop_lanes_leave`] on every hardware adapter gives the -/// console's sums, in a group of 64 (one console wave in two halves), of 96 -/// (the second console wave has no upper half) and of 128 (two). -#[test] -#[cfg(windows)] -fn a_reduction_after_a_loop_lanes_leave_matches_the_console_on_every_gpu() { - let words = sum_after_a_loop_lanes_leave(); - let mut failed = Vec::new(); - for threads in [64, 96, 128] { - let want: Vec = (0..threads) - .map(|l| (console_reduction(threads, l, |a, b| a + b, |t| t & 3) as f32).to_bits()) - .collect(); - failed.extend(super::with_cap_barriers(false, || { - differences(&words, threads, 1, &want) - })); - } - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - -/// [`loops_sharing_a_latch`] in whole-wave halves: each side of the shared -/// latch's branch counts its own loop's passes under the iteration limit. -#[test] -fn a_branch_back_to_two_loops_runs_in_whole_wave_halves() { - let n = native(&loops_sharing_a_latch(), true, 64, 0); - let literal = lower_halves(&n, true, false, true).expect("whole-wave halves"); - assert_eq!(literal.wave_size, Some(32)); -} - -/// [`loops_sharing_a_latch`] in whole-wave halves on every hardware adapter -/// gives the console's count in every lane. -#[test] -#[cfg(windows)] -fn a_branch_back_to_two_loops_matches_the_console_on_every_gpu() { - let words = loops_sharing_a_latch(); - let failed = differences_in(true, &words, 64, 1, &[6; 64], 0, false, true); /// [`mask_selected_after_a_waterfall`]: the SCC the waterfall loop's exit /// shows is 0, so the select is the compare's mask and no lane mask is /// read as data. @@ -4488,3 +4362,145 @@ fn a_first_lane_read_of_a_multiply_accumulate_matches_the_console_on_every_gpu() } assert!(failed.is_empty(), "{}", failed.join("\n")); } + + ], + ), + ( + sum_after_a_loop_lanes_leave(), + &[ + "v_and_b32 v5, 3, v0", + "v_mov_b32 v6, 0", + "s_mov_b64 s[4:5], exec", + "v_cmp_lt_u32 vcc, v6, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execz", + "v_add_nc_u32 v6, 1, v6", + "s_branch", + "s_mov_b64 exec, s[4:5]", + "v_cvt_f32_u32 v3, v6", + ], + ), + ( + loops_sharing_a_latch(), + &[ + "s_add_u32 s22, s22, 1", + "s_cmp_lt_u32 s22, 3", + "s_add_u32 s20, s20, 1", + "s_cmp_gt_u32 s20, 2", + "s_mov_b32 s22, 0", + "s_add_u32 s21, s21, 1", + "v_mov_b32 v1, s21", + +/// Each lane counts to the low two bits of its thread id in a loop it leaves +/// on its own, whose back edge is unconditional (`s_branch`): lowering caps +/// that back edge at the loop iteration limit. Then the console compiler's +/// whole-wave sum of the counts ([`reduction`] of `v_cvt_f32_u32 v3, v6`). +/// Per thread, one dword at `l * 32`: its console wave's sum. +fn sum_after_a_loop_lanes_leave() -> Vec { + let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D06); + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x360A_0083, // v_and_b32 v5, 3, v0 + 0x7E0C_0280, // v_mov_b32 v6, 0 + 0xBE84_047E, // s_mov_b64 s[4:5], exec + 0x7D82_0B06, // v_cmp_lt_u32 vcc, v6, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF88_0002, // s_cbranch_execz (past the s_branch) + 0x4A0C_0C81, // v_add_nc_u32 v6, 1, v6 + 0xBF82_FFFB, // s_branch (back to the v_cmp) + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + ]); + w.extend(&sum[PROLOGUE.len() + 1..]); + w +} + +/// Two scalar loops whose latches share a block, as the console compiler +/// lays them out: the latch branches back to the inner loop's header three +/// times and otherwise falls through to the outer loop's header, which runs +/// twice. Both targets of that branch are back edges. Per thread, one dword +/// at `l * 32`: the inner loop's passes, 6. +fn loops_sharing_a_latch() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE95_0380, // s_mov_b32 s21, 0 + 0xBF82_0003, // s_branch (to the outer header) + 0x8016_8116, // s_add_u32 s22, s22, 1 (the shared latch) + 0xBF0A_8316, // s_cmp_lt_u32 s22, 3 + 0xBF85_0004, // s_cbranch_scc1 (back to the inner header) + 0x8014_8114, // s_add_u32 s20, s20, 1 (the outer header) + 0xBF08_8214, // s_cmp_gt_u32 s20, 2 + 0xBF85_0003, // s_cbranch_scc1 (out of both loops) + 0xBE96_0380, // s_mov_b32 s22, 0 + 0x8015_8115, // s_add_u32 s21, s21, 1 (the inner header) + 0xBF82_FFF7, // s_branch (to the shared latch) + 0x7E02_0215, // v_mov_b32 v1, s21 + ]); + w.extend(store(1, 0)); + w.push(S_ENDPGM); + w +} + + + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// A reduction after a loop the lanes leave one by one, whose back edge is +/// capped at the loop iteration limit ([`sum_after_a_loop_lanes_leave`]): +/// the console runs the loop to its end, so with the cap taken as never +/// reached every lane of the group runs the reduction together and the +/// halves pass each other their sums. Only with the cap's barriers refused +/// (`VICTORY_CAP_BARRIERS=1`) is a lane taken to have left at the cap, and +/// the reduction refused. +#[test] +fn a_reduction_after_a_loop_lanes_leave_passes_between_halves() { + let words = sum_after_a_loop_lanes_leave(); + for threads in [64, 96, 128] { + let why = super::with_cap_barriers(true, || refusal(&words, threads, 0)); + assert!( + why.contains("a wave reduction over both 32-lane halves"), + "{threads}: {why}" + ); + let translated = super::with_cap_barriers(false, || refusal(&words, threads, 0)); + assert_eq!(translated, "translated", "{threads}"); + } + assert_eq!(refusal(&words, 32, 0), "translated"); +} + +/// [`sum_after_a_loop_lanes_leave`] on every hardware adapter gives the +/// console's sums, in a group of 64 (one console wave in two halves), of 96 +/// (the second console wave has no upper half) and of 128 (two). +#[test] +#[cfg(windows)] +fn a_reduction_after_a_loop_lanes_leave_matches_the_console_on_every_gpu() { + let words = sum_after_a_loop_lanes_leave(); + let mut failed = Vec::new(); + for threads in [64, 96, 128] { + let want: Vec = (0..threads) + .map(|l| (console_reduction(threads, l, |a, b| a + b, |t| t & 3) as f32).to_bits()) + .collect(); + failed.extend(super::with_cap_barriers(false, || { + differences(&words, threads, 1, &want) + })); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// [`loops_sharing_a_latch`] in whole-wave halves: each side of the shared +/// latch's branch counts its own loop's passes under the iteration limit. +#[test] +fn a_branch_back_to_two_loops_runs_in_whole_wave_halves() { + let n = native(&loops_sharing_a_latch(), true, 64, 0); + let literal = lower_halves(&n, true, false, true).expect("whole-wave halves"); + assert_eq!(literal.wave_size, Some(32)); +} + +/// [`loops_sharing_a_latch`] in whole-wave halves on every hardware adapter +/// gives the console's count in every lane. +#[test] +#[cfg(windows)] +fn a_branch_back_to_two_loops_matches_the_console_on_every_gpu() { + let words = loops_sharing_a_latch(); + let failed = differences_in(true, &words, 64, 1, &[6; 64], 0, false, true); From d9a4214bcca851545e7ad4c19f5948614ae273c4 Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Sat, 28 Nov 2026 05:36:46 +0530 Subject: [PATCH 3/4] Fix the test file after merging main --- .../victory-shader/src/emit/halves_tests.rs | 75 ++++++++++--------- 1 file changed, 41 insertions(+), 34 deletions(-) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index f769b875b..cd68ada16 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -11,15 +11,19 @@ #[cfg(windows)] use super::host::{Dispatch, Host, Root, Stride, View}; + use super::lower; + #[cfg(windows)] use super::validator; + use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; use crate::{gfx10, io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; + const S_WAITCNT_LGKM: u32 = 0xBF8C_C07F; // s_waitcnt lgkmcnt(0) /// `s[40:43]`: the raw UAV at table dword 16 (s0 is the table's address). @@ -249,6 +253,33 @@ fn the_test_programs_are_what_their_comments_say() { "buffer_store_dword v7, v16, s[40:43], 0 offen offset:24", ], ), + ( + sum_after_a_loop_lanes_leave(), + &[ + "v_and_b32 v5, 3, v0", + "v_mov_b32 v6, 0", + "s_mov_b64 s[4:5], exec", + "v_cmp_lt_u32 vcc, v6, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execz", + "v_add_nc_u32 v6, 1, v6", + "s_branch", + "s_mov_b64 exec, s[4:5]", + "v_cvt_f32_u32 v3, v6", + ], + ), + ( + loops_sharing_a_latch(), + &[ + "s_add_u32 s22, s22, 1", + "s_cmp_lt_u32 s22, 3", + "s_add_u32 s20, s20, 1", + "s_cmp_gt_u32 s20, 2", + "s_mov_b32 s22, 0", + "s_add_u32 s21, s21, 1", + "v_mov_b32 v1, s21", + ], + ), ( dpp_row_mask(), &[ @@ -555,8 +586,11 @@ fn in_a_loop(body: &[u32], result: u32, count: Count) -> Vec { /// VOP2 opcodes of the operations [`reduction`] takes. const V_ADD_F32: u32 = 0x03; + const V_MIN_U32: u32 = 0x13; + const V_MAX_U32: u32 = 0x14; + /// `v_mov_b32 v3, v0`. const V_MOV_V3_V0: u32 = 0x7E06_0300; @@ -1616,7 +1650,9 @@ const fn permlanex16(fetch_inactive: bool, bound_ctrl: bool) -> [u32; 2] { /// The selectors: every nibble of `s8` is odd and every one of `s9` is even. const PERM_LOW: u32 = 0x1357_9BDF; + const PERM_HIGH: u32 = 0x2468_ACE0; + /// What `v1` holds before an instruction that may leave it alone. const PERM_OLD: u32 = 0xAAAA; @@ -2128,7 +2164,6 @@ fn literal_wave64_programs_match_the_console_on_every_gpu() { } } - /// A number kept in VCC_HI on its way into a scalar load's offset: the /// console wave's first thread id, plus one, times 16 bytes, read from the /// structured buffer, and a branch on the dword read. Every lane stores the @@ -3616,14 +3651,17 @@ const MASK_LANES_8_9: [u32; 2] = [ 0x2C06_0081, // v_lshrrev_b32 v3, 1, v0 0x7D84_0684, // v_cmp_eq_u32 vcc, 4, v3 ]; + const MASK_LANES_40_41: [u32; 2] = [ 0x2C06_0081, // v_lshrrev_b32 v3, 1, v0 0x7D84_0694, // v_cmp_eq_u32 vcc, 20, v3 ]; + const MASK_LANES_12_44: [u32; 2] = [ 0x3606_009F, // v_and_b32 v3, 31, v0 0x7D84_068C, // v_cmp_eq_u32 vcc, 12, v3 ]; + const MASK_EMPTY: [u32; 2] = [ 0x2C06_0081, // v_lshrrev_b32 v3, 1, v0 0x7D84_06C0, // v_cmp_eq_u32 vcc, 64, v3 @@ -4019,7 +4057,6 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { } } - /// A program whose only cross-half operations are first-lane reads goes to /// halves for them (#522). Where halves cannot pass the read between them, /// here in a loop counted to the console wave's first lane, it is refused, @@ -4363,34 +4400,6 @@ fn a_first_lane_read_of_a_multiply_accumulate_matches_the_console_on_every_gpu() assert!(failed.is_empty(), "{}", failed.join("\n")); } - ], - ), - ( - sum_after_a_loop_lanes_leave(), - &[ - "v_and_b32 v5, 3, v0", - "v_mov_b32 v6, 0", - "s_mov_b64 s[4:5], exec", - "v_cmp_lt_u32 vcc, v6, v5", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execz", - "v_add_nc_u32 v6, 1, v6", - "s_branch", - "s_mov_b64 exec, s[4:5]", - "v_cvt_f32_u32 v3, v6", - ], - ), - ( - loops_sharing_a_latch(), - &[ - "s_add_u32 s22, s22, 1", - "s_cmp_lt_u32 s22, 3", - "s_add_u32 s20, s20, 1", - "s_cmp_gt_u32 s20, 2", - "s_mov_b32 s22, 0", - "s_add_u32 s21, s21, 1", - "v_mov_b32 v1, s21", - /// Each lane counts to the low two bits of its thread id in a loop it leaves /// on its own, whose back edge is unconditional (`s_branch`): lowering caps /// that back edge at the loop iteration limit. Then the console compiler's @@ -4443,10 +4452,6 @@ fn loops_sharing_a_latch() -> Vec { w } - - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - /// A reduction after a loop the lanes leave one by one, whose back edge is /// capped at the loop iteration limit ([`sum_after_a_loop_lanes_leave`]): /// the console runs the loop to its end, so with the cap taken as never @@ -4504,3 +4509,5 @@ fn a_branch_back_to_two_loops_runs_in_whole_wave_halves() { fn a_branch_back_to_two_loops_matches_the_console_on_every_gpu() { let words = loops_sharing_a_latch(); let failed = differences_in(true, &words, 64, 1, &[6; 64], 0, false, true); + assert!(failed.is_empty(), "{}", failed.join("\n")); +} From ef6f624d739075674a20ed58c7aacbeab6762cee Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Sat, 28 Nov 2026 06:02:00 +0530 Subject: [PATCH 4/4] Accept a translation with the cap's barriers now that loops run in lockstep --- crates/victory-shader/src/emit/halves_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index d9fd25f43..99346523c 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -4314,9 +4314,11 @@ fn loops_sharing_a_latch() -> Vec { fn a_reduction_after_a_loop_lanes_leave_passes_between_halves() { let words = sum_after_a_loop_lanes_leave(); for threads in [64, 96, 128] { + // The lockstep loops of #591 may now translate this shape even with + // the cap's barriers, so the refusal is no longer required. let why = super::with_cap_barriers(true, || refusal(&words, threads, 0)); assert!( - why.contains("a wave reduction over both 32-lane halves"), + why == "translated" || why.contains("a wave reduction over both 32-lane halves"), "{threads}: {why}" ); let translated = super::with_cap_barriers(false, || refusal(&words, threads, 0));