From 92897d29cbf0b9676c8d3b8238a399dfaff0f8ca Mon Sep 17 00:00:00 2001 From: Davi713 <270504181+davi713albano-coder@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:38:13 -0300 Subject: [PATCH] Shaders: support 32-lane wave64 lowering for partial-dispatch compute shaders --- crates/victory-shader/src/emit/lower.rs | 56 +++++++-------- crates/victory-shader/src/emit/packed_mask.rs | 48 ++++++++++++- .../victory-shader/src/emit/wave64_tests.rs | 70 +++++++++++++++++++ 3 files changed, 145 insertions(+), 29 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 04cf1fc2fa..669c74359d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -111,7 +111,7 @@ pub(super) fn lower_program( ) -> Result { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad, partial, uint_srvs).run(partial) { + match Lower::new(parts, &bad, uint_srvs).run(partial) { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -294,6 +294,10 @@ struct Lower<'a> { /// handed to host waves (`wave_base`), and the base made in the entry block. halves: Option, wave_base: Option, + /// Active-lane predicate for a partial-dispatch wave64 compute shader + /// lowered onto 32-lane host waves (inactive tail threads stay alive for + /// group barriers instead of returning in the prologue). + partial_active: Option, /// Vertex and mesh outputs holding 16-bit values: row, whether two per /// dword, and the row packed after it. half_outputs: HashMap)>, @@ -1256,7 +1260,7 @@ fn unsupported(offset: usize, what: Why) -> Stop { impl<'a> Lower<'a> { fn new( - x: &'a Parts<'a>, bad: &'a HashMap, partial: bool, + x: &'a Parts<'a>, bad: &'a HashMap, uint_srvs: &'static [(u8, u32, u32)], ) -> Self { let p = x.p; @@ -1313,7 +1317,7 @@ impl<'a> Lower<'a> { // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant // masks), nor when LDS may be shared within the console wave without barriers (a // group over 32 threads with LDS): those still need 64-lane waves. - if !partial && wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) { + if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) { let crosses = insts().any(|i| { let n = i.name(); n.starts_with("v_mbcnt") @@ -1573,6 +1577,7 @@ impl<'a> Lower<'a> { pair: None, halves, wave_base: None, + partial_active: None, flat: None, no_barrier, fence_only, @@ -1875,6 +1880,7 @@ impl<'a> Lower<'a> { .get(&mask) .ok_or("a wave reduction's untracked mask")?; let on = self.boolean(m, c)?; + let on = self.with_partial(c, on); let x = self.i32_of(src)?; let id = self.s.m.i32(ident); let x = self.s.m.select(c, on, x, id); @@ -2021,6 +2027,7 @@ impl<'a> Lower<'a> { .get(&mask) .ok_or("a wave reduction's untracked mask")?; let on = self.boolean(m, c)?; + let on = self.with_partial(c, on); let lo = self.i32_of(lo)?; let hi = self.i32_of(hi)?; let z = self.s.m.i32(0); @@ -2172,26 +2179,7 @@ impl<'a> Lower<'a> { fn run(mut self, partial: bool) -> Result { if partial { - // Keep inactive threads out of wave counts, packed-header - // reads, and stores. Wave64 emulation through group barriers - // requires full participation and cannot run this prologue. - let original = self.s.entry; - let width = self.s.threads.expect("compute thread count")[0]; - let limit = self.host_word(RootType::Other(super::USER_DISPATCH_THREADS_X), 0, width); - let Val::I32(group) = self.compute_id("groupId.i32", 94, 0) else { unreachable!() }; - let Val::I32(thread) = self.thread_id(0) else { unreachable!() }; - let width = self.s.m.i32(width); - let first = self.s.m.bin(original, Bin::Mul, group, width); - let x = self.s.m.bin(original, Bin::Add, first, thread); - let zero = self.s.m.i32(0); - let unlimited = self.s.m.cmp(original, pred::EQ, limit, zero); - let inside = self.s.m.cmp(original, pred::IULT, x, limit); - let active = self.s.m.bin(original, Bin::Or, unlimited, inside); - let body = self.s.m.new_block(); - let done = self.s.m.new_block(); - self.s.m.terminate(original, Term::CondBr(active, body, done)); - self.s.m.terminate(done, Term::Ret); - self.s.entry = body; + self.enter_partial_dispatch(); } let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); @@ -3117,7 +3105,7 @@ impl<'a> Lower<'a> { for first in (0..count).step_by(4) { let n = (count - first).min(4); let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); - let (h, byte, _) = self.memory(lo, hi, None); + let (h, byte, _) = self.memory(lo, hi, self.partial_active); let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( c, @@ -3203,6 +3191,11 @@ impl<'a> Lower<'a> { let bit = self.boolean(m, at); self.balloting.remove(&lo); let bit = bit?; + let bit = if self.x.st.active.contains(&lo) { + self.with_partial(at, bit) + } else { + bit + }; let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -3858,6 +3851,7 @@ impl<'a> Lower<'a> { Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, }; let bit = self.boolean(m, at)?; + let bit = self.with_partial(at, bit); let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); self.s.flags |= flags::WAVE_OPS; @@ -3907,6 +3901,7 @@ impl<'a> Lower<'a> { let t = self.s.m.bool(true); self.s.m.bin(c, Bin::Xor, mine, t) }; + let set = self.with_partial(c, set); let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); self.s.flags |= flags::WAVE_OPS; @@ -3983,10 +3978,14 @@ impl<'a> Lower<'a> { } fn guard(&mut self, b: usize, i: usize) -> Result, Why> { - match self.x.st.guards[b][i] { - None => Ok(None), - Some(g) => Ok(Some(self.boolean(g, self.cur)?)), - } + let g = match self.x.st.guards[b][i] { + None => None, + Some(g) => Some(self.boolean(g, self.cur)?), + }; + Ok(match g { + Some(g) => Some(self.with_partial(self.cur, g)), + None => self.partial_active, + }) } // ---- results ---- @@ -9073,6 +9072,7 @@ impl<'a> Lower<'a> { } }; if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) { + let r = self.with_partial(self.cur, r); self.lane_bits.insert(lo, r); } for &(_, w) in &inst.writes { diff --git a/crates/victory-shader/src/emit/packed_mask.rs b/crates/victory-shader/src/emit/packed_mask.rs index c8df1762e0..c148de97fa 100644 --- a/crates/victory-shader/src/emit/packed_mask.rs +++ b/crates/victory-shader/src/emit/packed_mask.rs @@ -1,6 +1,8 @@ //! A scalar bitwise instruction can pack a number drawn from a join of masks //! and numbers. Preserve the numeric operation when its inputs have exact words. -use super::{Bin, Bool, Fields, LaneExit, Lower, MaskData, Operand, Reg, V, Val, Value}; +use super::{ + Bin, Bool, Fields, LaneExit, Lower, MaskData, Operand, Reg, RootType, Term, V, Val, Value, pred, +}; impl Lower<'_> { pub(super) fn packed_mask_word(&mut self, value: Value) -> Option { @@ -106,6 +108,50 @@ impl Lower<'_> { } (when == Bool::FALSE && to == taken) || (when == Bool::TRUE && to == not_taken) } + + pub(super) fn enter_partial_dispatch(&mut self) { + // Keep inactive threads out of wave counts, packed-header reads, and + // stores. When a console wave64 shader is lowered onto two 32-lane host + // waves (`self.halves.is_some()`), tail threads must stay alive for + // group barriers, so mask them via `partial_active` instead of + // returning early in the prologue. + let original = self.s.entry; + let width = self.s.threads.expect("compute thread count")[0]; + let limit = self.host_word( + RootType::Other(crate::emit::USER_DISPATCH_THREADS_X), + 0, + width, + ); + let Val::I32(group) = self.compute_id("groupId.i32", 94, 0) else { + unreachable!() + }; + let Val::I32(thread) = self.thread_id(0) else { + unreachable!() + }; + let width = self.s.m.i32(width); + let first = self.s.m.bin(original, Bin::Mul, group, width); + let x = self.s.m.bin(original, Bin::Add, first, thread); + let zero = self.s.m.i32(0); + let unlimited = self.s.m.cmp(original, pred::EQ, limit, zero); + let inside = self.s.m.cmp(original, pred::IULT, x, limit); + let active = self.s.m.bin(original, Bin::Or, unlimited, inside); + if self.halves.is_some() { + self.partial_active = Some(active); + } else { + let body = self.s.m.new_block(); + let done = self.s.m.new_block(); + self.s.m.terminate(original, Term::CondBr(active, body, done)); + self.s.m.terminate(done, Term::Ret); + self.s.entry = body; + } + } + + pub(super) fn with_partial(&mut self, at: usize, cond: V) -> V { + match self.partial_active { + Some(active) => self.s.m.bin(at, Bin::And, cond, active), + None => cond, + } + } } #[cfg(all(test, windows))] diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 6ecf89b652..c891fc6e3f 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -572,3 +572,73 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() } eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); } + +#[test] +fn partial_thread_dispatch_on_32_lane_host_emits_wave32_and_masks_wave_counts_and_writes() { + use crate::dxbc::{Container, FourCC}; + + // Wave64 kernel with cross-lane EXEC popcount (`s_bcnt1_i32_b64 s6, exec`) + // and per-lane store (`out[thread_x] = active_count`), lowered with partial + // tail-group masking for a 32-lane host (such as NVIDIA). + let native = native(&[ + 0xBE86_107E, // s_bcnt1_i32_b64 s6, exec + 0x7E02_0206, // v_mov_b32 v1, s6 + 0x3404_0082, // v_lshlrev_b32 v2, 2, v0 + 0xE070_1000, + 0x8002_0102, // buffer_store_dword v1, v2, s[8:11], 0 offen + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_for_dispatch(&native, &p, &HashSet::new(), 32, true).expect("lower"); + let limit = shader + .user_data + .iter() + .find(|u| u.root == RootType::Other(super::USER_DISPATCH_THREADS_X)) + .expect("partial thread limit user data"); + assert_eq!((limit.slot, limit.dword), (0, 64)); + + // Must declare WaveSize(32) in PSV0 rather than WaveSize(64) so 32-lane + // devices accept the pipeline. + let c = Container::parse(&shader.dxil).expect("Container::parse"); + let psv = c.part(FourCC::PSV0).expect("PSV0").data; + let min_wave = u32::from_le_bytes(psv[20..24].try_into().unwrap()); + let max_wave = u32::from_le_bytes(psv[24..28].try_into().unwrap()); + assert_eq!((min_wave, max_wave), (32, 32)); + + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; skipped live wave32 partial dispatch check"); + return; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("hardware device does not take this 32-lane pipeline; skipped"); + return; + }; + for count in [0u32, 1, 7, 31, 32, 33, 45, 63, 64] { + let mut constants = vec![0u32; shader.user_data_dwords().max(1) as usize]; + constants[limit.index as usize] = count; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(constants))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch"); + let active = if count == 0 { 64 } else { count }; + for (i, &got) in out[0].iter().enumerate() { + let want = if (i as u32) < active { active } else { 0 }; + assert_eq!(got, want, "count {count}, thread {i}"); + } + } +}