diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f57cf8d7c0..91eabd5789 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -103,9 +103,10 @@ pub fn compact_mode() -> Option { } } -/// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity. +/// Non-default `XCL_DIRECT_COMPACT_NEST` and a set `XCL_WAVE64_LANE_LOOP` as cache tags for the translated cache identity. pub fn compact_nest_tag() -> Option { - super::compact::nest_mode().cache_tag() + let tags: Vec = [super::compact::nest_mode().cache_tag(), super::lane_loop::cache_tag()].into_iter().flatten().collect(); + (!tags.is_empty()).then(|| tags.join("-")) } /// `translate_full` in the compact form (`compact = true`) or the plain one. @@ -760,6 +761,7 @@ impl Lw { mask_override: None, local_masks: false, writes_lds: split && crate::gpu::recomp::emit::lds_order_wanted() && crate::gpu::recomp::emit::writes_lds(insts), + lane_loop: None, exchange_error: None, pc: 0, }; diff --git a/crates/xcl/src/gpu/dxil/lane_loop.rs b/crates/xcl/src/gpu/dxil/lane_loop.rs new file mode 100644 index 0000000000..09a40ca0d8 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lane_loop.rs @@ -0,0 +1,633 @@ +//! The lane loop: a wave64 compute program on a GPU with 32-lane waves, with nothing to +//! synchronise. One thread runs a whole console wave: a group of N threads is `ceil(N / 64)` +//! threads, each VGPR is 64 dwords local to the thread, and a vector instruction is a loop over +//! the lanes around its ordinary lowering (`Lw::inst_guarded`, the lane's EXEC bit as the +//! guard). A mask is gathered bit by bit and a lane read is a read of the array, so both are +//! whole when the last lane has run, which is where the scalar results are taken from. Scalar +//! instructions are lowered as they are. +//! +//! Slow (64 lanes in one thread) and exact: the fallback for the split form (`lanes.rs`), whose +//! halves wait for each other. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use super::cfg::{Cfg, Term}; +use super::kernel::{inside_limits, thread_limits, Entry, Kernel, KernelOptions}; +use super::lower::{ComputeInit, LResult, Lw, VAR_BUDGET, VAR_SCC, VAR_VGPR, VAR_WIN}; +use super::lower_mem::VAR_TMP; +use super::module::{BinOp, Block, Pred, Value}; +use super::reload::VAR_RELOAD; +use crate::gpu::rdna2::{self, Decoded}; +use crate::gpu::recomp::CsInterface; + +/// A split program of at most this many code dwords takes the lane loop with `XCL_WAVE64_LANE_LOOP=1`. +pub const MAX_WORDS: usize = 512; + +/// `XCL_WAVE64_LANE_LOOP`: unset none, `1` the programs of at most `MAX_WORDS`, `all` (true) every one +/// the form takes. +pub fn mode() -> Option { + static MODE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("XCL_WAVE64_LANE_LOOP").as_deref().map(str::trim) { + Ok("all") => Some(true), + Ok("1") => Some(false), + _ => None, + }) +} + +/// A set `XCL_WAVE64_LANE_LOOP`, for the translated cache's identity. +pub fn cache_tag() -> Option { + mode().map(|all| format!("xcl-wave64-lane-loop-{}", if all { "all" } else { "1" })) +} + +/// The lane loop of a split wave64 compute program that is to have one (`mode`: every program, +/// or by its size) and that the form takes. None: the split form. +pub fn choose(code: &[u8], o: KernelOptions, cs: &CsInterface, rodata: &[(u32, Vec)], mode: Option) -> Option { + if !(o.wave64 && o.split) || !mode.is_some_and(|all| all || code.len() / 4 <= MAX_WORDS) { + return None; + } + match translate(code, o, cs, rodata) { + Ok(k) => Some(k), + Err(e) => { + crate::xlog_info!("[SHADER] lane loop refused: {} – split form", e.lines().next().unwrap_or("")); + None + } + } +} + +/// A wave64 compute program as a lane loop, or why the form does not take it. +pub fn translate(code: &[u8], o: KernelOptions, cs: &CsInterface, rodata: &[(u32, Vec)]) -> Result { + let (code, cs, rodata) = (code.to_vec(), cs.clone(), rodata.to_vec()); + std::thread::Builder::new() + .name("xcl-dxil-translate".into()) + .stack_size(256 << 20) + .spawn(move || translate_on_this_thread(&code, o, &cs, rodata)) + .map_err(|e| format!("translator thread: {e}"))? + .join() + .map_err(|_| "the lane loop translator panicked".to_string())? +} + +#[derive(Default)] +pub struct LaneLoop { + /// the 64 lanes of each VGPR the program names + regs: BTreeMap, + /// the lanes the dispatch started + live: Option<(Value, Value)>, + /// the block before the loop being lowered + pre: Option, + /// the VGPR values this lane loaded for the instruction in the loop + loaded: HashMap, + /// that instruction read another lane + crossed: bool, + /// the mask words being gathered (lo, hi), and how many the loop has used + masks: Vec, + used: usize, + /// results kept until every lane has read its sources + held: Vec, + refused: Option<&'static str>, +} + +fn scalar(d: &Decoded) -> bool { + matches!(d.enc.name, "ENC_SOPP" | "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" | "ENC_SMEM") +} + +fn vgprs(d: &Decoded) -> impl Iterator { + let (r, w) = rdna2::vgpr_uses(d); + r.into_iter().chain(w).filter(|&v| v < 256).map(|v| v as u32) +} + +fn translate_on_this_thread(code: &[u8], o: KernelOptions, cs: &CsInterface, rodata: Vec<(u32, Vec)>) -> Result { + if !o.wave64 { + return Err("lane loop: not a wave64 program".into()); + } + let cfg = Cfg::build(code)?; + let waves = cs.threads.iter().product::().div_ceil(64).max(1); + for d in &cfg.insts { + let why = match d.inst.name { + "S_BARRIER" if waves > 1 => "s_barrier in a group of several waves", + n if n.starts_with("V_MOVREL") => "v_movrel", + _ if d.enc.name == "ENC_FLAT_SCRATCH" => "scratch memory", + _ => continue, + }; + return Err(format!("lane loop: {why}")); + } + let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let mut lw = Lw::new(&cfg.insts, &leaders, KernelOptions { split: false, ..o }, &Entry::Compute(cs.clone())); + if !lw.img_writes.is_empty() { + return Err("lane loop: image writes".into()); + } + if cfg.insts.iter().any(|d| d.inst.name == "S_GETPC_B64") { + lw.rodata = rodata; + } + let branchy = cfg.insts.iter().any(|d| rdna2::branch_target(d).is_some()); + (lw.dyn_rm, lw.has_f64_round_op) = super::lower::round_modes(&cfg.insts, !branchy); + lw.f32_rm = super::lower_round::f32_round_writes(&cfg.insts); + let regs: BTreeSet = (0..3).chain(cfg.insts.iter().flat_map(vgprs)).collect(); + let runs = lw.lane_loop_start(cs, waves, ®s)?; + + let entry = *cfg.rpo.first().ok_or("empty program")?; + let mut heads: Vec> = vec![None; cfg.blocks.len()]; + let mut head = |lw: &mut Lw, b: usize| -> Block { + *heads[b].get_or_insert_with(|| lw.block(Some(cfg.blocks[b].preds.len() + (b == entry) as usize))) + }; + let h0 = head(&mut lw, entry); + let exit = lw.block(None); + lw.cond_br(runs, h0, exit); + for &b in &cfg.rpo { + let h = head(&mut lw, b); + lw.s.m.set_block(h); + if cfg.headers.contains(&b) { + let left = lw.rd(VAR_BUDGET); + let none = lw.cmpc(Pred::Eq, left, 0); + let cont = lw.block(Some(1)); + lw.cond_br(none, exit, cont); + lw.s.m.set_block(cont); + let l = lw.addc(left, u32::MAX); + lw.wr(VAR_BUDGET, l); + } + for &i in &cfg.blocks[b].insts { + let d = &cfg.insts[i]; + if scalar(d) { + lw.inst(d)?; + } else { + lw.lane_loop_inst(d)?; + } + } + match cfg.blocks[b].term { + Term::Jump(t) => { + let t = head(&mut lw, t); + lw.br(t); + } + Term::Cond(i, t, f) => { + let c = lw.branch_cond(&cfg.insts[i])?; + let (t, f) = (head(&mut lw, t), head(&mut lw, f)); + lw.cond_br(c, t, f); + } + Term::End => lw.br(exit), + } + } + lw.s.m.set_block(exit); + lw.seal(exit); + lw.s.m.ret(); + if let Some(e) = lw.exchange_error.take() { + return Err(e); + } + let static_samplers = lw.static_used.iter().map(|&(w, c, _)| (w, c)).collect(); + let dxil = lw.s.try_finish([waves, 1, 1], None).map_err(|e| format!("direct DXIL builder error: {e}"))?; + if cfg!(any(test, debug_assertions)) { + super::validate::validate(&dxil).map_err(|e| format!("lane loop DXIL failed validation: {e}"))?; + } + Ok(Kernel { dxil, static_samplers, dispatch_chain: None }) +} + +impl Lw { + fn lane_array(&mut self, n: u64) -> Value { + let cur = self.cur(); + let before = self.s.m.set_insert_before_term(true); + self.s.m.set_block(self.init.entry); + let i32 = self.s.m.i32(); + let t = self.s.m.array(n, i32); + let a = self.s.m.alloca(t, 4); + self.s.m.set_block(cur); + self.s.m.set_insert_before_term(before); + a + } + + fn lane_ptr(&mut self, array: Value, i: Value) -> Value { + let z = self.c(0); + self.s.m.gep(array, &[z, i]) + } + + /// Runs `body` for each of the 64 lanes in turn, `Lw::lane` being the lane. The SSA sees the + /// body once and no way back: what it reads of the scalars is their value before the loop, + /// and what it writes is taken from the last lane. + fn each_lane(&mut self, body: &mut dyn FnMut(&mut Lw) -> LResult<()>) -> LResult<()> { + let pre = self.cur(); + let head = self.block(Some(1)); + self.br(head); + self.s.m.set_block(head); + let i32 = self.s.m.i32(); + let lane = self.s.m.phi_at(head, i32); + self.lane = lane; + self.lane31 = self.andc(lane, 31); + self.upper = self.cmpc(Pred::UGe, lane, 32); + self.half = self.lshrc(lane, 5); + let ll = self.lane_loop.as_mut().expect("lane loop"); + (ll.pre, ll.used) = (Some(pre), 0); + body(self)?; + let end = self.cur(); + let next = self.addc(lane, 1); + let z = self.c(0); + self.s.m.add_incoming(lane, z, pre); + self.s.m.add_incoming(lane, next, end); + let more = self.cmpc(Pred::ULt, next, 64); + let after = self.block(Some(1)); + self.s.m.cond_br(more, head, after); + self.edge(end, after); + self.s.m.set_block(after); + Ok(()) + } + + /// The entry: the fixed registers of `kernel::compute_init` for the console wave this + /// thread runs (thread `x` of a group of `waves`), v0..v2 and the launch EXEC lane by lane. + /// Returns whether the group runs. + fn lane_loop_start(&mut self, cs: &CsInterface, waves: u32, regs: &BTreeSet) -> LResult { + use crate::gpu::recomp::{FOLD_X, IO_GROUP_LIMIT}; + let mut ll = LaneLoop::default(); + for &n in regs { + ll.regs.insert(n, self.lane_array(64)); + } + let arrays: Vec<(u32, Value)> = ll.regs.iter().map(|(&n, &a)| (n, a)).collect(); + self.lane_loop = Some(ll); + let io = self.init.io.expect("the I/O buffer"); + let o = self.c((IO_GROUP_LIMIT * 4) as u32); + let limit = self.s.raw_load(io, o, 1)[0]; + let (gx, gy, gz) = (self.s.group_id(0), self.s.group_id(1), self.s.group_id(2)); + let k = self.c(FOLD_X); + let rows = self.mul(gy, k); + let flat = self.add(gx, rows); + let folded = self.cmpc(Pred::Ne, limit, 0); + let zero = self.c(0); + let groups = [self.sel(folded, flat, gx), self.sel(folded, zero, gy), gz]; + let inside = self.cmp(Pred::ULt, flat, limit); + let t = self.b(true); + let runs = self.sel(folded, inside, t); + let last = thread_limits(self); + let wave = self.s.thread_id_in_group(0); + let mut sgpr = HashMap::new(); + let mut next = cs.user_sgprs; + for k in 0..3 { + if cs.tgid[k] { + sgpr.insert(next, groups[k]); + next += 1; + } + } + if cs.tg_size { + let i = self.shlc(wave, 6); + sgpr.insert(next, self.orc(i, waves)); + } + sgpr.insert(VAR_SCC, zero); + self.init.compute = Some(ComputeInit { sgpr, vgpr: HashMap::new(), zero }); + let [x, y, _] = cs.threads; + let total: u32 = cs.threads.iter().product(); + let first = self.shlc(wave, 6); + let threads = cs.threads; + let ids = cs.tid_components; + self.each_lane(&mut |lw| { + let t = lw.add(first, lw.lane); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let q = lw.bin(BinOp::UDiv, t, kx); + let at = [lw.bin(BinOp::URem, t, kx), lw.bin(BinOp::URem, q, ky), lw.bin(BinOp::UDiv, t, kxy)]; + let there = lw.cmpc(Pred::ULt, t, total); + let inside = inside_limits(lw, threads, groups, last, at); + let started = lw.land(there, inside); + let (lo, hi) = lw.lane_loop_ballot(started); + lw.wr(126, lo); + lw.wr(127, hi); + for &(n, a) in &arrays { + let v = if n == 0 || n < ids.min(3) { at[n as usize] } else { zero }; + let p = lw.lane_ptr(a, lw.lane); + lw.s.m.store(p, v, 4); + } + Ok(()) + })?; + let live = (self.rd(126), self.rd(127)); + self.lane_loop.as_mut().expect("lane loop").live = Some(live); + Ok(runs) + } + + /// A vector instruction: every lane in turn loads the VGPRs it names, runs its lowering + /// with the lane's bit of EXEC as the guard and stores the VGPRs it wrote. + fn lane_loop_inst(&mut self, d: &Decoded) -> LResult<()> { + let refuse = |why: &str| -> LResult<()> { Err(format!("lane loop: {}: {why}", rdna2::format(d))) }; + let ll = self.lane_loop.as_ref().expect("lane loop"); + let live = ll.live.expect("the live lanes"); + let arrays: BTreeMap = vgprs(d).map(|n| (n, ll.regs[&n])).collect(); + let (el, eh) = (self.sreg(126), self.sreg(127)); + let mask = (self.and(el, live.0), self.and(eh, live.1)); + let before = std::mem::take(&mut self.init.touched); + let mut held: Vec<(Value, Value)> = Vec::new(); + let r = self.each_lane(&mut |lw| { + let mut loaded = HashMap::new(); + for (&n, &a) in &arrays { + let p = lw.lane_ptr(a, lw.lane); + let v = lw.s.m.load(p, 4); + lw.wr(VAR_VGPR + n, v); + loaded.insert(v, n); + } + let ll = lw.lane_loop.as_mut().expect("lane loop"); + (ll.loaded, ll.crossed) = (loaded, false); + let guard = lw.lanebit_at(mask.0, mask.1, lw.lane); + lw.ssa.begin_log(); + let r = lw.inst_guarded(d, guard, Some(mask)); + let written = lw.ssa.end_log(); + r?; + let ll = lw.lane_loop.as_mut().expect("lane loop"); + if let Some(why) = ll.refused.take() { + return refuse(why); + } + let crossed = ll.crossed; + for var in written { + match var { + v if (VAR_VGPR..VAR_BUDGET).contains(&v) => { + let Some(&a) = arrays.get(&(v - VAR_VGPR)) else { return refuse("writes a VGPR it does not name") }; + let val = lw.rd(v); + let to = if crossed { + let ll = lw.lane_loop.as_ref().expect("lane loop"); + let h = match ll.held.get(held.len()) { + Some(&h) => h, + None => { + let h = lw.lane_array(64); + lw.lane_loop.as_mut().expect("lane loop").held.push(h); + h + } + }; + held.push((h, a)); + h + } else { + a + }; + let p = lw.lane_ptr(to, lw.lane); + lw.s.m.store(p, val, 4); + } + 0..=127 | VAR_WIN => {} + v if (VAR_TMP..VAR_RELOAD).contains(&v) => {} + _ => return refuse("state of a lane besides its VGPRs"), + } + } + Ok(()) + }); + let touched = std::mem::replace(&mut self.init.touched, before); + r?; + if touched.iter().any(|v| (VAR_VGPR..VAR_BUDGET).contains(v) && !arrays.contains_key(&(v - VAR_VGPR))) { + return refuse("reads a VGPR it does not name"); + } + self.init.touched.extend(touched); + if !held.is_empty() { + self.each_lane(&mut |lw| { + for &(h, a) in &held { + let p = lw.lane_ptr(h, lw.lane); + let v = lw.s.m.load(p, 4); + let p = lw.lane_ptr(a, lw.lane); + lw.s.m.store(p, v, 4); + } + Ok(()) + })?; + } + Ok(()) + } + + /// `Lw::ballot` in a lane loop: the lane's bit joins the mask, which is whole in the last lane. + pub(super) fn lane_loop_ballot(&mut self, cond: Value) -> (Value, Value) { + let ll = self.lane_loop.as_mut().expect("lane loop"); + let (k, pre) = (ll.used, ll.pre.expect("a lane loop's body")); + ll.used += 1; + let acc = match ll.masks.get(k) { + Some(&a) => a, + None => { + let a = self.lane_array(2); + self.lane_loop.as_mut().expect("lane loop").masks.push(a); + a + } + }; + let z = self.c(0); + let cur = self.cur(); + let before = self.s.m.set_insert_before_term(true); + self.s.m.set_block(pre); + for w in 0..2 { + let i = self.c(w); + let p = self.lane_ptr(acc, i); + self.s.m.store(p, z, 4); + } + self.s.m.set_block(cur); + self.s.m.set_insert_before_term(before); + let bit = self.u(cond); + let bit = self.bin(BinOp::Shl, bit, self.lane31); + let up = self.upper; + let words = [self.sel(up, z, bit), self.sel(up, bit, z)]; + let mut out = [z; 2]; + for w in 0..2 { + let i = self.c(w as u32); + let p = self.lane_ptr(acc, i); + let old = self.s.m.load(p, 4); + out[w] = self.or(old, words[w]); + self.s.m.store(p, out[w], 4); + } + (out[0], out[1]) + } + + /// `Lw::rla` in a lane loop: lane `l` of the VGPR this lane loaded as `v`. + pub(super) fn lane_loop_read(&mut self, v: Value, l: Value) -> Value { + if self.s.m.const_u64(v).is_some() { + return v; + } + let ll = self.lane_loop.as_mut().expect("lane loop"); + let Some(&n) = ll.loaded.get(&v) else { + ll.refused = Some("a lane read of a computed value"); + return v; + }; + ll.crossed = true; + let a = ll.regs[&n]; + let l = self.andc(l, 63); + let p = self.lane_ptr(a, l); + self.s.m.load(p, 4) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::dxil::kernel; + use crate::gpu::recomp::{runner, IO_THREAD_LIMIT}; + + const V: u64 = 256; + const SPLIT: KernelOptions = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + + fn prog(list: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut v: Vec = list.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"))).collect(); + v.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + v + } + + fn cs(threads: [u32; 3]) -> CsInterface { + CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 } + } + + /// s0 = output base, s1 = x, s2 = x · y, s4 = group. Each thread stores four dwords at + /// base + (group · 256 + thread) · 16: a scalar loop's sum of ballots and lane reads, its + /// count of odd lanes below it, the passes of a saveexec loop it stayed in, and the LDS + /// dword its neighbour wrote an instruction earlier. + fn wave_ops() -> Vec { + prog(&[ + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)]), + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)]), + ("V_LSHRREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 134), ("VSRC1", 0)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 191), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 1)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 126)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 10)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)]), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)]), + // 2 (wave + 1) passes: k = 5 i + 3; sum += popcount(lanes < k) + v0 of lane k + ("S_MUL_I32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 12), ("SSRC1", 133)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 13), ("SSRC1", 131)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 13), ("VSRC1", 2)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", 106)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 14)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V), ("SRC1", 13)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 15)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 129)]), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 12), ("SSRC1", 10)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF5)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 11)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 21), ("SRC0", 129), ("VSRC1", 2)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 129), ("VSRC1", 21)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 106), ("SRC1", 128)]), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 107), ("SRC1", V + 5)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 131), ("VSRC1", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 126)]), + // a lane stays in for lane & 3 passes + ("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 10)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 106)]), + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 3)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 6)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 129), ("VSRC1", 10)]), + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 20)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 130), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 165), ("VSRC1", 0)]), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 12), ("DATA0", 13)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 129), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 130), ("VSRC1", 14)]), + ("DS_READ_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 14)]), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 16), ("SSRC0", 4), ("SSRC1", 136)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 16), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 132), ("VSRC1", 8)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 0), ("VSRC1", 8)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 4), ("SADDR", 0x7D)]), + ]) + } + + const BASE: usize = 0x100; + const GROUPS: usize = 3; + + fn run(dxil: &[u8], dims: [u32; 3]) -> Vec { + let mut io = vec![0u32; 128]; + io[..3].copy_from_slice(&[BASE as u32, dims[0], dims[0] * dims[1]]); + runner::dispatch(dxil, [GROUPS as u32, 1, 1], &io, &vec![0u32; (BASE + GROUPS * 256 * 16) / 4]).unwrap() + } + + #[test] + fn gpu_lane_loop_gives_the_console_waves_values() { + if let Err(e) = runner::device() { + return runner::skip_test(&e); + } + let code = wave_ops(); + for dims in [[48u32, 1, 1], [64, 1, 1], [96, 1, 1], [256, 1, 1], [8, 8, 4]] { + let threads = dims.iter().product::() as usize; + let k = translate(&code, SPLIT, &cs(dims), &[]).unwrap(); + let out = run(&k.dxil, dims); + for g in 0..GROUPS { + for t in 0..threads { + let (w, l) = (t / 64, t % 64); + let lanes = (threads - 64 * w).min(64); + let sum: usize = lanes + w + (0..2 * (w + 1)).map(|i| 5 * i + 3).map(|k| k.min(lanes) + 64 * w + k).sum::(); + let want = [sum as u32, l as u32 / 2, l as u32 & 3, (t as u32 ^ 1) + 37]; + let at = (BASE + (g * 256 + t) * 16) / 4; + assert_eq!(out[at..at + 4], want, "{dims:?}, group {g} thread {t}"); + } + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32: not compared with the split form"); + continue; + } + let split = kernel::translate_compute(&code, SPLIT, &cs(dims)).unwrap(); + assert_eq!(out, run(&split.dxil, dims), "{dims:?}: the split form"); + } + } + + /// `ds_bpermute` into its own source: every lane reads the register as it was. + #[test] + fn gpu_lane_loop_reads_other_lanes_before_any_is_written() { + if let Err(e) = runner::device() { + return runner::skip_test(&e); + } + let code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 161), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 3)]), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 5), ("ADDR", 3), ("DATA0", 5)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 5), ("SADDR", 0x7D)]), + ]); + let c = CsInterface { threads: [128, 1, 1], tid_components: 1, ..Default::default() }; + let k = translate(&code, SPLIT, &c, &[]).unwrap(); + let out = runner::dispatch(&k.dxil, [1; 3], &[0; 128], &[0; 128]).unwrap(); + for t in 0..128u32 { + assert_eq!(out[t as usize], t & 64 | (t & 63 ^ 33), "thread {t}"); + } + } + + /// Two groups of 64 with a limit of 100 threads: the second wave has 36 lanes. + #[test] + fn gpu_lane_loop_leaves_out_the_lanes_past_a_thread_limit() { + if let Err(e) = runner::device() { + return runner::skip_test(&e); + } + let code = prog(&[ + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 126)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 11)]), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 16), ("SSRC0", 4), ("SSRC1", 134)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 16), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 6)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 5), ("SADDR", 0x7D)]), + ]); + let k = translate(&code, SPLIT, &cs([64, 1, 1]), &[]).unwrap(); + let mut io = vec![0u32; 128]; + io[IO_THREAD_LIMIT[0]] = 100; + let out = runner::dispatch(&k.dxil, [2, 1, 1], &io, &[7; 128]).unwrap(); + for t in 0..128 { + assert_eq!(out[t], [64, 36, 7][if t >= 100 { 2 } else { t / 64 }], "thread {t}"); + } + } + + #[test] + fn lane_loop_has_one_thread_a_wave_and_nothing_to_wait_for() { + let k = translate(&wave_ops(), SPLIT, &cs([96, 1, 1]), &[]).unwrap(); + let Ok(dis) = crate::gpu::dxil::validate::disassemble(&k.dxil) else { + return runner::skip_test("no DXC"); + }; + assert!(dis.contains("!{i32 2, i32 1, i32 1}"), "numthreads\n{dis}"); + for op in ["dx.op.barrier", "atomicrmw", "cmpxchg", "dx.op.wave"] { + assert!(!dis.contains(op), "{op}\n{dis}"); + } + } + + #[test] + fn lane_loop_is_chosen_by_size_and_refusals_keep_the_split_form() { + let small = wave_ops(); + assert!(choose(&small, SPLIT, &cs([64, 1, 1]), &[], Some(false)).is_some()); + assert!(choose(&small, SPLIT, &cs([64, 1, 1]), &[], None).is_none()); + assert!(choose(&small, KernelOptions { split: false, ..SPLIT }, &cs([64, 1, 1]), &[], Some(true)).is_none()); + let filler: &[(&str, &str, &[(&str, u64)])] = &[("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 6)])]; + let large = prog(&filler.repeat(MAX_WORDS)); + assert!(choose(&large, SPLIT, &cs([64, 1, 1]), &[], Some(false)).is_none()); + assert!(choose(&large, SPLIT, &cs([64, 1, 1]), &[], Some(true)).is_some()); + + let barrier = prog(&[ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 0)]), + ("S_BARRIER", "ENC_SOPP", &[]), + ("DS_READ_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 0)]), + ]); + assert!(choose(&barrier, SPLIT, &cs([64, 1, 1]), &[], Some(true)).is_some(), "one wave: nothing to wait for"); + let e = translate(&barrier, SPLIT, &cs([128, 1, 1]), &[]).err().expect("refused"); + assert!(e.contains("s_barrier"), "{e}"); + assert!(choose(&barrier, SPLIT, &cs([128, 1, 1]), &[], Some(true)).is_none()); + kernel::translate_compute(&barrier, SPLIT, &cs([128, 1, 1])).expect("the split form"); + } +} diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 5746adaa95..ca2eef5278 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -815,6 +815,9 @@ impl Lw { /// The program's ballot of `cond` → (lo, hi) mask words. pub fn ballot(&mut self, cond: Value) -> (Value, Value) { + if self.lane_loop.is_some() { + return self.lane_loop_ballot(cond); + } if self.is_pixel() { return self.ballot_ps(cond); } @@ -971,6 +974,9 @@ impl Lw { /// of the reader's own quad through quad reads (they see helper lanes, wave reads do /// not), and a helper lane of another quad through a live lane of that quad. pub fn rla(&mut self, v: Value, l: Value) -> Value { + if self.lane_loop.is_some() { + return self.lane_loop_read(v, l); + } let h = self.hw_lane(l); let w = self.s.wave_read_lane_at(v, h); if !self.is_pixel() { diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 07220732d1..5abbd14eec 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -364,6 +364,8 @@ pub struct Lw { /// split form: the program writes LDS (`recomp::emit::writes_lds`), so its LDS reads and /// atomics keep the console wave's order (`VAR_XLW`) pub writes_lds: bool, + /// one thread runs the console wave's 64 lanes in turn (`lane_loop`) + pub lane_loop: Option, } impl Lw { diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 9ce7088a19..dde4ebe69a 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -18,6 +18,7 @@ pub mod container; pub mod coverage; pub mod graphics; pub mod kernel; +pub(crate) mod lane_loop; mod lanes; mod mask_exchange; pub mod lower; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index f4a3b95d8c..3e5f465cde 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1324,7 +1324,11 @@ pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split } } } - let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?; + let lane_loop = crate::gpu::dxil::lane_loop::choose(code, o, &cs, &rodata, crate::gpu::dxil::lane_loop::mode()); + let k = match lane_loop { + Some(k) => k, + None => crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?, + }; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9945b2849d..e075b9a121 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -37,7 +37,7 @@ fn semantic_pipeline_setting(name: &str) -> bool { "XCL_HEAP_WINDOWS" | "XCL_LDS_TOP" | "XCL_LINK_MEM" | "XCL_MEM_ACCESSORS" | "XCL_MW" | "XCL_PAGE_ALIAS" | "XCL_PER_LANE" | "XCL_PIXEL" | "XCL_RECOMP_DXIL" | "XCL_RECOMP_NO_STRUCTURED" | "XCL_SAFE_BARRIER" | - "XCL_SPLIT_WAVE64" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" | + "XCL_SPLIT_WAVE64" | "XCL_WAVE64_LANE_LOOP" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" | "XCL_XC" | "XCL_XS" | "XCL_XW" | "XCL_X_FAIL" | "XCL_X_LDS_ORDER" | "XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES") } @@ -140,6 +140,14 @@ fn warm_settings_ignore_waits_watchdogs_and_traces_but_keep_pipeline_switches() assert_eq!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_TRACEX", "1")]), "unknown diagnostics stay cache-neutral until reviewed"); } +#[cfg(test)] +#[test] +fn warm_settings_keep_the_wave64_lane_loop_switch_on_both_backends() { + let key = |entries: &[(&str, &str)]| warm_settings(entries.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + assert_ne!(key(&[]), key(&[("XCL_WAVE64_LANE_LOOP", "1")])); + assert_ne!(key(&[("XCL_DIRECT_DXIL", "1")]), key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_WAVE64_LANE_LOOP", "1")])); +} + #[cfg(test)] #[test] fn warm_settings_are_canonical_and_only_hash_semantic_switches() { diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 9a01a70742..977784cdb5 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -200,6 +200,30 @@ What is left is readlane / readfirstlane, `ds_bpermute`, coherent scalar loads a read whole. Not measured on real compute shaders (none on that machine); Minecraft's 273 wave64 programs, translated as compute, have 38 mask writes, all only read lane by lane. +## The lane loop + +A split compute program can instead run with nothing to synchronise (`gpu/dxil/lane_loop.rs`): +one thread executes a whole console wave. A group of N threads is declared as `ceil(N / 64)` +threads, thread `x` being console wave `x`; each VGPR the program names is 64 dwords local to +the thread, EXEC / VCC and the other masks are the scalars they already were, and a vector +instruction is a loop over the 64 lanes around its ordinary lowering, with the lane's bit of +EXEC as the guard. A mask is gathered bit by bit and a lane read (`v_readlane`, +`v_readfirstlane`, DPP, `ds_swizzle`, `v_permlane(x)16`, `ds_bpermute`) reads the register's +array, so both are whole once the last lane has run, and the scalar results are taken there. +An instruction that reads other lanes of a register it writes keeps its results aside until +every lane has read. Lanes past the group's threads or the dispatch's thread limits never run, +whatever the program does to EXEC. LDS stays group-shared and its accesses are in the console's +order, instruction by instruction, with no meeting. + +It costs up to 64 lanes of arithmetic in one thread and 256 bytes of thread-local memory per +VGPR, so it is a fallback, and off unless asked for: with `XCL_WAVE64_LANE_LOOP=1` +`direct_compute` (`recomp/pso.rs`) takes it for a split program of at most +`lane_loop::MAX_WORDS` (512) code dwords, with `=all` for every one the form takes. The form +refuses, and the split form runs: `s_barrier` in a group of several console waves (the wave +threads would need a barrier that survives a wave leaving early), `v_movrel*`, scratch memory, +image stores and atomics, and a lane read of anything but a VGPR as the instruction found it. +Not measured on a GPU yet. + ## Vertex and pixel shaders The driver picks the wave size of a VS or PS (HLSL has no `[WaveSize]` for them), and on a