From ffea9f3b353cc92672a51071206e373816be1565 Mon Sep 17 00:00:00 2001 From: justrealyme <82029927+justrealyme@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:08:43 +0100 Subject: [PATCH] Shaders: in halves, a first lane is read only of a value alike in both halves A wave64 program in halves (two 32-lane host waves per console wave) read v_readfirstlane_b32 as the host wave's first lane. For lanes 32..63 that is console lane 32, not lane 0: a value that differs between the halves comes out per half. On an RTX 5070 Ti, the first lane of the thread id read 32 in all 32 upper lanes (the console: 0). Now the read is kept only for a value proven the same in every lane of the console wave (`halves::lane_uniform`: built from scalars, constants and such values, under conditions that are themselves alike, LDS reads at alike addresses, the thread id shifted past the console wave), which is what the console compiler reads first lanes for. Any other first-lane read is refused with its reason; one whose result is unused costs nothing, as with the other cross-half reads. Offline over the title's shaders (translate --list --wave32): 2,372 compute programs emitted before, 2,360 after; the 12 now refused say "a first-lane read of a value that may differ between 32-lane halves". No other program changes. The analysis is ported from the one in fxceless/victory-fork (#497 there). Co-Authored-By: Claude Opus 5.5 --- .../victory-shader/src/emit/halves_tests.rs | 139 +++++++++ crates/victory-shader/src/emit/lower.rs | 24 +- .../victory-shader/src/emit/lower/halves.rs | 267 ++++++++++++++++++ 3 files changed, 426 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index f92a24fb6e..c1caea7535 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -251,6 +251,43 @@ fn reads_across_32_lane_halves_are_refused_with_their_reason() { // first lane, in halves or not. assert_eq!(refusal(&first, 64, 0), "translated"); + // With console lanes the program runs in halves, where lane 32 is the + // second host wave's first lane: a value that differs between the + // halves (the thread id) would read 32 there, the console 0. + let first_varying = [ + PROLOGUE.as_slice(), + &[ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x7E18_0500, // v_readfirstlane_b32 s12, v0 + 0x7E04_020C, // v_mov_b32 v2, s12 + ], + &store(1, 0), + &store(2, 4), + &[S_ENDPGM], + ] + .concat(); + let why = refusal(&first_varying, 64, 0); + assert!( + why.contains("a first-lane read of a value that may differ between 32-lane halves"), + "{why}" + ); + // A first-lane read nothing uses costs nothing. + let unused_first = [ + PROLOGUE.as_slice(), + &[ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x7E18_0500, // v_readfirstlane_b32 s12, v0 + ], + &store(1, 0), + &[S_ENDPGM], + ] + .concat(); + assert_eq!(refusal(&unused_first, 64, 0), "translated"); + // A value read across halves that nothing uses costs nothing. let unused = [ PROLOGUE.as_slice(), @@ -374,3 +411,105 @@ fn wave64_programs_in_halves_match_the_console_on_every_gpu() { ) ); } + +/// Per thread `l` of a group of 128 (two console wave64s), two dwords at +/// `l * 32`: the first lane of `l >> 6` (one value per console wave, the +/// same in both its halves) and the lane `v_mbcnt` counts. +fn first_lane_alike() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD766_0001, + 0x0002_02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1 + 0x2C04_0086, // v_lshrrev_b32 v2, 6, v0 + 0x7E18_0502, // v_readfirstlane_b32 s12, v2 + 0x7E06_020C, // v_mov_b32 v3, s12 + ]); + w.extend(store(3, 0)); + w.extend(store(1, 4)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_first_lane_program_is_what_its_comments_say() { + let code: Vec = first_lane_alike() + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let all = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + for want in [ + "v_lshrrev_b32 v2, 6, v0", + "v_readfirstlane_b32 s12, v2", + "v_mov_b32 v3, s12", + "buffer_store_dword v1, v16, s[40:43], 0 offen offset:4", + ] { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } +} + +/// A first-lane read of a value the same in every lane of the console wave +/// ([`first_lane_alike`]) translates in halves, and every hardware adapter +/// gives the console's results: each half reads its console wave's value. +#[test] +fn first_lanes_of_alike_values_match_the_console_on_every_gpu() { + let n = native(&first_lane_alike(), true, 128, 0); + let shader = shader(lowered(&n, true).expect("halves")); + let want: Vec<[u32; 2]> = (0..128).map(|l| [l >> 6, l & 63]).collect(); + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(128 * 8), + ]; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts = Host::each_hardware(); + if hosts.is_empty() { + eprintln!("no SM 6.6 hardware device; skipped"); + } + let mut failed = Vec::new(); + for (adapter, host) in &hosts { + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{adapter}: no pipeline: {e}")); + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{adapter}: dispatch failed: {e}")); + let wrong: Vec = out[0] + .chunks(8) + .zip(&want) + .enumerate() + .filter(|(_, (got, want))| got[..2] != want[..]) + .map(|(l, (got, want))| { + format!("{adapter}: lane {l}: {:?}, the console {want:?}", &got[..2]) + }) + .collect(); + eprintln!( + "{adapter}: {} lanes of 128 differ from the console", + wrong.len() + ); + failed.extend(wrong); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index eb2f6c641b..cad6e44b0f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -247,6 +247,9 @@ struct Lower<'a> { halves_refused: Option, /// [`Lower::relabelled_flat`], once made. relabelled: Option, + /// In halves: VGPR values the same in every lane of the console wave + /// ([`halves::lane_uniform`]), whose first lane either half reads. + alike: HashSet, /// Pixel: an ordered section (POPS), whose UAVs the host makes /// rasterizer-ordered views. pops: bool, @@ -691,6 +694,11 @@ impl<'a> Lower<'a> { halves, halves_refused, relabelled: None, + alike: if halves { + halves::lane_uniform(x) + } else { + HashSet::new() + }, pops: matches!(x.native.io, StageIo::Ps { db_shader_control, .. } if db_shader_control & 1 << 16 != 0), root_memory, @@ -6451,11 +6459,19 @@ impl<'a> Lower<'a> { int(self, a) } "v_readfirstlane_b32" => { + // In halves the host wave's first lane is the console's only + // for a value the same in both halves. + if self.halves + && matches!(v.src.first(), Some(&Operand::Vector { reg, .. }) + if !inst.read(Reg::V(reg)).is_some_and(|x| self.alike.contains(&x))) + { + return Err(halves::FIRST_ACROSS); + } let a = s(self, 0)?; - // shortcut: in halves, the first lane of the host wave, as in - // every program without console lanes (whose host waves are - // the driver's choice): the console's where the value is the - // same in every lane, what the compiler reads first lanes for. + // shortcut: without console lanes, the first lane of the host + // wave (whose waves are the driver's choice): the console's + // where the value is the same in every lane, what the compiler + // reads first lanes for. self.s.flags |= flags::WAVE_OPS; let r = self.s.op( c, diff --git a/crates/victory-shader/src/emit/lower/halves.rs b/crates/victory-shader/src/emit/lower/halves.rs index 9f6065d7d2..4896fb5bf2 100644 --- a/crates/victory-shader/src/emit/lower/halves.rs +++ b/crates/victory-shader/src/emit/lower/halves.rs @@ -126,3 +126,270 @@ impl Lower<'_> { } } } + +/// Why a first-lane read stops in halves: the console's first lane may be +/// in the other half, and the value is not known to be the same there. +pub(super) const FIRST_ACROSS: Why = "a first-lane read of a value that may differ between 32-lane halves (wave64 on a 32-lane host)"; + +/// Every per-lane branch (by its block) with its region: the blocks +/// reachable from it that do not post-dominate it, which only some lanes +/// run. Not branches on uniform conditions. None with an indirect exit. +fn lane_regions(st: &Structured) -> Option)>> { + let n = st.exits.len(); + let mut succ: Vec> = vec![Vec::new(); n]; + for (b, e) in st.exits.iter().enumerate() { + match *e { + LaneExit::Jump(t) => succ[b].push(t), + LaneExit::Branch { + taken, not_taken, .. + } => { + succ[b].push(taken); + succ[b].push(not_taken); + } + LaneExit::End => {} + LaneExit::Indirect => return None, + } + } + // Post-dominators, as bitsets (a virtual exit after every end). + let words = n.div_ceil(64); + let full = vec![u64::MAX; words]; + let mut pdom: Vec> = (0..n) + .map(|b| { + if succ[b].is_empty() { + let mut v = vec![0; words]; + v[b / 64] |= 1 << (b % 64); + v + } else { + full.clone() + } + }) + .collect(); + let mut changed = true; + while changed { + changed = false; + for b in (0..n).rev() { + if succ[b].is_empty() { + continue; + } + let mut v = full.clone(); + for &t in &succ[b] { + for (w, p) in v.iter_mut().zip(&pdom[t]) { + *w &= p; + } + } + v[b / 64] |= 1 << (b % 64); + if v != pdom[b] { + pdom[b] = v; + changed = true; + } + } + } + let mut regions = Vec::new(); + for (d, e) in st.exits.iter().enumerate() { + let LaneExit::Branch { when, .. } = *e else { + continue; + }; + if st + .bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + continue; + } + let mut seen = vec![false; n]; + let mut stack: Vec = succ[d].clone(); + while let Some(b) = stack.pop() { + if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 { + continue; + } + seen[b] = true; + stack.extend(succ[b].iter().copied()); + } + regions.push((d, seen)); + } + Some(regions) +} + +/// 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. +fn wave_tid(x: &Parts) -> Option { + let StageIo::Cs(cs) = &x.native.io else { + return None; + }; + let [tx, ty, tz] = cs.threads; + if !x.native.wave64 || !(tx % 64 == 0 || ty * tz == 1) { + return None; + } + x.p.inputs + .iter() + .find(|(r, _)| *r == Reg::V(0)) + .map(|(_, v)| *v) +} + +/// VGPR values that are the same in every lane of a console wave holding +/// them, so that a first-lane read in either half gives the console's +/// value: written lane by lane from scalars, constants and such values, by +/// an instruction every arriving lane runs or that runs under a condition +/// itself the same in every lane (then only over an old value that is such +/// a value too); loaded from LDS at such an address; or the thread id's x +/// shifted right past the console wave ([`wave_tid`]). The console +/// compiler keeps wave-uniform data in VGPRs and fetches it with +/// `v_readfirstlane`. +/// +/// A phi counts where every predecessor is a block every lane of the wave +/// reaches together: no branch on a lane-dependent condition can have split +/// them (a branch on alike values does not). The analysis runs to a fixed +/// point from nothing, so a loop-carried value that needs itself to be +/// alike never is. +pub(super) fn lane_uniform(x: &Parts) -> HashSet { + let (p, st) = (x.p, x.st); + let wave_tid = wave_tid(x); + let regions = lane_regions(st); + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let mut same: HashSet = HashSet::new(); + loop { + let alike_atom = |same: &HashSet, a: &Atom| match *a { + Atom::Uniform(_) => true, + Atom::Lane(v) => same.contains(&v), + _ => false, + }; + let alike_bool = |same: &HashSet, b: Bool| { + st.bools.support(b).iter().all(|a| alike_atom(same, a)) + }; + // Blocks every lane of a console wave reaches together. + let wave_all: Vec = match ®ions { + Some(regions) => { + let mut w = vec![true; st.exits.len()]; + for (d, region) in regions { + let LaneExit::Branch { when, .. } = st.exits[*d] else { + continue; + }; + if alike_bool(&same, when) { + continue; + } + for (b, r) in region.iter().enumerate() { + if *r { + w[b] = false; + } + } + } + w + } + None => vec![false; st.exits.len()], + }; + let mut next: HashSet = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block + .preds + .iter() + .all(|&q| wave_all.get(q).copied().unwrap_or(false)); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) + && whole + && phi + .args + .iter() + .all(|a| next.contains(a) || same.contains(a)) + { + next.insert(phi.value); + } + } + let known = |next: &HashSet, v: &Value| next.contains(v) || same.contains(v); + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + // Under a condition: only one every lane holds alike, and + // over an old value that is alike too. + if let Some(g) = st.guards[b][i] { + if !alike_bool(&same, g) { + continue; + } + let old_alike = inst + .writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .all(|w| inst.read(w.0).is_none_or(|old| known(&next, &old))); + if !old_alike { + continue; + } + } + // An LDS read at an alike address reads one value in every lane. + if let Fields::Ds { + addr: Some(Operand::Vector { reg, .. }), + dst: Some(_), + data, + .. + } = &inst.fields + && name.starts_with("ds_read") + && data.is_empty() + { + if inst.read(Reg::V(*reg)).is_some_and(|a| known(&next, &a)) { + next.extend( + inst.writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .map(|w| w.1), + ); + } + continue; + } + let ops: Vec = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.clone() + } + _ => continue, + }; + // The thread id's x shifted past the console wave: one value + // per console wave (the b32 shift uses five bits of its count). + if let ( + Some(tid), + "v_lshrrev_b32", + [ + Operand::Const(k @ 128..=192), + Operand::Vector { reg, .. }, + .., + ], + ) = (wave_tid, name, ops.as_slice()) + && ((k - 128) & 31) >= 6 + && inst.read(Reg::V(*reg)) == Some(tid) + { + next.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + continue; + } + let alike = ops.iter().all(|op| match *op { + Operand::Vector { reg, .. } => { + // every dword the instruction reads from that register on + let read: Vec = inst + .reads + .iter() + .filter(|r| matches!(r.0, Reg::V(x) if x >= reg)) + .map(|r| r.1) + .collect(); + !read.is_empty() && read.iter().all(|x| known(&next, x)) + } + // A scalar is one value; a lane mask is not, unless a + // compare of alike values made it. + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .is_none_or(|x| !is_mask(x) || known(&next, &x)), + _ => true, + }); + if alike { + next.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + } + } + } + if next.is_subset(&same) { + return same; + } + same.extend(next); + } +}