From 1bab75769119611600050070c741e37dd8e4edc1 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:15:13 -0300 Subject: [PATCH 01/51] Recompiler: per-lane lane-mask analysis for a direct DXIL backend A backend that writes DXIL itself keeps the console CFG, so each lane can branch on its own EXEC bit instead of every vector write being guarded and branchy programs going through the `pc` dispatcher. This is the analysis it needs: every lane mask is followed as a per-lane boolean function (a BDD over the lanes' compare / carry results, uniform SCCs and unresolved joins), mask branches are taken lane by lane, and a forward dataflow gives what holds in each lane reaching a block. A vector instruction keeps its guard only where reaching it does not imply the lane's EXEC bit. Loop heads are guessed from their forward edges and checked against the back edges; a wrong guess becomes an atom and only that head recomputes. Results too large for a per-step node budget are weakened to atoms, which only costs precision. Indirect jumps and irreducible loops are refused. Nothing translates with it yet: `xcl shaders --recomp` prints its counts. On the retail pack: 25 695 of 26 698 programs analysed (983 indirect jumps, 20 irreducible), 10.65 M of 28.71 M vector instructions still guarded (37.1 %), 9 015 programs with no guard at all, 700 CPU-s for the whole pack (slowest program 1.5 s). --- crates/xcl/src/gpu/recomp/lane_masks.rs | 913 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 1 + crates/xcl/src/shaders.rs | 32 + 3 files changed, 946 insertions(+) create mode 100644 crates/xcl/src/gpu/recomp/lane_masks.rs diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs new file mode 100644 index 0000000000..4de6d4d5ac --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -0,0 +1,913 @@ +//! Lane masks as per-lane booleans: what a backend that writes DXIL itself (no HLSL, so no +//! structured control flow) needs in order to run console code without emulating EXEC. +//! +//! The HLSL path keeps EXEC as a wave-uniform value and guards every vector write with the +//! lane's bit of it. With an unstructured CFG each lane can instead branch on its own bit and +//! leave reconvergence to the host driver. Per program this works out: +//! - every lane mask (EXEC, VCC, any SGPR a mask is kept in) as a boolean function of *atoms* – +//! the lane's result of a VALU compare or carry, a wave-uniform SCC, a mask it cannot follow, +//! a join it cannot resolve – as a reduced ordered BDD; +//! - every branch on a mask (`s_cbranch_execz/execnz/vccz/vccnz`, SCC of a mask op) as a branch +//! of each lane on its own bit, and a branch on any other SCC as a uniform one; +//! - for every block, what holds in each lane that reaches it: a forward dataflow over the +//! branch conditions; facts a back edge carries about atoms its loop redefines are dropped; +//! - which vector instructions still need a guard: those where reaching the instruction does +//! not imply the lane's EXEC bit. +//! +//! Branching lane by lane on a mask assumes what compiled code does: it jumps over work that +//! inactive lanes would not change anyway, or it tests a uniform value. A join of a mask is +//! resolved when every lane coming in has it set (or clear) – EXEC restored where the branches +//! meet – and becomes an atom otherwise. A loop head's join is guessed from its forward edges +//! and checked against its back edges; a wrong guess becomes an atom and the analysis restarts. +//! +//! Nothing translates with this yet: `xcl shaders --recomp` reports its counts. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use super::x64_masks; +use crate::gpu::rdna2::{self, Decoded, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; + +type R = Result; + +/// A BDD node: 0 = false, 1 = true. +type B = u32; +const FALSE: B = 0; +const TRUE: B = 1; +/// More nodes than this: the program fails with "lane conditions too large". +const MAX_NODES: usize = 1 << 20; +/// New nodes one reach fact may take before it is weakened. +const STEP_NODES: usize = 1 << 9; +/// Passes of the reach fixpoint, restarts after wrong loop-head guesses included. +const MAX_ROUNDS: usize = 256; +const EXEC: usize = 126; +const VCC: usize = 106; +/// The SCC slot of a join. +const SCC: usize = 128; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Op { + And, + Or, + Xor, +} + +struct Bdd { + /// (atom, low, high); the terminals have atom u32::MAX, so atoms created first are on top + nodes: Vec<(u32, B, B)>, + unique: HashMap<(u32, B, B), B>, + memo: HashMap<(Op, B, B), B>, + /// node count `mk` fails at + limit: usize, +} + +impl Bdd { + fn new() -> Self { + Bdd { nodes: vec![(u32::MAX, 0, 0), (u32::MAX, 1, 1)], unique: HashMap::new(), memo: HashMap::new(), limit: MAX_NODES } + } + + /// `f`'s result, or None when it needs more than `STEP_NODES` new nodes (those it made stay: + /// they are valid nodes, and the memo stays right). For results that can be weakened. + fn within(&mut self, f: impl FnOnce(&mut Self) -> R) -> Option { + self.limit = (self.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = f(self); + self.limit = MAX_NODES; + r.ok() + } + + /// The function "atom v", whatever the limits: what a weakened result falls back on. + fn atom(&mut self, v: u32) -> B { + if let Some(&n) = self.unique.get(&(v, FALSE, TRUE)) { + return n; + } + let n = self.nodes.len() as B; + self.nodes.push((v, FALSE, TRUE)); + self.unique.insert((v, FALSE, TRUE), n); + n + } + + fn mk(&mut self, v: u32, lo: B, hi: B) -> R { + if lo == hi { + return Ok(lo); + } + if let Some(&n) = self.unique.get(&(v, lo, hi)) { + return Ok(n); + } + if self.nodes.len() >= self.limit { + return Err("lane conditions too large"); + } + let n = self.nodes.len() as B; + self.nodes.push((v, lo, hi)); + self.unique.insert((v, lo, hi), n); + Ok(n) + } + + fn apply(&mut self, op: Op, a: B, b: B) -> R { + let (a, b) = (a.min(b), a.max(b)); + match (op, a) { + (Op::And, FALSE) => return Ok(FALSE), + (Op::Or, TRUE) => return Ok(TRUE), + (Op::And, TRUE) | (Op::Or | Op::Xor, FALSE) => return Ok(b), + _ if a == b => return Ok(if op == Op::Xor { FALSE } else { a }), + _ => {} + } + if let Some(&n) = self.memo.get(&(op, a, b)) { + return Ok(n); + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + let lo = self.apply(op, a0, b0)?; + let hi = self.apply(op, a1, b1)?; + let n = self.mk(v, lo, hi)?; + self.memo.insert((op, a, b), n); + Ok(n) + } + + fn and(&mut self, a: B, b: B) -> R { + self.apply(Op::And, a, b) + } + + fn or(&mut self, a: B, b: B) -> R { + self.apply(Op::Or, a, b) + } + + fn not(&mut self, a: B) -> R { + self.apply(Op::Xor, a, TRUE) + } + + /// a → b, without building a ∧ ¬b. + fn implies(&self, a: B, b: B) -> bool { + self.implies_in(a, b, &mut HashSet::new()) + } + + fn implies_in(&self, a: B, b: B, seen: &mut HashSet<(B, B)>) -> bool { + if a == FALSE || b == TRUE || a == b { + return true; + } + if a == TRUE && b == FALSE { + return false; + } + if !seen.insert((a, b)) { + return true; + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + self.implies_in(a0, b0, seen) && self.implies_in(a1, b1, seen) + } + + /// a → ¬b, i.e. a ∧ b is false, without building it. + fn disjoint(&self, a: B, b: B, seen: &mut HashSet<(B, B)>) -> bool { + if a == FALSE || b == FALSE { + return true; + } + if a == TRUE && b == TRUE { + return false; + } + if a == b || !seen.insert((a, b)) { + return a != b; + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + self.disjoint(a0, b0, seen) && self.disjoint(a1, b1, seen) + } + + /// `a` with the atoms `drop` names quantified away (∃). + fn exists(&mut self, a: B, drop: &dyn Fn(u32) -> bool, memo: &mut HashMap) -> R { + if a <= TRUE { + return Ok(a); + } + if let Some(&n) = memo.get(&a) { + return Ok(n); + } + let (v, lo, hi) = self.nodes[a as usize]; + let (lo, hi) = (self.exists(lo, drop, memo)?, self.exists(hi, drop, memo)?); + let n = if drop(v) { self.or(lo, hi)? } else { self.mk(v, lo, hi)? }; + memo.insert(a, n); + Ok(n) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Atom { + /// the lane's result of the VALU compare / carry at this pc (before EXEC) + Lane(u64), + /// SCC written at this pc: uniform + Scc(u64), + /// a mask the analysis cannot follow, read at this pc from this register + Opaque(u64, usize), + /// an unresolved join of this slot (SGPR, `SCC`) at the start of this block + Join(usize, usize), +} + +/// The masks at a program point. `regs[r]`: the lane function of the mask SGPR r holds (wave64: +/// in the pair's first register), None when it holds nothing the analysis knows as a mask. +/// EXEC always has one. `scc`: (lane function, true when it is a mask op's "result has the +/// lane's bit" rather than a uniform value). +#[derive(Clone, PartialEq)] +struct State { + regs: Vec>, + scc: Option<(B, bool)>, +} + +#[derive(Clone, Copy, PartialEq)] +enum Edge { + Always, + Taken, + NotTaken, +} + +/// What the analysis found in a program. +#[derive(Debug, Default)] +pub struct Summary { + /// vector instructions (VALU writes, memory, LDS, exports) + pub vector: usize, + /// pcs of those that still need a guard on the lane's EXEC bit + pub guarded: Vec, + /// conditional branches on a lane mask (each lane decides) and on uniform values + pub lane_branches: usize, + pub uniform_branches: usize, +} + +/// Executed with the lane's EXEC bit (VOPC and the lane reads / writes are mask producers). +fn is_vector(d: &Decoded) -> bool { + let n = d.inst.name; + !n.starts_with("S_") && !n.starts_with("V_CMP") && !matches!(n, "V_READLANE_B32" | "V_READFIRSTLANE_B32" | "V_WRITELANE_B32") +} + +struct Lanes<'a> { + insts: &'a [Decoded], + wave64: bool, + bdd: Bdd, + atoms: HashMap, + /// block each atom is born in + born: Vec, + /// block → its instruction index range, successors (block, edge), predecessors (block, + /// index in its successors) + blocks: Vec<(usize, usize)>, + succ: Vec>, + preds: Vec>, + /// reverse postorder, and for each block: Some(blocks of its loop) when it heads one + order: Vec, + body: Vec>>, + /// per instruction: SGPRs it overwrites (`x64_masks::uses`), SGPRs it may change, whether + /// it writes SCC + effects: Vec<(u128, u128, bool)>, +} + +impl<'a> Lanes<'a> { + fn new(insts: &'a [Decoded], wave64: bool) -> R { + let starts: HashMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut leaders = BTreeSet::from([0usize]); + let mut target = vec![None; insts.len()]; + for (i, d) in insts.iter().enumerate() { + let indirect = d.far_target.is_none() && (d.inst.flags & F_INDIRECT != 0 || matches!(d.inst.name, "S_SETPC_B64" | "S_SWAPPC_B64")); + if indirect { + return Err("indirect jump"); + } + if let Some(t) = rdna2::branch_target(d) { + let &j = starts.get(&t).ok_or("branch into an instruction")?; + if j == 0 { + return Err("branch to the entry"); + } + target[i] = Some(j); + leaders.extend([j, i + 1]); + } else if d.inst.flags & F_TERMINATOR != 0 { + leaders.insert(i + 1); + } + } + leaders.retain(|&i| i < insts.len()); + let firsts: Vec = leaders.into_iter().collect(); + let block_of: HashMap = firsts.iter().enumerate().map(|(b, &i)| (i, b)).collect(); + let blocks: Vec<(usize, usize)> = firsts.iter().enumerate().map(|(b, &i)| (i, firsts.get(b + 1).copied().unwrap_or(insts.len()))).collect(); + let succ: Vec> = blocks + .iter() + .map(|&(_, end)| { + let d = &insts[end - 1]; + let next = block_of.get(&end).copied(); + match target[end - 1] { + Some(t) if d.inst.flags & F_CONDITIONAL != 0 => [Some((block_of[&t], Edge::Taken)), next.map(|n| (n, Edge::NotTaken))].into_iter().flatten().collect(), + Some(t) => vec![(block_of[&t], Edge::Always)], + None if d.inst.flags & F_TERMINATOR != 0 => vec![], + None => next.map(|n| (n, Edge::Always)).into_iter().collect(), + } + }) + .collect(); + let n = blocks.len(); + // reverse postorder of what the entry reaches + let (mut order, mut seen, mut stack) = (Vec::new(), vec![false; n], vec![(0usize, 0usize)]); + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, i) = *top; + if let Some(&(s, _)) = succ[b].get(i) { + top.1 += 1; + if !seen[s] { + seen[s] = true; + stack.push((s, 0)); + } + } else { + order.push(b); + stack.pop(); + } + } + order.reverse(); + let mut rpo = vec![usize::MAX; n]; + for (i, &b) in order.iter().enumerate() { + rpo[b] = i; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for (k, &(s, _)) in succ[b].iter().enumerate() { + preds[s].push((b, k)); + } + } + // dominators (Cooper, Harvey, Kennedy) – a retreating edge must go to a dominator + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while rpo[a] > rpo[b] { + a = idom[a]; + } + while rpo[b] > rpo[a] { + b = idom[b]; + } + } + a + }; + loop { + let mut changed = false; + for &b in &order[1..] { + let new = preds[b].iter().map(|p| p.0).filter(|&p| idom[p] != usize::MAX).reduce(|a, p| intersect(&idom, a, p)).unwrap_or(usize::MAX); + changed |= idom[b] != new; + idom[b] = new; + } + if !changed { + break; + } + } + let dominates = |h: usize, mut b: usize| loop { + if b == h { + return true; + } + if b == 0 { + return false; + } + b = idom[b]; + }; + let mut body: Vec>> = vec![None; n]; + for &h in &order { + for &(p, _) in &preds[h] { + if rpo[p] < rpo[h] { + continue; + } + if !dominates(h, p) { + return Err("irreducible control flow"); + } + let inside = body[h].get_or_insert_with(|| vec![false; n]); + inside[h] = true; + let mut work = vec![p]; + while let Some(b) = work.pop() { + if !inside[b] { + inside[b] = true; + work.extend(preds[b].iter().map(|q| q.0)); + } + } + } + } + let effects = insts + .iter() + .map(|d| { + let written = x64_masks::uses(d).1; + let explicit = rdna2::sgpr_uses(d).1.iter().fold(0u128, |m, &r| m | 1 << r); + let kill = if d.inst.name.starts_with("S_MOVREL") { !0 } else { written | explicit }; + (written, kill, d.ienc.operands.iter().any(|o| o.output && o.ty == "OPR_SSRC_SPECIAL_SCC")) + }) + .collect(); + Ok(Lanes { insts, wave64, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, body, effects }) + } + + fn atom(&mut self, a: Atom, block: usize) -> R { + let fresh = self.born.len() as u32; + let v = *self.atoms.entry(a).or_insert(fresh); + if v == fresh { + self.born.push(block); + } + Ok(self.bdd.atom(v)) + } + + /// `step` within `STEP_NODES` new nodes; past that, what the instruction writes becomes + /// unknown: EXEC and SCC atoms, no mask in the other registers (weaker, still sound). + fn step_bounded(&mut self, st: &mut State, i: usize, block: usize) -> R<()> { + let mut next = st.clone(); + self.bdd.limit = (self.bdd.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = self.step(&mut next, i, block); + self.bdd.limit = MAX_NODES; + if r.is_ok() { + *st = next; + return Ok(()); + } + let d = &self.insts[i]; + let (_, kill, writes_scc) = self.effects[i]; + for r in (0..128).filter(|&r| kill >> r & 1 != 0) { + self.kill(st, r); + } + if st.regs[EXEC].is_none() || d.inst.name.starts_with("V_CMPX") { + st.regs[EXEC] = Some(self.atom(Atom::Opaque(d.pc, EXEC), block)?); + } + if writes_scc { + st.scc = Some((self.atom(Atom::Scc(d.pc), block)?, true)); + } + Ok(()) + } + + /// A scalar source read as a mask: a register's lane function, all lanes, none, or None. + fn mask_src(&self, st: &State, d: &Decoded, code: u64) -> Option { + match code { + 128 => Some(FALSE), + 193 => Some(TRUE), + 255 if d.literal == Some(0) => Some(FALSE), + 255 if d.literal == Some(!0) && !self.wave64 => Some(TRUE), + c if c < 128 => st.regs[c as usize], + _ => None, + } + } + + /// … and an atom where the analysis cannot follow it. + fn need(&mut self, st: &State, d: &Decoded, code: u64, block: usize) -> R { + match self.mask_src(st, d, code) { + Some(v) => Ok(v), + None => self.atom(Atom::Opaque(d.pc, code as usize), block), + } + } + + fn combine(&mut self, op: &str, a: B, b: B) -> R> { + let bdd = &mut self.bdd; + Ok(Some(match op { + "AND" => bdd.and(a, b)?, + "OR" => bdd.or(a, b)?, + "XOR" => bdd.apply(Op::Xor, a, b)?, + "ANDN2" => (bdd.not(b).and_then(|nb| bdd.and(a, nb)))?, + "ORN2" => (bdd.not(b).and_then(|nb| bdd.or(a, nb)))?, + "ANDN1" => (bdd.not(a).and_then(|na| bdd.and(na, b)))?, + "ORN1" => (bdd.not(a).and_then(|na| bdd.or(na, b)))?, + "NAND" => (bdd.and(a, b).and_then(|x| bdd.not(x)))?, + "NOR" => (bdd.or(a, b).and_then(|x| bdd.not(x)))?, + "XNOR" => (bdd.apply(Op::Xor, a, b).and_then(|x| bdd.not(x)))?, + _ => return Ok(None), + })) + } + + /// One instruction's effect on the masks. + fn step(&mut self, st: &mut State, i: usize, block: usize) -> R<()> { + let d = &self.insts[i]; + let (written, kill, writes_scc) = self.effects[i]; + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let e = st.regs[EXEC].expect("EXEC"); + let mut set: Vec<(usize, B)> = Vec::new(); + let mut scc = None; + if name.starts_with("V_") { + if name.starts_with("V_CMPX") { + let l = self.atom(Atom::Lane(d.pc), block)?; + set.push((EXEC, self.bdd.and(l, e)?)); + } else if written != 0 && !matches!(name, "V_READLANE_B32" | "V_READFIRSTLANE_B32") { + // compares and carries: the lane's result, 0 in inactive lanes + let l = self.atom(Atom::Lane(d.pc), block)?; + set.push((written.trailing_zeros() as usize, self.bdd.and(l, e)?)); + } + } else if let Some(base) = name.strip_suffix(if self.wave64 { "_B64" } else { "_B32" }) { + let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").map(|v| v as usize)); + let op = base.trim_start_matches("S_"); + if let Some(op) = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")) { + let a = self.need(st, d, s0, block)?; + let new = self.combine(op, a, e)?.ok_or("unknown saveexec")?; + set.push((EXEC, new)); + if let Some(sd) = sd.filter(|&r| r < 128) { + set.push((sd, if base.ends_with("_WREXEC") { new } else { e })); + } + scc = Some((new, true)); + } else { + let (a, b) = (self.mask_src(st, d, s0), self.mask_src(st, d, s1)); + let value = match (op, a, b) { + ("MOV", Some(a), _) => Some(a), + ("NOT", Some(a), _) => Some(self.bdd.not(a)?), + ("CSELECT", Some(a), Some(b)) => match st.scc { + Some((u, false)) => { + let (ua, nu) = (self.bdd.and(u, a)?, self.bdd.not(u)?); + let nub = self.bdd.and(nu, b)?; + Some(self.bdd.or(ua, nub)?) + } + _ => None, + }, + (_, Some(a), Some(b)) => self.combine(op, a, b)?, + _ => None, + }; + if let (Some(v), Some(sd)) = (value, sd.filter(|&r| r < 128)) { + set.push((sd, v)); + if !matches!(op, "MOV" | "CSELECT") { + scc = Some((v, true)); + } + } + } + } + // mask compares (`s_cmp_lg_u64 exec, 0`): whether the lane's bits differ / agree + let cmp = if self.wave64 { ("S_CMP_EQ_U64", "S_CMP_LG_U64") } else { ("S_CMP_EQ_U32", "S_CMP_LG_U32") }; + if name == cmp.0 || name == cmp.1 { + let (s0, s1) = (fv("SSRC0").unwrap_or(255), fv("SSRC1").unwrap_or(255)); + if let (Some(a), Some(b)) = (self.mask_src(st, d, s0), self.mask_src(st, d, s1)) { + if s0 < 128 || s1 < 128 { + let x = self.bdd.apply(Op::Xor, a, b)?; + scc = Some((if name == cmp.0 { self.bdd.not(x)? } else { x }, true)); + } + } + } + // whatever else the instruction writes is no longer a known mask + for r in (0..128).filter(|&r| kill >> r & 1 != 0) { + self.kill(st, r); + } + for (r, v) in set { + self.kill(st, r); + st.regs[r] = Some(v); + } + if st.regs[EXEC].is_none() { + st.regs[EXEC] = Some(self.atom(Atom::Opaque(d.pc, EXEC), block)?); + } + if writes_scc { + st.scc = match scc { + Some(s) => Some(s), + None => Some((self.atom(Atom::Scc(d.pc), block)?, false)), + }; + } + Ok(()) + } + + fn kill(&self, st: &mut State, r: usize) { + st.regs[r] = None; + // wave64: the pair starting one register lower + if self.wave64 && r > 0 { + st.regs[r - 1] = None; + } + } + + /// The condition under which a lane takes the branch ending a block, and whether it is a + /// lane mask's. + fn cond(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { + let e = st.regs[EXEC].expect("EXEC"); + let (c, lane, negate) = match d.inst.name { + n @ ("S_CBRANCH_SCC0" | "S_CBRANCH_SCC1") => { + let (c, lane) = match st.scc { + Some(s) => s, + None => (self.atom(Atom::Scc(d.pc), block)?, false), + }; + (c, lane, n == "S_CBRANCH_SCC0") + } + n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { + let v = match st.regs[VCC] { + Some(v) => v, + None => self.atom(Atom::Opaque(d.pc, VCC), block)?, + }; + (self.bdd.and(v, e)?, true, n == "S_CBRANCH_VCCZ") + } + n @ ("S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ") => (e, true, n == "S_CBRANCH_EXECZ"), + _ => (self.atom(Atom::Scc(d.pc), block)?, false, false), + }; + Ok((if negate { self.bdd.not(c)? } else { c }, lane)) + } + + /// `cond` within `STEP_NODES` new nodes; past that, an unknown per-lane condition. + fn cond_bounded(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { + self.bdd.limit = (self.bdd.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = self.cond(st, d, block); + self.bdd.limit = MAX_NODES; + match r { + Ok(c) => Ok(c), + Err(_) => Ok((self.atom(Atom::Scc(d.pc), block)?, true)), + } + } + + /// Simulates a block from `st`: the facts and states on its outgoing edges. + fn run_block(&mut self, b: usize, reach: B, mut st: State) -> R> { + let (first, end) = self.blocks[b]; + for i in first..end { + self.step_bounded(&mut st, i, b)?; + } + let last = &self.insts[end - 1]; + let mut out = Vec::new(); + for k in 0..self.succ[b].len() { + let fact = match self.succ[b][k].1 { + Edge::Always => reach, + edge => { + // a fact too large to build is left without the branch's condition (weaker) + let (c, _) = self.cond_bounded(&st, last, b)?; + self.bdd + .within(|bdd| { + let c = if edge == Edge::Taken { c } else { bdd.not(c)? }; + bdd.and(reach, c) + }) + .unwrap_or(reach) + } + }; + out.push((fact, st.clone())); + } + Ok(out) + } + + /// Block b's reach and masks from its predecessors' edges. Back edges add their facts + /// with the loop's atoms dropped; their masks only count with `back_masks` (the check of a + /// loop head's guess). + fn join(&mut self, b: usize, outs: &[Vec<(B, State)>], forced: &HashSet<(usize, usize)>, back_masks: bool) -> R<(B, State)> { + let mut reach = FALSE; + let mut edges: Vec<(B, State)> = Vec::new(); + for &(p, k) in &self.preds[b].clone() { + let Some((fact, st)) = outs[p].get(k) else { continue }; + let back = self.body[b].as_ref().is_some_and(|inside| inside[p]); + let carried = if back { + let (inside, born) = (self.body[b].as_ref().unwrap(), &self.born); + self.bdd.within(|bdd| bdd.exists(*fact, &|v| inside[born[v as usize]], &mut HashMap::new())).unwrap_or(TRUE) + } else { + *fact + }; + reach = self.bdd.within(|bdd| bdd.or(reach, carried)).unwrap_or(TRUE); + if *fact != FALSE && (!back || back_masks) { + edges.push((*fact, st.clone())); + } + } + let mut st = State { regs: vec![None; 128], scc: None }; + st.regs[EXEC] = Some(FALSE); + if edges.is_empty() { + return Ok((reach, st)); + } + for slot in 0..=SCC { + let get = |s: &State| if slot == SCC { s.scc.map(|x| x.0) } else { s.regs[slot] }; + let lane = edges.iter().any(|(_, s)| s.scc.is_some_and(|x| x.1)); + let v = if forced.contains(&(b, slot)) { + Some(self.atom(Atom::Join(b, slot), b)?) + } else if edges.iter().any(|(_, s)| get(s).is_none()) { + None + } else { + let first = get(&edges[0].1).unwrap(); + Some(if edges.iter().all(|(_, s)| get(s) == Some(first)) { + first + } else if edges.iter().all(|(fact, s)| self.bdd.implies(*fact, get(s).unwrap())) { + TRUE + } else if edges.iter().all(|(fact, s)| self.bdd.disjoint(*fact, get(s).unwrap(), &mut HashSet::new())) { + FALSE + } else { + self.atom(Atom::Join(b, slot), b)? + }) + }; + if slot == SCC { + st.scc = v.map(|v| (v, lane)); + } else { + st.regs[slot] = v; + } + } + if st.regs[EXEC].is_none() { + st.regs[EXEC] = Some(self.atom(Atom::Join(b, EXEC), b)?); + } + Ok((reach, st)) + } + + fn analyze(mut self) -> R { + let n = self.blocks.len(); + let mut entry = State { regs: vec![None; 128], scc: None }; + entry.regs[EXEC] = Some(TRUE); + let mut forced = HashSet::new(); + let mut reach = vec![FALSE; n]; + let mut ins: Vec> = vec![None; n]; + let mut outs: Vec> = vec![Vec::new(); n]; + // blocks to recompute: every block first, then those an incoming edge changed for. Any + // fixpoint of the facts is sound (it is weaker than the least one), so a wrong loop-head + // guess only makes that head recompute instead of restarting from nothing. + let order = self.order.clone(); + let mut dirty = vec![false; n]; + for &b in &order { + dirty[b] = true; + } + let heads: Vec = order.iter().copied().filter(|&h| self.body[h].is_some()).collect(); + let mut rounds = 0; + loop { + while order.iter().any(|&b| dirty[b]) { + rounds += 1; + if rounds > MAX_ROUNDS { + return Err("no fixpoint"); + } + for &b in &order { + if !std::mem::take(&mut dirty[b]) { + continue; + } + let (r, st) = if b == 0 { (TRUE, entry.clone()) } else { self.join(b, &outs, &forced, false)? }; + if ins[b].as_ref() == Some(&st) && reach[b] == r { + continue; + } + reach[b] = r; + ins[b] = Some(st.clone()); + let out = self.run_block(b, r, st)?; + if out != outs[b] { + for &(s, _) in &self.succ[b] { + dirty[s] = true; + } + outs[b] = out; + } + } + } + // loop heads: does the guess from the forward edges hold on the back edges too? + let mut wrong = false; + for &h in &heads { + let (_, full) = self.join(h, &outs, &forced, true)?; + let guess = ins[h].as_ref().unwrap(); + for slot in 0..=SCC { + let (g, f) = if slot == SCC { (guess.scc.map(|x| x.0), full.scc.map(|x| x.0)) } else { (guess.regs[slot], full.regs[slot]) }; + if g != f && forced.insert((h, slot)) { + wrong = true; + dirty[h] = true; + } + } + } + if !wrong { + break; + } + } + let mut sum = Summary::default(); + let mut implied: HashMap<(B, B), bool> = HashMap::new(); + for &b in &self.order.clone() { + let mut st = ins[b].clone().unwrap(); + let (first, end) = self.blocks[b]; + for i in first..end { + let d = &self.insts[i]; + if is_vector(d) { + sum.vector += 1; + let key = (reach[b], st.regs[EXEC].unwrap()); + let covered = match implied.get(&key) { + Some(&c) => c, + None => *implied.entry(key).or_insert(self.bdd.implies(key.0, key.1)), + }; + if !covered { + sum.guarded.push(d.pc); + } + } + self.step_bounded(&mut st, i, b)?; + } + let last = &self.insts[end - 1]; + if self.succ[b].iter().any(|s| s.1 != Edge::Always) { + let (_, lane) = self.cond_bounded(&st, last, b)?; + if lane { + sum.lane_branches += 1; + } else { + sum.uniform_branches += 1; + } + } + } + Ok(sum) + } +} + +/// Analyses a decoded program (far jumps resolved). +pub fn analyze(insts: &[Decoded], wave64: bool) -> R { + if insts.is_empty() { + return Ok(Summary::default()); + } + Lanes::new(insts, wave64)?.analyze() +} + +/// Decodes and analyses a program. +pub fn analyze_code(code: &[u8], wave64: bool) -> R { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { return Err("cannot decode") }; + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + analyze(&insts, wave64) +} + +#[cfg(test)] +mod tests { + use super::*; + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + const MOV2: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]); + const MOV3: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 130)]); + const RESTORE: I = ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]); + + /// Every instruction here is one dword: a branch's SIMM16 is (target − index − 1). + fn run(lines: &[I]) -> R { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + assert_eq!(bytes.len(), lines.len() * 4); + analyze_code(&bytes, true) + } + + #[test] + fn implication_tests_agree_with_the_built_formulas() { + let mut bdd = Bdd::new(); + let x: Vec = (0..4).map(|v| bdd.mk(v, FALSE, TRUE).unwrap()).collect(); + let mut fs = vec![FALSE, TRUE]; + for &a in &x { + for &b in &x { + let (and, or, xor) = (bdd.and(a, b).unwrap(), bdd.or(a, b).unwrap(), bdd.apply(Op::Xor, a, b).unwrap()); + let na = bdd.not(a).unwrap(); + fs.extend([a, and, or, xor, na]); + } + } + for &a in &fs { + for &b in &fs { + let nb = bdd.not(b).unwrap(); + let (built_imp, built_dis) = (bdd.and(a, nb).unwrap() == FALSE, bdd.and(a, b).unwrap() == FALSE); + assert_eq!(bdd.implies(a, b), built_imp, "{a} → {b}"); + assert_eq!(bdd.disjoint(a, b, &mut HashSet::new()), built_dis, "{a} ∧ {b}"); + } + } + } + + #[test] + fn a_skipped_if_needs_no_guard() { + // v_cmp; s_and_saveexec s[0:1], vcc; s_cbranch_execz L; v_mov; L: exec |= s[0:1]; v_mov + let s = run(&[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + RESTORE, + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches), (2, 0, 1, 0)); + } + + #[test] + fn an_if_without_its_skip_is_guarded() { + let s = run(&[CMP, ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), MOV2, RESTORE, MOV3, ENDPGM]).unwrap(); + assert_eq!(s.vector, 2); + assert_eq!(s.guarded, vec![8], "only the v_mov under the narrowed EXEC"); + } + + #[test] + fn lanes_leaving_a_loop_keep_it_unguarded() { + // s_mov s[0:1], exec; L: v_cmp; v_add; exec &= ~vcc; s_cbranch_execnz L; exec |= s[0:1] + let s = run(&[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + CMP, + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 5)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + RESTORE, + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 0, 1)); + } + + #[test] + fn a_loop_that_narrows_exec_is_found_on_its_back_edge() { + // s4 = 0; L: v_mov; v_cmp; exec &= vcc; s4 += 1; s_cmp_lt s4, 10; s_cbranch_scc1 L; v_mov + // – the head's guess (all lanes) is wrong once the back edge is seen + let s = run(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 128)]), + MOV2, + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 138)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!(s.guarded, vec![4, 28]); + assert_eq!((s.lane_branches, s.uniform_branches), (0, 1)); + } + + #[test] + fn a_vccz_branch_is_a_lane_branch() { + // v_cmp; s_cbranch_vccz L; v_mov (lanes with the bit only); L: v_mov + let s = run(&[CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 0, 1)); + } + + #[test] + fn unsupported_control_flow_is_refused() { + // a loop entered at two places + let two_entries = run(&[ + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + MOV3, + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0xFFFD)]), + ENDPGM, + ]); + assert_eq!(two_entries.unwrap_err(), "irreducible control flow"); + assert_eq!(run(&[("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]), ENDPGM]).unwrap_err(), "indirect jump"); + assert_eq!(run(&[MOV2, ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFE)]), ENDPGM]).unwrap_err(), "branch to the entry"); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 71012d565c..99242570b1 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -52,6 +52,7 @@ //! `ByteAddressBuffer` (`mem`); initial SGPRs (user data) come from `io`. Textures come next. pub mod dxc; +pub mod lane_masks; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 591ca94cbb..1048e6a68f 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -309,6 +309,10 @@ struct RecompAgg { wave_resolved: BTreeMap, /// `--example MNEMONIC`: listing of the first program missing it, its HLSL and profile example: Option<(String, String, &'static str)>, + /// `lane_masks` (direct DXIL): programs analysed, those with no guard left, vector + /// instructions, those still guarded, lane branches, uniform branches; failures by reason + lanes: [usize; 6], + lanes_failed: BTreeMap, } impl RecompAgg { @@ -349,6 +353,12 @@ impl RecompAgg { e.1 += b; } self.hlsl_bytes += o.hlsl_bytes; + for (a, b) in self.lanes.iter_mut().zip(o.lanes) { + *a += b; + } + for (k, v) in o.lanes_failed { + *self.lanes_failed.entry(k).or_default() += v; + } } fn add(&mut self, name: &str, code: &[u8], keep: usize, mode: recomp::Mode) { @@ -389,6 +399,15 @@ impl RecompAgg { self.graphics_wave32 += 1; } } + match recomp::lane_masks::analyze_code(code, wave64) { + Ok(s) => { + let counts = [1, s.guarded.is_empty() as usize, s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches]; + for (a, b) in self.lanes.iter_mut().zip(counts) { + *a += b; + } + } + Err(why) => *self.lanes_failed.entry(why.to_string()).or_default() += 1, + } // `XCL_RECOMP_WINDOWS=4`: as a title with unified memory translates (`pso::mem_windows`) let mem_windows = std::env::var("XCL_RECOMP_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1); match recomp::translate(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) { @@ -1493,6 +1512,19 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim "VS/PS and the wave size (the driver picks it): wave32 {} (handled – the halves of a 64-wide wave run separately), wave64 {}; hazards in 32-thread waves: {:?}; reads of lanes ≥ 32 resolved (32-lane GPUs): {:?}", rc.graphics_wave32, rc.graphics_wave64, rc.wave_hazards, rc.wave_resolved ); + let l = &rc.lanes; + println!( + "lane masks (direct DXIL, no EXEC emulation): analysed {} of {} programs, {} with no guard left; vector instructions {}, still guarded {} ({:.1}%); branches per lane {}, uniform {}; not analysed: {:?}", + l[0], + rc.programs, + l[1], + l[2], + l[3], + l[3] as f64 * 100.0 / l[2].max(1) as f64, + l[4], + l[5], + rc.lanes_failed + ); if let Some((x, hlsl, profile)) = &rc.example { println!("example: {x}"); From 9b8db83fdd7076338d2368f5184d14a3d28db0fe Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 16:35:32 +0100 Subject: [PATCH 02/51] Recompiler: assemble and sign a DXIL module from LLVM IR text `dxil::assemble::assemble` turns a module written as LLVM IR text (or bitcode) into a signed container: dxcompiler.dll's assembler builds the container from the module's `dx.*` metadata, dxil.dll's validator checks and signs it. No HLSL front end and no optimiser: a retail compute program's module (8.6 MB of IR, 1 MB of DXIL) takes 0.75 s, its HLSL 25 s through DXC. This is the text path under the module builder (`to_text()`), so the lowering can run real programs on the GPU before the binary writer is done. The test assembles a hand-written CS of the ABI root signature, runs it on the GPU and checks its output, and checks that a use before its definition is refused by the validator. A module needs an `!llvm.ident`: without one it validates but the AMD driver faults in CreateComputePipelineState. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XTYmP5ub3Zjdi8PYaDNwsV --- crates/xcl/src/gpu/recomp/dxil/assemble.rs | 122 +++++++++++++++++++++ crates/xcl/src/gpu/recomp/dxil/mod.rs | 3 + crates/xcl/src/gpu/recomp/mod.rs | 1 + 3 files changed, 126 insertions(+) create mode 100644 crates/xcl/src/gpu/recomp/dxil/assemble.rs create mode 100644 crates/xcl/src/gpu/recomp/dxil/mod.rs diff --git a/crates/xcl/src/gpu/recomp/dxil/assemble.rs b/crates/xcl/src/gpu/recomp/dxil/assemble.rs new file mode 100644 index 0000000000..9383c684b4 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/dxil/assemble.rs @@ -0,0 +1,122 @@ +//! A DXIL module as LLVM IR text (or bitcode) to a signed container, through the PC DXC's +//! libraries: `dxcompiler.dll`'s assembler builds the container from the module's `dx.*` +//! metadata, `dxil.dll`'s validator checks and signs it. Neither DXC's HLSL front end nor its +//! optimiser runs: a retail compute program's module (8.6 MB of IR, 1 MB of DXIL) takes 0.75 s, +//! where its HLSL takes 25 s through `dxc::compile`. +//! +//! What a module needs on top of what the validator checks (RX 7800 XT, Windows driver): +//! an `!llvm.ident`. Without one the container validates and signs, but +//! `CreateComputePipelineState` faults inside the AMD driver. + +use std::ffi::c_void; + +use windows::core::{Interface, GUID, HRESULT}; +use windows::Win32::Graphics::Direct3D::Dxc::{ + DxcValidatorFlags_InPlaceEdit, IDxcAssembler, IDxcOperationResult, IDxcUtils, IDxcValidator, CLSID_DxcAssembler, CLSID_DxcUtils, CLSID_DxcValidator, DXC_CP_UTF8, +}; + +type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; + +fn errors(r: &IDxcOperationResult) -> String { + unsafe { r.GetErrorBuffer().map(|b| String::from_utf8_lossy(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize())).into_owned()).unwrap_or_default() } +} + +unsafe fn make(create: CreateInstance, clsid: &GUID) -> Result { + let mut p = std::ptr::null_mut(); + create(clsid, &T::IID, &mut p).ok().map_err(|e| format!("DxcCreateInstance: {e}"))?; + Ok(T::from_raw(p)) +} + +/// The module `ir` as a validated, signed DXIL container; the assembler's or the validator's +/// messages as the error. +pub fn assemble(ir: &str) -> Result, String> { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; + let create = super::super::dxc::create_instance().ok_or("dxcompiler.dll not found")?; + unsafe { + let create = std::mem::transmute::(create); + // (`dxc` loaded dxil.dll by its full path, before dxcompiler.dll) + let signer = GetModuleHandleW(crate::util::wide("dxil.dll").as_ptr()); + let sign = (!signer.is_null()).then(|| GetProcAddress(signer, b"DxcCreateInstance\0".as_ptr())).flatten().ok_or("assemble: no dxil.dll to sign with")?; + let utils: IDxcUtils = make(create, &CLSID_DxcUtils)?; + let blob = utils.CreateBlob(ir.as_ptr() as *const c_void, ir.len() as u32, DXC_CP_UTF8).map_err(|e| format!("assemble: {e}"))?; + let asm: IDxcAssembler = make(create, &CLSID_DxcAssembler)?; + let r = asm.AssembleToContainer(&blob).map_err(|e| format!("assemble: {e}"))?; + if r.GetStatus().map_err(|e| format!("assemble: {e}"))?.is_err() { + return Err(format!("assemble: {}", errors(&r))); + } + let container = r.GetResult().map_err(|e| format!("assemble: {e}"))?; + let v: IDxcValidator = make(std::mem::transmute::(sign as usize), &CLSID_DxcValidator)?; + let r = v.Validate(&container, DxcValidatorFlags_InPlaceEdit).map_err(|e| format!("validate: {e}"))?; + if r.GetStatus().map_err(|e| format!("validate: {e}"))?.is_err() { + return Err(format!("validate: {}", errors(&r))); + } + Ok(std::slice::from_raw_parts(container.GetBufferPointer() as *const u8, container.GetBufferSize()).to_vec()) + } +} + +#[cfg(test)] +mod tests { + use super::super::super::runner; + + /// A CS of the ABI root signature, written by hand: `mem[i] = 3 i + 1` through `u2`. + const IR: &str = r#"target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64" +target triple = "dxil-ms-dx" +%dx.types.Handle = type { i8* } +%dx.types.ResBind = type { i32, i32, i32, i8 } +%dx.types.ResourceProperties = type { i32, i32 } +%struct.RWByteAddressBuffer = type { i32 } +define void @main() { + %1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 2, i32 2, i32 0, i8 1 }, i32 2, i1 false) + %2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) + %3 = mul i32 %2, 3 + %4 = add i32 %3, 1 + %5 = shl i32 %2, 2 + %6 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) + call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %6, i32 %5, i32 undef, i32 %4, i32 undef, i32 undef, i32 undef, i8 1, i32 4) + ret void +} +declare i32 @dx.op.threadId.i32(i32, i32) #0 +declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #1 +declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0 +declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0 +attributes #0 = { nounwind readnone } +attributes #1 = { nounwind } +!llvm.ident = !{!0} +!dx.version = !{!1} +!dx.valver = !{!2} +!dx.shaderModel = !{!3} +!dx.resources = !{!4} +!dx.entryPoints = !{!7} +!0 = !{!"xcl"} +!1 = !{i32 1, i32 6} +!2 = !{i32 1, i32 9} +!3 = !{!"cs", i32 6, i32 6} +!4 = !{null, !5, null, null} +!5 = !{!6} +!6 = !{i32 0, %struct.RWByteAddressBuffer* undef, !"", i32 0, i32 2, i32 1, i32 11, i1 false, i1 false, i1 false, null} +!7 = !{void ()* @main, !"main", null, !4, !8} +!8 = !{i32 0, i64 16, i32 4, !9} +!9 = !{i32 64, i32 1, i32 1} +"#; + + /// The text assembles, signs and runs on the GPU; a module the validator rejects (a use + /// before its definition) is an error, not a container. + #[test] + fn ir_text_assembles_signs_and_runs() { + if super::super::super::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let dxil = super::assemble(IR).unwrap(); + assert_eq!(&dxil[..4], b"DXBC"); + let bad = super::assemble(&IR.replace("%3 = mul i32 %2, 3", "%3 = mul i32 %4, 3")).unwrap_err(); + assert!(bad.contains("dominate"), "{bad}"); + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return; + } + let out = runner::dispatch(&dxil, [1, 1, 1], &[], &[0u32; 64]).unwrap(); + let want: Vec = (0..64).map(|i| 3 * i + 1).collect(); + assert_eq!(&out[..64], &want[..]); + } +} diff --git a/crates/xcl/src/gpu/recomp/dxil/mod.rs b/crates/xcl/src/gpu/recomp/dxil/mod.rs new file mode 100644 index 0000000000..fb1a5dffd8 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/dxil/mod.rs @@ -0,0 +1,3 @@ +//! A DXIL module without HLSL: assembled and signed from LLVM IR text (`assemble`). + +pub mod assemble; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 99242570b1..f0e029f031 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -52,6 +52,7 @@ //! `ByteAddressBuffer` (`mem`); initial SGPRs (user data) come from `io`. Textures come next. pub mod dxc; +pub mod dxil; pub mod lane_masks; pub(crate) mod emit; pub mod mesh_dispatch; From b3c0b3733cbd0333c28d963b3ec9b2e3a82fad69 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:45:46 -0300 Subject: [PATCH 03/51] Recompiler: lower kernel programs to DXIL-shaped IR on the lane masks The direct backend's lowering, for kernel mode first. The console CFG is kept and every register dword is an SSA value, built on the fly while the blocks are lowered (`ssa.rs`). EXEC is each lane's own bit: mask branches are per-lane branches and a vector write keeps `select(bit, new, old)` only where the lane-mask analysis could not prove the bit set. An SGPR has a number view and, when it holds a mask, a lane-bit view; a number read where a mask was written (or the reverse across a join) is refused once every phi is complete, and the program stays on the HLSL path. At the end, where every lane is back, a mask stored as a number is the wave's ballot. A mask written in a block some lanes skip (a loop lanes leave one by one, an arm some lanes jump over) and read after they meet again differs from the console, whose whole-wave write left the absent lanes' bits 0. Those blocks are found from the post-dominators of the lane branches; such reads are refused, and kernel mode's final store reports those registers. The IR goes through an `Ir` trait, the part of the DXIL module builder the lowering needs. The tests run it lane by lane on a CPU interpreter, and run the same programs through the HLSL path on the GPU: every register agrees (GTX 1650, wave32). The analysis now exports its CFG for the lowering. --- crates/xcl/src/gpu/recomp/lane_masks.rs | 39 +- crates/xcl/src/gpu/recomp/lower.rs | 1364 +++++++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 2 + crates/xcl/src/gpu/recomp/ssa.rs | 304 +++++ 4 files changed, 1707 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/lower.rs create mode 100644 crates/xcl/src/gpu/recomp/ssa.rs diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 4de6d4d5ac..0fd1491dba 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -214,13 +214,26 @@ struct State { scc: Option<(B, bool)>, } -#[derive(Clone, Copy, PartialEq)] -enum Edge { +/// How a block's successor is reached: unconditionally, or by its branch taken / not taken. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Edge { Always, Taken, NotTaken, } +/// A basic block of the program, as the lowering walks it. +#[derive(Clone, Debug)] +pub struct Block { + /// its instructions: indices into the decoded program + pub insts: std::ops::Range, + pub succ: Vec<(usize, Edge)>, + /// predecessors that the entry reaches, back edges included + pub preds: Vec, + /// it ends in a branch on a lane mask: each lane takes it on its own bit + pub lane_branch: bool, +} + /// What the analysis found in a program. #[derive(Debug, Default)] pub struct Summary { @@ -231,6 +244,10 @@ pub struct Summary { /// conditional branches on a lane mask (each lane decides) and on uniform values pub lane_branches: usize, pub uniform_branches: usize, + /// the CFG (block 0 is the entry) and the order to lower it in (reverse postorder of the + /// blocks the entry reaches: every block after its forward predecessors) + pub blocks: Vec, + pub order: Vec, } /// Executed with the lane's EXEC bit (VOPC and the lane reads / writes are mask producers). @@ -735,6 +752,7 @@ impl<'a> Lanes<'a> { } let mut sum = Summary::default(); let mut implied: HashMap<(B, B), bool> = HashMap::new(); + let mut lane_branch = vec![false; self.blocks.len()]; for &b in &self.order.clone() { let mut st = ins[b].clone().unwrap(); let (first, end) = self.blocks[b]; @@ -761,8 +779,18 @@ impl<'a> Lanes<'a> { } else { sum.uniform_branches += 1; } + lane_branch[b] = lane; } } + sum.blocks = (0..self.blocks.len()) + .map(|b| Block { + insts: self.blocks[b].0..self.blocks[b].1, + succ: self.succ[b].clone(), + preds: self.preds[b].iter().map(|p| p.0).collect(), + lane_branch: lane_branch[b], + }) + .collect(); + sum.order = self.order.clone(); Ok(sum) } } @@ -843,6 +871,13 @@ mod tests { ]) .unwrap(); assert_eq!((s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches), (2, 0, 1, 0)); + // the CFG the lowering walks: entry (to the skip), the v_mov, the join + let b = &s.blocks; + assert_eq!(b.iter().map(|b| b.insts.clone()).collect::>(), vec![0..3, 3..4, 4..7]); + assert_eq!(b[0].succ, vec![(2, Edge::Taken), (1, Edge::NotTaken)]); + assert_eq!((b[1].succ.clone(), b[2].preds.clone()), (vec![(2, Edge::Always)], vec![0, 1])); + assert_eq!(b.iter().map(|b| b.lane_branch).collect::>(), vec![true, false, false]); + assert_eq!(s.order, vec![0, 1, 2]); } #[test] diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs new file mode 100644 index 0000000000..c12936f2a5 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -0,0 +1,1364 @@ +//! Lowering of console programs to DXIL-shaped IR, for the direct backend (`XCL_RECOMP_DXIL`). +//! +//! The console CFG is kept: blocks become blocks, and every register dword is an SSA value +//! (`ssa`). EXEC is not a number here but each lane's own bit (`i1`): a mask branch +//! (`s_cbranch_execz`, `vccz`, SCC of a mask op) is a branch of each lane on its bit, and a +//! vector instruction keeps a guard (`select(bit, new, old)`) only where `lane_masks` could not +//! prove the bit set. An SGPR therefore has two views: its number (`Var::S`) and, when it holds +//! a mask, the lane's bit of it (`Var::M`). Writing one view leaves a marker in the other – `undef` +//! – so a number read where only a mask was written (or the reverse, across a join) is found once +//! every phi is complete, and the program is refused (it stays on the HLSL path). A bit read where +//! only a number was written is the lane's bit of that number. At the end of the program every +//! lane is back, so a mask stored as a number there is the wave's ballot of the bits. +//! +//! Kernel mode only for now (the ABI of `runner`): registers come from `io` and go back to `res`. +//! The IR is written through `Ir`, the part of the DXIL module builder this needs. + +use std::collections::HashSet; + +use super::lane_masks::{self, Edge, Summary}; +use super::ssa::{Sink, Ssa, Var}; +use super::{KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +type R = Result; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Bin { + Add, + Sub, + Mul, + And, + Or, + Xor, + Shl, + LShr, + AShr, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Cmp { + Eq, + Ne, + Ult, + Ule, + Ugt, + Uge, + Slt, + Sle, + Sgt, + Sge, +} + +/// What the lowering needs from the DXIL module builder. Blocks are numbered in the order +/// `new_block` creates them, the first being the entry; `And` / `Or` / `Xor` take `i1` or `i32`. +pub trait Ir: Sink { + fn new_block(&mut self) -> usize; + fn at(&mut self, block: usize); + fn int(&mut self, v: u32) -> Self::V; + fn boolean(&mut self, v: bool) -> Self::V; + fn bin(&mut self, op: Bin, a: Self::V, b: Self::V) -> Self::V; + fn icmp(&mut self, c: Cmp, a: Self::V, b: Self::V) -> Self::V; + fn select(&mut self, c: Self::V, a: Self::V, b: Self::V) -> Self::V; + /// `i1` → `i32` (0 / 1) + fn zext(&mut self, b: Self::V) -> Self::V; + /// the console lane of this thread + fn lane(&mut self) -> Self::V; + /// the wave's ballot of `c`: lanes 0–31, 32–63 + fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; + fn io_load(&mut self, dword: Self::V) -> Self::V; + fn res_store(&mut self, dword: Self::V, value: Self::V); + fn br(&mut self, target: usize); + fn br_if(&mut self, c: Self::V, then: usize, otherwise: usize); + fn ret(&mut self); +} + +const EXEC: u8 = 126; +const VCC: u8 = 106; + +struct Lower<'a, I: Ir> { + ir: I, + ssa: Ssa, + sum: &'a Summary, + guarded: HashSet, + wave64: bool, + /// the markers: a number where a mask was written, a bit where a number was + num_marker: I::V, + bit_marker: I::V, + /// values read as numbers / as mask bits, checked once every phi is complete + num_uses: Vec, + bit_uses: Vec, + lane: Option, + /// per IR block: not every lane that reached one of the program's lane branches gets here + /// before they meet again (a loop that lanes leave one by one, an arm some lanes skip) + partial: Vec, + /// the IR block each mask bit was written in, and the mask bits read (block, value) + def_block: std::collections::HashMap, + lane_uses: Vec<(usize, I::V)>, +} + +/// IR block of analysis block b (block 0 is the prologue). +fn blk(b: usize) -> usize { + b + 1 +} + +impl<'a, I: Ir> Lower<'a, I> { + fn lane(&mut self) -> I::V { + *self.lane.get_or_insert_with(|| self.ir.lane()) + } + + fn read(&mut self, b: usize, var: Var) -> I::V { + self.ssa.read(&mut self.ir, b, var) + } + + fn read_num(&mut self, b: usize, r: u8) -> R { + let v = self.read(b, Var::S(r)); + if self.ssa.resolve_value(v) == self.num_marker { + return Err(format!("s{r}: a mask read as a number")); + } + self.num_uses.push(v); + Ok(v) + } + + /// The lane's bit of the mask in s (wave64: the pair from s). + fn read_bit(&mut self, b: usize, r: u8) -> R { + let m = self.read(b, Var::M(r)); + if self.ssa.resolve_value(m) != self.bit_marker { + self.bit_uses.push(m); + if r != EXEC { + self.lane_uses.push((b, m)); + } + return Ok(m); + } + // only numbers written: the lane's bit of them + let lane = self.lane(); + let word = if self.wave64 { + let (lo, hi) = (self.read_num(b, r)?, self.read_num(b, r + 1)?); + let c32 = self.ir.int(32); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + self.ir.select(upper, hi, lo) + } else { + self.read_num(b, r)? + }; + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let shifted = self.ir.bin(Bin::LShr, word, sh); + let one = self.ir.int(1); + let bit = self.ir.bin(Bin::And, shifted, one); + let zero = self.ir.int(0); + Ok(self.ir.icmp(Cmp::Ne, bit, zero)) + } + + fn write_num(&mut self, b: usize, r: u8, v: I::V) { + self.ssa.write(b, Var::S(r), v); + self.ssa.write(b, Var::M(r), self.bit_marker); + if self.wave64 && r > 0 { + // a mask in the pair from s is no longer that mask + self.ssa.write(b, Var::M(r - 1), self.bit_marker); + } + } + + fn write_bit(&mut self, b: usize, r: u8, bit: I::V) { + if r != EXEC { + self.def_block.entry(bit).or_insert(b); + } + self.ssa.write(b, Var::M(r), bit); + self.ssa.write(b, Var::S(r), self.num_marker); + if self.wave64 { + self.ssa.write(b, Var::S(r + 1), self.num_marker); + self.ssa.write(b, Var::M(r + 1), self.bit_marker); + if r > 0 { + self.ssa.write(b, Var::M(r - 1), self.bit_marker); + } + } + } + + /// Whether s holds a mask here (its bit view is not the marker). + fn holds_mask(&mut self, b: usize, r: u8) -> bool { + let m = self.read(b, Var::M(r)); + self.ssa.resolve_value(m) != self.bit_marker + } + + /// A scalar or vector source operand as a number. + fn src(&mut self, b: usize, d: &Decoded, code: u64) -> R { + Ok(match code { + 0..=105 | 106 | 107 | 124 | 126 | 127 => self.read_num(b, code as u8)?, + 128..=192 => self.ir.int((code - 128) as u32), + 193..=208 => self.ir.int((-((code - 192) as i32)) as u32), + 240..=247 => self.ir.int([0.5f32, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0][(code - 240) as usize].to_bits()), + 248 => self.ir.int(0x3E22_F983), + 253 => { + let s = self.read(b, Var::Scc); + self.ir.zext(s) + } + 255 => self.ir.int(d.literal.ok_or("missing literal")?), + 256..=511 => self.read(b, Var::V((code - 256) as u16)), + _ => return Err(format!("source code {code}")), + }) + } + + /// A scalar source operand as a mask's lane bit: a register, all lanes or none. + fn src_bit(&mut self, b: usize, code: u64) -> R { + match code { + 0..=105 | 106 | 107 | 126 | 127 => self.read_bit(b, code as u8), + 128 => Ok(self.ir.boolean(false)), + 193 => Ok(self.ir.boolean(true)), + _ => Err(format!("mask source code {code}")), + } + } + + fn write_v(&mut self, b: usize, d: &Decoded, r: u16, v: I::V) -> R<()> { + let v = if self.guarded.contains(&d.pc) { + let old = self.read(b, Var::V(r)); + let e = self.read_bit(b, EXEC)?; + self.ir.select(e, v, old) + } else { + v + }; + self.ssa.write(b, Var::V(r), v); + Ok(()) + } + + fn not(&mut self, a: I::V) -> I::V { + let t = self.ir.boolean(true); + self.ir.bin(Bin::Xor, a, t) + } + + /// A bitwise mask op of SALU / saveexec on lane bits. + fn bit_op(&mut self, op: &str, a: I::V, e: I::V) -> R { + Ok(match op { + "AND" => self.ir.bin(Bin::And, a, e), + "OR" => self.ir.bin(Bin::Or, a, e), + "XOR" => self.ir.bin(Bin::Xor, a, e), + "ANDN2" => { + let ne = self.not(e); + self.ir.bin(Bin::And, a, ne) + } + "ORN2" => { + let ne = self.not(e); + self.ir.bin(Bin::Or, a, ne) + } + "ANDN1" => { + let na = self.not(a); + self.ir.bin(Bin::And, na, e) + } + "ORN1" => { + let na = self.not(a); + self.ir.bin(Bin::Or, na, e) + } + "NAND" | "NOR" | "XNOR" => { + let inner = match op { + "NAND" => Bin::And, + "NOR" => Bin::Or, + _ => Bin::Xor, + }; + let x = self.ir.bin(inner, a, e); + self.not(x) + } + _ => return Err(format!("mask op {op}")), + }) + } + + fn salu(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").unwrap_or(0) as u8); + let width = if self.wave64 { "_B64" } else { "_B32" }; + // mask-width ops: on lane bits when they write EXEC, are a saveexec, or read a mask + if let Some(base) = name.strip_suffix(width) { + let op = base.trim_start_matches("S_"); + let saveexec = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")); + let reads_mask = [s0, s1].iter().any(|&c| c <= 127 && c != 124 && self.holds_mask(b, c as u8)); + let bitwise = matches!(op, "MOV" | "NOT" | "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "NAND" | "NOR" | "XNOR"); + if let Some(op) = saveexec { + let a = self.src_bit(b, s0)?; + let old = self.read_bit(b, EXEC)?; + let new = self.bit_op(op, a, old)?; + self.write_bit(b, EXEC, new); + if sd != 125 { + self.write_bit(b, sd, if base.ends_with("_WREXEC") { new } else { old }); + } + self.ssa.write(b, Var::Scc, new); + return Ok(()); + } + if bitwise && (sd == EXEC || reads_mask) { + let a = self.src_bit(b, s0)?; + let v = match op { + "MOV" => a, + "NOT" => self.not(a), + _ => { + let c = self.src_bit(b, s1)?; + self.bit_op(op, a, c)? + } + }; + self.write_bit(b, sd, v); + if op != "MOV" { + self.ssa.write(b, Var::Scc, v); + } + return Ok(()); + } + } + // mask compares (`s_cmp_lg_u64 exec, 0`): whether the lane's bits differ / agree + let cmp64 = if self.wave64 { ["S_CMP_EQ_U64", "S_CMP_LG_U64"] } else { ["S_CMP_EQ_U32", "S_CMP_LG_U32"] }; + if cmp64.contains(&name) && [s0, s1].iter().any(|&c| c <= 127 && self.holds_mask(b, c as u8)) { + let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); + let x = self.ir.bin(Bin::Xor, a, c); + let v = if name == cmp64[0] { self.not(x) } else { x }; + self.ssa.write(b, Var::Scc, v); + return Ok(()); + } + // numbers + let num2 = |l: &mut Self, op: Bin| -> R { + let (a, c) = (l.src(b, d, s0)?, l.src(b, d, s1)?); + Ok(l.ir.bin(op, a, c)) + }; + let nonzero = |l: &mut Self, v: I::V| { + let z = l.ir.int(0); + l.ir.icmp(Cmp::Ne, v, z) + }; + match name { + "S_MOV_B32" => { + let v = self.src(b, d, s0)?; + self.write_num(b, sd, v); + } + "S_MOVK_I32" => { + let v = self.ir.int(fv("SIMM16").unwrap_or(0) as u16 as i16 as i32 as u32); + self.write_num(b, sd, v); + } + "S_MOV_B64" => { + let (lo, hi) = self.src64(b, d, s0)?; + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + } + "S_ADD_U32" | "S_SUB_U32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let (op, carry) = if name == "S_ADD_U32" { (Bin::Add, true) } else { (Bin::Sub, false) }; + let v = self.ir.bin(op, a, c); + // carry out: the sum wrapped below a; borrow: a < b + let scc = if carry { self.ir.icmp(Cmp::Ult, v, a) } else { self.ir.icmp(Cmp::Ult, a, c) }; + self.write_num(b, sd, v); + self.ssa.write(b, Var::Scc, scc); + } + "S_ADD_I32" | "S_SUB_I32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let op = if name == "S_ADD_I32" { Bin::Add } else { Bin::Sub }; + let v = self.ir.bin(op, a, c); + // signed overflow: the operands' signs agree (add) / differ (sub) and the result's differs + let (av, cv) = (self.ir.bin(Bin::Xor, a, v), self.ir.bin(Bin::Xor, c, v)); + let both = if op == Bin::Add { + self.ir.bin(Bin::And, av, cv) + } else { + let ac = self.ir.bin(Bin::Xor, a, c); + self.ir.bin(Bin::And, ac, av) + }; + let z = self.ir.int(0); + let scc = self.ir.icmp(Cmp::Slt, both, z); + self.write_num(b, sd, v); + self.ssa.write(b, Var::Scc, scc); + } + "S_MUL_I32" => { + let v = num2(self, Bin::Mul)?; + self.write_num(b, sd, v); + } + "S_AND_B32" | "S_OR_B32" | "S_XOR_B32" => { + let op = match name { + "S_AND_B32" => Bin::And, + "S_OR_B32" => Bin::Or, + _ => Bin::Xor, + }; + let v = num2(self, op)?; + let scc = nonzero(self, v); + self.write_num(b, sd, v); + self.ssa.write(b, Var::Scc, scc); + } + "S_LSHL_B32" | "S_LSHR_B32" | "S_ASHR_I32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, c, c31); + let op = match name { + "S_LSHL_B32" => Bin::Shl, + "S_LSHR_B32" => Bin::LShr, + _ => Bin::AShr, + }; + let v = self.ir.bin(op, a, sh); + let scc = nonzero(self, v); + self.write_num(b, sd, v); + self.ssa.write(b, Var::Scc, scc); + } + n if n.starts_with("S_CMP_") && (n.ends_with("_U32") || n.ends_with("_I32")) => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let signed = n.ends_with("_I32"); + let p = match &n[6..8] { + "EQ" => Cmp::Eq, + "LG" => Cmp::Ne, + "GT" => if signed { Cmp::Sgt } else { Cmp::Ugt }, + "GE" => if signed { Cmp::Sge } else { Cmp::Uge }, + "LT" => if signed { Cmp::Slt } else { Cmp::Ult }, + "LE" => if signed { Cmp::Sle } else { Cmp::Ule }, + _ => return Err(format!("unsupported {n}")), + }; + let v = self.ir.icmp(p, a, c); + self.ssa.write(b, Var::Scc, v); + } + "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" => {} + n => return Err(format!("unsupported {n}")), + } + Ok(()) + } + + /// A 64-bit scalar source: a register pair or a constant. + fn src64(&mut self, b: usize, d: &Decoded, code: u64) -> R<(I::V, I::V)> { + Ok(match code { + 0..=105 | 106 | 126 => (self.read_num(b, code as u8)?, self.read_num(b, code as u8 + 1)?), + 128..=192 => (self.ir.int((code - 128) as u32), self.ir.int(0)), + 193..=208 => (self.ir.int((-((code - 192) as i32)) as u32), self.ir.int(u32::MAX)), + 255 => (self.ir.int(d.literal.ok_or("missing literal")?), self.ir.int(0)), + _ => return Err(format!("64-bit source code {code}")), + }) + } + + fn valu(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if d.variant != Variant::Plain { + return Err(format!("{name}: SDWA / DPP")); + } + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); + if vop3 && ["ABS", "NEG", "CLAMP", "OMOD", "OPSEL"].iter().any(|f| fv(f).unwrap_or(0) != 0) { + return Err(format!("{name}: VOP3 modifiers")); + } + // sources: VOP1 / VOP2 / VOPC put src1 in VSRC1 (a VGPR); VOP3 in SRC1 + let s0 = fv("SRC0").unwrap_or(0); + let s1 = if vop3 { fv("SRC1").unwrap_or(0) } else { fv("VSRC1").map(|v| v + 256).unwrap_or(0) }; + let vdst = fv("VDST").unwrap_or(0); + if let Some(rest) = name.strip_prefix("V_CMP") { + let (x, cond) = match rest.strip_prefix("X_") { + Some(c) => (true, c), + None => (false, rest.trim_start_matches('_')), + }; + let (pred, ty) = cond.split_once('_').ok_or_else(|| format!("unsupported {name}"))?; + let signed = match ty { + "U32" => false, + "I32" => true, + _ => return Err(format!("unsupported {name}")), + }; + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c = match pred { + "EQ" => self.ir.icmp(Cmp::Eq, a, c), + "NE" => self.ir.icmp(Cmp::Ne, a, c), + "GT" => self.ir.icmp(if signed { Cmp::Sgt } else { Cmp::Ugt }, a, c), + "GE" => self.ir.icmp(if signed { Cmp::Sge } else { Cmp::Uge }, a, c), + "LT" => self.ir.icmp(if signed { Cmp::Slt } else { Cmp::Ult }, a, c), + "LE" => self.ir.icmp(if signed { Cmp::Sle } else { Cmp::Ule }, a, c), + "F" => self.ir.boolean(false), + "T" => self.ir.boolean(true), + _ => return Err(format!("unsupported {name}")), + }; + // the lane's result, 0 in inactive lanes + let e = self.read_bit(b, EXEC)?; + let bit = self.ir.bin(Bin::And, c, e); + let dst = if x { EXEC } else if vop3 { vdst as u8 } else { VCC }; + self.write_bit(b, dst, bit); + return Ok(()); + } + let v = match name { + "V_MOV_B32" => self.src(b, d, s0)?, + "V_CNDMASK_B32" => { + let sel = if vop3 { fv("SRC2").unwrap_or(0) } else { VCC as u64 }; + let m = self.src_bit(b, sel)?; + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + self.ir.select(m, c, a) + } + _ => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c31 = self.ir.int(31); + match name { + "V_ADD_NC_U32" | "V_ADD_U32" => self.ir.bin(Bin::Add, a, c), + "V_SUB_NC_U32" | "V_SUB_U32" => self.ir.bin(Bin::Sub, a, c), + "V_SUBREV_NC_U32" | "V_SUBREV_U32" => self.ir.bin(Bin::Sub, c, a), + "V_AND_B32" => self.ir.bin(Bin::And, a, c), + "V_OR_B32" => self.ir.bin(Bin::Or, a, c), + "V_XOR_B32" => self.ir.bin(Bin::Xor, a, c), + "V_MUL_LO_U32" => self.ir.bin(Bin::Mul, a, c), + "V_LSHLREV_B32" | "V_LSHRREV_B32" | "V_ASHRREV_I32" => { + let sh = self.ir.bin(Bin::And, a, c31); + let op = match name { + "V_LSHLREV_B32" => Bin::Shl, + "V_LSHRREV_B32" => Bin::LShr, + _ => Bin::AShr, + }; + self.ir.bin(op, c, sh) + } + n => return Err(format!("unsupported {n}")), + } + } + }; + self.write_v(b, d, vdst as u16, v) + } + + /// The condition under which a lane takes the branch ending block b. + fn cond(&mut self, b: usize, d: &Decoded) -> R { + Ok(match d.inst.name { + "S_CBRANCH_SCC1" => self.read(b, Var::Scc), + "S_CBRANCH_SCC0" => { + let s = self.read(b, Var::Scc); + self.not(s) + } + n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { + let (v, e) = (self.read_bit(b, VCC)?, self.read_bit(b, EXEC)?); + let c = self.ir.bin(Bin::And, v, e); + if n == "S_CBRANCH_VCCZ" { + self.not(c) + } else { + c + } + } + "S_CBRANCH_EXECNZ" => self.read_bit(b, EXEC)?, + "S_CBRANCH_EXECZ" => { + let e = self.read_bit(b, EXEC)?; + self.not(e) + } + n => return Err(format!("unsupported branch {n}")), + }) + } + + /// Whether a lane reading mask bit v in block c may see its own stale bit: v (or a phi + /// operand reaching it) was written in another block that not every lane passed through. + /// The hardware's whole-wave write left the absent lanes' bits 0 there; this lane kept its + /// own older one. EXEC is not concerned: an absent lane's bit is 0 in both. + fn stale(&self, c: usize, v: I::V) -> bool { + let mut seen = HashSet::new(); + let mut work = vec![v]; + while let Some(v) = work.pop() { + let v = self.ssa.resolve_value(v); + if !seen.insert(v) { + continue; + } + match self.ssa.phi_operands(v) { + Some(ops) => work.extend_from_slice(ops), + None => { + if let Some(&b) = self.def_block.get(&v) { + if b != c && self.partial[b] { + return true; + } + } + } + } + } + false + } + + /// Whether v is (or is a phi reaching) `marker`. + fn reaches(&self, v: I::V, marker: I::V) -> bool { + let mut seen = HashSet::new(); + let mut work = vec![v]; + while let Some(v) = work.pop() { + let v = self.ssa.resolve_value(v); + if v == marker { + return true; + } + if seen.insert(v) { + if let Some(ops) = self.ssa.phi_operands(v) { + work.extend_from_slice(ops); + } + } + } + false + } +} + +/// Per analysis block: whether some lane that reached a lane branch may not pass through it +/// before the lanes meet again – it is reachable from the branch but does not post-dominate +/// both of its successors (lanes that take the other one never get there; a loop's own latch +/// counts: the lanes that leave do not come back to it). +fn partial_blocks(sum: &Summary) -> Vec { + let n = sum.blocks.len(); + let words = (n + 1).div_ceil(64); + // post-dominators over the blocks the entry reaches, with a virtual exit n + let full = vec![!0u64; words]; + let mut pdom: Vec> = vec![full; n + 1]; + pdom[n] = vec![0u64; words]; + pdom[n][n / 64] |= 1 << (n % 64); + let mut changed = true; + while changed { + changed = false; + for &b in sum.order.iter().rev() { + let succ: Vec = if sum.blocks[b].succ.is_empty() { vec![n] } else { sum.blocks[b].succ.iter().map(|s| s.0).collect() }; + let mut new = vec![!0u64; words]; + for s in succ { + for (w, x) in new.iter_mut().zip(&pdom[s]) { + *w &= x; + } + } + new[b / 64] |= 1 << (b % 64); + if new != pdom[b] { + pdom[b] = new; + changed = true; + } + } + } + let mut partial = vec![false; n]; + for &x in &sum.order { + if !sum.blocks[x].lane_branch { + continue; + } + let mut seen = vec![false; n]; + let mut work: Vec = sum.blocks[x].succ.iter().map(|s| s.0).collect(); + while let Some(b) = work.pop() { + if std::mem::replace(&mut seen[b], true) { + continue; + } + if sum.blocks[x].succ.iter().any(|&(s, _)| pdom[s][b / 64] >> (b % 64) & 1 == 0) { + partial[b] = true; + } + work.extend(sum.blocks[b].succ.iter().map(|s| s.0)); + } + } + partial +} + +/// Lowers a kernel-mode program (far jumps resolved) into `ir`, which gets it complete, with +/// the mask registers whose value at the end may differ from the console's: written in a block +/// some lanes skipped, so those lanes still hold their own older bits (`stale`). Nothing reads +/// them in the program (that would be refused); only the kernel ABI's store of every register. +pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, Vec)> { + let sum = lane_masks::analyze(insts, wave64).map_err(|e| e.to_string())?; + let n = sum.blocks.len(); + if n == 0 { + return Err("empty program".into()); + } + let mut partial = vec![false; n + 5]; + for (b, p) in partial_blocks(&sum).into_iter().enumerate() { + partial[blk(b)] = p; + } + // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores, + // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch + let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4); + let ends: Vec = sum.order.iter().copied().filter(|&b| sum.blocks[b].succ.is_empty()).collect(); + let mut preds = vec![Vec::new(); n + 5]; + preds[blk(0)] = vec![0]; + for &b in &sum.order { + let mut seen = Vec::new(); + for &(s, _) in &sum.blocks[b].succ { + if !seen.contains(&s) { + seen.push(s); + preds[blk(s)].push(blk(b)); + } + } + } + preds[skip] = vec![0]; + preds[exit] = std::iter::once(skip).chain(ends.iter().map(|&b| blk(b))).collect(); + preds[sstore] = vec![exit]; + preds[vstore] = vec![exit, sstore]; + for i in 0..n + 5 { + let id = ir.new_block(); + debug_assert_eq!(id, i); + } + let num_marker = ir.undef(Var::S(0)); + let bit_marker = ir.undef(Var::M(0)); + let mut l = Lower { + ssa: Ssa::new(preds.clone()), + ir, + + sum: &sum, + guarded: sum.guarded.iter().copied().collect(), + wave64, + num_marker, + bit_marker, + num_uses: Vec::new(), + bit_uses: Vec::new(), + lane: None, + partial, + def_block: std::collections::HashMap::new(), + lane_uses: Vec::new(), + }; + // the registers the program names, and the ones the runner reads back + let mut sregs: Vec = vec![VCC, VCC + 1, 124, EXEC, EXEC + 1]; + let mut vregs: Vec = Vec::new(); + for d in insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as u8)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as u16)); + } + sregs.retain(|&r| (r as usize) < KERNEL_SGPRS && r != 125); + sregs.sort_unstable(); + sregs.dedup(); + vregs.sort_unstable(); + vregs.dedup(); + + // prologue: the register file from `io`; lanes outside EXEC go straight to the end + l.ir.at(0); + l.ssa.seal(&mut l.ir, 0); + let lane = l.lane(); + for &r in &sregs { + let a = l.ir.int(r as u32); + let v = l.ir.io_load(a); + l.write_num(0, r, v); + } + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let scc = l.ir.io_load(a); + let z = l.ir.int(0); + let scc = l.ir.icmp(Cmp::Ne, scc, z); + l.ssa.write(0, Var::Scc, scc); + let (base, stride) = (l.ir.int(KERNEL_SGPRS as u32), l.ir.int(KERNEL_VGPRS as u32)); + let row = l.ir.bin(Bin::Mul, lane, stride); + let row = l.ir.bin(Bin::Add, base, row); + for &v in &vregs { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, row, o); + let x = l.ir.io_load(a); + l.ssa.write(0, Var::V(v), x); + } + let active = l.read_bit(0, EXEC)?; + l.write_bit(0, EXEC, active); + l.ir.br_if(active, blk(0), skip); + // lanes outside EXEC: their bits of every mask are 0, as a whole-wave write leaves them + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + let f = l.ir.boolean(false); + for &r in &sregs { + l.ssa.write(skip, Var::M(r), f); + } + l.ir.br(exit); + + // the program, in reverse postorder; a block is sealed once all its predecessors are in + let mut done = vec![false; n + 5]; + done[0] = true; + done[skip] = true; + let seal_ready = |l: &mut Lower, done: &[bool], b: usize| { + if preds[b].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, b); + true + } else { + false + } + }; + let mut sealed = vec![false; n + 5]; + sealed[0] = true; + for &b in &sum.order.clone() { + let ib = blk(b); + l.ir.at(ib); + if !sealed[ib] { + sealed[ib] = seal_ready(&mut l, &done, ib); + } + if b == 0 { + // the analysis takes the lanes that start the program as its EXEC + let t = l.ir.boolean(true); + l.write_bit(ib, EXEC, t); + } + let block = &sum.blocks[b]; + let last = block.insts.end - 1; + for i in block.insts.clone() { + let d = &insts[i]; + let name = d.inst.name; + if i == last && (name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM")) { + break; + } + if name.starts_with("S_") { + l.salu(ib, d)?; + } else if name.starts_with("V_") { + l.valu(ib, d)?; + } else { + return Err(format!("unsupported {name}")); + } + } + match block.succ.as_slice() { + [] => l.ir.br(exit), + [(t, Edge::Always)] => l.ir.br(blk(*t)), + [(t, _), (f, _)] if t == f => l.ir.br(blk(*t)), + [(t, Edge::Taken), (f, Edge::NotTaken)] => { + let c = l.cond(ib, &insts[last])?; + l.ir.br_if(c, blk(*t), blk(*f)); + } + s => return Err(format!("block {b}: successors {s:?}")), + } + done[ib] = true; + for &(s, _) in &block.succ { + let is = blk(s); + if !sealed[is] && l.sum.order.contains(&s) { + // the successor's own code comes later; sealing it early is fine once its + // predecessors are all in + if preds[is].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, is); + sealed[is] = true; + } + } + } + } + for b in 1..=n { + if !sealed[b] && preds[b].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, b); + sealed[b] = true; + } + } + + // exit: every lane is here; masks the runner reads as numbers are the wave's ballots + l.ir.at(exit); + l.ssa.seal(&mut l.ir, exit); + let mut sval: Vec<(u8, I::V)> = Vec::new(); + let mut stale: Vec = Vec::new(); + let mut i = 0; + while i < sregs.len() { + let r = sregs[i]; + i += 1; + let s = l.read(exit, Var::S(r)); + if l.ssa.resolve_value(s) != l.num_marker && !l.reaches(s, l.num_marker) { + l.num_uses.push(s); + sval.push((r, s)); + continue; + } + if !l.holds_mask(exit, r) { + if l.wave64 && r > 0 && sval.iter().any(|&(x, _)| x == r) { + continue; // the upper half of a mask stored with its pair + } + return Err(format!("s{r}: neither a number nor a mask at the end")); + } + // read directly: a stale bit here is reported, not refused (only the ABI's store sees it) + let m = l.read(exit, Var::M(r)); + if r != EXEC && l.stale(exit, m) { + stale.push(r); + } + let [lo, hi] = l.ir.ballot(m); + sval.push((r, lo)); + if l.wave64 { + sval.retain(|&(x, _)| x != r + 1); + sval.push((r + 1, hi)); + if sregs.get(i) == Some(&(r + 1)) { + i += 1; + } + } + } + let scc = l.read(exit, Var::Scc); + let vval: Vec<(u16, I::V)> = vregs.iter().map(|&v| (v, l.read(exit, Var::V(v)))).collect(); + let z = l.ir.int(0); + let first = l.ir.icmp(Cmp::Eq, lane, z); + l.ir.br_if(first, sstore, vstore); + l.ir.at(sstore); + l.ssa.seal(&mut l.ir, sstore); + for &(r, v) in &sval { + let a = l.ir.int(r as u32); + l.ir.res_store(a, v); + } + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let s = l.ir.zext(scc); + l.ir.res_store(a, s); + l.ir.br(vstore); + l.ir.at(vstore); + l.ssa.seal(&mut l.ir, vstore); + for &(v, x) in &vval { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, row, o); + l.ir.res_store(a, x); + } + l.ir.ret(); + + // every phi is complete: no number may come from a mask, nor a mask bit from a number + for &v in &l.num_uses { + if l.reaches(v, l.num_marker) { + return Err("a mask read as a number (through a join)".into()); + } + } + for &v in &l.bit_uses { + if l.reaches(v, l.bit_marker) { + return Err("a number read as a mask (through a join)".into()); + } + } + for &(c, v) in &l.lane_uses { + if l.stale(c, v) { + return Err("a mask written while some lanes were elsewhere, read after they met again".into()); + } + } + stale.sort_unstable(); + stale.dedup(); + Ok((l.ir, stale)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + /// The IR as a small program, run lane by lane on the CPU: what the lowering means, + /// without a DXIL writer or a GPU. + #[derive(Clone, Debug)] + enum Ins { + Int(u32), + Bool(bool), + Bin(Bin, u32, u32), + Icmp(Cmp, u32, u32), + Select(u32, u32, u32), + Zext(u32), + Lane, + Ballot(u32, usize), + IoLoad(u32), + ResStore(u32, u32), + Phi(Vec<(u32, usize)>), + } + + #[derive(Clone, Debug)] + enum Term { + None, + Br(usize), + BrIf(u32, usize, usize), + Ret, + } + + #[derive(Default)] + struct Interp { + /// per block: (value id, instruction) in order, and the terminator + blocks: Vec<(Vec<(u32, Ins)>, Term)>, + cur: usize, + next: u32, + forward: HashMap, + undef: HashMap, + phi_block: HashMap, + } + + impl Interp { + fn push(&mut self, ins: Ins) -> u32 { + self.next += 1; + let v = self.next; + self.blocks[self.cur].0.push((v, ins)); + v + } + fn res(&self, mut v: u32) -> u32 { + while let Some(&n) = self.forward.get(&v) { + v = n; + } + v + } + } + + impl Sink for Interp { + type V = u32; + fn phi(&mut self, block: usize, _: Var) -> u32 { + self.next += 1; + let v = self.next; + self.blocks[block].0.insert(0, (v, Ins::Phi(Vec::new()))); + self.phi_block.insert(v, block); + v + } + fn incoming(&mut self, phi: u32, value: u32, pred: usize) { + let b = self.phi_block[&phi]; + for (id, ins) in &mut self.blocks[b].0 { + if *id == phi { + if let Ins::Phi(ops) = ins { + ops.push((value, pred)); + } + } + } + } + fn replace(&mut self, old: u32, new: u32) { + self.forward.insert(old, new); + let b = self.phi_block[&old]; + self.blocks[b].0.retain(|(id, _)| *id != old); + } + fn undef(&mut self, var: Var) -> u32 { + let bit = matches!(var, Var::M(_) | Var::Scc); + if let Some(&v) = self.undef.get(&bit) { + return v; + } + self.next += 1; + let v = self.next; + self.undef.insert(bit, v); + v + } + } + + impl Ir for Interp { + fn new_block(&mut self) -> usize { + self.blocks.push((Vec::new(), Term::None)); + self.blocks.len() - 1 + } + fn at(&mut self, block: usize) { + self.cur = block; + } + fn int(&mut self, v: u32) -> u32 { + self.push(Ins::Int(v)) + } + fn boolean(&mut self, v: bool) -> u32 { + self.push(Ins::Bool(v)) + } + fn bin(&mut self, op: Bin, a: u32, b: u32) -> u32 { + self.push(Ins::Bin(op, a, b)) + } + fn icmp(&mut self, c: Cmp, a: u32, b: u32) -> u32 { + self.push(Ins::Icmp(c, a, b)) + } + fn select(&mut self, c: u32, a: u32, b: u32) -> u32 { + self.push(Ins::Select(c, a, b)) + } + fn zext(&mut self, b: u32) -> u32 { + self.push(Ins::Zext(b)) + } + fn lane(&mut self) -> u32 { + self.push(Ins::Lane) + } + fn ballot(&mut self, c: u32) -> [u32; 2] { + [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] + } + fn io_load(&mut self, dword: u32) -> u32 { + self.push(Ins::IoLoad(dword)) + } + fn res_store(&mut self, dword: u32, value: u32) { + self.push(Ins::ResStore(dword, value)); + } + fn br(&mut self, target: usize) { + self.blocks[self.cur].1 = Term::Br(target); + } + fn br_if(&mut self, c: u32, then: usize, otherwise: usize) { + self.blocks[self.cur].1 = Term::BrIf(c, then, otherwise); + } + fn ret(&mut self) { + self.blocks[self.cur].1 = Term::Ret; + } + } + + /// One lane's position: block, instruction index, the block it came from, its values. + struct LaneState { + block: usize, + at: usize, + from: usize, + env: HashMap, + done: bool, + } + + impl Interp { + /// A value in a lane: what it computed, or 0 for `undef` (a marker of the lowering). + fn value(&self, env: &HashMap, v: u32) -> u32 { + let v = self.res(v); + if self.undef.values().any(|&u| u == v) { + return 0; + } + *env.get(&v).unwrap_or_else(|| panic!("value {v} not defined")) + } + } + + impl Interp { + /// Runs the program over `lanes` lanes; `io` in, `res` out. Ballots wait for every lane. + fn run(&self, lanes: usize, io: &[u32], res: &mut [u32]) { + let mut ls: Vec = (0..lanes).map(|_| LaneState { block: 0, at: 0, from: 0, env: HashMap::new(), done: false }).collect(); + let mut steps = 0usize; + loop { + // run every lane up to a ballot or its end + for (lane, s) in ls.iter_mut().enumerate() { + while !s.done { + steps += 1; + assert!(steps < 10_000_000, "runaway program"); + let (ins, term) = &self.blocks[s.block]; + if s.at == 0 { + // phis read their operands from the edge taken, all at once + let vals: Vec<(u32, u32)> = ins + .iter() + .filter_map(|(id, i)| match i { + Ins::Phi(ops) => { + let (v, _) = ops.iter().find(|(_, p)| *p == s.from).unwrap_or_else(|| panic!("phi {id} in block {} has no operand from {}", s.block, s.from)); + Some((*id, self.value(&s.env, *v))) + } + _ => None, + }) + .collect(); + s.env.extend(vals); + } + if s.at < ins.len() { + let (id, i) = &ins[s.at]; + let g = |v: &u32| self.value(&s.env, *v); + let r = match i { + Ins::Phi(_) => None, + Ins::Int(x) => Some(*x), + Ins::Bool(x) => Some(*x as u32), + Ins::Bin(op, a, b) => { + let (a, b) = (g(a), g(b)); + Some(match op { + Bin::Add => a.wrapping_add(b), + Bin::Sub => a.wrapping_sub(b), + Bin::Mul => a.wrapping_mul(b), + Bin::And => a & b, + Bin::Or => a | b, + Bin::Xor => a ^ b, + Bin::Shl => a << (b & 31), + Bin::LShr => a >> (b & 31), + Bin::AShr => ((a as i32) >> (b & 31)) as u32, + }) + } + Ins::Icmp(c, a, b) => { + let (a, b) = (g(a), g(b)); + let (sa, sb) = (a as i32, b as i32); + Some(match c { + Cmp::Eq => a == b, + Cmp::Ne => a != b, + Cmp::Ult => a < b, + Cmp::Ule => a <= b, + Cmp::Ugt => a > b, + Cmp::Uge => a >= b, + Cmp::Slt => sa < sb, + Cmp::Sle => sa <= sb, + Cmp::Sgt => sa > sb, + Cmp::Sge => sa >= sb, + } as u32) + } + Ins::Select(c, a, b) => Some(if g(c) != 0 { g(a) } else { g(b) }), + Ins::Zext(b) => Some(g(b)), + Ins::Lane => Some(lane as u32), + Ins::Ballot(..) => break, + Ins::IoLoad(a) => Some(io[g(a) as usize]), + Ins::ResStore(a, v) => { + res[g(a) as usize] = g(v); + None + } + }; + if let Some(r) = r { + s.env.insert(*id, r); + } + s.at += 1; + continue; + } + match term { + Term::Br(t) => { + s.from = s.block; + s.block = *t; + } + Term::BrIf(c, t, f) => { + s.from = s.block; + s.block = if s.env[&self.res(*c)] != 0 { *t } else { *f }; + } + Term::Ret => s.done = true, + Term::None => panic!("block {} has no terminator", s.block), + } + s.at = 0; + } + } + if ls.iter().all(|s| s.done) { + return; + } + // every lane waits at the same ballot + let (b, at) = (ls[0].block, ls[0].at); + assert!(ls.iter().all(|s| !s.done && s.block == b && s.at == at), "a ballot not reached by every lane"); + let (id, Ins::Ballot(c, half)) = &self.blocks[b].0[at] else { unreachable!() }; + let mut bits = 0u64; + for (lane, s) in ls.iter().enumerate() { + if s.env[&self.res(*c)] != 0 { + bits |= 1 << lane; + } + } + let word = (bits >> (32 * half)) as u32; + for s in &mut ls { + s.env.insert(*id, word); + s.at += 1; + } + } + } + } + + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const V: u64 = 256; + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + + // wave32 programs shared by the CPU tests and the comparison with the HLSL path + const STRAIGHT: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 1)]), + ENDPGM, + ]; + /// v_cmp_gt_u32 vcc, 16, v0; s_and_saveexec s0, vcc; s_cbranch_execz L; v_mov v1, 7; + /// L: s_or exec, exec, s0; v_add v2, v1, 1 + const SKIPPED_IF: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), + ENDPGM, + ]; + /// s_mov s0, exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; exec &= ~vcc; + /// s_cbranch_execnz L; exec |= s0 → v1 = max(1, lane) + const LEAVING_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + /// s1 = 0; L: s1 += 3; v1 += 1; s_cmp_lt_u32 s1, 12; s_cbranch_scc1 L + const UNIFORM_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 140)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ENDPGM, + ]; + + fn decode(lines: &[I]) -> Vec { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let mut out = Vec::new(); + let mut off = 0; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + out + } + + /// The kernel run on the CPU: initial (sgpr, vgpr[lane]) → final ones. + fn run(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec]) -> (Vec, Vec>) { + let insts = decode(lines); + let (ir, _) = lower_kernel(&insts, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let lanes = if wave64 { 64 } else { 32 }; + let mut io = vec![0u32; KERNEL_SGPRS + 64 * KERNEL_VGPRS]; + io[..sgpr.len()].copy_from_slice(sgpr); + for (l, regs) in vgpr.iter().enumerate().take(lanes) { + io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); + } + let mut res = io.clone(); + ir.run(lanes, &io, &mut res); + let v = (0..lanes).map(|l| res[KERNEL_SGPRS + l * KERNEL_VGPRS..][..KERNEL_VGPRS].to_vec()).collect(); + (res[..KERNEL_SGPRS].to_vec(), v) + } + + fn state(lanes: usize) -> (Vec, Vec>) { + let mut s = vec![0u32; KERNEL_SGPRS]; + s[126] = u32::MAX; + s[127] = u32::MAX; + // v0 = the lane, v1 = 0 + (s, (0..lanes).map(|l| { let mut v = vec![0u32; 8]; v[0] = l as u32; v }).collect()) + } + + #[test] + fn straight_line_scalar_and_vector_arithmetic() { + let (s, v) = state(32); + let (s, v) = run(STRAIGHT, false, &s, &v); + assert_eq!((s[0], s[1]), (5, 10)); + for (l, regs) in v.iter().enumerate() { + assert_eq!((regs[1], regs[2]), (10, 10 + l as u32), "lane {l}"); + } + } + + #[test] + fn a_skipped_if_runs_only_its_lanes() { + let (s, v) = state(32); + let (s, v) = run(SKIPPED_IF, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + let want = if l < 16 { 7 } else { 0 }; + assert_eq!((regs[1], regs[2]), (want, want + 1), "lane {l}"); + } + assert_eq!(s[106], 0xFFFF, "vcc: the lanes below 16"); + assert_eq!((s[0], s[126]), (u32::MAX, u32::MAX), "saved and restored EXEC"); + } + + #[test] + fn lanes_leave_a_loop_one_by_one() { + let (s, v) = state(32); + let (s, v) = run(LEAVING_LOOP, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + assert_eq!(regs[1], (l as u32).max(1), "lane {l}"); + } + assert_eq!(s[126], u32::MAX); + } + + #[test] + fn a_uniform_loop_with_a_scalar_counter() { + let (s, v) = state(32); + let (s, v) = run(UNIFORM_LOOP, false, &s, &v); + assert_eq!(s[1], 12); + assert!(v.iter().all(|r| r[1] == 4)); + } + + #[test] + fn lanes_outside_exec_at_launch_keep_their_registers() { + let (mut s, v) = state(32); + s[126] = 0x0000_00FF; + let (s, v) = run(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 137)]), ENDPGM], false, &s, &v); + for (l, regs) in v.iter().enumerate() { + assert_eq!(regs[1], if l < 8 { 9 } else { 0 }, "lane {l}"); + } + assert_eq!(s[126], 0xFF); + } + + #[test] + fn wave64_masks_span_both_words() { + // v_cmp_gt_u32 vcc, 40, v0 over 64 lanes: lanes 0–39 + let (s, v) = state(64); + let (s, _) = run(&[("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), ENDPGM], true, &s, &v); + assert_eq!((s[106], s[107]), (u32::MAX, 0xFF)); + } + + /// The lowering run on the CPU and the HLSL path run on the GPU give the same registers. + #[test] + fn the_lowering_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + return; + } + for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP)] { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let gpu = runner::run(&dxil, &st, &[]).unwrap(); + let (cs, cv) = run(lines, false, &s, &v); + let insts = decode(lines); + // masks some lanes kept their own older bits of (`lower_kernel`'s `stale`): only the + // kernel ABI's final store sees them + let (_, stale) = lower_kernel(&insts, false, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..32 { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + #[test] + fn a_mask_left_behind_by_lanes_that_skipped_its_write() { + // VCC written inside the loop that lanes leave one by one: the console's last write left + // the earlier leavers' bits 0, each lane here kept its own. Stored at the end: reported. + let insts = decode(LEAVING_LOOP); + let (_, stale) = lower_kernel(&insts, false, Interp::default()).unwrap(); + assert_eq!(stale, vec![106]); + // read after the loop (v_cndmask on VCC): refused + let mut lines = LEAVING_LOOP.to_vec(); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128), ("VSRC1", 0)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + // a mask written before the lanes split is read after they meet: fine + let insts = decode(SKIPPED_IF); + assert_eq!(lower_kernel(&insts, false, Interp::default()).unwrap().1, Vec::::new()); + } + + #[test] + fn a_mask_read_as_a_number_is_refused() { + // s_bcnt1-like use: s_add_u32 s2, vcc_lo, 0 after a v_cmp + let insts = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 128)]), + ENDPGM, + ]); + assert!(lower_kernel(&insts, false, Interp::default()).is_err()); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index f0e029f031..e5c2c4c35a 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -54,6 +54,7 @@ pub mod dxc; pub mod dxil; pub mod lane_masks; +pub mod lower; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; @@ -61,6 +62,7 @@ pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; pub mod runner; +pub mod ssa; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/ssa.rs b/crates/xcl/src/gpu/recomp/ssa.rs new file mode 100644 index 0000000000..0a7fd4698d --- /dev/null +++ b/crates/xcl/src/gpu/recomp/ssa.rs @@ -0,0 +1,304 @@ +//! SSA form of the console registers for the direct DXIL lowering, built while the blocks are +//! lowered (the on-the-fly construction of Braun et al., "Simple and Efficient Construction of +//! Static Single Assignment Form", CC 2013). +//! +//! Every register dword (s0–s127, v0–v255, SCC) is a variable. The lowering writes a variable +//! when an instruction defines it and reads it when one uses it; a read in a block without a +//! definition looks through the predecessors, placing a phi where they can disagree. A block +//! whose predecessors are not all lowered yet (a loop head, before its back edges) is *unsealed*: +//! its phis are left incomplete and filled in when it is sealed. A phi whose operands are all one +//! value (or itself) is trivial and is replaced by that value, through the sink's `replace`. +//! +//! The values themselves live in the DXIL module; this only decides where phis go. The sink is +//! the module builder. + +use std::collections::HashMap; +use std::hash::Hash; + +/// A register dword of the console program: what the SSA form tracks. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum Var { + /// s as a number (`i32`) + S(u8), + /// the lane's bit of the mask held in s (wave64: the pair from s) (`i1`) + M(u8), + V(u16), + Scc, +} + +/// What the construction needs from the module builder. +pub trait Sink { + type V: Copy + Eq + Hash + std::fmt::Debug; + /// A new phi at the top of `block` for `var` (`i1` for SCC, `i32` for a register). + fn phi(&mut self, block: usize, var: Var) -> Self::V; + fn incoming(&mut self, phi: Self::V, value: Self::V, pred: usize); + /// Every use of `old` becomes `new`, and `old` (a trivial phi) is dropped. + fn replace(&mut self, old: Self::V, new: Self::V); + /// The value of a variable read before any definition reaches it. + fn undef(&mut self, var: Var) -> Self::V; +} + +pub struct Ssa { + preds: Vec>, + defs: Vec>, + sealed: Vec, + /// per unsealed block: the phis placed before its predecessors were known + incomplete: Vec>, + /// the operands of each live phi, and the phis that use each value + operands: HashMap>, + users: HashMap>, + /// trivial phis removed → what replaced them + forward: HashMap, +} + +impl Ssa { + /// `preds[b]`: the predecessors of block b, all of them, back edges included. + pub fn new(preds: Vec>) -> Self { + let n = preds.len(); + Ssa { + preds, + defs: vec![HashMap::new(); n], + sealed: vec![false; n], + incomplete: vec![Vec::new(); n], + operands: HashMap::new(), + users: HashMap::new(), + forward: HashMap::new(), + } + } + + /// What a value stands for now: itself, or what replaced it as a trivial phi. + pub fn resolve_value(&self, v: V) -> V { + self.resolve(v) + } + + /// The operands of a live phi (None for any other value). + pub fn phi_operands(&self, v: V) -> Option<&[V]> { + self.operands.get(&v).map(|o| o.as_slice()) + } + + fn resolve(&self, mut v: V) -> V { + while let Some(&n) = self.forward.get(&v) { + v = n; + } + v + } + + pub fn write(&mut self, block: usize, var: Var, value: V) { + self.defs[block].insert(var, value); + } + + pub fn read>(&mut self, sink: &mut S, block: usize, var: Var) -> V { + if let Some(&v) = self.defs[block].get(&var) { + return self.resolve(v); + } + let v = if !self.sealed[block] { + let phi = self.new_phi(sink, block, var); + self.incomplete[block].push((var, phi)); + phi + } else if self.preds[block].len() == 1 { + let p = self.preds[block][0]; + self.read(sink, p, var) + } else if self.preds[block].is_empty() { + sink.undef(var) + } else { + // the phi is the definition while its operands are read (a loop through here) + let phi = self.new_phi(sink, block, var); + self.write(block, var, phi); + self.add_operands(sink, block, var, phi) + }; + self.write(block, var, v); + v + } + + /// Every predecessor of `block` has been lowered: complete its phis. + pub fn seal>(&mut self, sink: &mut S, block: usize) { + for (var, phi) in std::mem::take(&mut self.incomplete[block]) { + self.add_operands(sink, block, var, phi); + } + self.sealed[block] = true; + } + + fn new_phi>(&mut self, sink: &mut S, block: usize, var: Var) -> V { + let phi = sink.phi(block, var); + self.operands.insert(phi, Vec::new()); + phi + } + + fn add_operands>(&mut self, sink: &mut S, block: usize, var: Var, phi: V) -> V { + for p in self.preds[block].clone() { + let v = self.read(sink, p, var); + sink.incoming(phi, v, p); + self.operands.get_mut(&phi).expect("live phi").push(v); + self.users.entry(v).or_default().push(phi); + } + self.remove_trivial(sink, phi) + } + + fn remove_trivial>(&mut self, sink: &mut S, phi: V) -> V { + let mut same = None; + for &op in &self.operands[&phi] { + let op = self.resolve(op); + if Some(op) == same || op == phi { + continue; + } + if same.is_some() { + return phi; + } + same = Some(op); + } + let Some(same) = same else { return phi }; // only reachable through itself: kept + sink.replace(phi, same); + self.forward.insert(phi, same); + self.operands.remove(&phi); + // phis that used this one may have become trivial in turn + for user in self.users.remove(&phi).unwrap_or_default() { + if user != phi && self.operands.contains_key(&user) { + self.remove_trivial(sink, user); + } + } + same + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Records what the construction asks of a module builder. + #[derive(Default)] + struct Log { + next: u32, + phis: Vec<(u32, usize, Var)>, + incoming: Vec<(u32, u32, usize)>, + replaced: Vec<(u32, u32)>, + } + + impl Log { + fn value(&mut self) -> u32 { + self.next += 1; + self.next + } + fn live_phis(&self) -> Vec { + self.phis.iter().map(|p| p.0).filter(|p| !self.replaced.iter().any(|r| r.0 == *p)).collect() + } + } + + impl Sink for Log { + type V = u32; + fn phi(&mut self, block: usize, var: Var) -> u32 { + let v = self.value(); + self.phis.push((v, block, var)); + v + } + fn incoming(&mut self, phi: u32, value: u32, pred: usize) { + self.incoming.push((phi, value, pred)); + } + fn replace(&mut self, old: u32, new: u32) { + self.replaced.push((old, new)); + } + fn undef(&mut self, _: Var) -> u32 { + 0 + } + } + + const R: Var = Var::V(3); + + #[test] + fn a_straight_line_needs_no_phi() { + // 0 → 1 → 2 + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![1]]), Log::default()); + let a = log.value(); + ssa.write(0, R, a); + for b in 0..3 { + ssa.seal(&mut log, b); + } + assert_eq!(ssa.read(&mut log, 2, R), a); + assert!(log.phis.is_empty()); + } + + #[test] + fn a_diamond_joins_two_definitions() { + // 0 → {1, 2} → 3, each arm defines R + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![0], vec![1, 2]]), Log::default()); + let (a, b) = (log.value(), log.value()); + for blk in 0..4 { + ssa.seal(&mut log, blk); + } + ssa.write(1, R, a); + ssa.write(2, R, b); + let j = ssa.read(&mut log, 3, R); + assert_eq!(log.live_phis(), vec![j]); + assert_eq!(log.incoming, vec![(j, a, 1), (j, b, 2)]); + } + + #[test] + fn one_arm_defining_still_joins_with_the_value_from_before() { + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![0], vec![1, 2]]), Log::default()); + let (a, b) = (log.value(), log.value()); + for blk in 0..4 { + ssa.seal(&mut log, blk); + } + ssa.write(0, R, a); + ssa.write(1, R, b); + let j = ssa.read(&mut log, 3, R); + assert_eq!(log.incoming, vec![(j, b, 1), (j, a, 2)]); + } + + #[test] + fn a_loop_that_changes_the_register_keeps_its_phi() { + // 0 → 1 (head) → 2 (body) → 1, 1 → 3 (exit); the body increments R + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0, 2], vec![1], vec![1]]), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let head = ssa.read(&mut log, 1, R); // head not sealed yet: incomplete phi + ssa.seal(&mut log, 2); + let body_in = ssa.read(&mut log, 2, R); + assert_eq!(body_in, head); + let inc = log.value(); + ssa.write(2, R, inc); + ssa.seal(&mut log, 1); // back edge known + ssa.seal(&mut log, 3); + assert_eq!(ssa.read(&mut log, 3, R), head); + assert_eq!(log.live_phis(), vec![head]); + assert_eq!(log.incoming, vec![(head, a, 0), (head, inc, 2)]); + } + + #[test] + fn a_loop_that_leaves_the_register_alone_drops_its_phi() { + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0, 2], vec![1], vec![1]]), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let head = ssa.read(&mut log, 1, R); + ssa.seal(&mut log, 2); + let _ = ssa.read(&mut log, 2, R); + ssa.seal(&mut log, 1); + ssa.seal(&mut log, 3); + assert_eq!(log.replaced, vec![(head, a)]); + assert!(log.live_phis().is_empty()); + assert_eq!(ssa.read(&mut log, 3, R), a, "reads after the removal see the replacement"); + } + + #[test] + fn removing_a_phi_cascades_to_the_phis_built_on_it() { + // nested loops that never change R: inner head 2's phi uses outer head 1's phi + // 0 → 1 → 2 → 3 → 2, 3 → 4 → 1, 4 → 5 + let preds = vec![vec![], vec![0, 4], vec![1, 3], vec![2], vec![3], vec![4]]; + let (mut ssa, mut log) = (Ssa::new(preds), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let outer = ssa.read(&mut log, 1, R); + let inner = ssa.read(&mut log, 2, R); + ssa.seal(&mut log, 3); + let _ = ssa.read(&mut log, 3, R); + ssa.seal(&mut log, 2); + ssa.seal(&mut log, 4); + let _ = ssa.read(&mut log, 4, R); + ssa.seal(&mut log, 1); + ssa.seal(&mut log, 5); + assert!(log.live_phis().is_empty(), "both heads' phis go: {:?} {:?}", outer, inner); + assert_eq!(ssa.read(&mut log, 5, R), a); + } +} From 430f0a332b605eddcdff26646374374c53533553 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:51:57 -0300 Subject: [PATCH 04/51] Recompiler: scalar and vector memory in the direct lowering `s_load_dword{,x2,x4,x8,x16}` and `global_` / `flat_` `load` / `store_dword {,x2,x3,x4}` on the flat memory, with the addressing of the HLSL path's single-window form. A guarded load runs in every lane and keeps the old register where the lane's EXEC bit is clear (a raw buffer read out of range is 0, so an inactive lane's address can't fault). A guarded store gets a block of its own that only the lanes with their bit enter, and the rest of the console block continues after it; the blocks are reserved before the SSA form is built, so the predecessor lists stay exact. The CPU interpreter in the tests gets the memory too, and the comparison with the HLSL path on the GPU now also checks the memory after the run: a program with an SMEM load, a per-lane load, a guarded store and an unguarded one agrees word for word (GTX 1650, wave32). --- crates/xcl/src/gpu/recomp/lower.rs | 244 ++++++++++++++++++++++++++--- 1 file changed, 222 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index c12936f2a5..09fd6ff1e0 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -68,6 +68,10 @@ pub trait Ir: Sink { fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; fn io_load(&mut self, dword: Self::V) -> Self::V; fn res_store(&mut self, dword: Self::V, value: Self::V); + /// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of + /// range reads 0 and writes nothing, as D3D12 raw buffers do + fn mem_load(&mut self, addr: Self::V) -> Self::V; + fn mem_store(&mut self, addr: Self::V, value: Self::V); fn br(&mut self, target: usize); fn br_if(&mut self, c: Self::V, then: usize, otherwise: usize); fn ret(&mut self); @@ -97,6 +101,12 @@ struct Lower<'a, I: Ir> { lane_uses: Vec<(usize, I::V)>, } +/// A vector memory store: a side effect inactive lanes must not have. +fn is_store(d: &Decoded) -> bool { + let n = d.inst.name; + (n.starts_with("GLOBAL_STORE_") || n.starts_with("FLAT_STORE_")) && matches!(d.enc.name, "ENC_FLAT_GLBL" | "ENC_FLAT") +} + /// IR block of analysis block b (block 0 is the prologue). fn blk(b: usize) -> usize { b + 1 @@ -496,6 +506,92 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_v(b, d, vdst as u16, v) } + /// `s_load_dword{,x2,x4,x8,x16}`: dwords of the flat memory into SGPRs, from + /// `s[sbase] + offset + soffset` (one memory window, as `emit::smem` with `mem_windows` 1). + fn smem(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let count = match name.strip_prefix("S_LOAD_") { + Some("DWORD") => 1, + Some("DWORDX2") => 2, + Some("DWORDX4") => 4, + Some("DWORDX8") => 8, + Some("DWORDX16") => 16, + _ => return Err(format!("unsupported {name}")), + }; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + let (sdata, sbase) = (fv("SDATA") as u8, fv("SBASE") as u8); + let imm = (((fv("OFFSET") as u32) << 11) as i32 >> 11) as u32; // 21-bit signed + let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); + let base = self.read_num(b, sbase)?; + let imm = self.ir.int(imm); + let mut a = self.ir.bin(Bin::Add, base, imm); + if soff != 125 { + let s = self.src(b, d, soff)?; + a = self.ir.bin(Bin::Add, a, s); + } + let m = self.ir.int(!3); + let a = self.ir.bin(Bin::And, a, m); + let vals: Vec = (0..count) + .map(|i| { + let o = self.ir.int(4 * i as u32); + let ai = self.ir.bin(Bin::Add, a, o); + self.ir.mem_load(ai) + }) + .collect(); + for (i, v) in vals.into_iter().enumerate() { + self.write_num(b, sdata + i as u8, v); + } + Ok(()) + } + + /// `global_` / `flat_` `load` / `store_dword{,x2,x3,x4}` on the flat memory. A guarded load + /// keeps the old register in lanes without their EXEC bit (`write_v`); a guarded store is + /// lowered in a block only those lanes enter (the caller's split). + fn vmem(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let op = name.trim_start_matches("GLOBAL_").trim_start_matches("FLAT_"); + let (store, count) = match op { + "LOAD_DWORD" => (false, 1), + "LOAD_DWORDX2" => (false, 2), + "LOAD_DWORDX3" => (false, 3), + "LOAD_DWORDX4" => (false, 4), + "STORE_DWORD" => (true, 1), + "STORE_DWORDX2" => (true, 2), + "STORE_DWORDX3" => (true, 3), + "STORE_DWORDX4" => (true, 4), + _ => return Err(format!("unsupported {name}")), + }; + let global = d.enc.name == "ENC_FLAT_GLBL"; + if !global && d.enc.name != "ENC_FLAT" { + return Err(format!("{name}: {}", d.enc.name)); + } + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let raw = fv("OFFSET") as u32; + let off = if global { ((raw << 20) as i32 >> 20) as u32 } else { raw }; + let saddr = fv("SADDR"); + let mut a = self.read(b, Var::V(fv("ADDR") as u16)); + if global && saddr != 0x7D && saddr != 0x7F { + let s = self.read_num(b, saddr as u8)?; + a = self.ir.bin(Bin::Add, s, a); + } + let off = self.ir.int(off); + let a = self.ir.bin(Bin::Add, a, off); + for i in 0..count { + let o = self.ir.int(4 * i as u32); + let ai = self.ir.bin(Bin::Add, a, o); + let m = self.ir.int(!3); + let ai = self.ir.bin(Bin::And, ai, m); + if store { + let v = self.read(b, Var::V(fv("DATA") as u16 + i as u16)); + self.ir.mem_store(ai, v); + } else { + let v = self.ir.mem_load(ai); + self.write_v(b, d, fv("VDST") as u16 + i as u16, v)?; + } + } + Ok(()) + } + /// The condition under which a lane takes the branch ending block b. fn cond(&mut self, b: usize, d: &Decoded) -> R { Ok(match d.inst.name { @@ -627,30 +723,55 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, if n == 0 { return Err("empty program".into()); } - let mut partial = vec![false; n + 5]; + // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores, + // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch, + // then for every guarded store (only the lanes with their EXEC bit may write): the block of + // the store and the one the rest of its block continues in. `tail[b]`: the IR block the + // program's block b ends in. + let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4); + let guarded: HashSet = sum.guarded.iter().copied().collect(); + let mut splits: Vec> = vec![Vec::new(); n]; // (inst, store, cont) + let mut count = n + 5; + for (b, block) in sum.blocks.iter().enumerate() { + for i in block.insts.clone() { + if is_store(&insts[i]) && guarded.contains(&insts[i].pc) { + splits[b].push((i, count, count + 1)); + count += 2; + } + } + } + let tail: Vec = (0..n).map(|b| splits[b].last().map_or(blk(b), |s| s.2)).collect(); + let mut partial = vec![false; count]; for (b, p) in partial_blocks(&sum).into_iter().enumerate() { partial[blk(b)] = p; + for &(_, s, c) in &splits[b] { + partial[s] = true; + partial[c] = p; + } } - // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores, - // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch - let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4); let ends: Vec = sum.order.iter().copied().filter(|&b| sum.blocks[b].succ.is_empty()).collect(); - let mut preds = vec![Vec::new(); n + 5]; + let mut preds = vec![Vec::new(); count]; preds[blk(0)] = vec![0]; for &b in &sum.order { let mut seen = Vec::new(); for &(s, _) in &sum.blocks[b].succ { if !seen.contains(&s) { seen.push(s); - preds[blk(s)].push(blk(b)); + preds[blk(s)].push(tail[b]); } } + let mut prev = blk(b); + for &(_, s, c) in &splits[b] { + preds[s] = vec![prev]; + preds[c] = vec![prev, s]; + prev = c; + } } preds[skip] = vec![0]; - preds[exit] = std::iter::once(skip).chain(ends.iter().map(|&b| blk(b))).collect(); + preds[exit] = std::iter::once(skip).chain(ends.iter().map(|&b| tail[b])).collect(); preds[sstore] = vec![exit]; preds[vstore] = vec![exit, sstore]; - for i in 0..n + 5 { + for i in 0..count { let id = ir.new_block(); debug_assert_eq!(id, i); } @@ -661,7 +782,7 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, ir, sum: &sum, - guarded: sum.guarded.iter().copied().collect(), + guarded, wave64, num_marker, bit_marker, @@ -723,7 +844,7 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, l.ir.br(exit); // the program, in reverse postorder; a block is sealed once all its predecessors are in - let mut done = vec![false; n + 5]; + let mut done = vec![false; count]; done[0] = true; done[skip] = true; let seal_ready = |l: &mut Lower, done: &[bool], b: usize| { @@ -734,7 +855,7 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, false } }; - let mut sealed = vec![false; n + 5]; + let mut sealed = vec![false; count]; sealed[0] = true; for &b in &sum.order.clone() { let ib = blk(b); @@ -749,16 +870,35 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, } let block = &sum.blocks[b]; let last = block.insts.end - 1; + let mut cur = ib; + let mut split = splits[b].iter().peekable(); for i in block.insts.clone() { let d = &insts[i]; let name = d.inst.name; if i == last && (name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM")) { break; } - if name.starts_with("S_") { - l.salu(ib, d)?; + if let Some(&(_, s, c)) = split.next_if(|x| x.0 == i) { + // a guarded store: only the lanes with their EXEC bit go through its block + let e = l.read_bit(cur, EXEC)?; + l.ir.br_if(e, s, c); + done[cur] = true; + l.ir.at(s); + l.ssa.seal(&mut l.ir, s); + l.vmem(s, d)?; + l.ir.br(c); + done[s] = true; + l.ir.at(c); + l.ssa.seal(&mut l.ir, c); + cur = c; + } else if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { + l.smem(cur, d)?; + } else if name.starts_with("S_") { + l.salu(cur, d)?; } else if name.starts_with("V_") { - l.valu(ib, d)?; + l.valu(cur, d)?; + } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { + l.vmem(cur, d)?; } else { return Err(format!("unsupported {name}")); } @@ -768,12 +908,12 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, [(t, Edge::Always)] => l.ir.br(blk(*t)), [(t, _), (f, _)] if t == f => l.ir.br(blk(*t)), [(t, Edge::Taken), (f, Edge::NotTaken)] => { - let c = l.cond(ib, &insts[last])?; + let c = l.cond(cur, &insts[last])?; l.ir.br_if(c, blk(*t), blk(*f)); } s => return Err(format!("block {b}: successors {s:?}")), } - done[ib] = true; + done[cur] = true; for &(s, _) in &block.succ { let is = blk(s); if !sealed[is] && l.sum.order.contains(&s) { @@ -893,6 +1033,8 @@ mod tests { Ballot(u32, usize), IoLoad(u32), ResStore(u32, u32), + MemLoad(u32), + MemStore(u32, u32), Phi(Vec<(u32, usize)>), } @@ -1004,6 +1146,12 @@ mod tests { fn res_store(&mut self, dword: u32, value: u32) { self.push(Ins::ResStore(dword, value)); } + fn mem_load(&mut self, addr: u32) -> u32 { + self.push(Ins::MemLoad(addr)) + } + fn mem_store(&mut self, addr: u32, value: u32) { + self.push(Ins::MemStore(addr, value)); + } fn br(&mut self, target: usize) { self.blocks[self.cur].1 = Term::Br(target); } @@ -1037,7 +1185,7 @@ mod tests { impl Interp { /// Runs the program over `lanes` lanes; `io` in, `res` out. Ballots wait for every lane. - fn run(&self, lanes: usize, io: &[u32], res: &mut [u32]) { + fn run(&self, lanes: usize, io: &[u32], res: &mut [u32], mem: &mut [u32]) { let mut ls: Vec = (0..lanes).map(|_| LaneState { block: 0, at: 0, from: 0, env: HashMap::new(), done: false }).collect(); let mut steps = 0usize; loop { @@ -1103,6 +1251,14 @@ mod tests { Ins::Lane => Some(lane as u32), Ins::Ballot(..) => break, Ins::IoLoad(a) => Some(io[g(a) as usize]), + Ins::MemLoad(a) => Some(mem.get((g(a) / 4) as usize).copied().unwrap_or(0)), + Ins::MemStore(a, v) => { + let (a, v) = (g(a), g(v)); + if let Some(w) = mem.get_mut((a / 4) as usize) { + *w = v; + } + None + } Ins::ResStore(a, v) => { res[g(a) as usize] = g(v); None @@ -1195,6 +1351,25 @@ mod tests { ENDPGM, ]; + /// v1 = 4·lane; s[4:5] = mem[2..4]; v2 = mem[lane] + s4; then lanes below 16 store v2 at + /// mem[64 + lane] (a guarded store: no skip branch), and every lane stores v0 at mem[128 + lane] + const MEMORY: &[I] = &[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 2), ("SADDR", 125), ("OFFSET", 0x100)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 6)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 125), ("OFFSET", 0x200)]), + ENDPGM, + ]; + + fn memory_image() -> Vec { + (0..256).map(|i| 1000 + i).collect() + } + fn decode(lines: &[I]) -> Vec { let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); let mut out = Vec::new(); @@ -1209,6 +1384,12 @@ mod tests { /// The kernel run on the CPU: initial (sgpr, vgpr[lane]) → final ones. fn run(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec]) -> (Vec, Vec>) { + let (s, v, _) = run_mem(lines, wave64, sgpr, vgpr, &[]); + (s, v) + } + + /// … with the flat memory too: (sgpr, vgpr[lane], memory after). + fn run_mem(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec], mem: &[u32]) -> (Vec, Vec>, Vec) { let insts = decode(lines); let (ir, _) = lower_kernel(&insts, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); let lanes = if wave64 { 64 } else { 32 }; @@ -1218,9 +1399,10 @@ mod tests { io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); } let mut res = io.clone(); - ir.run(lanes, &io, &mut res); + let mut mem = mem.to_vec(); + ir.run(lanes, &io, &mut res, &mut mem); let v = (0..lanes).map(|l| res[KERNEL_SGPRS + l * KERNEL_VGPRS..][..KERNEL_VGPRS].to_vec()).collect(); - (res[..KERNEL_SGPRS].to_vec(), v) + (res[..KERNEL_SGPRS].to_vec(), v, mem) } fn state(lanes: usize) -> (Vec, Vec>) { @@ -1298,7 +1480,7 @@ mod tests { runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); return; } - for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP)] { + for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); let (s, v) = state(32); let mut st = runner::KernelState::default(); @@ -1309,8 +1491,10 @@ mod tests { let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); assert!(t.complete(), "{name}: {:?}", t.unsupported_why); let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); - let gpu = runner::run(&dxil, &st, &[]).unwrap(); - let (cs, cv) = run(lines, false, &s, &v); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(lines, false, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); let insts = decode(lines); // masks some lanes kept their own older bits of (`lower_kernel`'s `stale`): only the // kernel ABI's final store sees them @@ -1334,6 +1518,22 @@ mod tests { } } + #[test] + fn scalar_and_vector_memory_with_a_guarded_store() { + let (s, v) = state(32); + let (s, v, mem) = run_mem(MEMORY, false, &s, &v, &memory_image()); + assert_eq!((s[4], s[5]), (1002, 1003)); + for l in 0..32 { + assert_eq!(v[l][2], 2002 + l as u32, "lane {l}"); + assert_eq!(mem[64 + l], if l < 16 { 2002 + l as u32 } else { 1064 + l as u32 }, "guarded store, lane {l}"); + assert_eq!(mem[128 + l], l as u32, "store, lane {l}"); + } + // the store under the narrowed EXEC is the guarded one + let insts = decode(MEMORY); + let sum = lane_masks::analyze(&insts, false).unwrap(); + assert_eq!(sum.guarded.iter().filter(|&&pc| insts.iter().any(|d| d.pc == pc && is_store(d))).count(), 1); + } + #[test] fn a_mask_left_behind_by_lanes_that_skipped_its_write() { // VCC written inside the loop that lanes leave one by one: the console's last write left From f33f64078520fa5bd7b9825101588adb00f73673 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:57:53 -0300 Subject: [PATCH 05/51] Recompiler: compute mode in the direct lowering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The lowering takes a stage: kernel (the runner's ABI, as before) or a compute program. In compute mode the user SGPRs come from `io`, then the group ids and TG_SIZE the program enables, the thread ids go into v0–v2, EXEC starts as every lane that runs, and the program ends without storing registers (so kernel mode's report of stale masks does not apply). One-dimensional groups only for now: in a 2-D / 3-D group the PC driver need not give a wave consecutive threads, which the console does; the HLSL path reorders them and those programs stay on it here. A compute program with user SGPRs and the group id, over three groups of 64 threads, writes the same memory through the HLSL path on the GPU and through the lowering on the CPU (GTX 1650, wave32). --- crates/xcl/src/gpu/recomp/lower.rs | 270 ++++++++++++++++++++++++----- 1 file changed, 223 insertions(+), 47 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 09fd6ff1e0..2cb8901bc9 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -64,6 +64,9 @@ pub trait Ir: Sink { fn zext(&mut self, b: Self::V) -> Self::V; /// the console lane of this thread fn lane(&mut self) -> Self::V; + /// compute: the group's id and the thread's id in its group, component k (x, y, z) + fn group_id(&mut self, k: u32) -> Self::V; + fn thread_id(&mut self, k: u32) -> Self::V; /// the wave's ballot of `c`: lanes 0–31, 32–63 fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; fn io_load(&mut self, dword: Self::V) -> Self::V; @@ -80,6 +83,16 @@ pub trait Ir: Sink { const EXEC: u8 = 126; const VCC: u8 = 106; +/// The program's stage: where its registers come from and go. +#[derive(Clone, Copy)] +pub enum Stage<'a> { + /// `runner`'s ABI: the whole register file from `io`, back to `res` + Kernel, + /// a compute program: user SGPRs from `io`, then the group ids and TG_SIZE it enables, + /// thread ids in v0–v2; it ends without storing registers + Compute(&'a super::CsInterface), +} + struct Lower<'a, I: Ir> { ir: I, ssa: Ssa, @@ -717,7 +730,22 @@ fn partial_blocks(sum: &Summary) -> Vec { /// the mask registers whose value at the end may differ from the console's: written in a block /// some lanes skipped, so those lanes still hold their own older bits (`stale`). Nothing reads /// them in the program (that would be refused); only the kernel ABI's store of every register. -pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, Vec)> { +pub fn lower_kernel(insts: &[Decoded], wave64: bool, ir: I) -> R<(I, Vec)> { + lower(insts, Stage::Kernel, wave64, ir) +} + +/// Lowers a compute program (far jumps resolved) into `ir`. One-dimensional groups only for +/// now: in a 2-D / 3-D group the PC driver need not give a wave consecutive threads, which the +/// console does (`emit` reorders them; not done here yet). +pub fn lower_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> R { + if cs.threads[1] * cs.threads[2] > 1 { + return Err("2-D / 3-D thread group".into()); + } + Ok(lower(insts, Stage::Compute(cs), wave64, ir)?.0) +} + +fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<(I, Vec)> { + let kernel = matches!(stage, Stage::Kernel); let sum = lane_masks::analyze(insts, wave64).map_err(|e| e.to_string())?; let n = sum.blocks.len(); if n == 0 { @@ -767,10 +795,14 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, prev = c; } } - preds[skip] = vec![0]; - preds[exit] = std::iter::once(skip).chain(ends.iter().map(|&b| tail[b])).collect(); - preds[sstore] = vec![exit]; - preds[vstore] = vec![exit, sstore]; + // compute: every lane that runs is in EXEC, and nothing is stored at the end – the skip and + // store blocks are left unreachable (a bare `ret`) + if kernel { + preds[skip] = vec![0]; + preds[sstore] = vec![exit]; + preds[vstore] = vec![exit, sstore]; + } + preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect(); for i in 0..count { let id = ir.new_block(); debug_assert_eq!(id, i); @@ -808,7 +840,7 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, vregs.sort_unstable(); vregs.dedup(); - // prologue: the register file from `io`; lanes outside EXEC go straight to the end + // prologue: the SGPRs from `io` (kernel: the whole register file; compute: the user data) l.ir.at(0); l.ssa.seal(&mut l.ir, 0); let lane = l.lane(); @@ -817,31 +849,79 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, let v = l.ir.io_load(a); l.write_num(0, r, v); } - let a = l.ir.int(KERNEL_SCC_SLOT as u32); - let scc = l.ir.io_load(a); - let z = l.ir.int(0); - let scc = l.ir.icmp(Cmp::Ne, scc, z); - l.ssa.write(0, Var::Scc, scc); - let (base, stride) = (l.ir.int(KERNEL_SGPRS as u32), l.ir.int(KERNEL_VGPRS as u32)); - let row = l.ir.bin(Bin::Mul, lane, stride); - let row = l.ir.bin(Bin::Add, base, row); - for &v in &vregs { - let o = l.ir.int(v as u32); - let a = l.ir.bin(Bin::Add, row, o); - let x = l.ir.io_load(a); - l.ssa.write(0, Var::V(v), x); - } - let active = l.read_bit(0, EXEC)?; - l.write_bit(0, EXEC, active); - l.ir.br_if(active, blk(0), skip); - // lanes outside EXEC: their bits of every mask are 0, as a whole-wave write leaves them - l.ir.at(skip); - l.ssa.seal(&mut l.ir, skip); - let f = l.ir.boolean(false); - for &r in &sregs { - l.ssa.write(skip, Var::M(r), f); + let mut row = None; + match stage { + Stage::Kernel => { + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let scc = l.ir.io_load(a); + let z = l.ir.int(0); + let scc = l.ir.icmp(Cmp::Ne, scc, z); + l.ssa.write(0, Var::Scc, scc); + let (base, stride) = (l.ir.int(KERNEL_SGPRS as u32), l.ir.int(KERNEL_VGPRS as u32)); + let r = l.ir.bin(Bin::Mul, lane, stride); + let r = l.ir.bin(Bin::Add, base, r); + for &v in &vregs { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, r, o); + let x = l.ir.io_load(a); + l.ssa.write(0, Var::V(v), x); + } + row = Some(r); + // lanes outside EXEC go straight to the end + let active = l.read_bit(0, EXEC)?; + l.write_bit(0, EXEC, active); + l.ir.br_if(active, blk(0), skip); + // … with their bits of every mask 0, as a whole-wave write leaves them + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + let f = l.ir.boolean(false); + for &r in &sregs { + l.ssa.write(skip, Var::M(r), f); + } + l.ir.br(exit); + } + Stage::Compute(cs) => { + // system SGPRs after the user data: the enabled group ids, then TG_SIZE + let mut next = cs.user_sgprs as u8; + for k in 0..3 { + if cs.tgid[k as usize] { + let g = l.ir.group_id(k); + l.write_num(0, next, g); + next += 1; + } + } + if cs.tg_size { + // waves in the group (a last partial one counts) | this wave's index << 6 + let lanes = if wave64 { 64 } else { 32 }; + let waves = l.ir.int(cs.threads.iter().product::().div_ceil(lanes)); + let t = l.ir.thread_id(0); + let sh = l.ir.int(lanes.trailing_zeros()); + let w = l.ir.bin(Bin::LShr, t, sh); + let six = l.ir.int(6); + let w = l.ir.bin(Bin::Shl, w, six); + let v = l.ir.bin(Bin::Or, waves, w); + l.write_num(0, next, v); + } + let f = l.ir.boolean(false); + l.ssa.write(0, Var::Scc, f); + for &v in &vregs { + let x = match v { + 0 => l.ir.thread_id(0), + 1 if cs.tid_components >= 2 => l.ir.thread_id(1), + 2 if cs.tid_components >= 3 => l.ir.thread_id(2), + _ => l.ir.int(0), + }; + l.ssa.write(0, Var::V(v), x); + } + // every lane that runs is in EXEC + let t = l.ir.boolean(true); + l.write_bit(0, EXEC, t); + l.ir.br(blk(0)); + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + l.ir.ret(); + } } - l.ir.br(exit); // the program, in reverse postorder; a block is sealed once all its predecessors are in let mut done = vec![false; count]; @@ -933,11 +1013,21 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, } } - // exit: every lane is here; masks the runner reads as numbers are the wave's ballots l.ir.at(exit); l.ssa.seal(&mut l.ir, exit); - let mut sval: Vec<(u8, I::V)> = Vec::new(); let mut stale: Vec = Vec::new(); + let Some(row) = row else { + // compute: nothing to store + l.ir.ret(); + for b in [sstore, vstore] { + l.ir.at(b); + l.ssa.seal(&mut l.ir, b); + l.ir.ret(); + } + return l.finish(stale); + }; + // kernel exit: every lane is here; masks the runner reads as numbers are the wave's ballots + let mut sval: Vec<(u8, I::V)> = Vec::new(); let mut i = 0; while i < sregs.len() { let r = sregs[i]; @@ -992,26 +1082,32 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, mut ir: I) -> R<(I, l.ir.res_store(a, x); } l.ir.ret(); + l.finish(stale) +} - // every phi is complete: no number may come from a mask, nor a mask bit from a number - for &v in &l.num_uses { - if l.reaches(v, l.num_marker) { - return Err("a mask read as a number (through a join)".into()); +impl Lower<'_, I> { + /// Every phi is complete: no number may come from a mask, nor a mask bit from a number, nor + /// a lane read a mask bit it kept from before a write it skipped. + fn finish(self, mut stale: Vec) -> R<(I, Vec)> { + for &v in &self.num_uses { + if self.reaches(v, self.num_marker) { + return Err("a mask read as a number (through a join)".into()); + } } - } - for &v in &l.bit_uses { - if l.reaches(v, l.bit_marker) { - return Err("a number read as a mask (through a join)".into()); + for &v in &self.bit_uses { + if self.reaches(v, self.bit_marker) { + return Err("a number read as a mask (through a join)".into()); + } } - } - for &(c, v) in &l.lane_uses { - if l.stale(c, v) { - return Err("a mask written while some lanes were elsewhere, read after they met again".into()); + for &(c, v) in &self.lane_uses { + if self.stale(c, v) { + return Err("a mask written while some lanes were elsewhere, read after they met again".into()); + } } + stale.sort_unstable(); + stale.dedup(); + Ok((self.ir, stale)) } - stale.sort_unstable(); - stale.dedup(); - Ok((l.ir, stale)) } #[cfg(test)] @@ -1030,6 +1126,8 @@ mod tests { Select(u32, u32, u32), Zext(u32), Lane, + GroupId(u32), + ThreadId(u32), Ballot(u32, usize), IoLoad(u32), ResStore(u32, u32), @@ -1137,6 +1235,12 @@ mod tests { fn lane(&mut self) -> u32 { self.push(Ins::Lane) } + fn group_id(&mut self, k: u32) -> u32 { + self.push(Ins::GroupId(k)) + } + fn thread_id(&mut self, k: u32) -> u32 { + self.push(Ins::ThreadId(k)) + } fn ballot(&mut self, c: u32) -> [u32; 2] { [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] } @@ -1186,6 +1290,11 @@ mod tests { impl Interp { /// Runs the program over `lanes` lanes; `io` in, `res` out. Ballots wait for every lane. fn run(&self, lanes: usize, io: &[u32], res: &mut [u32], mem: &mut [u32]) { + self.run_with(lanes, 0, [0; 3], io, res, mem) + } + + /// One wave of a compute group: its first thread `base`, the group `group`. + fn run_with(&self, lanes: usize, base: u32, group: [u32; 3], io: &[u32], res: &mut [u32], mem: &mut [u32]) { let mut ls: Vec = (0..lanes).map(|_| LaneState { block: 0, at: 0, from: 0, env: HashMap::new(), done: false }).collect(); let mut steps = 0usize; loop { @@ -1249,6 +1358,8 @@ mod tests { Ins::Select(c, a, b) => Some(if g(c) != 0 { g(a) } else { g(b) }), Ins::Zext(b) => Some(g(b)), Ins::Lane => Some(lane as u32), + Ins::GroupId(k) => Some(group[*k as usize]), + Ins::ThreadId(k) => Some(if *k == 0 { base + lane as u32 } else { 0 }), Ins::Ballot(..) => break, Ins::IoLoad(a) => Some(io[g(a) as usize]), Ins::MemLoad(a) => Some(mem.get((g(a) / 4) as usize).copied().unwrap_or(0)), @@ -1366,6 +1477,39 @@ mod tests { ENDPGM, ]; + /// A compute program: 64 threads, user SGPRs s0–s1, the group id x in s2; + /// mem[64·group + thread] = 3·thread + s0 + group + const COMPUTE: &[I] = &[ + ("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V + 1), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 2), ("VSRC1", 1)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]; + + fn compute_cs() -> crate::gpu::recomp::CsInterface { + crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } + } + + /// A compute program run on the CPU over `groups` groups (wave32): the memory after. + fn run_compute(lines: &[I], cs: &crate::gpu::recomp::CsInterface, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + let ir = lower_compute(&decode(lines), cs, false, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let mut io = vec![0u32; KERNEL_SGPRS]; + io[..sgprs.len()].copy_from_slice(sgprs); + let mut res = vec![0u32; KERNEL_SGPRS]; + let mut mem = mem.to_vec(); + for g in 0..groups { + for w in 0..cs.threads[0].div_ceil(32) { + ir.run_with(32, w * 32, [g, 0, 0], &io, &mut res, &mut mem); + } + } + mem + } + fn memory_image() -> Vec { (0..256).map(|i| 1000 + i).collect() } @@ -1534,6 +1678,38 @@ mod tests { assert_eq!(sum.guarded.iter().filter(|&&pc| insts.iter().any(|d| d.pc == pc && is_store(d))).count(), 1); } + #[test] + fn a_compute_program_takes_its_group_and_thread_ids() { + let mem = run_compute(COMPUTE, &compute_cs(), 3, &[100, 0], &vec![0u32; 256]); + for g in 0..3u32 { + for t in 0..64u32 { + assert_eq!(mem[(64 * g + t) as usize], 3 * t + 100 + g, "group {g} thread {t}"); + } + } + // 2-D groups are not lowered yet + let cs = crate::gpu::recomp::CsInterface { threads: [8, 8, 1], ..compute_cs() }; + assert!(lower_compute(&decode(COMPUTE), &cs, false, Interp::default()).is_err()); + } + + /// The compute program through the HLSL path on the GPU and through the lowering on the CPU. + #[test] + fn a_compute_program_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Mode, Options}; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + return; + } + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let cs = compute_cs(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..]); + } + #[test] fn a_mask_left_behind_by_lanes_that_skipped_its_write() { // VCC written inside the loop that lanes leave one by one: the console's last write left From 511eadd59e7dc8c952fc9cccd78c6c810258ced3 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:01:59 -0300 Subject: [PATCH 06/51] Recompiler: write the direct lowering through gpu::dxil's module builder `lower_dxil` implements the lowering's `Ir` trait on #1426's `Shader` / `Module`: blocks, phis, integer ops, compares, `select`, the lane / thread / group ids, `waveActiveBallot`, and raw buffer access on the ABI's root UAVs. A phi the SSA construction finds trivial keeps its identical incoming values (the builder has no use replacement; the driver folds them). Kernel and compute programs in their per-lane form now become signed DXIL containers with no HLSL and no DXC, and run on the GPU: the lowering's test programs agree with the CPU interpreter and with the HLSL path, registers and memory (GTX 1650, wave32). The lowering's test programs are visible to the crate's tests for this. --- crates/xcl/src/gpu/recomp/lower.rs | 28 +-- crates/xcl/src/gpu/recomp/lower_dxil.rs | 245 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 1 + 3 files changed, 260 insertions(+), 14 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/lower_dxil.rs diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 2cb8901bc9..d71e6be540 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1111,7 +1111,7 @@ impl Lower<'_, I> { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use std::collections::HashMap; @@ -1418,12 +1418,12 @@ mod tests { } } - type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + pub(crate) type I = (&'static str, &'static str, &'static [(&'static str, u64)]); const V: u64 = 256; const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); // wave32 programs shared by the CPU tests and the comparison with the HLSL path - const STRAIGHT: &[I] = &[ + pub(crate) const STRAIGHT: &[I] = &[ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)]), ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 0)]), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), @@ -1432,7 +1432,7 @@ mod tests { ]; /// v_cmp_gt_u32 vcc, 16, v0; s_and_saveexec s0, vcc; s_cbranch_execz L; v_mov v1, 7; /// L: s_or exec, exec, s0; v_add v2, v1, 1 - const SKIPPED_IF: &[I] = &[ + pub(crate) const SKIPPED_IF: &[I] = &[ ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), @@ -1443,7 +1443,7 @@ mod tests { ]; /// s_mov s0, exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; exec &= ~vcc; /// s_cbranch_execnz L; exec |= s0 → v1 = max(1, lane) - const LEAVING_LOOP: &[I] = &[ + pub(crate) const LEAVING_LOOP: &[I] = &[ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), @@ -1453,7 +1453,7 @@ mod tests { ENDPGM, ]; /// s1 = 0; L: s1 += 3; v1 += 1; s_cmp_lt_u32 s1, 12; s_cbranch_scc1 L - const UNIFORM_LOOP: &[I] = &[ + pub(crate) const UNIFORM_LOOP: &[I] = &[ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 131)]), ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), @@ -1464,7 +1464,7 @@ mod tests { /// v1 = 4·lane; s[4:5] = mem[2..4]; v2 = mem[lane] + s4; then lanes below 16 store v2 at /// mem[64 + lane] (a guarded store: no skip branch), and every lane stores v0 at mem[128 + lane] - const MEMORY: &[I] = &[ + pub(crate) const MEMORY: &[I] = &[ ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), @@ -1479,7 +1479,7 @@ mod tests { /// A compute program: 64 threads, user SGPRs s0–s1, the group id x in s2; /// mem[64·group + thread] = 3·thread + s0 + group - const COMPUTE: &[I] = &[ + pub(crate) const COMPUTE: &[I] = &[ ("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)]), ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 0)]), ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)]), @@ -1491,12 +1491,12 @@ mod tests { ENDPGM, ]; - fn compute_cs() -> crate::gpu::recomp::CsInterface { + pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } } /// A compute program run on the CPU over `groups` groups (wave32): the memory after. - fn run_compute(lines: &[I], cs: &crate::gpu::recomp::CsInterface, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + pub(crate) fn run_compute(lines: &[I], cs: &crate::gpu::recomp::CsInterface, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { let ir = lower_compute(&decode(lines), cs, false, Interp::default()).unwrap_or_else(|e| panic!("{e}")); let mut io = vec![0u32; KERNEL_SGPRS]; io[..sgprs.len()].copy_from_slice(sgprs); @@ -1510,11 +1510,11 @@ mod tests { mem } - fn memory_image() -> Vec { + pub(crate) fn memory_image() -> Vec { (0..256).map(|i| 1000 + i).collect() } - fn decode(lines: &[I]) -> Vec { + pub(crate) fn decode(lines: &[I]) -> Vec { let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); let mut out = Vec::new(); let mut off = 0; @@ -1533,7 +1533,7 @@ mod tests { } /// … with the flat memory too: (sgpr, vgpr[lane], memory after). - fn run_mem(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec], mem: &[u32]) -> (Vec, Vec>, Vec) { + pub(crate) fn run_mem(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec], mem: &[u32]) -> (Vec, Vec>, Vec) { let insts = decode(lines); let (ir, _) = lower_kernel(&insts, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); let lanes = if wave64 { 64 } else { 32 }; @@ -1549,7 +1549,7 @@ mod tests { (res[..KERNEL_SGPRS].to_vec(), v, mem) } - fn state(lanes: usize) -> (Vec, Vec>) { + pub(crate) fn state(lanes: usize) -> (Vec, Vec>) { let mut s = vec![0u32; KERNEL_SGPRS]; s[126] = u32::MAX; s[127] = u32::MAX; diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs new file mode 100644 index 0000000000..3b67001969 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -0,0 +1,245 @@ +//! The direct lowering (`lower`) written into a DXIL module through `gpu::dxil`'s builder: +//! the per-lane form of a program as a signed container, with no HLSL and no DXC. +//! +//! `Ir` maps one to one onto the builder: blocks, phis (`phi_at` / `add_incoming`), integer +//! ops, compares, `select`, the thread / group / lane ids, `waveActiveBallot`, and raw buffer +//! loads and stores on the ABI's root UAVs (u0 `io`, u1 `res`, u2 `mem`). A phi the SSA +//! construction finds trivial keeps its (identical) incoming values instead of being removed: +//! the builder has no use replacement, and the driver folds such phis. + +use super::lower::{self, Bin, Cmp, Ir}; +use super::ssa::{Sink, Var}; +use crate::gpu::dxil::container::Stage; +use crate::gpu::dxil::module::{BinOp, Block, CastOp, Pred, Value}; +use crate::gpu::dxil::shader::{RawUav, Shader}; +use crate::gpu::rdna2::Decoded; + +struct DxilIr { + s: Shader, + io: RawUav, + res: Option, + mem: RawUav, + blocks: Vec, +} + +impl DxilIr { + fn new(kernel: bool) -> DxilIr { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let res = kernel.then(|| s.raw_uav(1, 0)); + // compute: other waves may write the memory this one reads (as the HLSL path declares it) + let mem = if kernel { s.raw_uav(2, 0) } else { s.raw_uav_coherent(2, 0) }; + DxilIr { s, io, res, mem, blocks: Vec::new() } + } + + fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { + match var { + Var::M(_) | Var::Scc => self.s.m.i1(), + Var::S(_) | Var::V(_) => self.s.m.i32(), + } + } + + fn bytes(&mut self, dword: Value) -> Value { + let four = self.s.m.i32c(4); + self.s.m.bin(BinOp::Mul, dword, four) + } +} + +impl Sink for DxilIr { + type V = Value; + fn phi(&mut self, block: usize, var: Var) -> Value { + let t = self.ty(var); + self.s.m.phi_at(self.blocks[block], t) + } + fn incoming(&mut self, phi: Value, value: Value, pred: usize) { + self.s.m.add_incoming(phi, value, self.blocks[pred]); + } + fn replace(&mut self, _old: Value, _new: Value) { + // kept: its incoming values are all `new` (or itself), which is a valid phi + } + fn undef(&mut self, var: Var) -> Value { + let t = self.ty(var); + self.s.m.undef(t) + } +} + +impl Ir for DxilIr { + fn new_block(&mut self) -> usize { + let b = if self.blocks.is_empty() { self.s.m.entry_block() } else { self.s.m.new_block() }; + self.blocks.push(b); + self.blocks.len() - 1 + } + fn at(&mut self, block: usize) { + self.s.m.set_block(self.blocks[block]); + } + fn int(&mut self, v: u32) -> Value { + self.s.m.i32c(v) + } + fn boolean(&mut self, v: bool) -> Value { + self.s.m.i1c(v) + } + fn bin(&mut self, op: Bin, a: Value, b: Value) -> Value { + let op = match op { + Bin::Add => BinOp::Add, + Bin::Sub => BinOp::Sub, + Bin::Mul => BinOp::Mul, + Bin::And => BinOp::And, + Bin::Or => BinOp::Or, + Bin::Xor => BinOp::Xor, + Bin::Shl => BinOp::Shl, + Bin::LShr => BinOp::LShr, + Bin::AShr => BinOp::AShr, + }; + self.s.m.bin(op, a, b) + } + fn icmp(&mut self, c: Cmp, a: Value, b: Value) -> Value { + let p = match c { + Cmp::Eq => Pred::Eq, + Cmp::Ne => Pred::Ne, + Cmp::Ult => Pred::ULt, + Cmp::Ule => Pred::ULe, + Cmp::Ugt => Pred::UGt, + Cmp::Uge => Pred::UGe, + Cmp::Slt => Pred::SLt, + Cmp::Sle => Pred::SLe, + Cmp::Sgt => Pred::SGt, + Cmp::Sge => Pred::SGe, + }; + self.s.m.cmp(p, a, b) + } + fn select(&mut self, c: Value, a: Value, b: Value) -> Value { + self.s.m.select(c, a, b) + } + fn zext(&mut self, b: Value) -> Value { + let t = self.s.m.i32(); + self.s.m.cast(CastOp::ZExt, b, t) + } + fn lane(&mut self) -> Value { + self.s.wave_lane_index() + } + fn group_id(&mut self, k: u32) -> Value { + self.s.group_id(k) + } + fn thread_id(&mut self, k: u32) -> Value { + self.s.thread_id_in_group(k) + } + fn ballot(&mut self, c: Value) -> [Value; 2] { + let w = self.s.wave_ballot(c); + [w[0], w[1]] + } + fn io_load(&mut self, dword: Value) -> Value { + let a = self.bytes(dword); + let io = self.io; + self.s.raw_load(io, a, 1)[0] + } + fn res_store(&mut self, dword: Value, value: Value) { + let a = self.bytes(dword); + let res = self.res.expect("res is bound in kernel mode"); + self.s.raw_store(res, a, &[value]); + } + fn mem_load(&mut self, addr: Value) -> Value { + let mem = self.mem; + self.s.raw_load(mem, addr, 1)[0] + } + fn mem_store(&mut self, addr: Value, value: Value) { + let mem = self.mem; + self.s.raw_store(mem, addr, &[value]); + } + fn br(&mut self, target: usize) { + self.s.m.br(self.blocks[target]); + } + fn br_if(&mut self, c: Value, then: usize, otherwise: usize) { + self.s.m.cond_br(c, self.blocks[then], self.blocks[otherwise]); + } + fn ret(&mut self) { + self.s.m.ret(); + } +} + +/// A kernel-mode program in its per-lane form, as a signed DXIL container (one wave of +/// `WaveSize` = the program's wave size), and the masks whose final value may differ from +/// the console's (`lower::lower_kernel`). +pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), String> { + let (ir, stale) = lower::lower_kernel(insts, wave64, DxilIr::new(true))?; + let lanes = if wave64 { 64 } else { 32 }; + Ok((ir.s.finish([lanes, 1, 1], Some(lanes)), stale)) +} + +/// A compute program in its per-lane form, as a signed DXIL container. +pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { + let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(false))?; + Ok(ir.s.finish(cs.threads, Some(if wave64 { 64 } else { 32 }))) +} + +#[cfg(test)] +mod tests { + use super::super::lower::tests::*; + use super::super::{dxc, runner, translate, Mode, Options}; + + fn gpu() -> bool { + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return false; + } + true + } + + /// The per-lane form as real DXIL on the GPU agrees with the lowering run on the CPU (and so + /// with the HLSL path, which `lower`'s tests compare it with): registers and memory. + #[test] + fn per_lane_kernels_run_on_the_gpu() { + if !gpu() { + return; + } + for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { + let insts = decode(lines); + let (dxil, stale) = super::kernel(&insts, false).unwrap_or_else(|e| panic!("{name}: {e}")); + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap_or_else(|e| panic!("{name}: {e}")); + let (cs, cv, cmem) = run_mem(lines, false, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = crate::gpu::rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(gpu.sgpr[r], cs[r], "{name}: s{r}"); + } + for l in 0..32 { + for &r in &vregs { + assert_eq!(gpu.vgpr[l][r], cv[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + #[test] + fn a_per_lane_compute_program_runs_on_the_gpu() { + if !gpu() { + return; + } + let cs = compute_cs(); + let dxil = super::compute(&decode(COMPUTE), &cs, false).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..]); + // and the HLSL path, for good measure + if dxc::location().is_ok() { + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + let hlsl = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + assert_eq!(runner::dispatch(&hlsl, [3, 1, 1], &[100, 0], &mem).unwrap(), gpu); + } + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index e5c2c4c35a..2f503c9e4c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -55,6 +55,7 @@ pub mod dxc; pub mod dxil; pub mod lane_masks; pub mod lower; +pub mod lower_dxil; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; From ac34cb6de131aafad2ccc66265d1892da28f6903 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:07:43 -0300 Subject: [PATCH 07/51] Recompiler: refuse scalar values a lane kept from before a write it skipped An SGPR number or SCC written in a block that lanes leave one by one (a waterfall loop's key, a counter of the passes) and read after they meet again is each lane's own value in the per-lane form, where the console has the last pass's. Such reads are refused like the stale masks, so those programs fall back; kernel mode's final store reports the registers. Taking the last-leaving lane's value is left for later. Reported by Sr-0w on #1269 while putting wave operations on top of the lowering. Two fixes on the way: a VOP3 instruction's op_sel was never refused (the field is `OP_SEL`, not `OPSEL`), and an SOP1 mask-width op counted s0 as a second source because `SSRC1`, which SOP1 lacks, defaulted to 0. The assemble test declares validator 1.6, the oldest that knows SM 6.6. --- crates/xcl/src/gpu/recomp/dxil/assemble.rs | 2 +- crates/xcl/src/gpu/recomp/lower.rs | 85 ++++++++++++++++++---- 2 files changed, 72 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxil/assemble.rs b/crates/xcl/src/gpu/recomp/dxil/assemble.rs index 9383c684b4..29184c496a 100644 --- a/crates/xcl/src/gpu/recomp/dxil/assemble.rs +++ b/crates/xcl/src/gpu/recomp/dxil/assemble.rs @@ -89,7 +89,7 @@ attributes #1 = { nounwind } !dx.entryPoints = !{!7} !0 = !{!"xcl"} !1 = !{i32 1, i32 6} -!2 = !{i32 1, i32 9} +!2 = !{i32 1, i32 6} !3 = !{!"cs", i32 6, i32 6} !4 = !{null, !5, null, null} !5 = !{!6} diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index d71e6be540..4df4a461e3 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -140,6 +140,7 @@ impl<'a, I: Ir> Lower<'a, I> { return Err(format!("s{r}: a mask read as a number")); } self.num_uses.push(v); + self.lane_uses.push((b, v)); Ok(v) } @@ -172,7 +173,21 @@ impl<'a, I: Ir> Lower<'a, I> { Ok(self.ir.icmp(Cmp::Ne, bit, zero)) } + /// SCC, written and read like an SGPR number: a lane that skipped the block writing it + /// keeps its own older value (`stale`). + fn write_scc(&mut self, b: usize, v: I::V) { + self.def_block.entry(v).or_insert(b); + self.ssa.write(b, Var::Scc, v); + } + + fn read_scc(&mut self, b: usize) -> I::V { + let v = self.read(b, Var::Scc); + self.lane_uses.push((b, v)); + v + } + fn write_num(&mut self, b: usize, r: u8, v: I::V) { + self.def_block.entry(v).or_insert(b); self.ssa.write(b, Var::S(r), v); self.ssa.write(b, Var::M(r), self.bit_marker); if self.wave64 && r > 0 { @@ -211,7 +226,7 @@ impl<'a, I: Ir> Lower<'a, I> { 240..=247 => self.ir.int([0.5f32, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0][(code - 240) as usize].to_bits()), 248 => self.ir.int(0x3E22_F983), 253 => { - let s = self.read(b, Var::Scc); + let s = self.read_scc(b); self.ir.zext(s) } 255 => self.ir.int(d.literal.ok_or("missing literal")?), @@ -291,7 +306,9 @@ impl<'a, I: Ir> Lower<'a, I> { if let Some(base) = name.strip_suffix(width) { let op = base.trim_start_matches("S_"); let saveexec = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")); - let reads_mask = [s0, s1].iter().any(|&c| c <= 127 && c != 124 && self.holds_mask(b, c as u8)); + // SOP1 has no SSRC1: only the sources the encoding has + let srcs: Vec = std::iter::once(s0).chain(d.enc.field("SSRC1").map(|_| s1)).collect(); + let reads_mask = srcs.iter().any(|&c| c <= 127 && c != 124 && self.holds_mask(b, c as u8)); let bitwise = matches!(op, "MOV" | "NOT" | "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "NAND" | "NOR" | "XNOR"); if let Some(op) = saveexec { let a = self.src_bit(b, s0)?; @@ -301,7 +318,7 @@ impl<'a, I: Ir> Lower<'a, I> { if sd != 125 { self.write_bit(b, sd, if base.ends_with("_WREXEC") { new } else { old }); } - self.ssa.write(b, Var::Scc, new); + self.write_scc(b, new); return Ok(()); } if bitwise && (sd == EXEC || reads_mask) { @@ -316,7 +333,7 @@ impl<'a, I: Ir> Lower<'a, I> { }; self.write_bit(b, sd, v); if op != "MOV" { - self.ssa.write(b, Var::Scc, v); + self.write_scc(b, v); } return Ok(()); } @@ -327,7 +344,7 @@ impl<'a, I: Ir> Lower<'a, I> { let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); let x = self.ir.bin(Bin::Xor, a, c); let v = if name == cmp64[0] { self.not(x) } else { x }; - self.ssa.write(b, Var::Scc, v); + self.write_scc(b, v); return Ok(()); } // numbers @@ -360,7 +377,7 @@ impl<'a, I: Ir> Lower<'a, I> { // carry out: the sum wrapped below a; borrow: a < b let scc = if carry { self.ir.icmp(Cmp::Ult, v, a) } else { self.ir.icmp(Cmp::Ult, a, c) }; self.write_num(b, sd, v); - self.ssa.write(b, Var::Scc, scc); + self.write_scc(b, scc); } "S_ADD_I32" | "S_SUB_I32" => { let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); @@ -377,7 +394,7 @@ impl<'a, I: Ir> Lower<'a, I> { let z = self.ir.int(0); let scc = self.ir.icmp(Cmp::Slt, both, z); self.write_num(b, sd, v); - self.ssa.write(b, Var::Scc, scc); + self.write_scc(b, scc); } "S_MUL_I32" => { let v = num2(self, Bin::Mul)?; @@ -392,7 +409,7 @@ impl<'a, I: Ir> Lower<'a, I> { let v = num2(self, op)?; let scc = nonzero(self, v); self.write_num(b, sd, v); - self.ssa.write(b, Var::Scc, scc); + self.write_scc(b, scc); } "S_LSHL_B32" | "S_LSHR_B32" | "S_ASHR_I32" => { let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); @@ -406,7 +423,7 @@ impl<'a, I: Ir> Lower<'a, I> { let v = self.ir.bin(op, a, sh); let scc = nonzero(self, v); self.write_num(b, sd, v); - self.ssa.write(b, Var::Scc, scc); + self.write_scc(b, scc); } n if n.starts_with("S_CMP_") && (n.ends_with("_U32") || n.ends_with("_I32")) => { let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); @@ -421,7 +438,7 @@ impl<'a, I: Ir> Lower<'a, I> { _ => return Err(format!("unsupported {n}")), }; let v = self.ir.icmp(p, a, c); - self.ssa.write(b, Var::Scc, v); + self.write_scc(b, v); } "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" => {} n => return Err(format!("unsupported {n}")), @@ -447,7 +464,7 @@ impl<'a, I: Ir> Lower<'a, I> { } let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); - if vop3 && ["ABS", "NEG", "CLAMP", "OMOD", "OPSEL"].iter().any(|f| fv(f).unwrap_or(0) != 0) { + if vop3 && ["ABS", "NEG", "CLAMP", "OMOD", "OP_SEL"].iter().any(|f| fv(f).unwrap_or(0) != 0) { return Err(format!("{name}: VOP3 modifiers")); } // sources: VOP1 / VOP2 / VOPC put src1 in VSRC1 (a VGPR); VOP3 in SRC1 @@ -608,9 +625,9 @@ impl<'a, I: Ir> Lower<'a, I> { /// The condition under which a lane takes the branch ending block b. fn cond(&mut self, b: usize, d: &Decoded) -> R { Ok(match d.inst.name { - "S_CBRANCH_SCC1" => self.read(b, Var::Scc), + "S_CBRANCH_SCC1" => self.read_scc(b), "S_CBRANCH_SCC0" => { - let s = self.read(b, Var::Scc); + let s = self.read_scc(b); self.not(s) } n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { @@ -1035,6 +1052,9 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( let s = l.read(exit, Var::S(r)); if l.ssa.resolve_value(s) != l.num_marker && !l.reaches(s, l.num_marker) { l.num_uses.push(s); + if l.stale(exit, s) { + stale.push(r); + } sval.push((r, s)); continue; } @@ -1060,6 +1080,9 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( } } let scc = l.read(exit, Var::Scc); + if l.stale(exit, scc) { + stale.push(KERNEL_SCC_SLOT as u8); + } let vval: Vec<(u16, I::V)> = vregs.iter().map(|&v| (v, l.read(exit, Var::V(v)))).collect(); let z = l.ir.int(0); let first = l.ir.icmp(Cmp::Eq, lane, z); @@ -1101,7 +1124,7 @@ impl Lower<'_, I> { } for &(c, v) in &self.lane_uses { if self.stale(c, v) { - return Err("a mask written while some lanes were elsewhere, read after they met again".into()); + return Err("a value written while some lanes were elsewhere, read after they met again".into()); } } stale.sort_unstable(); @@ -1727,6 +1750,40 @@ pub(crate) mod tests { assert_eq!(lower_kernel(&insts, false, Interp::default()).unwrap().1, Vec::::new()); } + #[test] + fn a_scalar_counted_in_a_loop_lanes_leave_is_not_each_lanes_own() { + // s_add_u32 s1, s1, 1 in the loop lanes leave one by one: the console counts the wave's + // passes, each lane here only its own (a waterfall loop's key is the same case) + // s_mov s0, exec; s1 = 0; L: v_add v1, v1, 1; s1 += 1; v_cmp_ge vcc, v1, v0; + // exec &= ~vcc; s_cbranch_execnz L; exec |= s0 + let mut lines: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + let (_, stale) = lower_kernel(&decode(&lines), false, Interp::default()).unwrap(); + assert!(stale.contains(&1), "{stale:?}"); + // read after the loop: refused + lines.insert(8, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 1)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + + #[test] + fn vop3_operand_selects_are_refused() { + let op_sel: &[I] = &[("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("OP_SEL", 1)]), ENDPGM]; + let err = lower_kernel(&decode(op_sel), false, Interp::default()).err().expect("refused"); + assert!(err.contains("modifiers"), "{err}"); + let plain: &[I] = &[("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V)]), ENDPGM]; + assert!(lower_kernel(&decode(plain), false, Interp::default()).is_ok()); + } + #[test] fn a_mask_read_as_a_number_is_refused() { // s_bcnt1-like use: s_add_u32 s2, vcc_lo, 0 after a v_cmp From 13ac19638e0fcbe4e46ed12e1a018b41efbbb417 Mon Sep 17 00:00:00 2001 From: Frtuchinno <22376454+Frtuchinno@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:03:56 +0100 Subject: [PATCH 08/51] Recompiler: report both halves of a stale wave64 mask in the lowering At the kernel exit, lower_kernel pushes only r to `stale` for a mask some lanes kept their own older bits of. In wave64, r + 1 is stored from the upper half of the same ballot, so it carries the stale bits too, but it was not reported: VCC after a loop that lanes leave one by one gave [106] instead of [106, 107]. Found by a wave64 version of the GPU comparison with the HLSL path (the existing one runs only wave32 programs): on an RX 7800 XT (native wave64), `leaving loop` differed in s107, 0xFFFFFFFF in the lowering against 0x80000000 on the GPU, where only lane 63 was active in the last v_cmp. Tests: the_wave64_lowering_agrees_with_the_hlsl_path_on_the_gpu (the five programs with _B64 mask operations and lane thresholds past 32, native wave64 form, skipped without wave64) and a_wave64_mask_left_behind_is_reported_in_both_halves (CPU only). Both fail without the fix. Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 103 +++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 4df4a461e3..3da29afe76 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1068,6 +1068,9 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( let m = l.read(exit, Var::M(r)); if r != EXEC && l.stale(exit, m) { stale.push(r); + if l.wave64 { + stale.push(r + 1); // the upper half comes from the same mask + } } let [lo, hi] = l.ir.ballot(m); sval.push((r, lo)); @@ -1685,6 +1688,106 @@ pub(crate) mod tests { } } + // wave64 versions of the programs above: 64-bit EXEC / VCC / saved masks, and thresholds + // past lane 32 so that both words of every mask matter + /// v_cmp_gt_u32 vcc, 40, v0; s_and_saveexec_b64 s[0:1], vcc; s_cbranch_execz L; v_mov v1, 7; + /// L: s_or_b64 exec, exec, s[0:1]; v_add v2, v1, 1 + const SKIPPED_IF_W64: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), + ENDPGM, + ]; + /// s_mov_b64 s[0:1], exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; + /// exec &= ~vcc (b64); s_cbranch_execnz L; exec |= s[0:1] → v1 = max(1, lane), 64 lanes + const LEAVING_LOOP_W64: &[I] = &[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + /// `MEMORY` over 64 lanes: lanes below 40 take the guarded store + const MEMORY_W64: &[I] = &[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 2), ("SADDR", 125), ("OFFSET", 0x100)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 6)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 125), ("OFFSET", 0x200)]), + ENDPGM, + ]; + + #[test] + fn a_wave64_mask_left_behind_is_reported_in_both_halves() { + // VCC from the loop's last v_cmp: lanes that left earlier kept their own bits in both words + let (_, stale) = lower_kernel(&decode(LEAVING_LOOP_W64), true, Interp::default()).unwrap(); + assert_eq!(stale, vec![106, 107]); + } + + /// The wave64 lowering run on the CPU and the HLSL path's native wave64 form run on a GPU + /// with 64-lane waves give the same registers and memory. + #[test] + fn the_wave64_lowering_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + return; + } + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for (name, lines) in [ + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF_W64), + ("leaving loop", LEAVING_LOOP_W64), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY_W64), + ] { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(64); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64: true, split_wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(lines, true, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let insts = decode(lines); + let (_, stale) = lower_kernel(&insts, true, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 107, 126, 127]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..64 { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + #[test] fn scalar_and_vector_memory_with_a_guarded_store() { let (s, v) = state(32); From f90033c328deaa0af2e1418ef92fb8e2f4979907 Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 17:05:20 +0100 Subject: [PATCH 09/51] Recompiler: cross-lane operations in the lowering The lowering now takes v_readfirstlane, v_readlane, v_writelane, DPP16 and DPP8 sources, v_permlane16 / v_permlanex16, ds_swizzle_b32, v_mbcnt and s_bcnt0 / s_bcnt1 / s_ff1 of a mask, in wave32 and wave64 (lower/wave.rs). `Ir` gains `read_lane` (WaveReadLaneAt) and `count_bits`. A lane reads another through `read_lane`, which needs that lane to be at the same instruction. Lanes are where the console has them, except those that went the other way at a lane branch. So a read of a lane in EXEC is always defined (readfirstlane, and DPP / permlane / swizzle without fetch-inactive, whose source outside EXEC gives 0 or keeps the destination). A read of any lane (readlane, writelane, fetch-inactive) is refused in a block not every lane reaches, and the program stays on HLSL. A mask read as a number is the ballot of its bits: exact for EXEC (a lane elsewhere is outside it), and for any mask where every lane is here. The CPU interpreter runs a wave operation over the lanes waiting at it (the first such point in block order), instead of requiring every lane there; a waterfall loop's readfirstlane needs this. Tests: the operations on the CPU in wave32 and wave64 with expected values; a waterfall loop; a readlane in that loop is refused; and both programs agree with the HLSL path on the GPU, register by register, in wave32 and wave64 (RX 7800 XT). Registers the waterfall loop writes and the program reads after it (an SGPR, the saved EXEC) are left out of the comparison: each lane keeps its own last pass's value there, which the lowering does not refuse yet. A stale wave64 mask's second register is treated as stale too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XTYmP5ub3Zjdi8PYaDNwsV --- crates/xcl/src/gpu/recomp/lower.rs | 269 ++++++++++++++- crates/xcl/src/gpu/recomp/lower/wave.rs | 432 ++++++++++++++++++++++++ 2 files changed, 685 insertions(+), 16 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/lower/wave.rs diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 3da29afe76..e006083fa3 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -21,6 +21,8 @@ use super::ssa::{Sink, Ssa, Var}; use super::{KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS}; use crate::gpu::rdna2::{self, Decoded, Variant}; +mod wave; + type R = Result; #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -69,6 +71,11 @@ pub trait Ir: Sink { fn thread_id(&mut self, k: u32) -> Self::V; /// the wave's ballot of `c`: lanes 0–31, 32–63 fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; + /// `v` as lane `lane` holds it (`WaveReadLaneAt`); `lane` may differ between lanes and is + /// always one running this instruction too + fn read_lane(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// the number of bits set in `v` (`countbits`) + fn count_bits(&mut self, v: Self::V) -> Self::V; fn io_load(&mut self, dword: Self::V) -> Self::V; fn res_store(&mut self, dword: Self::V, value: Self::V); /// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of @@ -112,6 +119,9 @@ struct Lower<'a, I: Ir> { /// the IR block each mask bit was written in, and the mask bits read (block, value) def_block: std::collections::HashMap, lane_uses: Vec<(usize, I::V)>, + /// a DPP instruction's first source, read from its source lane, and its write enable + dpp_src: Option, + dpp_en: Option, } /// A vector memory store: a side effect inactive lanes must not have. @@ -219,6 +229,9 @@ impl<'a, I: Ir> Lower<'a, I> { /// A scalar or vector source operand as a number. fn src(&mut self, b: usize, d: &Decoded, code: u64) -> R { + if let (233 | 234 | 250, Some(v)) = (code, self.dpp_src) { + return Ok(v); + } Ok(match code { 0..=105 | 106 | 107 | 124 | 126 | 127 => self.read_num(b, code as u8)?, 128..=192 => self.ir.int((code - 128) as u32), @@ -246,6 +259,13 @@ impl<'a, I: Ir> Lower<'a, I> { } fn write_v(&mut self, b: usize, d: &Decoded, r: u16, v: I::V) -> R<()> { + let v = match self.dpp_en.take() { + Some(en) => { + let old = self.read(b, Var::V(r)); + self.ir.select(en, v, old) + } + None => v, + }; let v = if self.guarded.contains(&d.pc) { let old = self.read(b, Var::V(r)); let e = self.read_bit(b, EXEC)?; @@ -301,6 +321,9 @@ impl<'a, I: Ir> Lower<'a, I> { let name = d.inst.name; let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").unwrap_or(0) as u8); + if self.wave_salu(b, d)? { + return Ok(()); + } let width = if self.wave64 { "_B64" } else { "_B32" }; // mask-width ops: on lane bits when they write EXEC, are a saveexec, or read a mask if let Some(base) = name.strip_suffix(width) { @@ -458,9 +481,21 @@ impl<'a, I: Ir> Lower<'a, I> { } fn valu(&mut self, b: usize, d: &Decoded) -> R<()> { + if matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) { + self.dpp(b, d)?; + } + let r = self.valu_op(b, d); + (self.dpp_src, self.dpp_en) = (None, None); + r + } + + fn valu_op(&mut self, b: usize, d: &Decoded) -> R<()> { let name = d.inst.name; - if d.variant != Variant::Plain { - return Err(format!("{name}: SDWA / DPP")); + if d.variant == Variant::Sdwa { + return Err(format!("{name}: SDWA")); + } + if self.wave_valu(b, d)? { + return Ok(()); } let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); @@ -841,6 +876,8 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( partial, def_block: std::collections::HashMap::new(), lane_uses: Vec::new(), + dpp_src: None, + dpp_en: None, }; // the registers the program names, and the ones the runner reads back let mut sregs: Vec = vec![VCC, VCC + 1, 124, EXEC, EXEC + 1]; @@ -996,6 +1033,8 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( l.valu(cur, d)?; } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { l.vmem(cur, d)?; + } else if name == "DS_SWIZZLE_B32" { + l.swizzle(cur, d)?; } else { return Err(format!("unsupported {name}")); } @@ -1155,6 +1194,8 @@ pub(crate) mod tests { GroupId(u32), ThreadId(u32), Ballot(u32, usize), + ReadLane(u32, u32), + CountBits(u32), IoLoad(u32), ResStore(u32, u32), MemLoad(u32), @@ -1270,6 +1311,12 @@ pub(crate) mod tests { fn ballot(&mut self, c: u32) -> [u32; 2] { [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] } + fn read_lane(&mut self, v: u32, lane: u32) -> u32 { + self.push(Ins::ReadLane(v, lane)) + } + fn count_bits(&mut self, v: u32) -> u32 { + self.push(Ins::CountBits(v)) + } fn io_load(&mut self, dword: u32) -> u32 { self.push(Ins::IoLoad(dword)) } @@ -1386,7 +1433,8 @@ pub(crate) mod tests { Ins::Lane => Some(lane as u32), Ins::GroupId(k) => Some(group[*k as usize]), Ins::ThreadId(k) => Some(if *k == 0 { base + lane as u32 } else { 0 }), - Ins::Ballot(..) => break, + Ins::Ballot(..) | Ins::ReadLane(..) => break, + Ins::CountBits(v) => Some(g(v).count_ones()), Ins::IoLoad(a) => Some(io[g(a) as usize]), Ins::MemLoad(a) => Some(mem.get((g(a) / 4) as usize).copied().unwrap_or(0)), Ins::MemStore(a, v) => { @@ -1425,20 +1473,34 @@ pub(crate) mod tests { if ls.iter().all(|s| s.done) { return; } - // every lane waits at the same ballot - let (b, at) = (ls[0].block, ls[0].at); - assert!(ls.iter().all(|s| !s.done && s.block == b && s.at == at), "a ballot not reached by every lane"); - let (id, Ins::Ballot(c, half)) = &self.blocks[b].0[at] else { unreachable!() }; - let mut bits = 0u64; - for (lane, s) in ls.iter().enumerate() { - if s.env[&self.res(*c)] != 0 { - bits |= 1 << lane; + // the lanes waiting at the first wave operation (in block order: a loop's body + // before what follows it) run it together, as the lanes active there + let (b, at) = ls.iter().filter(|s| !s.done).map(|s| (s.block, s.at)).min().unwrap(); + let group: Vec = (0..ls.len()).filter(|&l| !ls[l].done && (ls[l].block, ls[l].at) == (b, at)).collect(); + let (id, ins) = &self.blocks[b].0[at]; + let out: Vec = match ins { + Ins::Ballot(c, half) => { + let mut bits = 0u64; + for &l in &group { + if self.value(&ls[l].env, *c) != 0 { + bits |= 1 << l; + } + } + vec![(bits >> (32 * half)) as u32; group.len()] } - } - let word = (bits >> (32 * half)) as u32; - for s in &mut ls { - s.env.insert(*id, word); - s.at += 1; + Ins::ReadLane(v, from) => group + .iter() + .map(|&l| { + let src = self.value(&ls[l].env, *from) as usize; + assert!(group.contains(&src), "lane {l} reads lane {src}, which is elsewhere"); + self.value(&ls[src].env, *v) + }) + .collect(), + _ => unreachable!(), + }; + for (&l, x) in group.iter().zip(out) { + ls[l].env.insert(*id, x); + ls[l].at += 1; } } } @@ -1897,4 +1959,179 @@ pub(crate) mod tests { ]); assert!(lower_kernel(&insts, false, Interp::default()).is_err()); } + + /// Cross-lane reads with EXEC narrowed to the lanes above 4 (`v_cmpx`): readfirstlane, + /// the counts of EXEC as a number, mbcnt, readlane / writelane, DPP16 / DPP8 sources, + /// permlanex16 and ds_swizzle. + fn lane_reads(wave64: bool) -> Vec { + let mut p: Vec = vec![ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 132)]), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", V + 2), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 126), ("SRC1", 128)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 4), ("SRC1", 137)]), + ("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 2), ("SRC1", 130)]), + // row_shr:1 with bound_ctrl; quad_perm [3,2,1,0] on rows 1 and 3; DPP8 reversed, added + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF), ("BOUND_CTRL", 1)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 7), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x1B), ("ROW_MASK", 0xA), ("BANK_MASK", 0xF)]), + ("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 8), ("SRC0", 0xE9), ("VSRC0", 4), ("VSRC1", 0), ("LANE_SEL_0", 7), ("LANE_SEL_1", 6), ("LANE_SEL_2", 5), ("LANE_SEL_3", 4), ("LANE_SEL_4", 3), ("LANE_SEL_5", 2), ("LANE_SEL_6", 1), ("LANE_SEL_7", 0)]), + ("S_MOVK_I32", "ENC_SOPK", &[("SDST", 5), ("SIMM16", 0x3210)]), + ("S_MOVK_I32", "ENC_SOPK", &[("SDST", 6), ("SIMM16", 0x7F54)]), + ("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 5), ("SRC2", 6)]), + // xor 1 (and 0x1F, or 0, xor 1); quad mode [3,2,1,0] + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 4), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 4), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + ]; + if wave64 { + p.extend_from_slice(&[ + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 127), ("SRC1", V + 3)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 126)]), + ("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 7), ("SSRC0", 126)]), + ]); + } else { + p.extend_from_slice(&[ + ("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 126)]), + ("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 7), ("SSRC0", 126)]), + ]); + } + p.push(ENDPGM); + p + } + + /// A waterfall loop: each pass takes the first lane's key (readfirstlane), the lanes with + /// that key do the work and leave; the readfirstlane is in a block lanes leave one by one. + fn waterfall(wave64: bool) -> Vec { + let w: [I; 4] = if wave64 { + [ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ] + } else { + [ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_XOR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ] + }; + vec![ + ("V_AND_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + w[0], + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 2)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 2), ("VSRC1", 2)]), + w[1], + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 3)]), + w[2], + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + w[3], + ENDPGM, + ] + } + + /// The lowering (on the CPU) and the HLSL path (on the GPU) give the same registers. + fn agrees_with_hlsl(name: &str, lines: &[I], wave64: bool, skip: &[usize]) { + use super::super::{dxc, runner, translate, Options}; + let lanes = if wave64 { 64 } else { 32 }; + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let gpu = runner::run(&dxil, &st, &[]).unwrap(); + let (cs, cv) = run(lines, wave64, &s, &v); + let insts = decode(lines); + let (_, stale) = lower_kernel(&insts, wave64, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + if wave64 { + sregs.extend([107, 127]); + } + // (a stale wave64 mask is reported by its first register; the pair's second is stale too) + let stale_at = |r: usize| stale.contains(&(r as u8)) || (wave64 && r > 0 && r % 2 == 1 && stale.contains(&(r as u8 - 1))); + for &r in sregs.iter().filter(|&&r| !stale_at(r) && !skip.contains(&r)) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..lanes { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + + #[test] + fn cross_lane_reads_on_the_cpu() { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let (s, v) = state(lanes); + let (s, v) = run(&lane_reads(wave64), wave64, &s, &v); + assert_eq!(s[2], 5, "readfirstlane: the first lane in EXEC"); + assert_eq!(s[3], lanes as u32 - 5, "s_bcnt1 of EXEC"); + assert_eq!(s[4], 27, "readlane 9 of 3 * lane"); + assert_eq!(s[7], 5, "s_ff1 of EXEC"); + for (l, r) in v.iter().enumerate() { + let (l32, active) = (l as u32, l > 4); + assert_eq!(r[3], if active { l32 - 5 } else { 0 }, "lane {l}: mbcnt"); + assert_eq!(r[5], if l == 2 { 5 } else { 0 }, "lane {l}: writelane, whatever EXEC holds"); + // row_shr:1, bound_ctrl: 0 at a row's first lane or from a lane outside EXEC + let want = if !active || l % 16 == 0 || l - 1 <= 4 { 0 } else { 3 * (l32 - 1) }; + assert_eq!(r[6], want, "lane {l}: DPP16 row_shr"); + let rev = (l32 & !7) | (7 - (l32 & 7)); + let want = if active { l32 + if rev > 4 { 3 * rev } else { 0 } } else { 0 }; + assert_eq!(r[8], want, "lane {l}: DPP8"); + let x = l32 ^ 1; + assert_eq!(r[10], if active && x > 4 { 3 * x } else { 0 }, "lane {l}: ds_swizzle xor 1"); + } + } + } + + #[test] + fn a_waterfall_loop_reads_the_first_lane_of_each_pass() { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let (s, v) = state(lanes); + let (_, v) = run(&waterfall(wave64), wave64, &s, &v); + for (l, r) in v.iter().enumerate() { + assert_eq!(r[3], l as u32 & 3, "lane {l}"); + } + } + // a lane of any lane, where some lanes have left: refused + let mut lines = waterfall(false); + lines.insert(3, ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 129)])); + lines[8] = ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFF8)]); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes are elsewhere"), "{err}"); + } + + #[test] + fn cross_lane_reads_agree_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner}; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + return; + } + agrees_with_hlsl("lane reads, wave32", &lane_reads(false), false, &[]); + // s2 and the saved EXEC s4 after the loop: the last pass's on the console; each lane's own + // last pass's in the lowering (written where lanes leave one by one; not refused yet) + agrees_with_hlsl("waterfall, wave32", &waterfall(false), false, &[2, 4]); + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + agrees_with_hlsl("lane reads, wave64", &lane_reads(true), true, &[]); + agrees_with_hlsl("waterfall, wave64", &waterfall(true), true, &[2, 4, 5]); + } } diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs new file mode 100644 index 0000000000..d7d2cf2828 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -0,0 +1,432 @@ +//! Cross-lane operations of the lowering: `v_readlane`, `v_readfirstlane`, `v_writelane`, +//! DPP16 / DPP8 sources, `v_permlane(x)16`, `ds_swizzle_b32`, `v_mbcnt`, and the counts of a +//! mask as a number (`s_bcnt1`, `s_ff1`). +//! +//! A lane reads another through `Ir::read_lane` (`WaveReadLaneAt`), which needs that lane to +//! be running the same instruction. Here a lane is where the console has it except across a +//! lane branch: the lanes that went the other way are elsewhere. So: +//! - a read of a lane in EXEC is always fine: that lane is here (readfirstlane, and DPP, +//! permlane and swizzle without fetch-inactive, whose source outside EXEC reads 0 or keeps +//! the destination); +//! - a read of any lane (readlane, writelane, fetch-inactive) needs every lane here, so it is +//! refused in a block not every lane reaches (`partial`), and the program stays on HLSL; +//! - a mask as a number is the ballot of its bits, which counts the lanes that are here: exact +//! for EXEC (a lane elsewhere is outside it), and for any mask where every lane is here. +//! +//! Lanes outside EXEC when a kernel-mode program starts leave at once (`lower_kernel`), so a +//! read of one of those is not the console's; compute waves start with every lane in EXEC. + +use super::{Bin, Cmp, Ir, Lower, Var, EXEC, R}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +impl Lower<'_, I> { + fn all_lanes(&self, b: usize, what: &str) -> R<()> { + if self.partial[b] { + Err(format!("{what} where some lanes are elsewhere")) + } else { + Ok(()) + } + } + + /// Whether operand `code` names a register holding a mask here, and the pair's register. + fn mask_reg(&mut self, b: usize, code: u64) -> Option<(u8, bool)> { + if code > 127 || code == 124 || code == 125 { + return None; + } + let r = code as u8; + if self.holds_mask(b, r) { + return Some((r, false)); + } + // the upper dword of a wave64 mask pair + (self.wave64 && r > 0 && self.holds_mask(b, r - 1)).then_some((r - 1, true)) + } + + /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits. + fn mask_words(&mut self, b: usize, r: u8) -> R<[I::V; 2]> { + if r != EXEC { + self.all_lanes(b, "a mask read as a number")?; + } + let bit = self.read_bit(b, r)?; + let [lo, hi] = self.ir.ballot(bit); + Ok(if self.wave64 { [lo, hi] } else { [lo, self.ir.int(0)] }) + } + + /// A 32-bit scalar operand as a number, also where it holds (half of) a mask. + fn word(&mut self, b: usize, d: &Decoded, code: u64) -> R { + match self.mask_reg(b, code) { + Some((r, hi)) => Ok(self.mask_words(b, r)?[hi as usize]), + None => self.src(b, d, code), + } + } + + /// A 64-bit scalar operand as numbers, also where it holds a mask. + fn words(&mut self, b: usize, d: &Decoded, code: u64) -> R<[I::V; 2]> { + match self.mask_reg(b, code) { + Some((r, false)) => self.mask_words(b, r), + Some((_, true)) => Err("a 64-bit operand across two masks".into()), + None => { + let (lo, hi) = self.src64(b, d, code)?; + Ok([lo, hi]) + } + } + } + + /// The lowest set bit of x, 32 if none. + fn ctz(&mut self, x: I::V) -> I::V { + let (z, one) = (self.ir.int(0), self.ir.int(1)); + let neg = self.ir.bin(Bin::Sub, z, x); + let low = self.ir.bin(Bin::And, x, neg); + let below = self.ir.bin(Bin::Sub, low, one); + self.ir.count_bits(below) + } + + /// The lowest set bit of the 64-bit (lo, hi), `none` if none. + fn first_set(&mut self, [lo, hi]: [I::V; 2], none: u32) -> I::V { + let z = self.ir.int(0); + let (cl, ch) = (self.ctz(lo), self.ctz(hi)); + let c32 = self.ir.int(32); + let ch = self.ir.bin(Bin::Add, ch, c32); + let none = self.ir.int(none); + let hz = self.ir.icmp(Cmp::Eq, hi, z); + let h = self.ir.select(hz, none, ch); + let lz = self.ir.icmp(Cmp::Eq, lo, z); + self.ir.select(lz, h, cl) + } + + /// Bit `l` of the 64-bit (lo, hi). + fn bit_at(&mut self, [lo, hi]: [I::V; 2], l: I::V) -> I::V { + let (c31, c32, one, z) = (self.ir.int(31), self.ir.int(32), self.ir.int(1), self.ir.int(0)); + let low = self.ir.icmp(Cmp::Ult, l, c32); + let w = self.ir.select(low, lo, hi); + let sh = self.ir.bin(Bin::And, l, c31); + let w = self.ir.bin(Bin::LShr, w, sh); + let w = self.ir.bin(Bin::And, w, one); + self.ir.icmp(Cmp::Ne, w, z) + } + + /// The lanes in EXEC, as numbers. + fn exec_words(&mut self, b: usize) -> R<[I::V; 2]> { + let e = self.read_bit(b, EXEC)?; + let [lo, hi] = self.ir.ballot(e); + Ok([lo, if self.wave64 { hi } else { self.ir.int(0) }]) + } + + /// `v` of lane `l` if that lane is in EXEC (or `inactive_too`); whether it was. + fn read_from(&mut self, b: usize, v: I::V, l: I::V, inactive_too: bool, what: &str) -> R<(I::V, I::V)> { + let ok = if inactive_too { + self.all_lanes(b, what)?; + self.ir.boolean(true) + } else { + let e = self.exec_words(b)?; + self.bit_at(e, l) + }; + // a lane outside EXEC may be elsewhere: read this lane's own value instead, unused + let me = self.lane(); + let at = self.ir.select(ok, l, me); + Ok((self.ir.read_lane(v, at), ok)) + } + + fn c(&mut self, v: u32) -> I::V { + self.ir.int(v) + } + + /// `(lane & !keep) | x` + fn lane_with(&mut self, keep_not: u32, x: I::V) -> I::V { + let me = self.lane(); + let k = self.c(!keep_not); + let hi = self.ir.bin(Bin::And, me, k); + self.ir.bin(Bin::Or, hi, x) + } + + /// `(k >> (bits * (lane & group))) & field`: a lane's entry of a packed selector. + fn packed(&mut self, k: I::V, bits: u32, group: u32, field: u32) -> I::V { + let me = self.lane(); + let (g, w, f) = (self.c(group), self.c(bits), self.c(field)); + let i = self.ir.bin(Bin::And, me, g); + let sh = self.ir.bin(Bin::Mul, i, w); + let x = self.ir.bin(Bin::LShr, k, sh); + self.ir.bin(Bin::And, x, f) + } + + /// The source lane of DPP16 control `ctrl`, and whether it is inside the row. + fn dpp16_lane(&mut self, ctrl: u64) -> R<(I::V, I::V)> { + let me = self.lane(); + let n = (ctrl & 15) as u32; + let t = self.ir.boolean(true); + let row = |l: &mut Self| { + let c = l.c(15); + l.ir.bin(Bin::And, me, c) + }; + Ok(match ctrl { + 0x000..=0x0FF => { + let k = self.c(ctrl as u32); + let x = self.packed(k, 2, 3, 3); + (self.lane_with(3, x), t) + } + 0x101..=0x10F => { + let (r, cn, c16) = (row(self), self.c(n), self.c(16)); + let to = self.ir.bin(Bin::Add, r, cn); + let ok = self.ir.icmp(Cmp::Ult, to, c16); + (self.ir.bin(Bin::Add, me, cn), ok) + } + 0x111..=0x11F => { + let (r, cn) = (row(self), self.c(n)); + let ok = self.ir.icmp(Cmp::Uge, r, cn); + (self.ir.bin(Bin::Sub, me, cn), ok) + } + 0x121..=0x12F => { + let (r, cn, c15) = (row(self), self.c(n), self.c(15)); + let x = self.ir.bin(Bin::Sub, r, cn); + let x = self.ir.bin(Bin::And, x, c15); + (self.lane_with(15, x), t) + } + 0x140 => { + let (r, c15) = (row(self), self.c(15)); + let x = self.ir.bin(Bin::Sub, c15, r); + (self.lane_with(15, x), t) + } + 0x141 => { + let (c7, c8) = (self.c(7), self.c(8)); + let x = self.ir.bin(Bin::And, me, c7); + let x = self.ir.bin(Bin::Sub, c7, x); + let h = self.ir.bin(Bin::And, me, c8); + let x = self.ir.bin(Bin::Or, x, h); + (self.lane_with(15, x), t) + } + 0x150..=0x15F => { + let x = self.c(n); + (self.lane_with(15, x), t) + } + 0x160..=0x16F => { + let cn = self.c(n); + (self.ir.bin(Bin::Xor, me, cn), t) + } + _ => return Err(format!("DPP_CTRL {ctrl:#x}")), + }) + } + + /// A DPP instruction's first source, read from its source lane, and its write enable + /// (`dpp_src`, `dpp_en`, taken by `src` and `write_v`). + pub(super) fn dpp(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if name.starts_with("V_CMP") { + return Err(format!("{name}: DPP compare")); + } + let e = super::super::emit::ext_encoding(d).ok_or("DPP encoding")?; + let f = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + if ["SRC0_ABS", "SRC0_NEG", "SRC1_ABS", "SRC1_NEG"].iter().any(|m| f(m) != 0) { + return Err(format!("{name}: DPP modifiers")); + } + let v = self.read(b, Var::V(f("VSRC0") as u16)); + let (val, en) = if d.variant == Variant::Dpp16 { + let (l, inside) = self.dpp16_lane(f("DPP_CTRL"))?; + // outside the row: this lane's own, unused (the lane number may be out of range) + let me = self.lane(); + let l = self.ir.select(inside, l, me); + let (val, ok) = self.read_from(b, v, l, f("FI") == 1, "DPP fetch-inactive")?; + let ok = self.ir.bin(Bin::And, ok, inside); + let z = self.c(0); + let mut en = None; + let val = if f("BOUND_CTRL") == 1 { + self.ir.select(ok, val, z) + } else { + en = Some(ok); + val + }; + let (rm, bm) = (f("ROW_MASK") as u32, f("BANK_MASK") as u32); + if rm != 0xF || bm != 0xF { + let me = self.lane(); + let (k, s4, s2, c3) = (self.c(rm), self.c(4), self.c(2), self.c(3)); + let r = self.ir.bin(Bin::LShr, me, s4); + let r = self.ir.bin(Bin::LShr, k, r); + let k = self.c(bm); + let q = self.ir.bin(Bin::LShr, me, s2); + let q = self.ir.bin(Bin::And, q, c3); + let q = self.ir.bin(Bin::LShr, k, q); + let both = self.ir.bin(Bin::And, r, q); + let one = self.c(1); + let both = self.ir.bin(Bin::And, both, one); + let on = self.ir.icmp(Cmp::Ne, both, z); + en = Some(match en { + Some(ok) => self.ir.bin(Bin::And, ok, on), + None => on, + }); + } + (val, en) + } else { + let sel: u64 = (0..8).map(|i| f(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); + let fi = rdna2::field_value(d.enc, &d.words, "SRC0") == Some(0xEA); + let k = self.c(sel as u32); + let x = self.packed(k, 3, 7, 7); + let l = self.lane_with(7, x); + let (val, ok) = self.read_from(b, v, l, fi, "DPP8 fetch-inactive")?; + let z = self.c(0); + (self.ir.select(ok, val, z), None) + }; + self.dpp_src = Some(val); + self.dpp_en = en; + Ok(()) + } + + /// The cross-lane VALU instructions; `false` for any other. + pub(super) fn wave_valu(&mut self, b: usize, d: &Decoded) -> R { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let (s0, s1, vdst) = (fv("SRC0"), fv("SRC1"), fv("VDST")); + let wmask = if self.wave64 { 63 } else { 31 }; + match name { + "V_READFIRSTLANE_B32" => { + let v = self.src(b, d, s0)?; + let r = if s0 >= 256 { + let e = self.exec_words(b)?; + let l = self.first_set(e, 0); + self.ir.read_lane(v, l) + } else { + v + }; + self.write_num(b, vdst as u8, r); + } + "V_READLANE_B32" => { + self.all_lanes(b, "v_readlane")?; + let (v, sel) = (self.src(b, d, s0)?, self.word(b, d, s1)?); + let m = self.c(wmask); + let l = self.ir.bin(Bin::And, sel, m); + let r = self.ir.read_lane(v, l); + self.write_num(b, vdst as u8, r); + } + "V_WRITELANE_B32" => { + // whatever EXEC holds + self.all_lanes(b, "v_writelane")?; + let (a, sel) = (self.word(b, d, s0)?, self.word(b, d, s1)?); + let m = self.c(wmask); + let l = self.ir.bin(Bin::And, sel, m); + let me = self.lane(); + let hit = self.ir.icmp(Cmp::Eq, me, l); + let old = self.read(b, Var::V(vdst as u16)); + let v = self.ir.select(hit, a, old); + self.ssa.write(b, Var::V(vdst as u16), v); + } + "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => { + let (m, add) = (self.word(b, d, s0)?, self.src(b, d, s1)?); + // the lanes below this one, in this half of the mask + let me = self.lane(); + let (c31, c32, one, z, all) = (self.c(31), self.c(32), self.c(1), self.c(0), self.c(u32::MAX)); + let sh = self.ir.bin(Bin::And, me, c31); + let below = self.ir.bin(Bin::Shl, one, sh); + let below = self.ir.bin(Bin::Sub, below, one); + let upper = self.ir.icmp(Cmp::Uge, me, c32); + let lt = if name == "V_MBCNT_LO_U32_B32" { self.ir.select(upper, all, below) } else { self.ir.select(upper, below, z) }; + let x = self.ir.bin(Bin::And, m, lt); + let n = self.ir.count_bits(x); + let r = self.ir.bin(Bin::Add, n, add); + self.write_v(b, d, vdst as u16, r)?; + } + "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" => { + let op_sel = fv("OP_SEL"); + if ["ABS", "NEG", "CLAMP", "OMOD"].iter().any(|f| fv(f) != 0) || op_sel & !3 != 0 { + return Err(format!("{name}: VOP3 modifiers")); + } + let (fi, bound) = (op_sel & 1 == 1, op_sel & 2 == 2); + let v = self.src(b, d, s0)?; + let (lo, hi) = (self.word(b, d, s1)?, self.word(b, d, fv("SRC2"))?); + let me = self.lane(); + let (c8, c15, c16) = (self.c(8), self.c(15), self.c(16)); + let r = self.ir.bin(Bin::And, me, c15); + let first8 = self.ir.icmp(Cmp::Ult, r, c8); + let k = self.ir.select(first8, lo, hi); + let n = self.packed(k, 4, 7, 15); + // the same row (permlane16) or the other row of the 32-lane half + let row = self.ir.bin(Bin::And, me, c16); + let row = if name == "V_PERMLANEX16_B32" { self.ir.bin(Bin::Xor, row, c16) } else { row }; + let x = self.ir.bin(Bin::Or, row, n); + let l = self.lane_with(31, x); + let (val, ok) = self.read_from(b, v, l, fi, "v_permlane fetch-inactive")?; + let other = if bound { self.c(0) } else { self.read(b, Var::V(vdst as u16)) }; + let r = self.ir.select(ok, val, other); + self.write_v(b, d, vdst as u16, r)?; + } + _ => return Ok(false), + } + Ok(true) + } + + /// `ds_swizzle_b32`: a lane reads another of its 32-lane half (`emit::swizzle_lane`). + pub(super) fn swizzle(&mut self, b: usize, d: &Decoded) -> R<()> { + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let off = fv("OFFSET0") | fv("OFFSET1") << 8; + let v = self.read(b, Var::V(fv("ADDR") as u16)); + let me = self.lane(); + let c31 = self.c(31); + let i = self.ir.bin(Bin::And, me, c31); + let x = if off >= 0xE000 { + return Err("ds_swizzle FFT mode".into()); + } else if off >= 0xC000 { + // rotate by offset[9:5] lanes, left or right (offset[10]); masked bits stay + let mask = (off & 0x1F) as u32; + let r = ((off >> 5) & 0x1F) as u32; + let r = if off & 0x400 != 0 { r.wrapping_neg() } else { r }; + let (cm, cn, cr) = (self.c(mask), self.c(!mask & 31), self.c(r)); + let kept = self.ir.bin(Bin::And, i, cm); + let moved = self.ir.bin(Bin::Add, i, cr); + let moved = self.ir.bin(Bin::And, moved, cn); + self.ir.bin(Bin::Or, kept, moved) + } else if off & 0x8000 != 0 { + let k = self.c(off as u32); + let q = self.packed(k, 2, 3, 3); + let c28 = self.c(28); + let base = self.ir.bin(Bin::And, i, c28); + self.ir.bin(Bin::Or, base, q) + } else { + let (and, or, xor) = (self.c((off & 0x1F) as u32), self.c(((off >> 5) & 0x1F) as u32), self.c(((off >> 10) & 0x1F) as u32)); + let x = self.ir.bin(Bin::And, i, and); + let x = self.ir.bin(Bin::Or, x, or); + self.ir.bin(Bin::Xor, x, xor) + }; + let l = self.lane_with(31, x); + let (val, ok) = self.read_from(b, v, l, false, "")?; + let z = self.c(0); + let r = self.ir.select(ok, val, z); + self.write_v(b, d, fv("VDST") as u16, r) + } + + /// Scalar counts of a mask; `false` for any other instruction. + pub(super) fn wave_salu(&mut self, b: usize, d: &Decoded) -> R { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let (s0, sd) = (fv("SSRC0"), fv("SDST") as u8); + let (ones, count) = match name { + "S_BCNT1_I32_B32" | "S_BCNT1_I32_B64" => (true, true), + "S_BCNT0_I32_B32" | "S_BCNT0_I32_B64" => (false, true), + "S_FF1_I32_B32" | "S_FF1_I32_B64" => (true, false), + _ => return Ok(false), + }; + // only where the source is a mask: numbers take the usual path + if self.mask_reg(b, s0).is_none() { + return Ok(false); + } + let w = if name.ends_with("_B64") { + self.words(b, d, s0)? + } else { + [self.word(b, d, s0)?, self.c(0)] + }; + let w = if ones { + w + } else { + let all = self.c(u32::MAX); + let hi = if name.ends_with("_B64") { self.ir.bin(Bin::Xor, w[1], all) } else { w[1] }; + [self.ir.bin(Bin::Xor, w[0], all), hi] + }; + let r = if count { + let (lo, hi) = (self.ir.count_bits(w[0]), self.ir.count_bits(w[1])); + let r = self.ir.bin(Bin::Add, lo, hi); + let z = self.c(0); + let c = self.ir.icmp(Cmp::Ne, r, z); + self.ssa.write(b, Var::Scc, c); + r + } else { + self.first_set(w, u32::MAX) + }; + self.write_num(b, sd, r); + Ok(true) + } +} From ac8f8b612962fab87982b9b1fc703745b1e6b2ef Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:13:18 -0300 Subject: [PATCH 10/51] Recompiler: lane reads and bit counts through gpu::dxil in the direct lowering Sr-0w's cross-lane operations add Ir::read_lane and Ir::count_bits; on #1426's builder they are waveReadLaneAt and countbits. --- crates/xcl/src/gpu/recomp/lower_dxil.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 3b67001969..acda17aadd 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -127,6 +127,12 @@ impl Ir for DxilIr { let w = self.s.wave_ballot(c); [w[0], w[1]] } + fn read_lane(&mut self, v: Value, lane: Value) -> Value { + self.s.wave_read_lane_at(v, lane) + } + fn count_bits(&mut self, v: Value) -> Value { + self.s.bit_count(crate::gpu::dxil::ops::BitCount::Countbits, v) + } fn io_load(&mut self, dword: Value) -> Value { let a = self.bytes(dword); let io = self.io; From f5d3e0547ad8306ed08f8fd049029f0680e891ee Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:34:34 -0300 Subject: [PATCH 11/51] Recompiler: per-lane coverage survey and the first coverage gaps `xcl shaders --recomp` now builds every compute program of the pack both ways: in its per-lane form (`lower_dxil::compute_code`) and in #1426's per-instruction form (`gpu::dxil::kernel::translate_compute`), and prints how many each covers, the DXIL size where both do, and why the per-lane form refused the rest. The first pass: per-instruction 2 689 of 2 689, per-lane 4. The commonest refusals were `v_nop` (now nothing), `s_setreg*` of MODE (now nothing: only float instructions read it, and the lowering refuses every float instruction so far), 2-D / 3-D groups, and the three-source integer ops, now lowered (`v_lshl_add_u32`, `v_add_lshl_u32`, `v_lshl_or_b32`, `v_and_or_b32`, `v_or3_b32`, `v_xor3_b32`, `v_add3_u32`). --- crates/xcl/src/gpu/recomp/lower.rs | 40 +++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 13 ++++++++ crates/xcl/src/shaders.rs | 35 ++++++++++++++++++++++ 3 files changed, 88 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index e006083fa3..fa12d46f70 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -464,6 +464,9 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_scc(b, v); } "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" => {} + // MODE (float rounding / denormals): only float instructions read it, and the + // lowering refuses every float instruction so far – revisit when floats come in + "S_SETREG_IMM32_B32" | "S_SETREG_B32" if self.sets_mode_only(d) => {} n => return Err(format!("unsupported {n}")), } Ok(()) @@ -481,6 +484,9 @@ impl<'a, I: Ir> Lower<'a, I> { } fn valu(&mut self, b: usize, d: &Decoded) -> R<()> { + if d.inst.name == "V_NOP" { + return Ok(()); + } if matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) { self.dpp(b, d)?; } @@ -555,6 +561,35 @@ impl<'a, I: Ir> Lower<'a, I> { "V_OR_B32" => self.ir.bin(Bin::Or, a, c), "V_XOR_B32" => self.ir.bin(Bin::Xor, a, c), "V_MUL_LO_U32" => self.ir.bin(Bin::Mul, a, c), + // three-source integer ops (VOP3): shifts take the low 5 bits of their amount + "V_LSHL_ADD_U32" | "V_ADD_LSHL_U32" | "V_LSHL_OR_B32" | "V_AND_OR_B32" | "V_OR3_B32" | "V_XOR3_B32" | "V_ADD3_U32" => { + let e = self.src(b, d, fv("SRC2").unwrap_or(0))?; + match name { + "V_LSHL_ADD_U32" | "V_LSHL_OR_B32" => { + let sh = self.ir.bin(Bin::And, c, c31); + let x = self.ir.bin(Bin::Shl, a, sh); + self.ir.bin(if name == "V_LSHL_ADD_U32" { Bin::Add } else { Bin::Or }, x, e) + } + "V_ADD_LSHL_U32" => { + let x = self.ir.bin(Bin::Add, a, c); + let sh = self.ir.bin(Bin::And, e, c31); + self.ir.bin(Bin::Shl, x, sh) + } + "V_AND_OR_B32" => { + let x = self.ir.bin(Bin::And, a, c); + self.ir.bin(Bin::Or, x, e) + } + _ => { + let op = match name { + "V_OR3_B32" => Bin::Or, + "V_XOR3_B32" => Bin::Xor, + _ => Bin::Add, + }; + let x = self.ir.bin(op, a, c); + self.ir.bin(op, x, e) + } + } + } "V_LSHLREV_B32" | "V_LSHRREV_B32" | "V_ASHRREV_I32" => { let sh = self.ir.bin(Bin::And, a, c31); let op = match name { @@ -571,6 +606,11 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_v(b, d, vdst as u16, v) } + /// `s_setreg*` writing `HW_REG_MODE` (id 1 of its `SIMM16`) and nothing else. + fn sets_mode_only(&self, d: &Decoded) -> bool { + rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) & 0x3F == 1 + } + /// `s_load_dword{,x2,x4,x8,x16}`: dwords of the flat memory into SGPRs, from /// `s[sbase] + offset + soffset` (one memory window, as `emit::smem` with `mem_windows` 1). fn smem(&mut self, b: usize, d: &Decoded) -> R<()> { diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index acda17aadd..04a4c98a2a 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -171,6 +171,19 @@ pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), Str Ok((ir.s.finish([lanes, 1, 1], Some(lanes)), stale)) } +/// `compute` from the program's code (decoded, far jumps resolved). +pub fn compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Result, String> { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + compute(&insts, cs, wave64) +} + /// A compute program in its per-lane form, as a signed DXIL container. pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(false))?; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 1048e6a68f..b9d6d86867 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -313,6 +313,11 @@ struct RecompAgg { /// instructions, those still guarded, lane branches, uniform branches; failures by reason lanes: [usize; 6], lanes_failed: BTreeMap, + /// compute programs, per-lane DXIL (`lower_dxil`) vs #1426's per-instruction form: tried, + /// per-lane ok, per-instruction ok, both ok, per-lane bytes and per-instruction bytes where + /// both are ok; why the per-lane form refused (first words of the reason) + cs_forms: [usize; 6], + cs_lane_why: BTreeMap, } impl RecompAgg { @@ -359,6 +364,12 @@ impl RecompAgg { for (k, v) in o.lanes_failed { *self.lanes_failed.entry(k).or_default() += v; } + for (a, b) in self.cs_forms.iter_mut().zip(o.cs_forms) { + *a += b; + } + for (k, v) in o.cs_lane_why { + *self.cs_lane_why.entry(k).or_default() += v; + } } fn add(&mut self, name: &str, code: &[u8], keep: usize, mode: recomp::Mode) { @@ -399,6 +410,23 @@ impl RecompAgg { self.graphics_wave32 += 1; } } + if let recomp::Mode::Compute(cs) = &mode { + let lane = recomp::lower_dxil::compute_code(code, cs, wave64); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let inst = crate::gpu::dxil::kernel::translate_compute(code, o, cs).map(|k| k.dxil); + self.cs_forms[0] += 1; + self.cs_forms[1] += lane.is_ok() as usize; + self.cs_forms[2] += inst.is_ok() as usize; + if let (Ok(a), Ok(b)) = (&lane, &inst) { + self.cs_forms[3] += 1; + self.cs_forms[4] += a.len(); + self.cs_forms[5] += b.len(); + } + if let Err(e) = &lane { + let key: String = e.split([':', '(']).next().unwrap_or("").split_whitespace().take(3).collect::>().join(" "); + *self.cs_lane_why.entry(key).or_default() += 1; + } + } match recomp::lane_masks::analyze_code(code, wave64) { Ok(s) => { let counts = [1, s.guarded.is_empty() as usize, s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches]; @@ -1512,6 +1540,13 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim "VS/PS and the wave size (the driver picks it): wave32 {} (handled – the halves of a 64-wide wave run separately), wave64 {}; hazards in 32-thread waves: {:?}; reads of lanes ≥ 32 resolved (32-lane GPUs): {:?}", rc.graphics_wave32, rc.graphics_wave64, rc.wave_hazards, rc.wave_resolved ); + let c = &rc.cs_forms; + let mut why: Vec<_> = rc.cs_lane_why.iter().collect(); + why.sort_by(|a, b| b.1.cmp(a.1)); + println!( + "compute programs, direct DXIL: {} tried; per-lane form {} ok, per-instruction form (#1426) {} ok; where both are ok ({}): per-lane {:.1} MB, per-instruction {:.1} MB of DXIL; per-lane refused for: {:?}", + c[0], c[1], c[2], c[3], c[4] as f64 / 1048576.0, c[5] as f64 / 1048576.0, &why[..why.len().min(15)] + ); let l = &rc.lanes; println!( "lane masks (direct DXIL, no EXEC emulation): analysed {} of {} programs, {} with no guard left; vector instructions {}, still guarded {} ({:.1}%); branches per lane {}, uniform {}; not analysed: {:?}", From 45025eb7c55050cc9c30090918d57c20609220ca Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 17:32:19 +0100 Subject: [PATCH 12/51] Recompiler: half-local wave operations in the lowering's Ir `Ir` gains `ballot_half` and `read_lane_half`: a ballot of which only the word of the lane's own 32-lane half is used, and a read of a lane in the same half. A wave64 split into two 32-lane hardware waves can do these without an exchange between the halves; `ballot` and `read_lane` keep their names and stay whole-wave, so existing callers are right by default. `lower/wave.rs` uses the half-local forms for DPP16 / DPP8, permlane(x)16 and ds_swizzle (their source lane and its EXEC bit are in the reader's half), and for a mask operand of `v_mbcnt_hi` (lanes below 32 add 0). The rest stays whole-wave: readfirstlane, readlane, writelane, `v_mbcnt_lo`, a mask as a number, and the kernel exit's ballot of masks. The DXIL adapter maps both forms to the same operations (one hardware wave per console wave). The CPU interpreter gives lanes of the other half a garbage word from `ballot_half` and asserts that `read_lane_half` stays in the half, so a call that needs the whole wave but uses a half-local form fails the tests: switching readfirstlane to the half-local ballot fails two of them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XTYmP5ub3Zjdi8PYaDNwsV --- crates/xcl/src/gpu/recomp/lower.rs | 29 ++++++++++++++--- crates/xcl/src/gpu/recomp/lower/wave.rs | 42 +++++++++++++++++-------- crates/xcl/src/gpu/recomp/lower_dxil.rs | 8 +++++ 3 files changed, 62 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index fa12d46f70..e38d57174f 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -71,9 +71,14 @@ pub trait Ir: Sink { fn thread_id(&mut self, k: u32) -> Self::V; /// the wave's ballot of `c`: lanes 0–31, 32–63 fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; + /// `ballot` where only the word of this lane's 32-lane half is used (the other may be + /// anything): a wave64 split into two 32-lane hardware waves needs no exchange for it + fn ballot_half(&mut self, c: Self::V) -> [Self::V; 2]; /// `v` as lane `lane` holds it (`WaveReadLaneAt`); `lane` may differ between lanes and is /// always one running this instruction too fn read_lane(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// `read_lane` of a lane in this lane's 32-lane half (DPP, permlane, swizzle) + fn read_lane_half(&mut self, v: Self::V, lane: Self::V) -> Self::V; /// the number of bits set in `v` (`countbits`) fn count_bits(&mut self, v: Self::V) -> Self::V; fn io_load(&mut self, dword: Self::V) -> Self::V; @@ -1235,6 +1240,9 @@ pub(crate) mod tests { ThreadId(u32), Ballot(u32, usize), ReadLane(u32, u32), + /// as `Ballot` and `ReadLane`, but the lowering may use only its own 32-lane half's part + BallotHalf(u32, usize), + ReadLaneHalf(u32, u32), CountBits(u32), IoLoad(u32), ResStore(u32, u32), @@ -1351,9 +1359,15 @@ pub(crate) mod tests { fn ballot(&mut self, c: u32) -> [u32; 2] { [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] } + fn ballot_half(&mut self, c: u32) -> [u32; 2] { + [self.push(Ins::BallotHalf(c, 0)), self.push(Ins::BallotHalf(c, 1))] + } fn read_lane(&mut self, v: u32, lane: u32) -> u32 { self.push(Ins::ReadLane(v, lane)) } + fn read_lane_half(&mut self, v: u32, lane: u32) -> u32 { + self.push(Ins::ReadLaneHalf(v, lane)) + } fn count_bits(&mut self, v: u32) -> u32 { self.push(Ins::CountBits(v)) } @@ -1473,7 +1487,7 @@ pub(crate) mod tests { Ins::Lane => Some(lane as u32), Ins::GroupId(k) => Some(group[*k as usize]), Ins::ThreadId(k) => Some(if *k == 0 { base + lane as u32 } else { 0 }), - Ins::Ballot(..) | Ins::ReadLane(..) => break, + Ins::Ballot(..) | Ins::BallotHalf(..) | Ins::ReadLane(..) | Ins::ReadLaneHalf(..) => break, Ins::CountBits(v) => Some(g(v).count_ones()), Ins::IoLoad(a) => Some(io[g(a) as usize]), Ins::MemLoad(a) => Some(mem.get((g(a) / 4) as usize).copied().unwrap_or(0)), @@ -1519,20 +1533,27 @@ pub(crate) mod tests { let group: Vec = (0..ls.len()).filter(|&l| !ls[l].done && (ls[l].block, ls[l].at) == (b, at)).collect(); let (id, ins) = &self.blocks[b].0[at]; let out: Vec = match ins { - Ins::Ballot(c, half) => { + Ins::Ballot(c, half) | Ins::BallotHalf(c, half) => { let mut bits = 0u64; for &l in &group { if self.value(&ls[l].env, *c) != 0 { bits |= 1 << l; } } - vec![(bits >> (32 * half)) as u32; group.len()] + let word = (bits >> (32 * half)) as u32; + // the half-local form: the other half's word is garbage, so a lowering + // that reads it gets a wrong result here + let local = matches!(ins, Ins::BallotHalf(..)); + group.iter().map(|&l| if local && l / 32 != *half { 0xA5A5_0000 | l as u32 } else { word }).collect() } - Ins::ReadLane(v, from) => group + Ins::ReadLane(v, from) | Ins::ReadLaneHalf(v, from) => group .iter() .map(|&l| { let src = self.value(&ls[l].env, *from) as usize; assert!(group.contains(&src), "lane {l} reads lane {src}, which is elsewhere"); + if matches!(ins, Ins::ReadLaneHalf(..)) { + assert_eq!(src / 32, l / 32, "lane {l} reads lane {src} of the other half"); + } self.value(&ls[src].env, *v) }) .collect(), diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs index d7d2cf2828..09d21fd5e1 100644 --- a/crates/xcl/src/gpu/recomp/lower/wave.rs +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -13,6 +13,12 @@ //! - a mask as a number is the ballot of its bits, which counts the lanes that are here: exact //! for EXEC (a lane elsewhere is outside it), and for any mask where every lane is here. //! +//! DPP, permlane(x)16, ds_swizzle and `v_mbcnt_hi` only need this lane's 32-lane half, so they +//! use `Ir::read_lane_half` / `Ir::ballot_half`; readfirstlane, readlane, writelane, `v_mbcnt_lo` +//! and a mask as a number need the whole wave (`read_lane`, `ballot`). With one hardware wave per +//! console wave they are the same; a wave64 split into two 32-lane hardware waves exchanges data +//! between the halves only for the whole-wave forms. +//! //! Lanes outside EXEC when a kernel-mode program starts leave at once (`lower_kernel`), so a //! read of one of those is not the console's; compute waves start with every lane in EXEC. @@ -41,20 +47,26 @@ impl Lower<'_, I> { (self.wave64 && r > 0 && self.holds_mask(b, r - 1)).then_some((r - 1, true)) } - /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits. - fn mask_words(&mut self, b: usize, r: u8) -> R<[I::V; 2]> { + /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits; with `half`, + /// only this lane's half of it is right (`Ir::ballot_half`). + fn mask_words(&mut self, b: usize, r: u8, half: bool) -> R<[I::V; 2]> { if r != EXEC { self.all_lanes(b, "a mask read as a number")?; } let bit = self.read_bit(b, r)?; - let [lo, hi] = self.ir.ballot(bit); + let [lo, hi] = if half { self.ir.ballot_half(bit) } else { self.ir.ballot(bit) }; Ok(if self.wave64 { [lo, hi] } else { [lo, self.ir.int(0)] }) } /// A 32-bit scalar operand as a number, also where it holds (half of) a mask. fn word(&mut self, b: usize, d: &Decoded, code: u64) -> R { + self.word_in(b, d, code, false) + } + + /// `word`; with `half`, a mask's word is only right for the lanes of the half it covers. + fn word_in(&mut self, b: usize, d: &Decoded, code: u64, half: bool) -> R { match self.mask_reg(b, code) { - Some((r, hi)) => Ok(self.mask_words(b, r)?[hi as usize]), + Some((r, hi)) => Ok(self.mask_words(b, r, half)?[hi as usize]), None => self.src(b, d, code), } } @@ -62,7 +74,7 @@ impl Lower<'_, I> { /// A 64-bit scalar operand as numbers, also where it holds a mask. fn words(&mut self, b: usize, d: &Decoded, code: u64) -> R<[I::V; 2]> { match self.mask_reg(b, code) { - Some((r, false)) => self.mask_words(b, r), + Some((r, false)) => self.mask_words(b, r, false), Some((_, true)) => Err("a 64-bit operand across two masks".into()), None => { let (lo, hi) = self.src64(b, d, code)?; @@ -104,26 +116,27 @@ impl Lower<'_, I> { self.ir.icmp(Cmp::Ne, w, z) } - /// The lanes in EXEC, as numbers. - fn exec_words(&mut self, b: usize) -> R<[I::V; 2]> { + /// The lanes in EXEC, as numbers; with `half`, only this lane's half is right. + fn exec_words(&mut self, b: usize, half: bool) -> R<[I::V; 2]> { let e = self.read_bit(b, EXEC)?; - let [lo, hi] = self.ir.ballot(e); + let [lo, hi] = if half { self.ir.ballot_half(e) } else { self.ir.ballot(e) }; Ok([lo, if self.wave64 { hi } else { self.ir.int(0) }]) } - /// `v` of lane `l` if that lane is in EXEC (or `inactive_too`); whether it was. + /// `v` of lane `l` (in this lane's 32-lane half) if that lane is in EXEC (or + /// `inactive_too`); whether it was. fn read_from(&mut self, b: usize, v: I::V, l: I::V, inactive_too: bool, what: &str) -> R<(I::V, I::V)> { let ok = if inactive_too { self.all_lanes(b, what)?; self.ir.boolean(true) } else { - let e = self.exec_words(b)?; + let e = self.exec_words(b, true)?; self.bit_at(e, l) }; // a lane outside EXEC may be elsewhere: read this lane's own value instead, unused let me = self.lane(); let at = self.ir.select(ok, l, me); - Ok((self.ir.read_lane(v, at), ok)) + Ok((self.ir.read_lane_half(v, at), ok)) } fn c(&mut self, v: u32) -> I::V { @@ -278,7 +291,7 @@ impl Lower<'_, I> { "V_READFIRSTLANE_B32" => { let v = self.src(b, d, s0)?; let r = if s0 >= 256 { - let e = self.exec_words(b)?; + let e = self.exec_words(b, false)?; let l = self.first_set(e, 0); self.ir.read_lane(v, l) } else { @@ -307,7 +320,10 @@ impl Lower<'_, I> { self.ssa.write(b, Var::V(vdst as u16), v); } "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => { - let (m, add) = (self.word(b, d, s0)?, self.src(b, d, s1)?); + // mbcnt_hi counts the upper lanes' own half only (0 below lane 32); mbcnt_lo + // gives the upper lanes all of the lower half + let hi_half = name == "V_MBCNT_HI_U32_B32"; + let (m, add) = (self.word_in(b, d, s0, hi_half)?, self.src(b, d, s1)?); // the lanes below this one, in this half of the mask let me = self.lane(); let (c31, c32, one, z, all) = (self.c(31), self.c(32), self.c(1), self.c(0), self.c(u32::MAX)); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 04a4c98a2a..f43359c8da 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -127,9 +127,17 @@ impl Ir for DxilIr { let w = self.s.wave_ballot(c); [w[0], w[1]] } + // one hardware wave per console wave (native wave64, or wave32): the half-local forms are + // the same operations + fn ballot_half(&mut self, c: Value) -> [Value; 2] { + self.ballot(c) + } fn read_lane(&mut self, v: Value, lane: Value) -> Value { self.s.wave_read_lane_at(v, lane) } + fn read_lane_half(&mut self, v: Value, lane: Value) -> Value { + self.read_lane(v, lane) + } fn count_bits(&mut self, v: Value) -> Value { self.s.bit_count(crate::gpu::dxil::ops::BitCount::Countbits, v) } From fbb3a7b87c55e51e989a9798e64483244e9af4fd Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:42:05 -0300 Subject: [PATCH 13/51] Recompiler: name the hardware register of a refused s_setreg in the coverage survey The 1 134 compute programs refused for s_setreg_imm32_b32 write hwreg 20 (FLAT_SCR_LO, the scratch base), not MODE. --- crates/xcl/src/gpu/recomp/lower.rs | 4 ++++ crates/xcl/src/shaders.rs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index e38d57174f..5ac4437ef2 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -472,6 +472,10 @@ impl<'a, I: Ir> Lower<'a, I> { // MODE (float rounding / denormals): only float instructions read it, and the // lowering refuses every float instruction so far – revisit when floats come in "S_SETREG_IMM32_B32" | "S_SETREG_B32" if self.sets_mode_only(d) => {} + "S_SETREG_IMM32_B32" | "S_SETREG_B32" => { + let s = fv("SIMM16").unwrap_or(0); + return Err(format!("unsupported {name} hwreg {} offset {} size {}", s & 0x3F, (s >> 6) & 0x1F, ((s >> 11) & 0x1F) + 1)); + } n => return Err(format!("unsupported {n}")), } Ok(()) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index b9d6d86867..d67a0ca3e5 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -423,7 +423,7 @@ impl RecompAgg { self.cs_forms[5] += b.len(); } if let Err(e) = &lane { - let key: String = e.split([':', '(']).next().unwrap_or("").split_whitespace().take(3).collect::>().join(" "); + let key: String = e.split([':', '(']).next().unwrap_or("").split_whitespace().take(5).collect::>().join(" "); *self.cs_lane_why.entry(key).or_default() += 1; } } From a5311f7f66025655b91899d3c72811790b5b0127 Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 18:03:14 +0100 Subject: [PATCH 14/51] Recompiler: thread ids of any compute group shape in the lowering's Ir `Ir::thread_id(k)` becomes `Ir::compute_ids(threads) -> (flat, [x, y, z])`: the thread's flat index in its group and that thread's id, numbered as the console does (a wave takes consecutive threads, lane l the l-th). The compute prologue takes the thread-id VGPRs and TG_SIZE's wave index from it, and `lower_compute` no longer refuses 2-D / 3-D groups. The CPU interpreter derives the ids from its wave's first thread plus the lane. The DXIL adapter keeps 1-D groups only (SV_GroupThreadID.x) and `lower_dxil::compute` refuses the others until `Lw::setup_lanes_compute` (#1426) is reachable from `DxilIr`, which will number 2-D / 3-D threads by arrival. Tests: an 8x8x1 and a 4x4x4 group storing each thread's ids and lane, on the CPU in wave32 and wave64, and against the HLSL path (which numbers by arrival) on the GPU. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XTYmP5ub3Zjdi8PYaDNwsV --- crates/xcl/src/gpu/recomp/lower.rs | 147 ++++++++++++++++++++---- crates/xcl/src/gpu/recomp/lower_dxil.rs | 12 +- 2 files changed, 134 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 5ac4437ef2..a28812660d 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -66,9 +66,13 @@ pub trait Ir: Sink { fn zext(&mut self, b: Self::V) -> Self::V; /// the console lane of this thread fn lane(&mut self) -> Self::V; - /// compute: the group's id and the thread's id in its group, component k (x, y, z) + /// compute: the group's id, component k (x, y, z) fn group_id(&mut self, k: u32) -> Self::V; - fn thread_id(&mut self, k: u32) -> Self::V; + /// compute, a group of `threads`: this thread's console thread (its flat index in the group) + /// and that thread's id (x, y, z). The console forms a wave from consecutive threads, lane l + /// the l-th of them, so the flat index is the wave's first thread plus `lane()`; a PC driver + /// need not, in 2-D / 3-D groups, so the threads are numbered as the waves arrive + fn compute_ids(&mut self, threads: [u32; 3]) -> (Self::V, [Self::V; 3]); /// the wave's ballot of `c`: lanes 0–31, 32–63 fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; /// `ballot` where only the word of this lane's 32-lane half is used (the other may be @@ -835,13 +839,8 @@ pub fn lower_kernel(insts: &[Decoded], wave64: bool, ir: I) -> R<(I, Vec< lower(insts, Stage::Kernel, wave64, ir) } -/// Lowers a compute program (far jumps resolved) into `ir`. One-dimensional groups only for -/// now: in a 2-D / 3-D group the PC driver need not give a wave consecutive threads, which the -/// console does (`emit` reorders them; not done here yet). +/// Lowers a compute program (far jumps resolved) into `ir`. pub fn lower_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> R { - if cs.threads[1] * cs.threads[2] > 1 { - return Err("2-D / 3-D thread group".into()); - } Ok(lower(insts, Stage::Compute(cs), wave64, ir)?.0) } @@ -984,6 +983,7 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( l.ir.br(exit); } Stage::Compute(cs) => { + let (flat, tid) = l.ir.compute_ids(cs.threads); // system SGPRs after the user data: the enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u8; for k in 0..3 { @@ -997,9 +997,8 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( // waves in the group (a last partial one counts) | this wave's index << 6 let lanes = if wave64 { 64 } else { 32 }; let waves = l.ir.int(cs.threads.iter().product::().div_ceil(lanes)); - let t = l.ir.thread_id(0); let sh = l.ir.int(lanes.trailing_zeros()); - let w = l.ir.bin(Bin::LShr, t, sh); + let w = l.ir.bin(Bin::LShr, flat, sh); let six = l.ir.int(6); let w = l.ir.bin(Bin::Shl, w, six); let v = l.ir.bin(Bin::Or, waves, w); @@ -1009,9 +1008,9 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( l.ssa.write(0, Var::Scc, f); for &v in &vregs { let x = match v { - 0 => l.ir.thread_id(0), - 1 if cs.tid_components >= 2 => l.ir.thread_id(1), - 2 if cs.tid_components >= 3 => l.ir.thread_id(2), + 0 => tid[0], + 1 if cs.tid_components >= 2 => tid[1], + 2 if cs.tid_components >= 3 => tid[2], _ => l.ir.int(0), }; l.ssa.write(0, Var::V(v), x); @@ -1241,7 +1240,10 @@ pub(crate) mod tests { Zext(u32), Lane, GroupId(u32), - ThreadId(u32), + /// the flat thread index in the group: the wave's first thread + lane + Flat, + /// component k of a flat index `v` in a group whose x, y sizes are given + ThreadId(u32, u32, [u32; 2]), Ballot(u32, usize), ReadLane(u32, u32), /// as `Ballot` and `ReadLane`, but the lowering may use only its own 32-lane half's part @@ -1357,8 +1359,10 @@ pub(crate) mod tests { fn group_id(&mut self, k: u32) -> u32 { self.push(Ins::GroupId(k)) } - fn thread_id(&mut self, k: u32) -> u32 { - self.push(Ins::ThreadId(k)) + fn compute_ids(&mut self, threads: [u32; 3]) -> (u32, [u32; 3]) { + let flat = self.push(Ins::Flat); + let xy = [threads[0], threads[1]]; + (flat, [0, 1, 2].map(|k| self.push(Ins::ThreadId(k, flat, xy)))) } fn ballot(&mut self, c: u32) -> [u32; 2] { [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] @@ -1490,7 +1494,12 @@ pub(crate) mod tests { Ins::Zext(b) => Some(g(b)), Ins::Lane => Some(lane as u32), Ins::GroupId(k) => Some(group[*k as usize]), - Ins::ThreadId(k) => Some(if *k == 0 { base + lane as u32 } else { 0 }), + Ins::Flat => Some(base + lane as u32), + Ins::ThreadId(k, v, [x, y]) => Some(match k { + 0 => g(v) % x, + 1 => g(v) / x % y, + _ => g(v) / (x * y), + }), Ins::Ballot(..) | Ins::BallotHalf(..) | Ins::ReadLane(..) | Ins::ReadLaneHalf(..) => break, Ins::CountBits(v) => Some(g(v).count_ones()), Ins::IoLoad(a) => Some(io[g(a) as usize]), @@ -1650,19 +1659,68 @@ pub(crate) mod tests { /// A compute program run on the CPU over `groups` groups (wave32): the memory after. pub(crate) fn run_compute(lines: &[I], cs: &crate::gpu::recomp::CsInterface, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { - let ir = lower_compute(&decode(lines), cs, false, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + run_compute_waves(lines, cs, false, groups, sgprs, mem) + } + + /// … in wave32 or wave64: each wave takes the next `lanes` threads of its group, as on the + /// console (the last one fewer). + pub(crate) fn run_compute_waves(lines: &[I], cs: &crate::gpu::recomp::CsInterface, wave64: bool, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + let ir = lower_compute(&decode(lines), cs, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let lanes = if wave64 { 64 } else { 32 }; let mut io = vec![0u32; KERNEL_SGPRS]; io[..sgprs.len()].copy_from_slice(sgprs); let mut res = vec![0u32; KERNEL_SGPRS]; let mut mem = mem.to_vec(); + let threads: u32 = cs.threads.iter().product(); for g in 0..groups { - for w in 0..cs.threads[0].div_ceil(32) { - ir.run_with(32, w * 32, [g, 0, 0], &io, &mut res, &mut mem); + for w in (0..threads).step_by(lanes as usize) { + ir.run_with(lanes.min(threads - w) as usize, w, [g, 0, 0], &io, &mut res, &mut mem); } } mem } + /// 2-D and 3-D groups of 64 threads. + pub(crate) const ID_SHAPES: [[u32; 3]; 2] = [[8, 8, 1], [4, 4, 4]]; + + /// Each thread of a 64-thread group of an `ID_SHAPES` shape stores its ids and its lane + /// (`mbcnt` of EXEC) as `x | y << 8 | z << 16 | lane << 24` at word `group * 64 + flat index`. + pub(crate) fn ids_program(threads: [u32; 3], wave64: bool) -> Vec { + let mut p: Vec = vec![("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)])]; + // v4 = flat index: (y << 3) + x, or (z << 4) + (y << 2) + x + if threads[2] == 1 { + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 131), ("SRC2", V)])); + } else { + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 130), ("SRC2", V)])); + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 2), ("SRC1", 132), ("SRC2", V + 4)])); + } + // v[8:9] = (group * 64 + flat) * 4; v5 = lane + p.extend_from_slice(&[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 3), ("VSRC1", 4)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 126), ("SRC1", 128)]), + ]); + if wave64 { + p.push(("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 127), ("SRC1", V + 5)])); + } + p.push(("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 1), ("SRC1", 136), ("SRC2", V)])); + if threads[2] > 1 { + p.push(("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 144), ("SRC2", V + 7)])); + } + p.extend_from_slice(&[ + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 152), ("SRC2", V + 7)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]); + p + } + + pub(crate) fn ids_cs(threads: [u32; 3]) -> crate::gpu::recomp::CsInterface { + let tid_components = if threads[2] > 1 { 3 } else { 2 }; + crate::gpu::recomp::CsInterface { threads, tid_components, ..compute_cs() } + } + pub(crate) fn memory_image() -> Vec { (0..256).map(|i| 1000 + i).collect() } @@ -1939,9 +1997,52 @@ pub(crate) mod tests { assert_eq!(mem[(64 * g + t) as usize], 3 * t + 100 + g, "group {g} thread {t}"); } } - // 2-D groups are not lowered yet - let cs = crate::gpu::recomp::CsInterface { threads: [8, 8, 1], ..compute_cs() }; - assert!(lower_compute(&decode(COMPUTE), &cs, false, Interp::default()).is_err()); + } + + #[test] + fn a_2d_or_3d_group_numbers_its_threads_as_the_console_does() { + // a wave takes consecutive threads, lane l the l-th: x fastest, then y, then z + for threads in ID_SHAPES { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let mem = run_compute_waves(&ids_program(threads, wave64), &ids_cs(threads), wave64, 2, &[100, 0], &[0u32; 256]); + for g in 0..2u32 { + for t in 0..64u32 { + let (x, y, z) = (t % threads[0], t / threads[0] % threads[1], t / (threads[0] * threads[1])); + let want = x | y << 8 | z << 16 | (t % lanes) << 24; + assert_eq!(mem[(64 * g + t) as usize], want, "{threads:?} wave64 {wave64}: group {g} thread {t}"); + } + } + } + } + } + + /// The same through the HLSL path on the GPU, which numbers the threads by arrival. + #[test] + fn a_2d_or_3d_group_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Mode, Options}; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + return; + } + for wave64 in [false, true] { + if wave64 && runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, wave64); + let cs = ids_cs(threads); + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(&lines, &cs, wave64, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?} wave64 {wave64}"); + } + } } /// The compute program through the HLSL path on the GPU and through the lowering on the CPU. diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index f43359c8da..cf6e3b6f98 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -120,8 +120,13 @@ impl Ir for DxilIr { fn group_id(&mut self, k: u32) -> Value { self.s.group_id(k) } - fn thread_id(&mut self, k: u32) -> Value { - self.s.thread_id_in_group(k) + fn compute_ids(&mut self, threads: [u32; 3]) -> (Value, [Value; 3]) { + // 1-D groups only until `Lw::setup_lanes_compute` numbers 2-D / 3-D threads by arrival + // (`compute` refuses the others): a 1-D group's waves are its consecutive threads + debug_assert!(threads[1] * threads[2] == 1); + let flat = self.s.thread_id_in_group(0); + let zero = self.s.m.i32c(0); + (flat, [flat, zero, zero]) } fn ballot(&mut self, c: Value) -> [Value; 2] { let w = self.s.wave_ballot(c); @@ -194,6 +199,9 @@ pub fn compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Resul /// A compute program in its per-lane form, as a signed DXIL container. pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { + if cs.threads[1] * cs.threads[2] > 1 { + return Err("2-D / 3-D thread group (waits for Lw::setup_lanes_compute)".into()); + } let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(false))?; Ok(ir.s.finish(cs.threads, Some(if wave64 { 64 } else { 32 }))) } From 9816a852f38ea7686ab2ec44ef1b9f386befc917 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:13:19 -0300 Subject: [PATCH 15/51] Recompiler: drop trivial phis through Module::replace_all_uses in the DXIL adapter #1426 now has replace_all_uses (and writes blocks in reverse post-order). A phi the SSA construction finds trivial has its uses replaced instead of keeping identical incoming values. --- crates/xcl/src/gpu/recomp/lower_dxil.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index cf6e3b6f98..4ace960b97 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -4,8 +4,8 @@ //! `Ir` maps one to one onto the builder: blocks, phis (`phi_at` / `add_incoming`), integer //! ops, compares, `select`, the thread / group / lane ids, `waveActiveBallot`, and raw buffer //! loads and stores on the ABI's root UAVs (u0 `io`, u1 `res`, u2 `mem`). A phi the SSA -//! construction finds trivial keeps its (identical) incoming values instead of being removed: -//! the builder has no use replacement, and the driver folds such phis. +//! construction finds trivial has its uses replaced (`Module::replace_all_uses`); the phi itself +//! stays in its block, unused. use super::lower::{self, Bin, Cmp, Ir}; use super::ssa::{Sink, Var}; @@ -54,8 +54,9 @@ impl Sink for DxilIr { fn incoming(&mut self, phi: Value, value: Value, pred: usize) { self.s.m.add_incoming(phi, value, self.blocks[pred]); } - fn replace(&mut self, _old: Value, _new: Value) { - // kept: its incoming values are all `new` (or itself), which is a valid phi + fn replace(&mut self, old: Value, new: Value) { + // every use of the trivial phi becomes `new`; the phi stays in its block, unused + self.s.m.replace_all_uses(old, new); } fn undef(&mut self, var: Var) -> Value { let t = self.ty(var); From 6bdef802ff83a3fd03b09c88204ac0fac4c7c79c Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:32:09 -0300 Subject: [PATCH 16/51] Tests: the IR assemble test skips without dxil.dll; survey sizes in KB A Windows SDK's bin\\x64 has dxcompiler.dll without dxil.dll, so ir_text_assembles_signs_and_runs failed with 'no dxil.dll to sign with' instead of skipping (reported by justrhoto on #1269). The coverage survey prints the both-forms DXIL size in KB while coverage is small. --- crates/xcl/src/gpu/recomp/dxil/assemble.rs | 9 ++++++++- crates/xcl/src/shaders.rs | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxil/assemble.rs b/crates/xcl/src/gpu/recomp/dxil/assemble.rs index 29184c496a..490db860aa 100644 --- a/crates/xcl/src/gpu/recomp/dxil/assemble.rs +++ b/crates/xcl/src/gpu/recomp/dxil/assemble.rs @@ -107,7 +107,14 @@ attributes #1 = { nounwind } runner::skip_test("no DXC"); return; } - let dxil = super::assemble(IR).unwrap(); + // a Windows SDK's `bin\\x64` has dxcompiler.dll without dxil.dll: nothing to sign with + let dxil = match super::assemble(IR) { + Err(e) if e.contains("no dxil.dll") => { + runner::skip_test("no dxil.dll"); + return; + } + r => r.unwrap(), + }; assert_eq!(&dxil[..4], b"DXBC"); let bad = super::assemble(&IR.replace("%3 = mul i32 %2, 3", "%3 = mul i32 %4, 3")).unwrap_err(); assert!(bad.contains("dominate"), "{bad}"); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index d67a0ca3e5..7591d5ded0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1544,8 +1544,8 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim let mut why: Vec<_> = rc.cs_lane_why.iter().collect(); why.sort_by(|a, b| b.1.cmp(a.1)); println!( - "compute programs, direct DXIL: {} tried; per-lane form {} ok, per-instruction form (#1426) {} ok; where both are ok ({}): per-lane {:.1} MB, per-instruction {:.1} MB of DXIL; per-lane refused for: {:?}", - c[0], c[1], c[2], c[3], c[4] as f64 / 1048576.0, c[5] as f64 / 1048576.0, &why[..why.len().min(15)] + "compute programs, direct DXIL: {} tried; per-lane form {} ok, per-instruction form (#1426) {} ok; where both are ok ({}): per-lane {} KB, per-instruction {} KB of DXIL; per-lane refused for: {:?}", + c[0], c[1], c[2], c[3], c[4] / 1024, c[5] / 1024, &why[..why.len().min(15)] ); let l = &rc.lanes; println!( From 85937007e01f181014479b793d4184eeea611a9a Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:17:01 -0500 Subject: [PATCH 17/51] Recompiler: survey every per-lane refusal, and the mesh pass both ways The coverage survey (`xcl shaders --recomp`) gave only the first reason the per-lane form refuses a program, and built compute programs only. It now also lowers each CS and MS program in a survey mode that notes every refusal and goes on past a refused instruction, and prints per stage: the programs each form covers, the wave64 ones, those refused only for instructions (no structural reason), every per-lane reason, the only structural reason of a program, and why #1426's per-instruction form refused (`translate_mesh` for the mesh pass). A refused instruction leaves the SGPRs (and, for a scalar instruction, SCC) it writes as 0 in both views, so that a later read does not report a refusal that only follows from it: without that, a skipped `s_cselect_b64 s[0:1], exec, 0` made every mesh program report a value written while some lanes were elsewhere. The mesh pass is surveyed as a compute program of its threads in a 1-D group (the per-lane form has no mesh stage yet), so its exports and `s_sendmsg` show as refused instructions. A 2-D / 3-D group is noted as `compute` refuses it and the rest surveyed as a 1-D group. `XCL_RECOMP_STAGES=CS,MS` keeps the survey to those stages and `XCL_RECOMP_NO_HLSL=1` skips the HLSL translation: the direct DXIL survey of a retail pack's 2 689 CS and 9 282 MS programs takes 57 s. There, #1426's per-instruction form takes all of them; the per-lane form takes 4 CS and no MS; every MS program is wave64 and the lane-mask analysis takes all of them (no indirect jump, no irreducible loop). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 127 ++++++++++++++++------ crates/xcl/src/gpu/recomp/lower_dxil.rs | 25 +++++ crates/xcl/src/shaders.rs | 137 ++++++++++++++++++++++++ 3 files changed, 258 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index a28812660d..96251963c4 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -131,6 +131,8 @@ struct Lower<'a, I: Ir> { /// a DPP instruction's first source, read from its source lane, and its write enable dpp_src: Option, dpp_en: Option, + /// survey mode (`survey_compute`): every refusal is noted here and the lowering goes on + noted: Option>, } /// A vector memory store: a side effect inactive lanes must not have. @@ -844,7 +846,21 @@ pub fn lower_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: Ok(lower(insts, Stage::Compute(cs), wave64, ir)?.0) } -fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<(I, Vec)> { +fn lower(insts: &[Decoded], stage: Stage, wave64: bool, ir: I) -> R<(I, Vec)> { + lower_with(insts, stage, wave64, ir, false).map(|(ir, stale, _)| (ir, stale)) +} + +/// Survey: every reason the per-lane form refuses a compute program, not only the first. An +/// instruction it refuses is left out and the lowering goes on, so a later reason may follow +/// from an earlier one; a program the lane-mask analysis refuses gives that one reason. +pub fn survey_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> Vec { + match lower_with(insts, Stage::Compute(cs), wave64, ir, true) { + Ok((_, _, noted)) => noted, + Err(e) => vec![e], + } +} + +fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, survey: bool) -> R<(I, Vec, Vec)> { let kernel = matches!(stage, Stage::Kernel); let sum = lane_masks::analyze(insts, wave64).map_err(|e| e.to_string())?; let n = sum.blocks.len(); @@ -926,6 +942,7 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( lane_uses: Vec::new(), dpp_src: None, dpp_en: None, + noted: survey.then(Vec::new), }; // the registers the program names, and the ones the runner reads back let mut sregs: Vec = vec![VCC, VCC + 1, 124, EXEC, EXEC + 1]; @@ -1067,35 +1084,46 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( done[cur] = true; l.ir.at(s); l.ssa.seal(&mut l.ir, s); - l.vmem(s, d)?; + let r = l.vmem(s, d); + l.note_inst(r, s, d)?; l.ir.br(c); done[s] = true; l.ir.at(c); l.ssa.seal(&mut l.ir, c); cur = c; - } else if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { - l.smem(cur, d)?; - } else if name.starts_with("S_") { - l.salu(cur, d)?; - } else if name.starts_with("V_") { - l.valu(cur, d)?; - } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { - l.vmem(cur, d)?; - } else if name == "DS_SWIZZLE_B32" { - l.swizzle(cur, d)?; } else { - return Err(format!("unsupported {name}")); + let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { + l.smem(cur, d) + } else if name.starts_with("S_") { + l.salu(cur, d) + } else if name.starts_with("V_") { + l.valu(cur, d) + } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { + l.vmem(cur, d) + } else if name == "DS_SWIZZLE_B32" { + l.swizzle(cur, d) + } else { + Err(format!("unsupported {name}")) + }; + l.note_inst(r, cur, d)?; } } match block.succ.as_slice() { [] => l.ir.br(exit), [(t, Edge::Always)] => l.ir.br(blk(*t)), [(t, _), (f, _)] if t == f => l.ir.br(blk(*t)), - [(t, Edge::Taken), (f, Edge::NotTaken)] => { - let c = l.cond(cur, &insts[last])?; - l.ir.br_if(c, blk(*t), blk(*f)); + [(t, Edge::Taken), (f, Edge::NotTaken)] => match l.cond(cur, &insts[last]) { + Ok(c) => l.ir.br_if(c, blk(*t), blk(*f)), + Err(e) => { + l.note(Err(e))?; + let c = l.ir.boolean(true); + l.ir.br_if(c, blk(*t), blk(*f)); + } + }, + s => { + l.note(Err(format!("block {b}: successors {s:?}")))?; + l.ir.br(blk(s[0].0)); } - s => return Err(format!("block {b}: successors {s:?}")), } done[cur] = true; for &(s, _) in &block.succ { @@ -1201,25 +1229,49 @@ fn lower(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I) -> R<( impl Lower<'_, I> { /// Every phi is complete: no number may come from a mask, nor a mask bit from a number, nor /// a lane read a mask bit it kept from before a write it skipped. - fn finish(self, mut stale: Vec) -> R<(I, Vec)> { - for &v in &self.num_uses { - if self.reaches(v, self.num_marker) { - return Err("a mask read as a number (through a join)".into()); - } + fn finish(mut self, mut stale: Vec) -> R<(I, Vec, Vec)> { + if self.num_uses.iter().any(|&v| self.reaches(v, self.num_marker)) { + self.note(Err("a mask read as a number (through a join)".into()))?; } - for &v in &self.bit_uses { - if self.reaches(v, self.bit_marker) { - return Err("a number read as a mask (through a join)".into()); - } + if self.bit_uses.iter().any(|&v| self.reaches(v, self.bit_marker)) { + self.note(Err("a number read as a mask (through a join)".into()))?; } - for &(c, v) in &self.lane_uses { - if self.stale(c, v) { - return Err("a value written while some lanes were elsewhere, read after they met again".into()); - } + if self.lane_uses.iter().any(|&(c, v)| self.stale(c, v)) { + self.note(Err("a value written while some lanes were elsewhere, read after they met again".into()))?; } stale.sort_unstable(); stale.dedup(); - Ok((self.ir, stale)) + Ok((self.ir, stale, self.noted.unwrap_or_default())) + } + + /// A refused instruction in block b: as `note`, and in survey mode the SGPRs (and, for a + /// scalar instruction, SCC) it writes are left as 0 in both views (number and mask bit), + /// so that a later read does not report a refusal that only follows from this one. + fn note_inst(&mut self, r: R<()>, b: usize, d: &Decoded) -> R<()> { + if r.is_err() && self.noted.is_some() { + let (z, f) = (self.ir.int(0), self.ir.boolean(false)); + for s in rdna2::sgpr_uses(d).1 { + if s < KERNEL_SGPRS as u64 && s != 125 { + self.ssa.write(b, Var::S(s as u8), z); + self.ssa.write(b, Var::M(s as u8), f); + } + } + if d.inst.name.starts_with("S_") { + self.ssa.write(b, Var::Scc, f); + } + } + self.note(r) + } + + /// A refusal: the error, or in survey mode noted and passed over. + fn note(&mut self, r: R<()>) -> R<()> { + match (r, &mut self.noted) { + (Err(e), Some(n)) => { + n.push(e); + Ok(()) + } + (r, _) => r, + } } } @@ -1778,6 +1830,19 @@ pub(crate) mod tests { } } + /// The survey goes on past a refused instruction: both are reported, and a program the + /// lowering takes gives none. + #[test] + fn the_survey_reports_every_refusal() { + let mut lines = STRAIGHT.to_vec(); + lines.insert(2, ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)])); + lines.insert(4, ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)])); + let cs = compute_cs(); + assert!(lower_compute(&decode(&lines), &cs, false, Interp::default()).is_err()); + assert_eq!(survey_compute(&decode(&lines), &cs, false, Interp::default()), ["unsupported V_ADD_F32", "unsupported V_MUL_F32"]); + assert!(survey_compute(&decode(STRAIGHT), &cs, false, Interp::default()).is_empty()); + } + #[test] fn a_skipped_if_runs_only_its_lanes() { let (s, v) = state(32); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 4ace960b97..c7931e903e 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -198,6 +198,31 @@ pub fn compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Resul compute(&insts, cs, wave64) } +/// Survey: every reason the per-lane form refuses a compute program (`lower::survey_compute`). +pub fn survey_compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Vec { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + match crate::gpu::rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + insts.push(d); + } + Err(e) => return vec![format!("cannot decode ({e:?})")], + } + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + // a 2-D / 3-D group is noted as `compute` refuses it, and the rest surveyed as a 1-D group + // of as many threads (the thread ids differ, the instructions are the same) + if cs.threads[1] * cs.threads[2] > 1 { + let flat = super::CsInterface { threads: [cs.threads.iter().product(), 1, 1], ..cs.clone() }; + let mut why = vec!["2-D / 3-D thread group (waits for Lw::setup_lanes_compute)".to_string()]; + why.extend(lower::survey_compute(&insts, &flat, wave64, DxilIr::new(false))); + return why; + } + lower::survey_compute(&insts, cs, wave64, DxilIr::new(false)) +} + /// A compute program in its per-lane form, as a signed DXIL container. pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { if cs.threads[1] * cs.threads[2] > 1 { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 7591d5ded0..0374628a55 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -318,6 +318,15 @@ struct RecompAgg { /// both are ok; why the per-lane form refused (first words of the reason) cs_forms: [usize; 6], cs_lane_why: BTreeMap, + /// survey of every refusal, per stage (CS, MS): tried, wave64, per-lane ok, per-instruction + /// ok, both ok, per-lane refused only for instructions (no structural reason), the same with + /// the per-instruction form ok, refused by the lane-mask analysis + forms: BTreeMap, + /// "stage | reason" → programs (each reason once per program): every per-lane reason, the + /// structural ones that are a program's only structural reason, the per-instruction reasons + lane_every: BTreeMap, + lane_sole: BTreeMap, + inst_why: BTreeMap, } impl RecompAgg { @@ -370,6 +379,16 @@ impl RecompAgg { for (k, v) in o.cs_lane_why { *self.cs_lane_why.entry(k).or_default() += v; } + for (k, v) in o.forms { + for (a, b) in self.forms.entry(k).or_default().iter_mut().zip(v) { + *a += b; + } + } + for (m, o) in [(&mut self.lane_every, o.lane_every), (&mut self.lane_sole, o.lane_sole), (&mut self.inst_why, o.inst_why)] { + for (k, v) in o { + *m.entry(k).or_default() += v; + } + } } fn add(&mut self, name: &str, code: &[u8], keep: usize, mode: recomp::Mode) { @@ -379,6 +398,20 @@ impl RecompAgg { return; } } + // `XCL_RECOMP_STAGES=CS,MS`: only programs of these stages + if let Ok(st) = std::env::var("XCL_RECOMP_STAGES") { + let l = match &mode { + recomp::Mode::Vertex(_) => "VS", + recomp::Mode::Pixel(_) => "PS", + recomp::Mode::Kernel => "kernel", + recomp::Mode::Mesh(_) => "MS", + recomp::Mode::Geometry(_) => "GS", + recomp::Mode::Compute(_) => "CS", + }; + if !st.split(',').any(|x| x == l) { + return; + } + } self.programs += 1; let wave64 = recomp::detect_wave64(code); self.wave32 += !wave64 as usize; @@ -427,6 +460,39 @@ impl RecompAgg { *self.cs_lane_why.entry(key).or_default() += 1; } } + let survey_cs = match &mode { + recomp::Mode::Compute(cs) => Some(("CS", cs.clone())), + // the mesh pass is a compute pass of the NGG program: its threads in a 1-D group + recomp::Mode::Mesh(ms) => Some(("MS", recomp::CsInterface { threads: [ms.threads, 1, 1], tid_components: 1, ..Default::default() })), + _ => None, + }; + if let Some((st, cs)) = survey_cs { + let lane = recomp::lower_dxil::survey_compute_code(code, &cs, wave64); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let inst = match &mode { + recomp::Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).map(|_| ()), + _ => crate::gpu::dxil::kernel::translate_compute(code, o, &cs).map(|_| ()), + }; + let mut keys: Vec<(String, bool)> = lane.iter().map(|r| (survey_key(r), survey_structural(r))).collect(); + keys.sort(); + keys.dedup(); + let structural: Vec<&String> = keys.iter().filter(|k| k.1).map(|k| &k.0).collect(); + let lm = lane.len() == 1 && ["lane conditions", "indirect jump", "branch to the entry", "irreducible", "no fixpoint", "cannot decode"].iter().any(|w| lane[0].starts_with(w)); + let f = self.forms.entry(st.to_string()).or_default(); + let bridge = !lane.is_empty() && structural.is_empty(); + for (i, c) in [true, wave64, lane.is_empty(), inst.is_ok(), lane.is_empty() && inst.is_ok(), bridge, bridge && inst.is_ok(), lm].into_iter().enumerate() { + f[i] += c as usize; + } + for (k, _) in &keys { + *self.lane_every.entry(format!("{st} | {k}")).or_default() += 1; + } + if let [k] = structural[..] { + *self.lane_sole.entry(format!("{st} | {k}")).or_default() += 1; + } + if let Err(e) = &inst { + *self.inst_why.entry(format!("{st} | {}", survey_key(e.lines().next().unwrap_or("")))).or_default() += 1; + } + } match recomp::lane_masks::analyze_code(code, wave64) { Ok(s) => { let counts = [1, s.guarded.is_empty() as usize, s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches]; @@ -436,6 +502,10 @@ impl RecompAgg { } Err(why) => *self.lanes_failed.entry(why.to_string()).or_default() += 1, } + // `XCL_RECOMP_NO_HLSL=1`: the direct DXIL survey alone + if std::env::var("XCL_RECOMP_NO_HLSL").is_ok() { + return; + } // `XCL_RECOMP_WINDOWS=4`: as a title with unified memory translates (`pso::mem_windows`) let mem_windows = std::env::var("XCL_RECOMP_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1); match recomp::translate(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) { @@ -1547,6 +1617,25 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim "compute programs, direct DXIL: {} tried; per-lane form {} ok, per-instruction form (#1426) {} ok; where both are ok ({}): per-lane {} KB, per-instruction {} KB of DXIL; per-lane refused for: {:?}", c[0], c[1], c[2], c[3], c[4] / 1024, c[5] / 1024, &why[..why.len().min(15)] ); + for (st, f) in &rc.forms { + println!( + "{st} programs, every refusal: {} tried ({} wave64); per-lane ok {}, per-instruction ok {}, both {}; per-lane refused for instructions only {} (per-instruction ok on {} of them); lane-mask analysis refused {}", + f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7] + ); + } + for (title, m) in [ + ("per-lane reasons (stage | reason → programs; [S] structural)", &rc.lane_every), + ("the only structural reason of a program (stage | reason → programs)", &rc.lane_sole), + ("per-instruction form (#1426) refused (stage | first line → programs)", &rc.inst_why), + ] { + let mut v: Vec<_> = m.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0))); + println!("{title}:"); + for (k, n) in v.iter().take(top.max(40)) { + let tag = if survey_structural(k.split(" | ").nth(1).unwrap_or("")) { "[S] " } else { "" }; + println!(" {n:>6} {tag}{k}"); + } + } let l = &rc.lanes; println!( "lane masks (direct DXIL, no EXEC emulation): analysed {} of {} programs, {} with no guard left; vector instructions {}, still guarded {} ({:.1}%); branches per lane {}, uniform {}; not analysed: {:?}", @@ -1881,3 +1970,51 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: } 0 } + +/// A survey reason without its program's numbers: registers as `sN`, other numbers as `N` +/// (an `s_setreg`'s hardware register is kept), at most eight words. +fn survey_key(r: &str) -> String { + let r = r.split(" (").next().unwrap_or(r); + let words: Vec<&str> = r.split_whitespace().collect(); + let mut out: Vec = Vec::new(); + for (i, raw) in words.iter().enumerate() { + let w = raw.trim_end_matches([':', ',']); + let digits = |x: &str| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit()); + let w = if w.strip_prefix('s').is_some_and(digits) { + "sN".to_string() + } else if digits(w) && !(i > 0 && words[i - 1] == "hwreg") { + "N".to_string() + } else { + w.to_string() + }; + out.push(if raw.ends_with(':') { format!("{w}:") } else { w }); + if out.len() == 8 { + break; + } + } + out.join(" ") +} + +/// A per-lane refusal no instruction lowering removes (the CFG, masks across joins, lanes +/// elsewhere, the group shape), as opposed to an instruction the per-lane form lacks. +fn survey_structural(r: &str) -> bool { + [ + "2-D / 3-D", + "elsewhere", + "read as a number", + "read as a mask", + "across two masks", + "successors", + "unsupported branch", + "neither a number nor a mask", + "empty program", + "lane conditions", + "indirect jump", + "branch to the entry", + "irreducible", + "no fixpoint", + "cannot decode", + ] + .iter() + .any(|w| r.contains(w)) +} From f9be7ccf80b0ece967a99e2b4349dbc0b0d5cec0 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:44:21 -0300 Subject: [PATCH 18/51] Recompiler: an unsupported VALU opcode is refused before its sources are read An unsupported VOP1 (e.g. v_bfrev_b32) has no SRC1; reading its sources first took the absent field as s0 and reported 'sN: a mask read as a number' instead of the instruction (found by Kalmarv's every-reason survey on #1269). --- crates/xcl/src/gpu/recomp/lower.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 96251963c4..7e68d9e404 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -566,6 +566,15 @@ impl<'a, I: Ir> Lower<'a, I> { self.ir.select(m, c, a) } _ => { + // the opcode first: an unsupported VOP1 has no SRC1, which would read as s0 + const TWO_SOURCE: &[&str] = &[ + "V_ADD_NC_U32", "V_ADD_U32", "V_SUB_NC_U32", "V_SUB_U32", "V_SUBREV_NC_U32", "V_SUBREV_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", + "V_MUL_LO_U32", "V_LSHL_ADD_U32", "V_ADD_LSHL_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XOR3_B32", "V_ADD3_U32", + "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", + ]; + if !TWO_SOURCE.contains(&name) { + return Err(format!("unsupported {name}")); + } let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); let c31 = self.ir.int(31); match name { From acdf922a7b7aa17a6a77fc1abb49ccbc2f7944d0 Mon Sep 17 00:00:00 2001 From: upipibi Date: Tue, 24 Nov 2026 11:21:38 -0600 Subject: [PATCH 19/51] Recompiler: whole-wave mask reads need every lane where an Ir meets another wave Ir::whole_needs_exchange (default false): an Ir whose whole-wave ballot / read_lane meets another hardware wave (the split form of a wave64 program, two wave32s) needs both halves to reach it. The lowering then refuses a mask read as a number, EXEC included, in a block lanes leave one by one (`partial`), as it already does for any read of a lane there. The half-local reads (ballot_half) are unchanged. No Ir sets it yet, so nothing changes for the lowerings on this branch. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 5 +++++ crates/xcl/src/gpu/recomp/lower/wave.rs | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 7e68d9e404..59dab305f4 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -83,6 +83,11 @@ pub trait Ir: Sink { fn read_lane(&mut self, v: Self::V, lane: Self::V) -> Self::V; /// `read_lane` of a lane in this lane's 32-lane half (DPP, permlane, swizzle) fn read_lane_half(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// Whether a whole-wave `ballot` / `read_lane` meets another hardware wave (the split form + /// of a wave64 program): then it needs every lane of the console wave where it runs. + fn whole_needs_exchange(&self) -> bool { + false + } /// the number of bits set in `v` (`countbits`) fn count_bits(&mut self, v: Self::V) -> Self::V; fn io_load(&mut self, dword: Self::V) -> Self::V; diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs index 09d21fd5e1..0d63229a80 100644 --- a/crates/xcl/src/gpu/recomp/lower/wave.rs +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -50,7 +50,7 @@ impl Lower<'_, I> { /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits; with `half`, /// only this lane's half of it is right (`Ir::ballot_half`). fn mask_words(&mut self, b: usize, r: u8, half: bool) -> R<[I::V; 2]> { - if r != EXEC { + if r != EXEC || (!half && self.ir.whole_needs_exchange()) { self.all_lanes(b, "a mask read as a number")?; } let bit = self.read_bit(b, r)?; @@ -118,6 +118,10 @@ impl Lower<'_, I> { /// The lanes in EXEC, as numbers; with `half`, only this lane's half is right. fn exec_words(&mut self, b: usize, half: bool) -> R<[I::V; 2]> { + // split: the other half's word comes through an exchange, which both halves must reach + if !half && self.ir.whole_needs_exchange() { + self.all_lanes(b, "EXEC as a number in the split form")?; + } let e = self.read_bit(b, EXEC)?; let [lo, hi] = if half { self.ir.ballot_half(e) } else { self.ir.ballot(e) }; Ok([lo, if self.wave64 { hi } else { self.ir.int(0) }]) From 9231d486d1d8509d9d46aef400cc090fcb28fc39 Mon Sep 17 00:00:00 2001 From: Vlad Bondarenko <12616782+vladbondarenko97@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:27:06 -0600 Subject: [PATCH 20/51] Tests: f32 programs for the per-lane lowering, on the HLSL path and per lane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six f32 programs (arithmetic with VOP3 modifiers, the 16 compares, conversions, rounding, transcendentals, literal-operand and three-source ops; NaN, ties, signed zeros, f16 denormals and out-of-range values among their inputs) and `f32_programs_on_the_gpu`, which for each: - runs it on the HLSL path on the GPU and checks every register against values computed in Rust (`check_f32_*`; wave32), the transcendentals within the tolerance of gpu::dxil's `approximate_float_unary_ops_are_within_tolerance`; - where the per-lane form lowers the program, compares its DXIL on the GPU with the HLSL path, register for register (rcp within that tolerance: HLSL's `rcp` is a fast fdiv), wave32 and, where the GPU has 64-lane waves, wave64. The per-lane form refuses f32 so far, so the second half prints `SKIPPED … per-lane form: refused (…)` for every program; it runs once f32 instructions are lowered. Test lines can now carry a literal dword. Tested on an RTX 3080 Ti (wave32): the HLSL path passes every check; the per-lane halves are SKIPPED (refused), the wave64 ones too (no 64-lane waves). On top of `vladbondarenko97/xcl` `recomp/lowering-f32`, which lowers these ops by hand, the per-lane halves run and agree with the HLSL path. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 342 +++++++++++++++++++++++- crates/xcl/src/gpu/recomp/lower_dxil.rs | 78 ++++++ 2 files changed, 419 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 59dab305f4..55f6d41f25 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1719,6 +1719,339 @@ pub(crate) mod tests { ENDPGM, ]; + // f32 programs: the per-lane form refuses f32 so far, and `lower_dxil`'s + // `f32_programs_on_the_gpu` runs them on the HLSL path, checks its registers with the + // `check_f32_*` below (32 lanes) and compares the per-lane form with it where it lowers them + + /// f32 VOP2 / VOP3 arithmetic on v1 = 2^lane and v2 = 2^lane · (1 + lane / 64), with the + /// VOP3 modifiers, and v19 = NaN (0x7FFFFFFF) into min / max / clamp. Every product is exact, + /// so `FMad` gives the same fused or not. + pub(crate) const F32_ARITHMETIC: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 192), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 191), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 151), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 145), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + // 0.5 + x, x - p, x - (-4), x · x, min / max(2, x) + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 240), ("VSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_SUBREV_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 247), ("VSRC1", 2)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 2), ("VSRC1", 2)]), + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 244), ("VSRC1", 2)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 244), ("VSRC1", 2)]), + // fma(x, -2, p), mad(x, 0.5, v3); mac v11 = 4 · x + p, fmac v12 = -0.5 · x + v3 + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 245), ("SRC2", V + 1)]), + ("V_MAD_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 240), ("SRC2", V + 3)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)]), + ("V_MAC_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 246), ("VSRC1", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 3)]), + ("V_FMAC_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 241), ("VSRC1", 2)]), + // -|x| · |-4| (abs before neg); omod 0.5, 2, 4 (with neg on src2); clamp at 1 and at 0 + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("SRC1", 247), ("ABS", 3), ("NEG", 1)]), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", V + 1), ("OMOD", 3)]), + ("V_SUB_F32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2), ("OMOD", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 1), ("SRC2", V + 2), ("NEG", 4), ("OMOD", 2)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", 240), ("CLAMP", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", 243), ("SRC2", 244), ("CLAMP", 1)]), + // min(NaN, x), max(x, -NaN), clamp(NaN · 1); VOP3 fmac v23 = |-0.5| · x + p + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 20), ("SRC0", V + 19), ("VSRC1", 2)]), + ("V_MAX_F32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 2), ("SRC1", V + 19), ("NEG", 2)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 19), ("SRC1", 242), ("CLAMP", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 1)]), + ("V_FMAC_F32", "ENC_VOP3", &[("VDST", 23), ("SRC0", 241), ("SRC1", V + 2), ("ABS", 1)]), + ENDPGM, + ]; + + /// f32 compares of a = v3 (NaN in every fourth lane, 2^lane in the others) with 4.0: all 16 + /// predicates into s[2k], two with VOP3 abs / neg, then VOPC into VCC and a cndmask of it, + /// and v_cmpx narrowing EXEC for a v_mov. + pub(crate) const F32_COMPARES: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 192), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 191), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 151), ("VSRC1", 1)]), + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 131), ("VSRC1", 0)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 4)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V + 1), ("VSRC1", 19)]), + ("V_CMP_F_F32", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LT_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_EQ_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LE_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_GT_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LG_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_GE_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_O_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_U_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NGE_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLG_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NGT_F32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLE_F32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NEQ_F32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLT_F32", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_TRU_F32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 3), ("SRC1", 246)]), + // -|a| == -4; !(|-2| > -a) + ("V_CMP_EQ_F32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 3), ("SRC1", 247), ("ABS", 1), ("NEG", 1)]), + ("V_CMP_NGT_F32", "ENC_VOP3", &[("VDST", 34), ("SRC0", 245), ("SRC1", V + 3), ("ABS", 1), ("NEG", 2)]), + // vcc = a < 4, v6 = vcc ? p : 0; exec = a >= 4, v7 = 1.0 there + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 246)]), + ("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", V + 3), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 128), ("VSRC1", 1)]), + ("V_CMPX_GE_F32", "ENC_VOPC", &[("SRC0", V + 3), ("VSRC1", 5)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 242)]), + ENDPGM, + ]; + + /// f32 ↔ i32 / u32 / f16 conversions: v2 = lane − 16, v4 = (lane << 26 | lane) rounded, + /// v6 = (lane − 16) / 4 into the f32 → integer ones, v11 = v4² (out of range) and v19 = NaN + /// into the saturating ones; binary16 in and out (denormals, ties to even, overflow, NaN), + /// with OP_SEL halves, omod and clamp. + pub(crate) const F32_CONVERSIONS: &[I] = &[ + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 154), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)]), + ("V_CVT_F32_I32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 1), ("OMOD", 3), ("CLAMP", 1)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 240), ("OMOD", 3)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + ("V_CVT_RPI_I32_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + ("V_CVT_FLR_I32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 6)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 4), ("VSRC1", 4)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 11)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + ("V_CVT_I32_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 11), ("NEG", 1)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 19)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 16), ("SRC0", V + 19)]), + // v17 = f16 (lane & 31) << 9 | (lane & 31), the lane in the high half; v20 = it in the + // high half, the lane in the low one + ("V_AND_B32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 159), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", 137), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 23), ("VSRC1", 17)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 144), ("VSRC1", 17)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", V), ("VSRC1", 20)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 144), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 18), ("VSRC1", 17)]), + ("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 21), ("SRC0", V + 17)]), + ("V_CVT_F32_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 20), ("OP_SEL", 1)]), + // v24 = 1 + (lane & 31) · 2^-14: f16 ties at lanes 8 and 24; into v25's low half + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 137), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3F80_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 20)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 24)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", V)]), + ("V_CVT_F16_F32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 6), ("OP_SEL", 8)]), + // f16 denormals (· 2^-20), below the smallest one (· 2^-25), NaN, overflow, clamp + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3580_0000)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 28)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3300_0000)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 29), ("SRC0", V + 28)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 30), ("SRC0", V + 19)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 31), ("SRC0", V + 11)]), + ("V_CVT_F16_F32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 6), ("CLAMP", 1)]), + ENDPGM, + ]; + + /// floor / ceil / trunc / rndne / fract of v3 = (lane − 16) / 8 (ties, signed zeros), fract + /// of −2^-30 (just below 1.0), and two with VOP3 modifiers. + pub(crate) const F32_ROUNDING: &[I] = &[ + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 2), ("LITERAL", 0x3E00_0000)]), + ("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)]), + ("V_CEIL_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 3)]), + ("V_TRUNC_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)]), + ("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 3)]), + ("V_FRACT_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)]), + ("V_FRACT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0xB080_0000)]), + ("V_FLOOR_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 3), ("NEG", 1), ("OMOD", 1)]), + ("V_FRACT_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 3), ("ABS", 1), ("CLAMP", 1)]), + ENDPGM, + ]; + + /// rcp / rsq / sqrt / log of v1 = 1 + (lane & 31) / 32, exp / sin / cos of v2 = v1 − 1.5, + /// and three with VOP3 modifiers (log2 |0| = −∞ at lane 16). The GPU's are approximate. + pub(crate) const F32_TRANSCENDENTALS: &[I] = &[ + ("V_AND_B32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 159), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 146), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 1), ("LITERAL", 0x3F80_0000)]), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 243)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 241), ("VSRC1", 2)]), + ("V_RCP_F32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 1)]), + ("V_RCP_IFLAG_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 1)]), + ("V_RSQ_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)]), + ("V_SQRT_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + ("V_EXP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 2)]), + ("V_LOG_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 1)]), + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 2)]), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)]), + ("V_EXP_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("NEG", 1), ("OMOD", 1)]), + ("V_SIN_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("CLAMP", 1)]), + ("V_LOG_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("ABS", 1)]), + ENDPGM, + ]; + + /// v_fmamk / fmaak / madmk / madak (products exact) and min3 / max3 / med3 of a = the lane + /// (NaN in every fourth lane), b = lane − 16 and 4.0, one with VOP3 abs / neg. + pub(crate) const F32_THREE_SOURCE: &[I] = &[ + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 131), ("VSRC1", 0)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 4)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 3), ("VSRC1", 19)]), + ("V_FMAMK_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3FC0_0000)]), + ("V_FMAAK_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3E80_0000)]), + ("V_MADMK_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3FC0_0000)]), + ("V_MADAK_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3E80_0000)]), + ("V_MIN3_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MAX3_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MED3_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MED3_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("SRC1", V + 5), ("SRC2", 246), ("ABS", 1), ("NEG", 2)]), + ENDPGM, + ]; + + pub(crate) fn check_f32_arithmetic(_: &[u32], v: &[Vec]) { + let sat = |x: f32| x.clamp(0.0, 1.0); + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (p, x) = (f(1), f(2)); + assert_eq!((p, x), (2f32.powi(l as i32), 2f32.powi(l as i32) * (1.0 + l as f32 / 64.0)), "lane {l}"); + let y = x + 0.5; + let want = [y, x - p, x + 4.0, x * x, x.min(2.0), x.max(2.0), x * -2.0 + p, x * 0.5 + y, 4.0 * x + p, -0.5 * x + y, -x * 4.0, (x + p) * 0.5, (p - x) * 2.0, (p * p - x) * 4.0, sat((x - p) * 0.5), sat(2.0 - x)]; + for (i, w) in want.iter().enumerate() { + assert_eq!(f(3 + i).to_bits(), w.to_bits(), "lane {l} v{}: {} against {w}", 3 + i, f(3 + i)); + } + assert_eq!((r[20], r[21], r[22]), (r[2], r[2], 0), "lane {l}: NaN into min, max, clamp"); + assert_eq!(f(23), 0.5 * x + p, "lane {l}: VOP3 fmac"); + } + } + + pub(crate) fn check_f32_compares(s: &[u32], v: &[Vec]) { + let preds: [fn(f32, f32) -> bool; 18] = [ + |_, _| false, + |a, b| a < b, + |a, b| a == b, + |a, b| a <= b, + |a, b| a > b, + |a, b| a < b || a > b, + |a, b| a >= b, + |a, b| !a.is_nan() && !b.is_nan(), + |a, b| a.is_nan() || b.is_nan(), + |a, b| !(a >= b), + |a, b| !(a < b || a > b), + |a, b| !(a > b), + |a, b| !(a <= b), + |a, b| !(a == b), + |a, b| !(a < b), + |_, _| true, + |a, _| -a.abs() == -4.0, + |a, _| !(2.0 > -a), + ]; + let a: Vec = (0..32).map(|l| if l % 4 == 0 { f32::from_bits(0x7FFF_FFFF) } else { 2f32.powi(l) }).collect(); + let mask = |p: &dyn Fn(f32) -> bool| (0..32).filter(|&l| p(a[l])).fold(0u32, |m, l| m | 1 << l); + for (k, p) in preds.iter().enumerate() { + assert_eq!(s[2 * k], mask(&|x| p(x, 4.0)), "s{}", 2 * k); + } + assert_eq!(s[106], mask(&|x| x < 4.0), "vcc"); + assert_eq!(s[126], mask(&|x| x >= 4.0), "exec"); + for (l, r) in v.iter().enumerate() { + assert_eq!(r[3], a[l].to_bits(), "lane {l}"); + assert_eq!(r[6], if a[l] < 4.0 { r[1] } else { 0 }, "lane {l}: cndmask"); + assert_eq!(r[7], if a[l] >= 4.0 { 1f32.to_bits() } else { 0 }, "lane {l}: under v_cmpx"); + } + } + + pub(crate) fn check_f32_conversions(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (li, q) = (l as i32 - 16, (l as i32 - 16) as f32 / 4.0); + assert_eq!(f(2), li as f32, "lane {l}"); + assert_eq!(f(4), ((l as u32) << 26 | l as u32) as f32, "lane {l}: u32 rounded to nearest even"); + assert_eq!(f(5), (li as f32 * 0.5).clamp(0.0, 1.0), "lane {l}: omod and clamp"); + assert_eq!(f(6), q, "lane {l}"); + // the HLSL path's cvt_i32 / cvt_u32 saturate as Rust's `as` does, NaN giving 0 + assert_eq!((r[7], r[8]), (q as i32 as u32, q as u32), "lane {l}: truncated"); + assert_eq!((r[9], r[10]), ((q + 0.5).floor() as i32 as u32, q.floor() as i32 as u32), "lane {l}: rpi, flr"); + assert_eq!((r[12], r[13], r[14]), (f(11) as i32 as u32, f(11) as u32, (-f(11)) as i32 as u32), "lane {l}: out of range"); + assert_eq!((r[15], r[16]), (0, 0), "lane {l}: NaN"); + assert_eq!(f(21), f16_to_f32(r[17] & 0xFFFF), "lane {l}"); + assert_eq!(r[22], r[21], "lane {l}: the high half"); + assert_eq!(r[25] >> 16, r[20] >> 16, "lane {l}: the half kept"); + assert_eq!(r[26] & 0xFFFF, l as u32, "lane {l}: the half kept"); + assert_eq!(r[29], (l != 0) as u32, "lane {l}: below the smallest denormal"); + assert_eq!(r[30], 0x7FFF, "lane {l}: NaN"); + assert_eq!(r[31], if l == 0 { 0 } else { 0x7C00 }, "lane {l}: overflow"); + } + let lo = |l: usize, i: usize| v[l][i] & 0xFFFF; + assert_eq!([lo(0, 21), lo(1, 17), lo(30, 17)], [0, 0x0201, 0x3C1E]); + assert_eq!((f32::from_bits(v[1][21]), f32::from_bits(v[30][21])), (513.0 * 2f32.powi(-24), 1.0 + 30.0 / 1024.0), "f16 in"); + // 1 + k · 2^-14 at k = 1, 8, 16, 24, 31: ties to even at 8 and 24 + assert_eq!([1, 8, 16, 24, 31].map(|l| lo(l, 25)), [0x3C00, 0x3C00, 0x3C01, 0x3C02, 0x3C02]); + assert_eq!([0, 16, 18, 20].map(|l| v[l][26] >> 16), [0xC400, 0, 0x3800, 0x3C00], "f16 into the high half"); + assert_eq!([0, 18, 20, 31].map(|l| lo(l, 32)), [0, 0x3800, 0x3C00, 0x3C00], "clamp"); + assert_eq!(lo(0, 27), 0x0010, "2^-20: an f16 denormal"); + } + + pub(crate) fn check_f32_rounding(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let x = (l as i32 - 16) as f32 / 8.0; + let want = [x.floor(), x.ceil(), x.trunc(), x.round_ties_even(), x - x.floor()]; + for (i, w) in want.iter().enumerate() { + assert_eq!(r[4 + i], w.to_bits(), "lane {l} v{}", 4 + i); + } + assert_eq!(r[9], 0x3F7F_FFFF, "fract(-2^-30): below 1.0"); + assert_eq!(f32::from_bits(r[10]), 2.0 * (-x).floor(), "lane {l}"); + assert_eq!(f32::from_bits(r[11]), x.abs() - x.abs().floor(), "lane {l}"); + } + } + + pub(crate) fn check_f32_three_source(_: &[u32], v: &[Vec]) { + let med3 = |a: f32, b: f32, c: f32| a.min(b).max(a.max(b).min(c)); + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (x, y) = (l as f32, l as f32 - 16.0); + let a = if l % 4 == 0 { f32::from_bits(0x7FFF_FFFF) } else { x }; + assert_eq!([f(6), f(7), f(8), f(9)], [x * 1.5 + y, x * y + 0.25, x * 1.5 + y, x * y + 0.25], "lane {l}"); + assert_eq!([f(10), f(11), f(12)], [a.min(y).min(4.0), a.max(y).max(4.0), med3(a, y, 4.0)], "lane {l}"); + assert_eq!(f(13), med3(y.abs(), -a, 4.0), "lane {l}"); + } + } + + pub(crate) fn check_f32_transcendentals(_: &[u32], v: &[Vec]) { + let sat = |x: f32| x.clamp(0.0, 1.0); + for (l, r) in v.iter().enumerate() { + let x = 1.0 + (l & 31) as f32 / 32.0; + let y = x - 1.5; + let t = y * 6.283_185_3; + assert_eq!((r[1], r[2]), (x.to_bits(), y.to_bits()), "lane {l}"); + let want = [1.0 / x, 1.0 / x, 1.0 / x.sqrt(), x.sqrt(), y.exp2(), x.log2(), t.sin(), t.cos(), 2.0 * (-y).exp2(), sat(t.sin()), y.abs().log2()]; + for (i, w) in want.iter().enumerate() { + assert!(f32_close(r[3 + i], w.to_bits()), "lane {l} v{}: {} against {w}", 3 + i, f32::from_bits(r[3 + i])); + } + } + } + + /// The same bits, or within `approximate_float_unary_ops_are_within_tolerance`'s tolerance. + pub(crate) fn f32_close(a: u32, b: u32) -> bool { + let (a, b) = (f32::from_bits(a), f32::from_bits(b)); + a.to_bits() == b.to_bits() || (a - b).abs() <= 1e-3f32.max(b.abs() * 1e-5) + } + + /// binary16 in the low 16 bits → f32 (`f16tof32`) + pub(crate) fn f16_to_f32(h: u32) -> f32 { + let (s, e, m) = (h >> 15 & 1, h >> 10 & 0x1F, h & 0x3FF); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 => f32::from_bits(0x7F80_0000 | m << 13), + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -v } else { v } + } + pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } } @@ -1791,8 +2124,15 @@ pub(crate) mod tests { (0..256).map(|i| 1000 + i).collect() } + /// A line's bytes; a `("LITERAL", k)` field is the instruction's literal dword. + pub(crate) fn encode_line((n, e, f): &I) -> Vec { + let lit = f.iter().find(|(k, _)| *k == "LITERAL").map(|&(_, v)| v as u32); + let f: Vec<(&str, u64)> = f.iter().copied().filter(|(k, _)| *k != "LITERAL").collect(); + rdna2::encode(n, e, &f, lit).unwrap() + } + pub(crate) fn decode(lines: &[I]) -> Vec { - let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); let mut out = Vec::new(); let mut off = 0; while off < bytes.len() { diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index c7931e903e..3bb382d7dc 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -284,6 +284,84 @@ mod tests { } } + /// The f32 programs of `lower`'s tests on the GPU: the HLSL path gives the expected + /// registers (`check_f32_*`, wave32), and the per-lane DXIL gives the HLSL path's, register + /// for register (rcp within `f32_close`: HLSL's `rcp` is a fast fdiv). While the per-lane + /// form refuses a program, that half is SKIPPED with the refusal. + #[test] + fn f32_programs_on_the_gpu() { + if !gpu() { + return; + } + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + type Check = fn(&[u32], &[Vec]); + let programs: [(&str, &[I], Check, &[usize]); 6] = [ + ("f32 arithmetic", F32_ARITHMETIC, check_f32_arithmetic, &[]), + ("f32 compares", F32_COMPARES, check_f32_compares, &[]), + ("f32 conversions", F32_CONVERSIONS, check_f32_conversions, &[]), + ("f32 rounding", F32_ROUNDING, check_f32_rounding, &[]), + ("f32 transcendentals", F32_TRANSCENDENTALS, check_f32_transcendentals, &[3, 4]), + ("f32 three-source", F32_THREE_SOURCE, check_f32_three_source, &[]), + ]; + let wave64 = runner::wave64_supported() == Ok(true); + for (name, lines, check, approx) in programs { + for w64 in [false, true] { + let lanes = if w64 { 64 } else { 32 }; + if w64 && !wave64 { + runner::skip_test(&format!("{name}, wave64: no wave64")); + continue; + } + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let t = translate(&bytes, &Options { wave64: w64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), &st, &[]).unwrap(); + if !w64 { + check(&hlsl.sgpr, &hlsl.vgpr[..32]); + } + let insts = decode(lines); + let (dxil, stale) = match super::kernel(&insts, w64) { + Ok(k) => k, + Err(e) => { + runner::skip_test(&format!("{name}, wave{lanes}, per-lane form: refused ({e})")); + continue; + } + }; + let direct = runner::run(&dxil, &st, &[]).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = crate::gpu::rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + if w64 { + sregs.extend([107, 127]); + } + let stale_at = |r: usize| stale.contains(&(r as u8)) || (w64 && r % 2 == 1 && stale.contains(&(r as u8 - 1))); + for &r in sregs.iter().filter(|&&r| !stale_at(r)) { + assert_eq!(direct.sgpr[r], hlsl.sgpr[r], "{name}, wave{lanes}: s{r}"); + } + for l in 0..lanes { + for &r in &vregs { + let (d, h) = (direct.vgpr[l][r], hlsl.vgpr[l][r]); + let same = if approx.contains(&r) { f32_close(d, h) } else { d == h }; + assert!(same, "{name}, wave{lanes}: lane {l} v{r}: {d:#x} against {h:#x}"); + } + } + } + } + } + #[test] fn a_per_lane_compute_program_runs_on_the_gpu() { if !gpu() { From ad39e4d52a2eff225ac8a697bfd95a1693f8603c Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 19:08:24 +0100 Subject: [PATCH 21/51] Direct DXIL: Lw::new and Lw::finish out of the kernel translator `translate_on_this_thread` built its `Lw` and finished the container inline. Both move into `pub fn Lw::new(insts, leaders, o, &Entry)` (the shader and its UAVs, the SSA's entry block, the LDS / exchange-slot scan, the constant samplers, the split form's storage and partner) and `pub fn Lw::finish(self, numthreads, hw)` (the exchange error, `try_finish` / `try_finish_graphics`, validation), so the recompiler's per-lane lowering can build the same state around its own block walk. `Entry`, `compute_init` and `mesh_init` become public for the per-entry setup. 50th compute program of a retail pack, native wave64 and split (106 translations), hashes the same before and after. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XTYmP5ub3Zjdi8PYaDNwsV --- crates/xcl/src/gpu/dxil/kernel.rs | 293 ++++++++++++++++-------------- 1 file changed, 161 insertions(+), 132 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 73867fee03..2b8d3e44cd 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -17,6 +17,7 @@ use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR use super::module::{Block, Pred, Value}; use super::shader::{RawUav, Shader}; use super::ssa::Ssa; +use crate::gpu::rdna2::Decoded; use crate::gpu::recomp::{CsInterface, MsInterface, PsInterface, VsInterface, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS, MESH_HEADER}; #[derive(Debug, Clone, Copy)] @@ -87,7 +88,7 @@ pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Resul /// The entry ABI. #[derive(Clone)] -enum Entry { +pub enum Entry { Kernel, Compute(CsInterface), Mesh(MsInterface), @@ -132,123 +133,14 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Result { let cfg = Cfg::build(code)?; - let split = o.wave64 && o.split; let kernel = matches!(entry, Entry::Kernel); - let cs = match &entry { - Entry::Compute(cs) => Some(cs.clone()), - _ => None, - }; - let ms = match &entry { - Entry::Mesh(ms) => Some(ms.clone()), - _ => None, - }; let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); - let split = split && !gfx; - let stage = match &entry { - Entry::Vertex(_) => Stage::Vertex, - Entry::Pixel(_) => Stage::Pixel, - _ => Stage::Compute, - }; - let mut s = Shader::new(stage, (6, 6)); - let io = s.raw_uav(0, 0); - let res = if kernel || ms.is_some() { Some(s.raw_uav(1, 0)) } else { None }; - let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); - let i32 = s.m.i32(); - let z = s.m.i32c(0); - let mut lw = Lw { - s, - ssa: Ssa::new(i32), - init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, - wave64: o.wave64, - split, - lane: z, - lane31: z, - upper: z, - half: z, - mems, - heap_mem, - res, - fmt_table: None, - fmt_desc_cache: HashMap::new(), - fmt_comp1_cache: HashMap::new(), - uma_base_val: None, - ntmp: 0, - scratch: None, - static_samplers: Default::default(), - static_used: Vec::new(), - sampler_base: o.sampler_base, - dyn_rm: false, - has_f64_round_op: false, - exec_cache: HashMap::new(), - xs: None, - xw: None, - xc: None, - waves: 1, - cw: z, - xn: z, - xslot: 1, - lds: None, - lds_top: 8191, - dpp_enable: None, - partner: Partner::Present, - mesh: None, - gfx: None, - gfx_half: None, - whole_live: Default::default(), - guard_override: None, - mask_override: None, - exchange_error: None, - pc: 0, - }; - { - let Lw { s, ssa, init, .. } = &mut lw; - ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); - } - // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, - // 32 for ds_bpermute), as the HLSL kernel sizes them - let mut uses_lds = false; - let mut slot = 1u32; - for d in &cfg.insts { - let n = d.inst.name; - if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { - uses_lds = true; - } - if n == "DS_BPERMUTE_B32" { - slot = slot.max(32); - } - if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { - let w = match n.rsplit('_').next().unwrap_or("") { - "DWORDX2" => 2, - "DWORDX4" => 4, - "DWORDX8" => 8, - "DWORDX16" => 16, - _ => 1, - }; - slot = slot.max(w); - } - } + let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); - lw.static_samplers = crate::gpu::recomp::constant_samplers(&cfg.insts, &leaders); - let group_threads: Option = match &entry { - Entry::Vertex(_) | Entry::Pixel(_) => None, - Entry::Kernel => None, - Entry::Compute(cs) => Some(cs.threads.iter().product()), - Entry::Mesh(ms) => Some(ms.threads), - }; - if let (Some(t), true) = (group_threads, split) { - lw.waves = t.div_ceil(64).max(1); - } - if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { - lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(&cfg.insts, kernel); - } - lw.setup_storage(uses_lds, if split { slot } else { 1 }); - if let (Some(t), true) = (group_threads, split) { - lw.partner = match t { - 0..=32 => Partner::Missing, - 33..=64 => Partner::Present, - _ => Partner::Spin, - }; - } + let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + let uses_lds = lw.lds.is_some(); + let res = lw.res; + let io = lw.init.io.expect("the I/O buffer"); let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -364,25 +256,162 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu lw.s.m.ret(); lw.s.m.set_block(Block(0)); lw.s.m.br(h0); - if let Some(e) = lw.exchange_error.take() { - return Err(e); - } let hw = if split || !o.wave64 { 32 } else { 64 }; - let c = if gfx { - let g = lw.gfx.take().ok_or("graphics entry without graphics I/O")?; - let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; - lw.s.try_finish_graphics(g.io, info) - } else { - lw.s.try_finish(numthreads, Some(hw)) + lw.finish(numthreads, hw) +} + +impl Lw { + /// The translator's state for a program (`insts`, its blocks starting at `leaders`) at + /// `entry`: the shader with its buffers, + /// the SSA's entry block, the program's LDS and the split form's exchange storage and + /// partner. The caller then sets up the lanes for its entry (`setup_lanes*`), lowers the + /// program's blocks, branches from `Block(0)` to the first of them and ends with + /// [`Lw::finish`]. #1426's block walk (`translate_on_this_thread`) and the recompiler's + /// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here. + pub fn new(insts: &[Decoded], leaders: &BTreeSet, o: KernelOptions, entry: &Entry) -> Lw { + let split = o.wave64 && o.split; + let kernel = matches!(entry, Entry::Kernel); + let cs = match entry { + Entry::Compute(cs) => Some(cs.clone()), + _ => None, + }; + let ms = match entry { + Entry::Mesh(ms) => Some(ms.clone()), + _ => None, + }; + let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); + let split = split && !gfx; + let stage = match entry { + Entry::Vertex(_) => Stage::Vertex, + Entry::Pixel(_) => Stage::Pixel, + _ => Stage::Compute, + }; + let mut s = Shader::new(stage, (6, 6)); + let io = s.raw_uav(0, 0); + let res = if kernel || ms.is_some() { Some(s.raw_uav(1, 0)) } else { None }; + let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); + let i32 = s.m.i32(); + let z = s.m.i32c(0); + let mut lw = Lw { + s, + ssa: Ssa::new(i32), + init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, + wave64: o.wave64, + split, + lane: z, + lane31: z, + upper: z, + half: z, + mems, + heap_mem, + res, + fmt_table: None, + fmt_desc_cache: HashMap::new(), + fmt_comp1_cache: HashMap::new(), + uma_base_val: None, + ntmp: 0, + scratch: None, + static_samplers: Default::default(), + static_used: Vec::new(), + sampler_base: o.sampler_base, + dyn_rm: false, + has_f64_round_op: false, + exec_cache: HashMap::new(), + xs: None, + xw: None, + xc: None, + waves: 1, + cw: z, + xn: z, + xslot: 1, + lds: None, + lds_top: 8191, + dpp_enable: None, + partner: Partner::Present, + mesh: None, + gfx: None, + gfx_half: None, + whole_live: Default::default(), + guard_override: None, + mask_override: None, + exchange_error: None, + pc: 0, + }; + { + let Lw { s, ssa, init, .. } = &mut lw; + ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); + } + // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, + // 32 for ds_bpermute), as the HLSL kernel sizes them + let mut uses_lds = false; + let mut slot = 1u32; + for d in insts { + let n = d.inst.name; + if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { + uses_lds = true; + } + if n == "DS_BPERMUTE_B32" { + slot = slot.max(32); + } + if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { + let w = match n.rsplit('_').next().unwrap_or("") { + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => 1, + }; + slot = slot.max(w); + } + } + lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders); + let group_threads: Option = match entry { + Entry::Vertex(_) | Entry::Pixel(_) => None, + Entry::Kernel => None, + Entry::Compute(cs) => Some(cs.threads.iter().product()), + Entry::Mesh(ms) => Some(ms.threads), + }; + if let (Some(t), true) = (group_threads, split) { + lw.waves = t.div_ceil(64).max(1); + } + if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { + lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); + } + lw.setup_storage(uses_lds, if split { slot } else { 1 }); + if let (Some(t), true) = (group_threads, split) { + lw.partner = match t { + 0..=32 => Partner::Missing, + 33..=64 => Partner::Present, + _ => Partner::Spin, + }; + } + lw } - .map_err(|e| format!("direct DXIL builder error: {e}"))?; - if cfg!(any(test, debug_assertions)) { - if let Err(e) = super::validate::validate(&c) { - let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); - return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + + /// The finished container and the static samplers the program bound, once every block + /// is closed: `numthreads` and the hardware wave size `hw` for a compute-like entry, the + /// stage's I/O for a VS / PS. + pub fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + if let Some(e) = self.exchange_error.take() { + return Err(e); + } + let stage = self.s.stage; + let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { + let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + self.s.try_finish_graphics(g.io, info) + } else { + self.s.try_finish(numthreads, Some(hw)) + } + .map_err(|e| format!("direct DXIL builder error: {e}"))?; + if cfg!(any(test, debug_assertions)) { + if let Err(e) = super::validate::validate(&c) { + let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); + return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + } } + Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) } - Ok(Kernel { dxil: c, static_samplers: lw.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) } /// The kernel's epilogue: SGPRs and SCC from lane 0, every touched VGPR per lane. @@ -415,7 +444,7 @@ fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { /// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids /// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. -fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { +pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { let mut sgpr = HashMap::new(); let mut next = cs.user_sgprs; for k in 0..3 { @@ -453,7 +482,7 @@ fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the /// wave index in s3[27:24], SCC 0, EXEC = the wave's threads, v5 = group · threads + slot, /// other VGPRs 0; and the record slots. -fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { +pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { let lanes: u32 = if lw.wave64 { 64 } else { 32 }; let l = lw.c(lanes); let wave = lw.bin(super::module::BinOp::UDiv, tid, l); From 77db49c9fa88aebcb7358c0a7b42d6077ffb0609 Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 19:13:06 +0100 Subject: [PATCH 22/51] Recompiler: the DXIL adapter holds #1426's Lw; 2-D / 3-D compute groups `DxilIr` builds its state with `Lw::new` (Entry::Kernel or Entry::Compute, one memory window, no split) and finishes it with `Lw::finish` (which also validates in tests and debug builds), so the per-entry setup and the instruction lowering of #1426 are reachable from the per-lane lowering. `compute_ids` is #1426's compute entry, `Lw::setup_lanes_compute`: 2-D / 3-D groups are numbered as their waves arrive (the counter in the program's top LDS word when it has LDS), and `lane()` returns the lane it set. `lower_dxil::compute` no longer refuses 2-D / 3-D groups. Test: the 8x8x1 and 4x4x4 programs through the per-lane form on the GPU, wave32 and native wave64, equal to the lowering run on the CPU. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XTYmP5ub3Zjdi8PYaDNwsV --- crates/xcl/src/gpu/recomp/lower_dxil.rs | 159 +++++++++++++++--------- 1 file changed, 97 insertions(+), 62 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 3bb382d7dc..85eea6d077 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -3,45 +3,62 @@ //! //! `Ir` maps one to one onto the builder: blocks, phis (`phi_at` / `add_incoming`), integer //! ops, compares, `select`, the thread / group / lane ids, `waveActiveBallot`, and raw buffer -//! loads and stores on the ABI's root UAVs (u0 `io`, u1 `res`, u2 `mem`). A phi the SSA +//! loads and stores on the ABI's root UAVs (u0 `io`, u1 `res`, u2 `mem`). The builder state is +//! #1426's translator state (`gpu::dxil::lower::Lw`, built by `Lw::new` and finished by +//! `Lw::finish`), so its per-entry setup (`setup_lanes_compute`) and its instruction +//! lowering are reachable from here. A phi the SSA //! construction finds trivial has its uses replaced (`Module::replace_all_uses`); the phi itself //! stays in its block, unused. use super::lower::{self, Bin, Cmp, Ir}; use super::ssa::{Sink, Var}; -use crate::gpu::dxil::container::Stage; +use crate::gpu::dxil::kernel::{Entry, KernelOptions}; +use crate::gpu::dxil::lower::Lw; use crate::gpu::dxil::module::{BinOp, Block, CastOp, Pred, Value}; -use crate::gpu::dxil::shader::{RawUav, Shader}; +use crate::gpu::dxil::shader::RawUav; use crate::gpu::rdna2::Decoded; +use std::collections::BTreeSet; struct DxilIr { - s: Shader, + lw: Lw, io: RawUav, res: Option, mem: RawUav, blocks: Vec, + /// `compute_ids` set up the lanes (`Lw::lane` is the console lane) + lanes_set: bool, } impl DxilIr { - fn new(kernel: bool) -> DxilIr { - let mut s = Shader::new(Stage::Compute, (6, 6)); - let io = s.raw_uav(0, 0); - let res = kernel.then(|| s.raw_uav(1, 0)); - // compute: other waves may write the memory this one reads (as the HLSL path declares it) - let mem = if kernel { s.raw_uav(2, 0) } else { s.raw_uav_coherent(2, 0) }; - DxilIr { s, io, res, mem, blocks: Vec::new() } + /// The builder state for `insts` at `entry` (a kernel or a compute program): one memory + /// window; a compute program's is coherent, as the HLSL path declares it. + fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { + // block leaders for the constant-sampler scan: the first instruction, branch targets + // and the instruction after a branch + let mut leaders: BTreeSet = insts.first().map(|d| d.pc).into_iter().collect(); + for (i, d) in insts.iter().enumerate() { + if let Some(t) = crate::gpu::rdna2::branch_target(d) { + leaders.insert(t); + leaders.extend(insts.get(i + 1).map(|n| n.pc)); + } + } + let o = KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let lw = Lw::new(insts, &leaders, o, entry); + let io = lw.init.io.expect("the I/O buffer"); + let (res, mem) = (lw.res, lw.mems[0]); + DxilIr { lw, io, res, mem, blocks: Vec::new(), lanes_set: false } } fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { match var { - Var::M(_) | Var::Scc => self.s.m.i1(), - Var::S(_) | Var::V(_) => self.s.m.i32(), + Var::M(_) | Var::Scc => self.lw.s.m.i1(), + Var::S(_) | Var::V(_) => self.lw.s.m.i32(), } } fn bytes(&mut self, dword: Value) -> Value { - let four = self.s.m.i32c(4); - self.s.m.bin(BinOp::Mul, dword, four) + let four = self.lw.s.m.i32c(4); + self.lw.s.m.bin(BinOp::Mul, dword, four) } } @@ -49,35 +66,35 @@ impl Sink for DxilIr { type V = Value; fn phi(&mut self, block: usize, var: Var) -> Value { let t = self.ty(var); - self.s.m.phi_at(self.blocks[block], t) + self.lw.s.m.phi_at(self.blocks[block], t) } fn incoming(&mut self, phi: Value, value: Value, pred: usize) { - self.s.m.add_incoming(phi, value, self.blocks[pred]); + self.lw.s.m.add_incoming(phi, value, self.blocks[pred]); } fn replace(&mut self, old: Value, new: Value) { // every use of the trivial phi becomes `new`; the phi stays in its block, unused - self.s.m.replace_all_uses(old, new); + self.lw.s.m.replace_all_uses(old, new); } fn undef(&mut self, var: Var) -> Value { let t = self.ty(var); - self.s.m.undef(t) + self.lw.s.m.undef(t) } } impl Ir for DxilIr { fn new_block(&mut self) -> usize { - let b = if self.blocks.is_empty() { self.s.m.entry_block() } else { self.s.m.new_block() }; + let b = if self.blocks.is_empty() { self.lw.s.m.entry_block() } else { self.lw.s.m.new_block() }; self.blocks.push(b); self.blocks.len() - 1 } fn at(&mut self, block: usize) { - self.s.m.set_block(self.blocks[block]); + self.lw.s.m.set_block(self.blocks[block]); } fn int(&mut self, v: u32) -> Value { - self.s.m.i32c(v) + self.lw.s.m.i32c(v) } fn boolean(&mut self, v: bool) -> Value { - self.s.m.i1c(v) + self.lw.s.m.i1c(v) } fn bin(&mut self, op: Bin, a: Value, b: Value) -> Value { let op = match op { @@ -91,7 +108,7 @@ impl Ir for DxilIr { Bin::LShr => BinOp::LShr, Bin::AShr => BinOp::AShr, }; - self.s.m.bin(op, a, b) + self.lw.s.m.bin(op, a, b) } fn icmp(&mut self, c: Cmp, a: Value, b: Value) -> Value { let p = match c { @@ -106,31 +123,35 @@ impl Ir for DxilIr { Cmp::Sgt => Pred::SGt, Cmp::Sge => Pred::SGe, }; - self.s.m.cmp(p, a, b) + self.lw.s.m.cmp(p, a, b) } fn select(&mut self, c: Value, a: Value, b: Value) -> Value { - self.s.m.select(c, a, b) + self.lw.s.m.select(c, a, b) } fn zext(&mut self, b: Value) -> Value { - let t = self.s.m.i32(); - self.s.m.cast(CastOp::ZExt, b, t) + let t = self.lw.s.m.i32(); + self.lw.s.m.cast(CastOp::ZExt, b, t) } fn lane(&mut self) -> Value { - self.s.wave_lane_index() + if self.lanes_set { + self.lw.lane + } else { + self.lw.s.wave_lane_index() + } } fn group_id(&mut self, k: u32) -> Value { - self.s.group_id(k) + self.lw.s.group_id(k) } fn compute_ids(&mut self, threads: [u32; 3]) -> (Value, [Value; 3]) { - // 1-D groups only until `Lw::setup_lanes_compute` numbers 2-D / 3-D threads by arrival - // (`compute` refuses the others): a 1-D group's waves are its consecutive threads - debug_assert!(threads[1] * threads[2] == 1); - let flat = self.s.thread_id_in_group(0); - let zero = self.s.m.i32c(0); - (flat, [flat, zero, zero]) + // #1426's compute entry: 2-D / 3-D groups numbered as their waves arrive, the counter + // in the program's top LDS word when it has LDS + let lds = self.lw.lds.is_some(); + let ids = self.lw.setup_lanes_compute(threads, lds); + self.lanes_set = true; + ids } fn ballot(&mut self, c: Value) -> [Value; 2] { - let w = self.s.wave_ballot(c); + let w = self.lw.s.wave_ballot(c); [w[0], w[1]] } // one hardware wave per console wave (native wave64, or wave32): the half-local forms are @@ -139,40 +160,40 @@ impl Ir for DxilIr { self.ballot(c) } fn read_lane(&mut self, v: Value, lane: Value) -> Value { - self.s.wave_read_lane_at(v, lane) + self.lw.s.wave_read_lane_at(v, lane) } fn read_lane_half(&mut self, v: Value, lane: Value) -> Value { self.read_lane(v, lane) } fn count_bits(&mut self, v: Value) -> Value { - self.s.bit_count(crate::gpu::dxil::ops::BitCount::Countbits, v) + self.lw.s.bit_count(crate::gpu::dxil::ops::BitCount::Countbits, v) } fn io_load(&mut self, dword: Value) -> Value { let a = self.bytes(dword); let io = self.io; - self.s.raw_load(io, a, 1)[0] + self.lw.s.raw_load(io, a, 1)[0] } fn res_store(&mut self, dword: Value, value: Value) { let a = self.bytes(dword); let res = self.res.expect("res is bound in kernel mode"); - self.s.raw_store(res, a, &[value]); + self.lw.s.raw_store(res, a, &[value]); } fn mem_load(&mut self, addr: Value) -> Value { let mem = self.mem; - self.s.raw_load(mem, addr, 1)[0] + self.lw.s.raw_load(mem, addr, 1)[0] } fn mem_store(&mut self, addr: Value, value: Value) { let mem = self.mem; - self.s.raw_store(mem, addr, &[value]); + self.lw.s.raw_store(mem, addr, &[value]); } fn br(&mut self, target: usize) { - self.s.m.br(self.blocks[target]); + self.lw.s.m.br(self.blocks[target]); } fn br_if(&mut self, c: Value, then: usize, otherwise: usize) { - self.s.m.cond_br(c, self.blocks[then], self.blocks[otherwise]); + self.lw.s.m.cond_br(c, self.blocks[then], self.blocks[otherwise]); } fn ret(&mut self) { - self.s.m.ret(); + self.lw.s.m.ret(); } } @@ -180,9 +201,9 @@ impl Ir for DxilIr { /// `WaveSize` = the program's wave size), and the masks whose final value may differ from /// the console's (`lower::lower_kernel`). pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), String> { - let (ir, stale) = lower::lower_kernel(insts, wave64, DxilIr::new(true))?; + let (ir, stale) = lower::lower_kernel(insts, wave64, DxilIr::new(insts, wave64, &Entry::Kernel))?; let lanes = if wave64 { 64 } else { 32 }; - Ok((ir.s.finish([lanes, 1, 1], Some(lanes)), stale)) + Ok((ir.lw.finish([lanes, 1, 1], lanes)?.dxil, stale)) } /// `compute` from the program's code (decoded, far jumps resolved). @@ -212,24 +233,13 @@ pub fn survey_compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) - } } crate::gpu::rdna2::resolve_far_jumps(&mut insts); - // a 2-D / 3-D group is noted as `compute` refuses it, and the rest surveyed as a 1-D group - // of as many threads (the thread ids differ, the instructions are the same) - if cs.threads[1] * cs.threads[2] > 1 { - let flat = super::CsInterface { threads: [cs.threads.iter().product(), 1, 1], ..cs.clone() }; - let mut why = vec!["2-D / 3-D thread group (waits for Lw::setup_lanes_compute)".to_string()]; - why.extend(lower::survey_compute(&insts, &flat, wave64, DxilIr::new(false))); - return why; - } - lower::survey_compute(&insts, cs, wave64, DxilIr::new(false)) + lower::survey_compute(&insts, cs, wave64, DxilIr::new(&insts, wave64, &Entry::Compute(cs.clone()))) } /// A compute program in its per-lane form, as a signed DXIL container. pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { - if cs.threads[1] * cs.threads[2] > 1 { - return Err("2-D / 3-D thread group (waits for Lw::setup_lanes_compute)".into()); - } - let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(false))?; - Ok(ir.s.finish(cs.threads, Some(if wave64 { 64 } else { 32 }))) + let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(insts, wave64, &Entry::Compute(cs.clone())))?; + Ok(ir.lw.finish(cs.threads, if wave64 { 64 } else { 32 })?.dxil) } #[cfg(test)] @@ -362,6 +372,31 @@ mod tests { } } + /// 2-D and 3-D groups in the per-lane form: the threads numbered as the waves arrive + /// (`Lw::setup_lanes_compute`), each wave's lanes the console's consecutive threads, as the + /// lowering run on the CPU has them. + #[test] + fn a_per_lane_2d_or_3d_group_runs_on_the_gpu() { + if !gpu() { + return; + } + for wave64 in [false, true] { + if wave64 && runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, wave64); + let cs = ids_cs(threads); + let dxil = super::compute(&decode(&lines), &cs, wave64).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(&lines, &cs, wave64, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?} wave64 {wave64}"); + } + } + } + #[test] fn a_per_lane_compute_program_runs_on_the_gpu() { if !gpu() { From 878afda23e04ec44aba2e99098e2eb4a09e44588 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:22:00 -0300 Subject: [PATCH 23/51] Recompiler: the per-lane form lowers unknown instructions with #1426's semantics An instruction the per-lane lowering has no semantics of goes through `Ir::foreign`, which the DXIL adapter implements with #1426's `Lw::inst_guarded`: its input registers are written into `Lw`'s SSA in the current block first, the guard is the lane-mask analysis's (`true` where EXEC is proven, or inside a guarded store's own block, else the lane's EXEC bit), and the registers it wrote come back. SGPR operands are read as numbers (a mask read whole is refused as everywhere), a mask read lane by lane (v_cndmask_b32's selector, a carry-in) is passed as a number holding only this lane's bit, and a mask a VALU writes comes back as this lane's bit of its ballot. Instructions writing EXEC are not taken yet, nor a barrier in a block some lanes skip, nor one that makes blocks of its own. VOP3 modifiers and SDWA no longer refuse a program outright: those instructions go through #1426's semantics too. V_CVT_F16_F32 is kept out: #1426 gives 0 for a value below the smallest f16 denormal where the HLSL path and the console round to it (found by vladbondarenko97's f32 tests; reported on #1426). vladbondarenko97's f32 programs in per-lane form now agree with the HLSL path on the GPU register for register: arithmetic with abs/neg/clamp/omod, rounding, transcendentals and the three-source ops (GTX 1650, wave32); the compares (v_cmpx) and conversions stay refused. --- crates/xcl/src/gpu/recomp/lower.rs | 156 +++++++++++++++++++++++- crates/xcl/src/gpu/recomp/lower_dxil.rs | 23 ++++ 2 files changed, 177 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 55f6d41f25..6a93382d77 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -90,6 +90,13 @@ pub trait Ir: Sink { } /// the number of bits set in `v` (`countbits`) fn count_bits(&mut self, v: Self::V) -> Self::V; + /// `d` lowered with another lowering's instruction semantics (#1426's `Lw::inst_guarded`): + /// `inputs` are the registers it reads, `guard` (i1) decides this lane's register writes and + /// memory effects, and the values of `outputs` after it come back in order. Err when there + /// is no such lowering or it refuses `d`. + fn foreign(&mut self, _d: &Decoded, _guard: Self::V, _inputs: &[(Var, Self::V)], _outputs: &[Var]) -> R> { + Err("no foreign lowering".into()) + } fn io_load(&mut self, dword: Self::V) -> Self::V; fn res_store(&mut self, dword: Self::V, value: Self::V); /// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of @@ -518,7 +525,7 @@ impl<'a, I: Ir> Lower<'a, I> { fn valu_op(&mut self, b: usize, d: &Decoded) -> R<()> { let name = d.inst.name; if d.variant == Variant::Sdwa { - return Err(format!("{name}: SDWA")); + return Err(format!("unsupported {name}: SDWA")); } if self.wave_valu(b, d)? { return Ok(()); @@ -526,7 +533,7 @@ impl<'a, I: Ir> Lower<'a, I> { let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); if vop3 && ["ABS", "NEG", "CLAMP", "OMOD", "OP_SEL"].iter().any(|f| fv(f).unwrap_or(0) != 0) { - return Err(format!("{name}: VOP3 modifiers")); + return Err(format!("unsupported {name}: VOP3 modifiers")); } // sources: VOP1 / VOP2 / VOPC put src1 in VSRC1 (a VGPR); VOP3 in SRC1 let s0 = fv("SRC0").unwrap_or(0); @@ -1099,6 +1106,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s l.ir.at(s); l.ssa.seal(&mut l.ir, s); let r = l.vmem(s, d); + let r = l.or_bridge(r, s, d, true); l.note_inst(r, s, d)?; l.ir.br(c); done[s] = true; @@ -1119,6 +1127,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s } else { Err(format!("unsupported {name}")) }; + let r = l.or_bridge(r, cur, d, false); l.note_inst(r, cur, d)?; } } @@ -1261,6 +1270,149 @@ impl Lower<'_, I> { /// A refused instruction in block b: as `note`, and in survey mode the SGPRs (and, for a /// scalar instruction, SCC) it writes are left as 0 in both views (number and mask bit), /// so that a later read does not report a refusal that only follows from this one. + /// An instruction this lowering has no semantics of, through `Ir::foreign` (#1426's + /// per-instruction lowering) with the lane-mask analysis's guard: `true` where EXEC is proven + /// (or in a guarded store's own block, `in_store_block`), else the lane's EXEC bit. Its SGPR + /// operands are read as numbers (a mask read whole is refused, as everywhere), the mask a + /// VALU reads lane by lane (`v_cndmask_b32`'s selector, a carry-in) as a number holding only + /// this lane's bit, and a mask it writes (a compare, a carry-out) comes back as this lane's + /// bit of the ballot it makes. Instructions writing EXEC are not taken. + fn bridge(&mut self, b: usize, d: &Decoded, in_store_block: bool) -> R<()> { + let name = d.inst.name; + let (whole, written) = super::x64_masks::uses(d); + let (_, explicit_w) = rdna2::sgpr_uses(d); + let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r); + if writes & (3 << 126) != 0 || name.starts_with("V_CMPX") { + return Err("writes EXEC".into()); + } + if name == "S_BARRIER" && self.partial[b] { + return Err("a barrier where some lanes are elsewhere".into()); + } + // instructions whose #1426 semantics are known to differ from the HLSL path and the + // console (each reported on #1426): left to the fallback until fixed there + const DIFFERS_ON_1426: &[&str] = &[ + // f32 → f16 of a value below the smallest f16 denormal: 0 instead of rounding to it + "V_CVT_F16_F32", + ]; + if DIFFERS_ON_1426.contains(&name) { + return Err("its #1426 semantics differ from the console's".into()); + } + let operand = |input: bool, ty: &str| d.ienc.operands.iter().any(|o| o.input == input && o.output != input && o.ty == ty); + let mut inputs: Vec<(Var, I::V)> = Vec::new(); + // SGPRs read whole: numbers (EXEC included, which holds a mask here: refused) + for r in (0..128u8).filter(|&r| whole >> r & 1 != 0 && r != 125) { + let v = self.read_num(b, r)?; + inputs.push((Var::S(r), v)); + } + // a mask read lane by lane: a number with only this lane's bit + let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); + if matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + let m = if vop3 { rdna2::field_value(d.enc, &d.words, "SRC2").unwrap_or(0) } else { VCC as u64 }; + if m > 127 { + return Err(format!("{name}: mask operand {m}")); + } + let bit = self.src_bit(b, m)?; + let lane = self.lane(); + let one = self.ir.zext(bit); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let own = self.ir.bin(Bin::Shl, one, sh); + if self.wave64 { + let (c32, z) = (self.ir.int(32), self.ir.int(0)); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + let (lo, hi) = (self.ir.select(upper, z, own), self.ir.select(upper, own, z)); + inputs.push((Var::S(m as u8), lo)); + inputs.push((Var::S(m as u8 + 1), hi)); + } else { + inputs.push((Var::S(m as u8), own)); + } + } + if operand(true, "OPR_SSRC_SPECIAL_SCC") { + let s = self.read_scc(b); + let s = self.ir.zext(s); + inputs.push((Var::Scc, s)); + } + // VGPRs read, and the ones written (a write keeps the old value where the guard is off) + let (vr, vw) = rdna2::vgpr_uses(d); + let mut vregs: Vec = vr.iter().chain(&vw).map(|&v| v as u16).collect(); + vregs.sort_unstable(); + vregs.dedup(); + for &v in &vregs { + let x = self.read(b, Var::V(v)); + inputs.push((Var::V(v), x)); + } + // outputs: VGPRs, SGPRs (their current values seeded too, so an output the instruction + // leaves alone reads back unchanged), SCC + let sw: Vec = (0..128u8).filter(|&r| writes >> r & 1 != 0 && r != 125).collect(); + for &r in &sw { + if !inputs.iter().any(|&(v, _)| v == Var::S(r)) { + let x = self.read(b, Var::S(r)); + inputs.push((Var::S(r), x)); + } + } + let writes_scc = operand(false, "OPR_SSRC_SPECIAL_SCC"); + let mut outputs: Vec = vw.iter().map(|&v| Var::V(v as u16)).collect(); + outputs.extend(sw.iter().map(|&r| Var::S(r))); + if writes_scc { + outputs.push(Var::Scc); + } + let guard = if in_store_block || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; + let vals = self.ir.foreign(d, guard, &inputs, &outputs)?; + for (&var, &v) in outputs.iter().zip(&vals) { + match var { + Var::V(_) => self.ssa.write(b, var, v), + Var::Scc => { + let z = self.ir.int(0); + let s = self.ir.icmp(Cmp::Ne, v, z); + self.write_scc(b, s); + } + Var::S(_) | Var::M(_) => {} + } + } + if name.starts_with("V_") && !sw.is_empty() { + // a mask (a compare, a carry-out): this lane's bit of the ballot the instruction made + let base = sw[0]; + let lo = vals[outputs.iter().position(|&v| v == Var::S(base)).unwrap()]; + let word = match (self.wave64, outputs.iter().position(|&v| v == Var::S(base + 1))) { + (true, Some(k)) => { + let lane = self.lane(); + let c32 = self.ir.int(32); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + self.ir.select(upper, vals[k], lo) + } + _ => lo, + }; + let lane = self.lane(); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let x = self.ir.bin(Bin::LShr, word, sh); + let one = self.ir.int(1); + let x = self.ir.bin(Bin::And, x, one); + let z = self.ir.int(0); + let bit = self.ir.icmp(Cmp::Ne, x, z); + self.write_bit(b, base, bit); + } else { + for (&var, &v) in outputs.iter().zip(&vals) { + if let Var::S(r) = var { + self.write_num(b, r, v); + } + } + } + Ok(()) + } + + /// `r`, or an instruction it calls unsupported lowered through `bridge`. + fn or_bridge(&mut self, r: R<()>, b: usize, d: &Decoded, in_store_block: bool) -> R<()> { + match r { + Err(e) if e.starts_with("unsupported ") => match self.bridge(b, d, in_store_block) { + Ok(()) => Ok(()), + Err(f) if f == "no foreign lowering" => Err(e), + Err(f) => Err(format!("{e} ({f})")), + }, + r => r, + } + } + fn note_inst(&mut self, r: R<()>, b: usize, d: &Decoded) -> R<()> { if r.is_err() && self.noted.is_some() { let (z, f) = (self.ir.int(0), self.ir.boolean(false)); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 85eea6d077..14850a9027 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -159,6 +159,29 @@ impl Ir for DxilIr { fn ballot_half(&mut self, c: Value) -> [Value; 2] { self.ballot(c) } + /// #1426's semantics of `d` (`Lw::inst_guarded`) in the current block: the inputs are written + /// into `Lw`'s SSA there first, so it reads them and nothing from other blocks (which its SSA + /// doesn't know); one that makes blocks of its own (a guarded memory access with a guard that + /// isn't `true`) is refused rather than left half-placed. + fn foreign(&mut self, d: &Decoded, guard: Value, inputs: &[(Var, Value)], outputs: &[Var]) -> Result, String> { + use crate::gpu::dxil::lower::{VAR_SCC, VAR_VGPR}; + let var = |v: Var| match v { + Var::S(r) => r as u32, + Var::V(n) => VAR_VGPR + n as u32, + Var::Scc => VAR_SCC, + Var::M(_) => unreachable!("a lane-bit view is not a register"), + }; + for &(v, x) in inputs { + self.lw.wr(var(v), x); + } + let block = self.lw.cur(); + self.lw.pc = d.pc; + self.lw.inst_guarded(d, guard, None)?; + if self.lw.cur() != block { + return Err("it made blocks of its own".into()); + } + Ok(outputs.iter().map(|&v| self.lw.rd(var(v))).collect()) + } fn read_lane(&mut self, v: Value, lane: Value) -> Value { self.lw.s.wave_read_lane_at(v, lane) } From ddfbf39fff6acf20ab56d238b87f2ee90aa9cafb Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:51:06 -0300 Subject: [PATCH 24/51] Recompiler: the per-lane form in the runtime behind XCL_PER_LANE=1 With XCL_DIRECT_DXIL and XCL_PER_LANE=1, `pso::direct_compute` tries the per-lane form first, #1426's per-instruction form where it refuses, then the HLSL path. Per-lane entries of the translated-shader cache get their own identity. Refusals are counted as "CS per-lane" fallbacks. The adapter takes the runtime's KernelOptions (`compute_with`): with several 4 GiB memory windows, the per-lane form's own memory lowering (window 0 only) gives way and memory instructions go through #1426's lowering, whose window switch makes blocks. `Ir` blocks therefore keep a start (their phis) and a current end (their branch, incoming edges), and an instruction lowered by #1426 may now make blocks of its own. The bridge also refuses an instruction when #1426's lowering touches a register that was neither passed in nor read back: `Lw` would silently read that register's value at the program's start. The split wave64 form and heap memory windows are refused for now. Like #1426's translator, the lowering runs on a thread with a 256 MiB stack, and a panic there is a refusal. Test: the compute program with four memory windows runs on the GPU and matches the CPU lowering (GTX 1650). --- crates/xcl/src/gpu/recomp/lower.rs | 11 +++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 107 +++++++++++++++++++++--- crates/xcl/src/gpu/recomp/pso.rs | 24 +++++- 3 files changed, 128 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 6a93382d77..0b383a955e 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -103,6 +103,11 @@ pub trait Ir: Sink { /// range reads 0 and writes nothing, as D3D12 raw buffers do fn mem_load(&mut self, addr: Self::V) -> Self::V; fn mem_store(&mut self, addr: Self::V, value: Self::V); + /// the 4 GiB memory windows the program addresses: with more than one, `mem_load` / + /// `mem_store` (window 0 only) are not used, and memory instructions go to `foreign` + fn mem_windows(&self) -> u32 { + 1 + } fn br(&mut self, target: usize); fn br_if(&mut self, c: Self::V, then: usize, otherwise: usize); fn ret(&mut self); @@ -651,6 +656,9 @@ impl<'a, I: Ir> Lower<'a, I> { /// `s[sbase] + offset + soffset` (one memory window, as `emit::smem` with `mem_windows` 1). fn smem(&mut self, b: usize, d: &Decoded) -> R<()> { let name = d.inst.name; + if self.ir.mem_windows() > 1 { + return Err(format!("unsupported {name}: several memory windows")); + } let count = match name.strip_prefix("S_LOAD_") { Some("DWORD") => 1, Some("DWORDX2") => 2, @@ -690,6 +698,9 @@ impl<'a, I: Ir> Lower<'a, I> { /// lowered in a block only those lanes enter (the caller's split). fn vmem(&mut self, b: usize, d: &Decoded) -> R<()> { let name = d.inst.name; + if self.ir.mem_windows() > 1 { + return Err(format!("unsupported {name}: several memory windows")); + } let op = name.trim_start_matches("GLOBAL_").trim_start_matches("FLAT_"); let (store, count) = match op { "LOAD_DWORD" => (false, 1), diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 14850a9027..e10662e12c 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -24,15 +24,25 @@ struct DxilIr { io: RawUav, res: Option, mem: RawUav, + /// each `Ir` block: where it starts (its phis) and where it ends now (its branch; later than + /// the start when #1426's lowering of an instruction in it made blocks of its own) blocks: Vec, + tails: Vec, + /// the `Ir` block being written + cur: usize, /// `compute_ids` set up the lanes (`Lw::lane` is the console lane) lanes_set: bool, } impl DxilIr { - /// The builder state for `insts` at `entry` (a kernel or a compute program): one memory + /// The builder state for `insts` at `entry` (a kernel or a compute program), with one memory /// window; a compute program's is coherent, as the HLSL path declares it. fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { + Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) + } + + /// The builder state with the runtime's options `o` (memory windows, sampler registers). + fn with(insts: &[Decoded], o: KernelOptions, entry: &Entry) -> DxilIr { // block leaders for the constant-sampler scan: the first instruction, branch targets // and the instruction after a branch let mut leaders: BTreeSet = insts.first().map(|d| d.pc).into_iter().collect(); @@ -42,11 +52,10 @@ impl DxilIr { leaders.extend(insts.get(i + 1).map(|n| n.pc)); } } - let o = KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; let lw = Lw::new(insts, &leaders, o, entry); let io = lw.init.io.expect("the I/O buffer"); let (res, mem) = (lw.res, lw.mems[0]); - DxilIr { lw, io, res, mem, blocks: Vec::new(), lanes_set: false } + DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set: false } } fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { @@ -69,7 +78,7 @@ impl Sink for DxilIr { self.lw.s.m.phi_at(self.blocks[block], t) } fn incoming(&mut self, phi: Value, value: Value, pred: usize) { - self.lw.s.m.add_incoming(phi, value, self.blocks[pred]); + self.lw.s.m.add_incoming(phi, value, self.tails[pred]); } fn replace(&mut self, old: Value, new: Value) { // every use of the trivial phi becomes `new`; the phi stays in its block, unused @@ -85,10 +94,12 @@ impl Ir for DxilIr { fn new_block(&mut self) -> usize { let b = if self.blocks.is_empty() { self.lw.s.m.entry_block() } else { self.lw.s.m.new_block() }; self.blocks.push(b); + self.tails.push(b); self.blocks.len() - 1 } fn at(&mut self, block: usize) { - self.lw.s.m.set_block(self.blocks[block]); + self.cur = block; + self.lw.s.m.set_block(self.tails[block]); } fn int(&mut self, v: u32) -> Value { self.lw.s.m.i32c(v) @@ -156,15 +167,19 @@ impl Ir for DxilIr { } // one hardware wave per console wave (native wave64, or wave32): the half-local forms are // the same operations + fn mem_windows(&self) -> u32 { + self.lw.mems.len() as u32 + } fn ballot_half(&mut self, c: Value) -> [Value; 2] { self.ballot(c) } /// #1426's semantics of `d` (`Lw::inst_guarded`) in the current block: the inputs are written /// into `Lw`'s SSA there first, so it reads them and nothing from other blocks (which its SSA - /// doesn't know); one that makes blocks of its own (a guarded memory access with a guard that - /// isn't `true`) is refused rather than left half-placed. + /// doesn't know). A register it touches that is neither an input nor an output refuses the + /// instruction: `Lw` would read that register's value at the program's start. Blocks it makes + /// (a guarded access, the memory window switch) end the `Ir` block in the last of them. fn foreign(&mut self, d: &Decoded, guard: Value, inputs: &[(Var, Value)], outputs: &[Var]) -> Result, String> { - use crate::gpu::dxil::lower::{VAR_SCC, VAR_VGPR}; + use crate::gpu::dxil::lower::{VAR_BUDGET, VAR_SCC, VAR_VGPR}; let var = |v: Var| match v { Var::S(r) => r as u32, Var::V(n) => VAR_VGPR + n as u32, @@ -174,12 +189,19 @@ impl Ir for DxilIr { for &(v, x) in inputs { self.lw.wr(var(v), x); } - let block = self.lw.cur(); + // the registers `Lw` touches for `d` alone + let before = std::mem::take(&mut self.lw.init.touched); self.lw.pc = d.pc; - self.lw.inst_guarded(d, guard, None)?; - if self.lw.cur() != block { - return Err("it made blocks of its own".into()); + let r = self.lw.inst_guarded(d, guard, None); + let used = std::mem::replace(&mut self.lw.init.touched, before); + self.lw.init.touched.extend(&used); + r?; + let known: BTreeSet = inputs.iter().map(|&(v, _)| var(v)).chain(outputs.iter().map(|&v| var(v))).collect(); + if let Some(r) = used.iter().find(|&&r| r < VAR_BUDGET && !known.contains(&r)) { + return Err(format!("it reads register {r} the per-lane form did not pass")); } + let tail = self.lw.cur(); + self.tails[self.cur] = tail; Ok(outputs.iter().map(|&v| self.lw.rd(var(v))).collect()) } fn read_lane(&mut self, v: Value, lane: Value) -> Value { @@ -265,6 +287,47 @@ pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Resu Ok(ir.lw.finish(cs.threads, if wave64 { 64 } else { 32 })?.dxil) } + +/// `XCL_PER_LANE=1` (with `XCL_DIRECT_DXIL`): compute programs try the per-lane form first, then +/// #1426's per-instruction form, then the HLSL path. +pub fn enabled() -> bool { + std::env::var("XCL_PER_LANE").is_ok_and(|v| v == "1") +} + +/// A compute program in its per-lane form with the runtime's options `o` (`pso::direct_compute`): +/// the container and its static samplers. The split wave64 form is not lowered yet. +pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> Result { + if o.split { + return Err("the split wave64 form".into()); + } + if o.mem_windows & super::HEAP_WINDOWS != 0 { + return Err("heap memory windows".into()); + } + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + // as `kernel::translate_entry`: a thread with a large stack, a panic is a refusal + let cs = cs.clone(); + std::thread::Builder::new() + .name("xcl-per-lane".into()) + .stack_size(256 << 20) + .spawn(move || { + let ir = lower::lower_compute(&insts, &cs, o.wave64, DxilIr::with(&insts, o, &Entry::Compute(cs.clone())))?; + ir.lw.finish(cs.threads, if o.wave64 { 64 } else { 32 }) + }) + .map_err(|e| format!("per-lane thread: {e}"))? + .join() + .map_err(|e| { + let msg = e.downcast_ref::().cloned().or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default(); + format!("the per-lane lowering panicked: {msg}") + })? +} + #[cfg(test)] mod tests { use super::super::lower::tests::*; @@ -439,4 +502,24 @@ mod tests { assert_eq!(runner::dispatch(&hlsl, [3, 1, 1], &[100, 0], &mem).unwrap(), gpu); } } + + /// With the runtime's four memory windows (`compute_with`), the memory instructions go + /// through #1426's window switch (blocks of its own in the `Ir` block) and the program + /// still gives the CPU lowering's memory; the split wave64 form is refused. + #[test] + fn a_per_lane_program_with_four_memory_windows_runs_on_the_gpu() { + let cs = compute_cs(); + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + let split = super::compute_with(&bytes, &cs, super::KernelOptions { wave64: true, split: true, ..o }).err().unwrap_or_default(); + assert!(split.contains("split"), "{split}"); + if !gpu() { + return; + } + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let mem = vec![0u32; 256]; + let out = runner::dispatch(&k.dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..]); + } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 496543a53c..cca24d7c89 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -235,12 +235,18 @@ mod translated { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { return 0; } - identity_with( + let id = identity_with( env!("XCL_TRANSLATOR_SOURCE_ID"), super::dxc::toolchain_identity(), Backend::current(), crate::gpu::dxil::kernel::TRANSLATOR_VERSION, - ) + ); + // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity + if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { + identity_for(&id.to_string(), "xcl-per-lane") + } else { + id + } }) } @@ -605,6 +611,20 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::detect_wave64(code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; + // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses + if super::lower_dxil::enabled() { + match super::lower_dxil::compute_with(code, &cs, o) { + Ok(k) => { + crate::gpu::dxil::coverage::record_translated("CS per-lane"); + dump_direct(blob, &k.dxil); + return Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }); + } + Err(e) => { + let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); + crate::xlog_info!("[SHADER] per-lane fallback reason=\"{reason}\" detail=\"{}\" – per-instruction form", e.lines().next().unwrap_or("")); + } + } + } let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) From 5963c264b1cd67e5fb772e111e183fe1f17b0de7 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:58:26 -0300 Subject: [PATCH 25/51] Recompiler: far jumps in the per-lane form The largest retail compute program (14.7 MB of per-instruction DXIL) was refused for `s_setpc_b64`: its seven are all far jumps (`s_getpc_b64`, a constant added, `s_setpc_b64`) that `resolve_far_jumps` resolves and the lane-mask analysis already turns into an edge. A resolved `s_setpc_b64` now ends its block like `s_branch`. `s_getpc_b64` gives the address after it as the program's offset, as #1426 does; `s_addc_u32` / `s_subb_u32` are lowered with SCC as the carry / borrow, in and out. The test decoder resolves far jumps as the real one does. --- crates/xcl/src/gpu/recomp/lower.rs | 77 +++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 0b383a955e..7336c75b62 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -352,6 +352,14 @@ impl<'a, I: Ir> Lower<'a, I> { if self.wave_salu(b, d)? { return Ok(()); } + if name == "S_GETPC_B64" { + // the address after it, as the program's offset (#1426's `s_getpc_b64`): read only by + // the far jump `resolve_far_jumps` resolved + let (lo, hi) = (self.ir.int((d.pc + d.len as u64) as u32), self.ir.int(0)); + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + return Ok(()); + } let width = if self.wave64 { "_B64" } else { "_B32" }; // mask-width ops: on lane bits when they write EXEC, are a saveexec, or read a mask if let Some(base) = name.strip_suffix(width) { @@ -430,6 +438,25 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_num(b, sd, v); self.write_scc(b, scc); } + "S_ADDC_U32" | "S_SUBB_U32" => { + // with SCC as the carry in / borrow in, and the carry / borrow out in SCC + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let cin = self.read_scc(b); + let cin = self.ir.zext(cin); + let (v, out) = if name == "S_ADDC_U32" { + let t = self.ir.bin(Bin::Add, a, c); + let v = self.ir.bin(Bin::Add, t, cin); + let (c1, c2) = (self.ir.icmp(Cmp::Ult, t, a), self.ir.icmp(Cmp::Ult, v, t)); + (v, self.ir.bin(Bin::Or, c1, c2)) + } else { + let t = self.ir.bin(Bin::Sub, a, c); + let v = self.ir.bin(Bin::Sub, t, cin); + let (b1, b2) = (self.ir.icmp(Cmp::Ult, a, c), self.ir.icmp(Cmp::Ult, t, cin)); + (v, self.ir.bin(Bin::Or, b1, b2)) + }; + self.write_num(b, sd, v); + self.write_scc(b, out); + } "S_ADD_I32" | "S_SUB_I32" => { let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); let op = if name == "S_ADD_I32" { Bin::Add } else { Bin::Sub }; @@ -1106,7 +1133,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s for i in block.insts.clone() { let d = &insts[i]; let name = d.inst.name; - if i == last && (name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM")) { + if i == last && (name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM") || d.far_target.is_some()) { break; } if let Some(&(_, s, c)) = split.next_if(|x| x.0 == i) { @@ -2303,9 +2330,57 @@ pub(crate) mod tests { off += d.len; out.push(d); } + rdna2::resolve_far_jumps(&mut out); out } + /// `s_addc_u32` / `s_subb_u32` take SCC as the carry / borrow in and leave theirs in SCC. + #[test] + fn add_with_carry_and_subtract_with_borrow() { + let lines: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255), ("LITERAL", 0xFFFF_FFFF)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 129)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 128), ("SSRC1", 128)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 0), ("SSRC1", 128)]), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 128), ("SSRC1", 129)]), + ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 133), ("SSRC1", 129)]), + ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 133), ("SSRC1", 129)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, _) = run(lines, false, &s, &v); + // 0xFFFFFFFF + 1 = 0 carry 1; 0 + 0 + 1 = 1; 0xFFFFFFFF + 0 + 0 = 0xFFFFFFFF + assert_eq!((s[1], s[2], s[5]), (0, 1, 0xFFFF_FFFF)); + // 0 - 1 = 0xFFFFFFFF borrow 1; 5 - 1 - 1 = 3; 5 - 1 - 0 = 4 + assert_eq!((s[3], s[4], s[6]), (0xFFFF_FFFF, 3, 4)); + } + + /// A far jump (`s_getpc_b64`, a constant added, `s_setpc_b64`, as a retail program jumps + /// over a long `then` block) is a plain jump: the lanes skip the instructions it jumps over. + #[test] + fn a_far_jump_skips_what_it_jumps_over() { + let far: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 2)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 255), ("LITERAL", 32)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 128)]), + ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 136)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 137)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 138)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 139)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 0)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, v) = run(far, false, &s, &v); + // the address it computed: after `s_getpc_b64` (8) plus 32, past the four moves + assert_eq!((s[2], s[3]), (40, 0)); + for (l, regs) in v.iter().enumerate() { + assert_eq!((regs[1], regs[2]), (7, 7 + l as u32), "lane {l}"); + } + } + /// The kernel run on the CPU: initial (sgpr, vgpr[lane]) → final ones. fn run(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec]) -> (Vec, Vec>) { let (s, v, _) = run_mem(lines, wave64, sgpr, vgpr, &[]); From bc0d77c9b06f59d942a829979019d73b04263b95 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:09:31 -0300 Subject: [PATCH 26/51] Recompiler: xcl shaders --direct --lanes measures the per-lane form With `--lanes`, the direct sweep also lowers every compute program in the per-lane form (`lower_dxil::compute_with`, the sweep's options), and prints how many it translates, their DXIL size against the per-instruction form's for the same programs, and its refusals ranked. `--trace` lists each per-lane program's size. --- crates/xcl/src/shaders.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0374628a55..2ada0d332b 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1869,6 +1869,14 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: let max_bytes = opt("--max-bytes").map(|v| v as usize).unwrap_or(16384); let timeout = std::time::Duration::from_secs(opt("--timeout").unwrap_or(10)); let skipped = AtomicUsize::new(0); + // `--lanes`: compute programs through the per-lane form too (`recomp::lower_dxil`); where it + // translates, its DXIL size against the per-instruction form's, and the refusals ranked + let lanes = args.iter().any(|a| a == "--lanes"); + let lanes_tried = AtomicUsize::new(0); + let lanes_ok = AtomicUsize::new(0); + let lanes_bytes = AtomicUsize::new(0); + let lanes_vs = AtomicUsize::new(0); + let lanes_why: Mutex> = Mutex::new(HashMap::new()); // `--hash H`: only the container whose `[SHADER]` hash (FNV-64 of the container) is H, every // record searched; `--dump DIR`: write each program's direct DXIL (and with `--compare` the // HLSL path's source and DXIL) to DIR, for diffing the two (`dxc -dumpbin`) @@ -1923,6 +1931,20 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; let time = t.elapsed(); + if let (true, recomp::Mode::Compute(cs)) = (lanes, &mode) { + lanes_tried.fetch_add(1, Ordering::Relaxed); + match recomp::lower_dxil::compute_with(code, cs, o) { + Ok(k) => { + lanes_ok.fetch_add(1, Ordering::Relaxed); + lanes_bytes.fetch_add(k.dxil.len(), Ordering::Relaxed); + lanes_vs.fetch_add(r.as_ref().map_or(0, |d| d.len()), Ordering::Relaxed); + if trace { + eprintln!("per-lane: {name} FSSM#{fi}: {} B, per-instruction {:?} B", k.dxil.len(), r.as_ref().map(|d| d.len())); + } + } + Err(e) => *lanes_why.lock().unwrap().entry(survey_key(&e)).or_default() += 1, + } + } let dump = |suffix: &str, bytes: &[u8]| { if let Some(d) = &dump_dir { let _ = std::fs::write(d.join(format!("{blob_hash:016x}_f{fi}_{:x}.{suffix}", p.offset)), bytes); @@ -1965,6 +1987,12 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: println!("{}", rep.json(top)); } else { println!("{} programs from {} sampled records (seed {seed}; {} over {max_bytes} B skipped){}{}", results.len(), order.len().min(input.len()), skipped.load(Ordering::Relaxed), if validate { ", validated" } else { "" }, if compare { ", compared with HLSL+DXC" } else { "" }); + if lanes { + let mut why: Vec<(String, usize)> = lanes_why.into_inner().unwrap().into_iter().collect(); + why.sort_by(|a, b| b.1.cmp(&a.1)); + why.truncate(top); + println!("per-lane form: {} of {} compute programs; where it translates, {} B against {} B per instruction; refused for: {why:?}", lanes_ok.load(Ordering::Relaxed), lanes_tried.load(Ordering::Relaxed), lanes_bytes.load(Ordering::Relaxed), lanes_vs.load(Ordering::Relaxed)); + } print!("{}", rep.text(top)); println!("time {:.1} s", t0.elapsed().as_secs_f64()); } From 372be9daba5a5b7475a588707da7e662c21d721a Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:09:31 -0300 Subject: [PATCH 27/51] Recompiler: s_cselect, s_wqm and v_cmpx in the per-lane form The first whole-pack sweep of the per-lane form (250 of 2 689 compute programs) was refused mostly for `s_wqm_b32` (754), `s_cselect_b32` / `_b64` (605) and float `v_cmpx_*` (about 400), and 44 programs hit a builder error. - `s_cselect` picks numbers by SCC, or, where a source holds a mask (`s_cselect_b64 s, exec, 0`), the lane's bit by its SCC. - `s_wqm` of a mask: a lane's bit is set when any lane of its quad has its bit (the quad is in the lane's own half of the ballot). - `v_cmpx_*` without a lowering of its own goes through #1426's: EXEC goes in as a number with only this lane's bit and comes back as the lane's bit of the result. - `Lw` writes to its entry block (`Block(0)`) until the end (static samplers, the scratch array): the adapter's first block is a new one, and `Block(0)` jumps to it at `finish`, as #1426's translator ends it. Before, an instruction #1426 lowered could append after Block(0)'s branch ("instruction after a terminator"). Tests: `s_wqm` and `s_cselect` on the CPU lowering; scratch through #1426's lowering gives a container and runs on the GPU (fails before the entry fix); vladbondarenko97's f32 compares (with v_cmpx) now run per lane and match the HLSL path on the GPU. --- crates/xcl/src/gpu/recomp/lower.rs | 75 ++++++++++++++++++++++--- crates/xcl/src/gpu/recomp/lower/wave.rs | 19 +++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 46 +++++++++++++-- 3 files changed, 128 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 7336c75b62..36ae8c4f09 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -380,6 +380,14 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_scc(b, new); return Ok(()); } + if op == "CSELECT" && (sd == EXEC || reads_mask) { + // `s_cselect_b64 s, exec, 0`: the lane's bit of the source SCC picks + let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); + let scc = self.read_scc(b); + let v = self.ir.select(scc, a, c); + self.write_bit(b, sd, v); + return Ok(()); + } if bitwise && (sd == EXEC || reads_mask) { let a = self.src_bit(b, s0)?; let v = match op { @@ -438,6 +446,19 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_num(b, sd, v); self.write_scc(b, scc); } + "S_CSELECT_B32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let scc = self.read_scc(b); + let v = self.ir.select(scc, a, c); + self.write_num(b, sd, v); + } + "S_CSELECT_B64" => { + let ((al, ah), (cl, ch)) = (self.src64(b, d, s0)?, self.src64(b, d, s1)?); + let scc = self.read_scc(b); + let (lo, hi) = (self.ir.select(scc, al, cl), self.ir.select(scc, ah, ch)); + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + } "S_ADDC_U32" | "S_SUBB_U32" => { // with SCC as the carry in / borrow in, and the carry / borrow out in SCC let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); @@ -1314,13 +1335,15 @@ impl Lower<'_, I> { /// operands are read as numbers (a mask read whole is refused, as everywhere), the mask a /// VALU reads lane by lane (`v_cndmask_b32`'s selector, a carry-in) as a number holding only /// this lane's bit, and a mask it writes (a compare, a carry-out) comes back as this lane's - /// bit of the ballot it makes. Instructions writing EXEC are not taken. + /// bit of the ballot it makes. Of the instructions writing EXEC, only `v_cmpx_*` is taken. fn bridge(&mut self, b: usize, d: &Decoded, in_store_block: bool) -> R<()> { let name = d.inst.name; let (whole, written) = super::x64_masks::uses(d); let (_, explicit_w) = rdna2::sgpr_uses(d); let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r); - if writes & (3 << 126) != 0 || name.starts_with("V_CMPX") { + // `v_cmpx_*`: EXEC goes in as this lane's bit and comes back as its bit of the result + let cmpx = name.starts_with("V_CMPX"); + if writes & (3 << 126) != 0 && !cmpx { return Err("writes EXEC".into()); } if name == "S_BARRIER" && self.partial[b] { @@ -1338,14 +1361,20 @@ impl Lower<'_, I> { let operand = |input: bool, ty: &str| d.ienc.operands.iter().any(|o| o.input == input && o.output != input && o.ty == ty); let mut inputs: Vec<(Var, I::V)> = Vec::new(); // SGPRs read whole: numbers (EXEC included, which holds a mask here: refused) - for r in (0..128u8).filter(|&r| whole >> r & 1 != 0 && r != 125) { + for r in (0..128u8).filter(|&r| whole >> r & 1 != 0 && r != 125 && !(cmpx && r >= EXEC)) { let v = self.read_num(b, r)?; inputs.push((Var::S(r), v)); } // a mask read lane by lane: a number with only this lane's bit let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); - if matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { - let m = if vop3 { rdna2::field_value(d.enc, &d.words, "SRC2").unwrap_or(0) } else { VCC as u64 }; + let lane_mask = if cmpx { + Some(EXEC as u64) + } else if matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + Some(if vop3 { rdna2::field_value(d.enc, &d.words, "SRC2").unwrap_or(0) } else { VCC as u64 }) + } else { + None + }; + if let Some(m) = lane_mask { if m > 127 { return Err(format!("{name}: mask operand {m}")); } @@ -1394,7 +1423,7 @@ impl Lower<'_, I> { if writes_scc { outputs.push(Var::Scc); } - let guard = if in_store_block || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; + let guard = if cmpx || in_store_block || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; let vals = self.ir.foreign(d, guard, &inputs, &outputs)?; for (&var, &v) in outputs.iter().zip(&vals) { match var { @@ -1837,8 +1866,8 @@ pub(crate) mod tests { } pub(crate) type I = (&'static str, &'static str, &'static [(&'static str, u64)]); - const V: u64 = 256; - const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + pub(crate) const V: u64 = 256; + pub(crate) const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); // wave32 programs shared by the CPU tests and the comparison with the HLSL path pub(crate) const STRAIGHT: &[I] = &[ @@ -2334,6 +2363,36 @@ pub(crate) mod tests { out } + /// `s_wqm` of a mask sets every lane of a quad with a bit; `s_cselect` picks a mask or a + /// number by SCC. + #[test] + fn whole_quad_mode_and_conditional_selects() { + let lines: &[I] = &[ + // vcc = lane 5 only; s0 = wqm(vcc) = lanes 4–7 + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 133), ("VSRC1", 0)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128), ("SRC1", 129), ("SRC2", 0)]), + // scc = (0 == 0): s1 = s0 (a mask), s2 = 5 + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 133), ("SSRC1", 135)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 128), ("SRC1", 129), ("SRC2", 1)]), + // scc = (0 == 1): s3 = 7, s4 = no lanes + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 129)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 133), ("SSRC1", 135)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 0), ("SSRC1", 128)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 128), ("SRC1", 129), ("SRC2", 4)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, v) = run(lines, false, &s, &v); + assert_eq!((s[2], s[3]), (5, 7)); + for (l, regs) in v.iter().enumerate() { + let quad = (4..8).contains(&l) as u32; + assert_eq!((regs[1], regs[2], regs[3]), (quad, quad, 0), "lane {l}"); + } + } + /// `s_addc_u32` / `s_subb_u32` take SCC as the carry / borrow in and leave theirs in SCC. #[test] fn add_with_carry_and_subtract_with_borrow() { diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs index 0d63229a80..89e92d5164 100644 --- a/crates/xcl/src/gpu/recomp/lower/wave.rs +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -414,6 +414,25 @@ impl Lower<'_, I> { let name = d.inst.name; let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); let (s0, sd) = (fv("SSRC0"), fv("SDST") as u8); + // `s_wqm` of a mask (`s_wqm_b64 exec, exec`): a lane's bit is set when any lane of its + // quad has its bit; the quad is in the lane's own half of the mask + let wqm = if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" }; + if name == wqm { + let Some((r, false)) = self.mask_reg(b, s0) else { return Err(format!("unsupported {name} of a number")) }; + let [lo, hi] = self.mask_words(b, r, true)?; + let lane = self.lane(); + let (c32, c28, f) = (self.c(32), self.c(28), self.c(0xF)); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + let w = self.ir.select(upper, hi, lo); + let q = self.ir.bin(Bin::And, lane, c28); + let w = self.ir.bin(Bin::LShr, w, q); + let w = self.ir.bin(Bin::And, w, f); + let z = self.c(0); + let bit = self.ir.icmp(Cmp::Ne, w, z); + self.write_bit(b, sd, bit); + self.write_scc(b, bit); + return Ok(true); + } let (ones, count) = match name { "S_BCNT1_I32_B32" | "S_BCNT1_I32_B64" => (true, true), "S_BCNT0_I32_B32" | "S_BCNT0_I32_B64" => (false, true), diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index e10662e12c..31aa5515bc 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -65,6 +65,14 @@ impl DxilIr { } } + /// `Lw`'s entry block jumps to the first `Ir` block, as `kernel.rs` ends it, then `Lw::finish`. + fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + let first = *self.blocks.first().ok_or("no blocks")?; + self.lw.s.m.set_block(Block(0)); + self.lw.s.m.br(first); + self.lw.finish(numthreads, hw) + } + fn bytes(&mut self, dword: Value) -> Value { let four = self.lw.s.m.i32c(4); self.lw.s.m.bin(BinOp::Mul, dword, four) @@ -92,7 +100,8 @@ impl Sink for DxilIr { impl Ir for DxilIr { fn new_block(&mut self) -> usize { - let b = if self.blocks.is_empty() { self.lw.s.m.entry_block() } else { self.lw.s.m.new_block() }; + // not `Block(0)`: `Lw` keeps writing there (static samplers, scratch) until `finish` + let b = self.lw.s.m.new_block(); self.blocks.push(b); self.tails.push(b); self.blocks.len() - 1 @@ -248,7 +257,7 @@ impl Ir for DxilIr { pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), String> { let (ir, stale) = lower::lower_kernel(insts, wave64, DxilIr::new(insts, wave64, &Entry::Kernel))?; let lanes = if wave64 { 64 } else { 32 }; - Ok((ir.lw.finish([lanes, 1, 1], lanes)?.dxil, stale)) + Ok((ir.finish([lanes, 1, 1], lanes)?.dxil, stale)) } /// `compute` from the program's code (decoded, far jumps resolved). @@ -284,7 +293,7 @@ pub fn survey_compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) - /// A compute program in its per-lane form, as a signed DXIL container. pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(insts, wave64, &Entry::Compute(cs.clone())))?; - Ok(ir.lw.finish(cs.threads, if wave64 { 64 } else { 32 })?.dxil) + Ok(ir.finish(cs.threads, if wave64 { 64 } else { 32 })?.dxil) } @@ -318,7 +327,7 @@ pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> R .stack_size(256 << 20) .spawn(move || { let ir = lower::lower_compute(&insts, &cs, o.wave64, DxilIr::with(&insts, o, &Entry::Compute(cs.clone())))?; - ir.lw.finish(cs.threads, if o.wave64 { 64 } else { 32 }) + ir.finish(cs.threads, if o.wave64 { 64 } else { 32 }) }) .map_err(|e| format!("per-lane thread: {e}"))? .join() @@ -341,6 +350,35 @@ mod tests { true } + /// An instruction lowered by #1426 that writes to `Lw`'s entry block after the program's + /// blocks are written (scratch) gives a container, and runs. + #[test] + fn a_bridged_instruction_may_write_to_the_entry_block() { + // scratch through #1426's lowering: its array is allocated in `Lw`'s entry block once + // the program's blocks are written (an "instruction after a terminator" before) + let lines: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), + ("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7F)]), + ("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 3), ("ADDR", 2), ("SADDR", 0x7F)]), + ENDPGM, + ]; + let dxil = super::kernel(&decode(lines), false).map(|r| r.0); + let dxil = dxil.unwrap_or_else(|e| panic!("{e}")); + if !gpu() { + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let out = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..32 { + assert_eq!(out.vgpr[l][3], l as u32, "lane {l}"); + } + } + /// The per-lane form as real DXIL on the GPU agrees with the lowering run on the CPU (and so /// with the HLSL path, which `lower`'s tests compare it with): registers and memory. #[test] From 77a5eee12201f4092ae518552a4ae3496906b50e Mon Sep 17 00:00:00 2001 From: upipibi Date: Tue, 24 Nov 2026 12:35:00 -0600 Subject: [PATCH 28/51] Recompiler: the split wave64 form in the direct lowering, through #1426's Lw A wave64 program on 32-lane hardware as two wave32 halves, with #1426's lane machinery instead of a copy: KernelOptions::split, so Lw::new lays out the halves' exchange storage and picks the meet (a group barrier for one console wave per group, the spin meet with arrival counters for more); lanes numbered as the hardware waves arrive (setup_lanes for a kernel, setup_lanes_compute for a compute program, both in the entry block: the lowering takes lane() before compute_ids, and in the split form the console lane is not the hardware lane). The whole-wave ballot and lane read meet the other half (Lw::ballot, Lw::read_lane_uniform); the half-local ones stay in the half; Ir::whole_needs_exchange keeps them out of blocks lanes leave one by one. Branches go through Lw::br / Lw::cond_br so Lw's own variables (the exchange count, the dead flag) get their edges, and the lowering's blocks are sealed for them before Lw::finish. lower_dxil::kernel_split / compute_split. The GPU test runs the lowering's wave64 programs in this form against the CPU interpreter's wave64 run, and a 128-thread group (two console waves, the spin meet). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 104 +++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 106 ++++++++++++++++++++---- 2 files changed, 195 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 36ae8c4f09..42a9c9f1ab 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -2689,6 +2689,110 @@ pub(crate) mod tests { } } + /// The split form (two hardware wave32s per console wave64, `lower_dxil::kernel_split`) run + /// on the GPU gives the registers and memory of the wave64 lowering run on the CPU: masks + /// across both halves, lane reads through the exchange (readfirstlane, readlane, the counts + /// of EXEC as numbers, mbcnt), and the reads that stay in their half (DPP, permlanex16, + /// ds_swizzle). A whole-wave read where lanes leave one by one is refused. + #[test] + fn the_split_form_agrees_with_the_wave64_lowering_on_the_gpu() { + use super::super::{lower_dxil, runner}; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return; + } + let reads = lane_reads(true); + // reads across the halves both ways: readlane of lane 41 (the lower half needs the + // upper's), readfirstlane with EXEC from lane 40 up (the first lane is in the upper + // half), and a 64-bit compare mask counted as a number + const ACROSS: &[I] = &[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 169)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", 131)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 106)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 168)]), + ("V_CMPX_LE_U32", "ENC_VOPC", &[("SRC0", V + 2), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 126)]), + ENDPGM, + ]; + for (name, lines) in [ + ("across the halves", ACROSS), + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF_W64), + ("leaving loop", LEAVING_LOOP_W64), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY_W64), + ("lane reads", &reads[..]), + ] { + let insts = decode(lines); + let (dxil, stale) = lower_dxil::kernel_split(&insts).unwrap_or_else(|e| panic!("{name}: {e}")); + let (s, v) = state(64); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap_or_else(|e| panic!("{name}: {e}")); + let (cs, cv, cmem) = run_mem(lines, true, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let mut sregs: Vec = vec![106, 107, 126, 127]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(gpu.sgpr[r], cs[r], "{name}: s{r}"); + } + for l in 0..64 { + for &r in &vregs { + assert_eq!(gpu.vgpr[l][r], cv[l][r], "{name}: lane {l} v{r}"); + } + } + } + // compute mode: a 64-thread group as two hardware wave32s, threads numbered by arrival + let cs = compute_cs(); + let dxil = lower_dxil::compute_split(&decode(COMPUTE), &cs).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..], "compute"); + // two console waves per group: their halves pair up through #1426's arrival counters + // and meet in its spin loop. Each thread stores its lane (`mbcnt` of EXEC: the mask + // words exchanged), its thread id and its console wave's first thread + // (`readfirstlane`: a lane of the other half for the upper one) + const TWO_WAVES: &[I] = &[ + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 135)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 3), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 126), ("SRC1", 128)]), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 127), ("SRC1", V + 5)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 136), ("SRC2", V)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 10), ("SRC1", 144), ("SRC2", V + 7)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]; + let big = crate::gpu::recomp::CsInterface { threads: [128, 1, 1], ..compute_cs() }; + let dxil = lower_dxil::compute_split(&decode(TWO_WAVES), &big).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(TWO_WAVES, &big, true, 2, &[100, 0], &mem); + assert_eq!(&gpu[..256], &cpu[..256], "two console waves per group"); + assert!(cpu[..256].iter().any(|&w| w >> 16 == 64), "the CPU run's second wave starts at thread 64"); + // the waterfall's readfirstlane is in a block lanes leave one by one: native wave64 + // takes it, the split form cannot meet the other half there + let insts = decode(&waterfall(true)); + assert!(lower_kernel(&insts, true, Interp::default()).is_ok()); + let e = lower_dxil::kernel_split(&insts).unwrap_err(); + assert!(e.contains("split form"), "{e}"); + } + #[test] fn scalar_and_vector_memory_with_a_guarded_store() { let (s, v) = state(32); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 31aa5515bc..3bd492b9dc 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -32,6 +32,10 @@ struct DxilIr { cur: usize, /// `compute_ids` set up the lanes (`Lw::lane` is the console lane) lanes_set: bool, + /// a split compute program's thread ids, set up with its lanes in the constructor: the + /// lowering takes `lane()` before `compute_ids`, and in the split form the console lane + /// is not the hardware lane (the upper half's are 32-63) + ids: Option<(Value, [Value; 3])>, } impl DxilIr { @@ -41,7 +45,16 @@ impl DxilIr { Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) } - /// The builder state with the runtime's options `o` (memory windows, sampler registers). + /// `new` in the split form (two hardware wave32s per console wave64): #1426's `Lw` numbers + /// the threads as the hardware waves arrive and lays out the halves' exchange storage; its + /// `ballot` / `read_lane_uniform` meet the other half (a group barrier for one console + /// wave per group, the spin meet for more). + fn split(insts: &[Decoded], entry: &Entry) -> DxilIr { + Self::with(insts, KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }, entry) + } + + /// The builder state with the runtime's options `o` (memory windows, sampler registers, the + /// split form). fn with(insts: &[Decoded], o: KernelOptions, entry: &Entry) -> DxilIr { // block leaders for the constant-sampler scan: the first instruction, branch targets // and the instruction after a branch @@ -52,10 +65,25 @@ impl DxilIr { leaders.extend(insts.get(i + 1).map(|n| n.pc)); } } - let lw = Lw::new(insts, &leaders, o, entry); + let mut lw = Lw::new(insts, &leaders, o, entry); + // a kernel's lanes in the split form: the console lane each hardware lane stands for, + // set up in the entry block (a compute program's come with `compute_ids`) + let mut ids = None; + let lanes_set = match entry { + Entry::Kernel if lw.split => { + lw.setup_lanes(); + true + } + Entry::Compute(cs) if lw.split => { + let lds = lw.lds.is_some(); + ids = Some(lw.setup_lanes_compute(cs.threads, lds)); + true + } + _ => false, + }; let io = lw.init.io.expect("the I/O buffer"); let (res, mem) = (lw.res, lw.mems[0]); - DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set: false } + DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set, ids } } fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { @@ -65,11 +93,19 @@ impl DxilIr { } } - /// `Lw`'s entry block jumps to the first `Ir` block, as `kernel.rs` ends it, then `Lw::finish`. + /// The container: `Lw`'s entry block jumps to the first `Ir` block (as `kernel.rs` ends it), + /// the lowering's blocks are sealed for `Lw`'s variables (every edge into them is known once + /// the lowering is done), then `Lw::finish`. fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { let first = *self.blocks.first().ok_or("no blocks")?; self.lw.s.m.set_block(Block(0)); - self.lw.s.m.br(first); + self.lw.br(first); + for i in 0..self.blocks.len() { + let b = self.blocks[i]; + if !self.lw.ssa.is_sealed(b) { + self.lw.seal(b); + } + } self.lw.finish(numthreads, hw) } @@ -165,21 +201,36 @@ impl Ir for DxilIr { fn compute_ids(&mut self, threads: [u32; 3]) -> (Value, [Value; 3]) { // #1426's compute entry: 2-D / 3-D groups numbered as their waves arrive, the counter // in the program's top LDS word when it has LDS + if let Some(ids) = self.ids { + return ids; + } let lds = self.lw.lds.is_some(); let ids = self.lw.setup_lanes_compute(threads, lds); self.lanes_set = true; ids } + fn whole_needs_exchange(&self) -> bool { + self.lw.split + } fn ballot(&mut self, c: Value) -> [Value; 2] { + if self.lw.split { + // this half's word from the hardware, the other's through the exchange + let (lo, hi) = self.lw.ballot(c); + return [lo, hi]; + } let w = self.lw.s.wave_ballot(c); [w[0], w[1]] } // one hardware wave per console wave (native wave64, or wave32): the half-local forms are - // the same operations fn mem_windows(&self) -> u32 { self.lw.mems.len() as u32 } + // the same operations; in the split form only the reader's half is right (`Ir::ballot_half`) fn ballot_half(&mut self, c: Value) -> [Value; 2] { + if self.lw.split { + let w = self.lw.s.wave_ballot(c); + return [w[0], w[0]]; + } self.ballot(c) } /// #1426's semantics of `d` (`Lw::inst_guarded`) in the current block: the inputs are written @@ -214,9 +265,17 @@ impl Ir for DxilIr { Ok(outputs.iter().map(|&v| self.lw.rd(var(v))).collect()) } fn read_lane(&mut self, v: Value, lane: Value) -> Value { + if self.lw.split { + // the lowering's lane reads take the same lane in every lane (readlane, + // readfirstlane, writelane's source) + return self.lw.read_lane_uniform(v, lane); + } self.lw.s.wave_read_lane_at(v, lane) } fn read_lane_half(&mut self, v: Value, lane: Value) -> Value { + if self.lw.split { + return self.lw.read_lane_half(v, lane); + } self.read_lane(v, lane) } fn count_bits(&mut self, v: Value) -> Value { @@ -240,11 +299,15 @@ impl Ir for DxilIr { let mem = self.mem; self.lw.s.raw_store(mem, addr, &[value]); } + // through `Lw`, which records the edges for its own variables (the split form's exchange + // count and dead flag, its temporaries); the lowering's blocks are sealed in `finish` fn br(&mut self, target: usize) { - self.lw.s.m.br(self.blocks[target]); + let b = self.blocks[target]; + self.lw.br(b); } fn br_if(&mut self, c: Value, then: usize, otherwise: usize) { - self.lw.s.m.cond_br(c, self.blocks[then], self.blocks[otherwise]); + let (t, f) = (self.blocks[then], self.blocks[otherwise]); + self.lw.cond_br(c, t, f); } fn ret(&mut self) { self.lw.s.m.ret(); @@ -260,6 +323,21 @@ pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), Str Ok((ir.finish([lanes, 1, 1], lanes)?.dxil, stale)) } +/// `kernel` in the split form: a wave64 program as two hardware wave32s (`DxilIr::split`). +/// EXEC at launch must be the whole console wave, as the CPU interpreter and the HLSL path +/// start it. +pub fn kernel_split(insts: &[Decoded]) -> Result<(Vec, Vec), String> { + let (ir, stale) = lower::lower_kernel(insts, true, DxilIr::split(insts, &Entry::Kernel))?; + Ok((ir.finish([64, 1, 1], 32)?.dxil, stale)) +} + +/// `compute` in the split form: each console wave64 as two hardware wave32s, threads numbered +/// by arrival (`Lw::setup_lanes_compute`). +pub fn compute_split(insts: &[Decoded], cs: &super::CsInterface) -> Result, String> { + let ir = lower::lower_compute(insts, cs, true, DxilIr::split(insts, &Entry::Compute(cs.clone())))?; + Ok(ir.finish(cs.threads, 32)?.dxil) +} + /// `compute` from the program's code (decoded, far jumps resolved). pub fn compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Result, String> { let mut insts = Vec::new(); @@ -304,11 +382,8 @@ pub fn enabled() -> bool { } /// A compute program in its per-lane form with the runtime's options `o` (`pso::direct_compute`): -/// the container and its static samplers. The split wave64 form is not lowered yet. +/// the container and its static samplers. pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> Result { - if o.split { - return Err("the split wave64 form".into()); - } if o.mem_windows & super::HEAP_WINDOWS != 0 { return Err("heap memory windows".into()); } @@ -543,14 +618,15 @@ mod tests { /// With the runtime's four memory windows (`compute_with`), the memory instructions go /// through #1426's window switch (blocks of its own in the `Ir` block) and the program - /// still gives the CPU lowering's memory; the split wave64 form is refused. + /// still gives the CPU lowering's memory; heap memory windows are refused. #[test] fn a_per_lane_program_with_four_memory_windows_runs_on_the_gpu() { let cs = compute_cs(); let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; - let split = super::compute_with(&bytes, &cs, super::KernelOptions { wave64: true, split: true, ..o }).err().unwrap_or_default(); - assert!(split.contains("split"), "{split}"); + let heap = super::KernelOptions { mem_windows: 4 | super::super::HEAP_WINDOWS, ..o }; + let heap = super::compute_with(&bytes, &cs, heap).err().unwrap_or_default(); + assert!(heap.contains("heap"), "{heap}"); if !gpu() { return; } From d2cc6ff15b3f414fdc60329cbd319c4d3e848c1e Mon Sep 17 00:00:00 2001 From: teidenzero <8762337+teidenzero@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:44:54 -0500 Subject: [PATCH 29/51] Recompiler: the lane-mask analysis can start from an unknown EXEC The analysis takes EXEC at the entry as every lane. That holds in kernel mode (lanes outside EXEC leave at once) and in compute, but not in a PS, whose helper lanes start outside EXEC and run the program too: a vector write before EXEC is written would lose the guard that keeps a helper lane from writing. `analyze_launch` takes the launch EXEC as `LaunchExec::All` (what `analyze` still does) or `LaunchExec::Unknown`, an atom: then a vector instruction keeps its guard until EXEC is written, and a lane branch still proves EXEC where it does. Agreed for VS / PS in #1269. Tested on an RTX 4090 (Windows 10 22H2, DXC 1.8.2502): cargo test -p xcl --lib -- recomp::lower recomp::lane_masks gpu::dxil --test-threads=4: 115 passed, 0 failed, 1 ignored (the base: 113 passed). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lane_masks.rs | 72 +++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 0fd1491dba..6de1fc40ad 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -202,6 +202,18 @@ enum Atom { Opaque(u64, usize), /// an unresolved join of this slot (SGPR, `SCC`) at the start of this block Join(usize, usize), + /// EXEC at launch, where it need not hold every lane that runs (`LaunchExec::Unknown`) + Launch, +} + +/// EXEC at the program's start, as the analysis takes it. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum LaunchExec { + /// every lane that runs is in EXEC: kernel mode (lanes outside it leave at once) and compute + All, + /// unknown per lane: a PS, whose helper lanes start outside EXEC and run on. A vector + /// instruction keeps its guard until EXEC is written. + Unknown, } /// The masks at a program point. `regs[r]`: the lane function of the mask SGPR r holds (wave64: @@ -259,6 +271,7 @@ fn is_vector(d: &Decoded) -> bool { struct Lanes<'a> { insts: &'a [Decoded], wave64: bool, + launch: LaunchExec, bdd: Bdd, atoms: HashMap, /// block each atom is born in @@ -277,7 +290,7 @@ struct Lanes<'a> { } impl<'a> Lanes<'a> { - fn new(insts: &'a [Decoded], wave64: bool) -> R { + fn new(insts: &'a [Decoded], wave64: bool, launch: LaunchExec) -> R { let starts: HashMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); let mut leaders = BTreeSet::from([0usize]); let mut target = vec![None; insts.len()]; @@ -405,7 +418,7 @@ impl<'a> Lanes<'a> { (written, kill, d.ienc.operands.iter().any(|o| o.output && o.ty == "OPR_SSRC_SPECIAL_SCC")) }) .collect(); - Ok(Lanes { insts, wave64, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, body, effects }) + Ok(Lanes { insts, wave64, launch, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, body, effects }) } fn atom(&mut self, a: Atom, block: usize) -> R { @@ -693,7 +706,10 @@ impl<'a> Lanes<'a> { fn analyze(mut self) -> R { let n = self.blocks.len(); let mut entry = State { regs: vec![None; 128], scc: None }; - entry.regs[EXEC] = Some(TRUE); + entry.regs[EXEC] = Some(match self.launch { + LaunchExec::All => TRUE, + LaunchExec::Unknown => self.atom(Atom::Launch, 0)?, + }); let mut forced = HashSet::new(); let mut reach = vec![FALSE; n]; let mut ins: Vec> = vec![None; n]; @@ -795,12 +811,17 @@ impl<'a> Lanes<'a> { } } -/// Analyses a decoded program (far jumps resolved). +/// Analyses a decoded program (far jumps resolved) that starts with every lane in EXEC. pub fn analyze(insts: &[Decoded], wave64: bool) -> R { + analyze_launch(insts, wave64, LaunchExec::All) +} + +/// Analyses a decoded program (far jumps resolved) that starts with EXEC as `launch` says. +pub fn analyze_launch(insts: &[Decoded], wave64: bool, launch: LaunchExec) -> R { if insts.is_empty() { return Ok(Summary::default()); } - Lanes::new(insts, wave64)?.analyze() + Lanes::new(insts, wave64, launch)?.analyze() } /// Decodes and analyses a program. @@ -945,4 +966,45 @@ mod tests { assert_eq!(run(&[("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]), ENDPGM]).unwrap_err(), "indirect jump"); assert_eq!(run(&[MOV2, ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFE)]), ENDPGM]).unwrap_err(), "branch to the entry"); } + + fn run_launch(lines: &[I], launch: LaunchExec) -> R { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let mut insts = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + analyze_launch(&insts, true, launch) + } + + #[test] + fn a_lane_outside_exec_at_launch_keeps_its_guard_until_exec_is_written() { + // v_mov (a helper lane must not write); exec = -1; v_mov (every lane writes) + let p = [MOV2, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), MOV3, ENDPGM]; + let all = run_launch(&p, LaunchExec::All).unwrap(); + assert_eq!((all.vector, all.guarded.len()), (2, 0)); + let unknown = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!(unknown.guarded, vec![0], "only the v_mov before EXEC is written"); + } + + #[test] + fn a_lane_branch_still_proves_exec_when_the_launch_exec_is_unknown() { + // as `a_skipped_if_needs_no_guard`: inside the if only lanes with their bit run, but the + // restored EXEC after the join is the launch EXEC again + let p = [ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + RESTORE, + MOV3, + ENDPGM, + ]; + assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); + let s = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!((s.vector, s.guarded.clone(), s.lane_branches), (2, vec![20], 1)); + } } From 27d28cec5f19f01c189165b79e33dd007f18beaf Mon Sep 17 00:00:00 2001 From: teidenzero <8762337+teidenzero@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:44:54 -0500 Subject: [PATCH 30/51] Recompiler: lane masks follow s_wqm of the launch EXEC Nearly every PS starts with `s_wqm exec, exec`. The analysis did not follow s_wqm, so with the launch EXEC unknown, EXEC after it was an unknown mask too and every vector instruction of the program kept its guard. Every lane that runs a PS is either in the launch EXEC or a helper lane of a quad with a lane in it, so whole-quad mode of the launch EXEC is every lane. s_wqm of none or every lane is followed as well; of any other mask it is still an unknown mask. Tested on an RTX 4090 (Windows 10 22H2, DXC 1.8.2502): cargo test -p xcl --lib -- recomp::lower recomp::lane_masks gpu::dxil --test-threads=4: 116 passed, 0 failed, 1 ignored. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lane_masks.rs | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 6de1fc40ad..fde6bc9512 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -526,6 +526,7 @@ impl<'a> Lanes<'a> { let value = match (op, a, b) { ("MOV", Some(a), _) => Some(a), ("NOT", Some(a), _) => Some(self.bdd.not(a)?), + ("WQM", Some(a), _) => self.wqm(a), ("CSELECT", Some(a), Some(b)) => match st.scc { Some((u, false)) => { let (ua, nu) = (self.bdd.and(u, a)?, self.bdd.not(u)?); @@ -576,6 +577,17 @@ impl<'a> Lanes<'a> { Ok(()) } + /// `s_wqm` of a mask: the lanes whose quad has a lane in it. Followed only where that is a + /// mask the analysis knows: none or every lane, and the launch EXEC (`LaunchExec::Unknown`), + /// since a lane that runs outside it is a helper lane of a quad with a lane in it. + fn wqm(&mut self, a: B) -> Option { + if a <= TRUE { + return Some(a); + } + let launch = *self.atoms.get(&Atom::Launch)?; + (a == self.bdd.atom(launch)).then_some(TRUE) + } + fn kill(&self, st: &mut State, r: usize) { st.regs[r] = None; // wave64: the pair starting one register lower @@ -1007,4 +1019,24 @@ mod tests { let s = run_launch(&p, LaunchExec::Unknown).unwrap(); assert_eq!((s.vector, s.guarded.clone(), s.lane_branches), (2, vec![20], 1)); } + + #[test] + fn whole_quad_mode_of_the_launch_exec_is_every_lane() { + // s[0:1] = exec; s_wqm exec, exec; v_mov (helper lanes too); exec &= s[0:1]; v_mov + let wqm: I = ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]); + let p: [I; 6] = [ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + wqm, + MOV2, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + MOV3, + ENDPGM, + ]; + let s = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!(s.guarded, vec![16], "only the v_mov after EXEC is narrowed to the launch EXEC again"); + assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); + // the quads of any other mask are not followed + let s = run_launch(&[CMP, ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), MOV2, ENDPGM], LaunchExec::All).unwrap(); + assert_eq!(s.guarded, vec![8]); + } } From a24899e7fb97fed7226f716c9e275981f95f997b Mon Sep 17 00:00:00 2001 From: teidenzero <8762337+teidenzero@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:44:54 -0500 Subject: [PATCH 31/51] Recompiler: VS / PS stages in the per-lane lowering `lower_graphics` lowers a vertex or pixel shader in the per-lane form, as agreed in #1269: - `Ir::graphics_start` / `Ir::graphics_end`: one opaque method each for a stage's start and end, which the DXIL adapter will map onto #1426's `setup_vertex` / `setup_pixel` and `finish_gfx`. An IR without them refuses the program. The CPU interpreter takes the stage's VGPRs and launch EXEC from `io`, as in kernel mode. - Every lane runs the program: a PS's helper lanes start with their EXEC bit clear instead of taking the kernel's way out, and the lane-mask analysis takes the launch EXEC as unknown, so their vector writes and stores keep their guards. - `s_wqm` is followed where the analysis finds it gives every lane (`Summary::wqm_all`), and refused otherwise. - In a PS, instructions that need whole quads (implicit-LOD samples and gathers, `image_get_lod`, `s_wqm`) are refused in a block not every lane reaches. - A wave64 VS / PS in 32-lane waves is refused where `upper_lanes` finds a read of lanes 32-63 that holds anything. Exports and `v_interp_*` come through `inst_guarded`; until then the stages lower integer programs only, and the tests observe memory stores. Tested on an RTX 4090 (Windows 10 22H2, DXC 1.8.2502): - cargo test -p xcl --lib -- recomp::lower recomp::lane_masks gpu::dxil --test-threads=4: 119 passed, 0 failed, 1 ignored; - cargo test --workspace --no-fail-fast -- --test-threads=4: lib 855 passed, 0 failed, 22 ignored; every other test binary passed; - with the launch EXEC taken as every lane, a_ps_helper_lane_runs_the_program_but_does_not_store fails (the helper lanes store). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lane_masks.rs | 12 +- crates/xcl/src/gpu/recomp/lower.rs | 222 +++++++++++++++++++++++- 2 files changed, 229 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index fde6bc9512..29d64f725c 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -253,6 +253,9 @@ pub struct Summary { pub vector: usize, /// pcs of those that still need a guard on the lane's EXEC bit pub guarded: Vec, + /// pcs of the mask-width `s_wqm` whose result is every lane (whole-quad mode of the launch + /// EXEC, `LaunchExec::Unknown`) + pub wqm_all: Vec, /// conditional branches on a lane mask (each lane decides) and on uniform values pub lane_branches: usize, pub uniform_branches: usize, @@ -797,6 +800,12 @@ impl<'a> Lanes<'a> { sum.guarded.push(d.pc); } } + if d.inst.name == if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" } { + let s0 = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0); + if self.mask_src(&st, d, s0).and_then(|a| self.wqm(a)) == Some(TRUE) { + sum.wqm_all.push(d.pc); + } + } self.step_bounded(&mut st, i, b)?; } let last = &self.insts[end - 1]; @@ -1034,9 +1043,10 @@ mod tests { ]; let s = run_launch(&p, LaunchExec::Unknown).unwrap(); assert_eq!(s.guarded, vec![16], "only the v_mov after EXEC is narrowed to the launch EXEC again"); + assert_eq!(s.wqm_all, vec![4]); assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); // the quads of any other mask are not followed let s = run_launch(&[CMP, ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), MOV2, ENDPGM], LaunchExec::All).unwrap(); - assert_eq!(s.guarded, vec![8]); + assert_eq!((s.guarded, s.wqm_all), (vec![8], vec![])); } } diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 42a9c9f1ab..6d759f353c 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -111,6 +111,25 @@ pub trait Ir: Sink { fn br(&mut self, target: usize); fn br_if(&mut self, c: Self::V, then: usize, otherwise: usize); fn ret(&mut self); + /// VS / PS: the stage's start (in the DXIL adapter #1426's `setup_vertex` / `setup_pixel`), + /// with `vregs` the VGPRs the program names. None: this IR has no graphics entry, and the + /// program is refused. + fn graphics_start(&mut self, vregs: &[u16]) -> Option> { + let _ = vregs; + None + } + /// … and its end (`finish_gfx`: the outputs, the PS discard), where every lane is back + fn graphics_end(&mut self) {} +} + +/// What a VS / PS starts with (`Ir::graphics_start`). +pub struct GraphicsStart { + /// the registers the stage sets beyond the user SGPRs from `io`: (SGPR, value), (VGPR, + /// value); a VGPR it does not set starts as 0 + pub sgprs: Vec<(u8, V)>, + pub vgprs: Vec<(u16, V)>, + /// the lane's bit of the launch EXEC: false in a PS's helper lanes, which run the program too + pub exec: V, } const EXEC: u8 = 126; @@ -124,6 +143,10 @@ pub enum Stage<'a> { /// a compute program: user SGPRs from `io`, then the group ids and TG_SIZE it enables, /// thread ids in v0–v2; it ends without storing registers Compute(&'a super::CsInterface), + /// a vertex / pixel shader: user SGPRs from `io`, the rest from `Ir::graphics_start`; it ends + /// in `Ir::graphics_end` + Vertex, + Pixel, } struct Lower<'a, I: Ir> { @@ -158,6 +181,20 @@ fn is_store(d: &Decoded) -> bool { (n.starts_with("GLOBAL_STORE_") || n.starts_with("FLAT_STORE_")) && matches!(d.enc.name, "ENC_FLAT_GLBL" | "ENC_FLAT") } +/// A PS instruction that needs all four lanes of each quad: an image sample or gather with an +/// implicit LOD (no `_L` / `_LZ`, no gradients `_D` / `_CD`), `image_get_lod`, `s_wqm`. The +/// console has them from whole-quad mode; DXIL leaves derivatives undefined where control flow is +/// not uniform over the quad. +fn whole_quad(name: &str) -> bool { + if name == "IMAGE_GET_LOD" || name.starts_with("S_WQM_") { + return true; + } + match name.strip_prefix("IMAGE_SAMPLE").or_else(|| name.strip_prefix("IMAGE_GATHER4")) { + Some(rest) => !rest.split('_').any(|t| matches!(t, "L" | "LZ" | "D" | "CD")), + None => false, + } +} + /// IR block of analysis block b (block 0 is the prologue). fn blk(b: usize) -> usize { b + 1 @@ -361,6 +398,17 @@ impl<'a, I: Ir> Lower<'a, I> { return Ok(()); } let width = if self.wave64 { "_B64" } else { "_B32" }; + // s_wqm: every lane where the analysis found it so (whole-quad mode of the launch EXEC); + // any other mask would need the lanes of the quad + if name.strip_prefix("S_WQM") == Some(width) { + if !self.sum.wqm_all.contains(&d.pc) { + return Err(format!("{name} of a mask other than the launch EXEC")); + } + let t = self.ir.boolean(true); + self.write_bit(b, sd, t); + self.write_scc(b, t); + return Ok(()); + } // mask-width ops: on lane bits when they write EXEC, are a saveexec, or read a mask if let Some(base) = name.strip_suffix(width) { let op = base.trim_start_matches("S_"); @@ -926,6 +974,16 @@ pub fn lower_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: Ok(lower(insts, Stage::Compute(cs), wave64, ir)?.0) } +/// Lowers a vertex or pixel shader (`pixel`; far jumps resolved) into `ir`. `lanes32`: a wave64 +/// program runs in 32-lane hardware waves (NVIDIA), as the HLSL path runs it with `upper_lanes`; +/// the per-lane form takes such a program only where it reads no lane 32–63 that holds anything. +pub fn lower_graphics(insts: &[Decoded], pixel: bool, wave64: bool, lanes32: bool, ir: I) -> R { + if wave64 && lanes32 && super::upper_lanes::analyze(insts).reads.values().any(|&r| r != super::upper_lanes::Read::Native) { + return Err("wave64 VS / PS in 32-lane waves: a read of lanes 32–63".into()); + } + Ok(lower(insts, if pixel { Stage::Pixel } else { Stage::Vertex }, wave64, ir)?.0) +} + fn lower(insts: &[Decoded], stage: Stage, wave64: bool, ir: I) -> R<(I, Vec)> { lower_with(insts, stage, wave64, ir, false).map(|(ir, stale, _)| (ir, stale)) } @@ -942,7 +1000,10 @@ pub fn survey_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, survey: bool) -> R<(I, Vec, Vec)> { let kernel = matches!(stage, Stage::Kernel); - let sum = lane_masks::analyze(insts, wave64).map_err(|e| e.to_string())?; + let graphics = matches!(stage, Stage::Vertex | Stage::Pixel); + // a VS / PS: lanes may run outside the launch EXEC (a PS's helper lanes) + let launch = if graphics { lane_masks::LaunchExec::Unknown } else { lane_masks::LaunchExec::All }; + let sum = lane_masks::analyze_launch(insts, wave64, launch).map_err(|e| e.to_string())?; let n = sum.blocks.len(); if n == 0 { return Err("empty program".into()); @@ -1120,6 +1181,30 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s l.ssa.seal(&mut l.ir, skip); l.ir.ret(); } + Stage::Vertex | Stage::Pixel => { + let Some(start) = l.ir.graphics_start(&vregs) else { + return Err("VS / PS: this IR has no graphics entry".into()); + }; + for &(r, v) in &start.sgprs { + l.write_num(0, r, v); + } + let f = l.ir.boolean(false); + l.ssa.write(0, Var::Scc, f); + for &v in &vregs { + let x = match start.vgprs.iter().find(|x| x.0 == v) { + Some(&(_, x)) => x, + None => l.ir.int(0), + }; + l.ssa.write(0, Var::V(v), x); + } + // every lane runs the program: a PS's helper lanes with their EXEC bit clear (the + // kernel's way out for lanes outside EXEC would leave their quads short) + l.write_bit(0, EXEC, start.exec); + l.ir.br(blk(0)); + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + l.ir.ret(); + } } // the program, in reverse postorder; a block is sealed once all its predecessors are in @@ -1142,8 +1227,9 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s if !sealed[ib] { sealed[ib] = seal_ready(&mut l, &done, ib); } - if b == 0 { - // the analysis takes the lanes that start the program as its EXEC + if b == 0 && !graphics { + // the analysis takes the lanes that start the program as its EXEC (a VS / PS keeps + // the launch EXEC from its start: there the analysis does not know it) let t = l.ir.boolean(true); l.write_bit(ib, EXEC, t); } @@ -1157,6 +1243,10 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s if i == last && (name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM") || d.far_target.is_some()) { break; } + if matches!(stage, Stage::Pixel) && whole_quad(name) && l.partial[cur] { + l.note_inst(Err(format!("{name}: needs whole quads, in a block not every lane reaches")), cur, d)?; + continue; + } if let Some(&(_, s, c)) = split.next_if(|x| x.0 == i) { // a guarded store: only the lanes with their EXEC bit go through its block let e = l.read_bit(cur, EXEC)?; @@ -1231,7 +1321,10 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s l.ssa.seal(&mut l.ir, exit); let mut stale: Vec = Vec::new(); let Some(row) = row else { - // compute: nothing to store + // compute: nothing to store; a VS / PS: its end + if graphics { + l.ir.graphics_end(); + } l.ir.ret(); for b in [sstore, vstore] { l.ir.at(b); @@ -1540,6 +1633,10 @@ pub(crate) mod tests { MemLoad(u32), MemStore(u32, u32), Phi(Vec<(u32, usize)>), + /// a VS / PS start: VGPR v from the lane's row of `io` (as in kernel mode), and the + /// lane's bit of the launch EXEC from `io[126..=127]` + GfxVgpr(u16), + GfxExec, } #[derive(Clone, Debug)] @@ -1685,6 +1782,11 @@ pub(crate) mod tests { fn ret(&mut self) { self.blocks[self.cur].1 = Term::Ret; } + fn graphics_start(&mut self, vregs: &[u16]) -> Option> { + let vgprs = vregs.iter().map(|&v| (v, self.push(Ins::GfxVgpr(v)))).collect(); + let exec = self.push(Ins::GfxExec); + Some(GraphicsStart { sgprs: Vec::new(), vgprs, exec }) + } } /// One lane's position: block, instruction index, the block it came from, its values. @@ -1800,6 +1902,8 @@ pub(crate) mod tests { res[g(a) as usize] = g(v); None } + Ins::GfxVgpr(v) => Some(io[KERNEL_SGPRS + lane * KERNEL_VGPRS + *v as usize]), + Ins::GfxExec => Some(io[EXEC as usize + lane / 32] >> (lane % 32) & 1), }; if let Some(r) = r { s.env.insert(*id, r); @@ -2535,6 +2639,116 @@ pub(crate) mod tests { assert_eq!(s[126], 0xFF); } + /// A VS / PS run on the CPU in one wave of `lanes` lanes (a wave64 one in 32 lanes: in + /// 32-lane waves): `launch` its launch EXEC, `vgpr[lane]` the registers it starts with. The + /// memory after. + fn run_graphics(lines: &[I], pixel: bool, wave64: bool, lanes: usize, launch: u64, vgpr: &[Vec], mem: &[u32]) -> Vec { + let ir = lower_graphics(&decode(lines), pixel, wave64, wave64 && lanes == 32, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let mut io = vec![0u32; KERNEL_SGPRS + 64 * KERNEL_VGPRS]; + io[EXEC as usize] = launch as u32; + io[EXEC as usize + 1] = (launch >> 32) as u32; + for (l, regs) in vgpr.iter().enumerate().take(lanes) { + io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); + } + let mut res = vec![0u32; KERNEL_SGPRS]; + let mut mem = mem.to_vec(); + ir.run(lanes, &io, &mut res, &mut mem); + mem + } + + /// v7 = 9, stored at v[8:9] (the lane's address: 4 × lane) + const SET_V7: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 137)]); + const STORE_V7: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]); + + fn store_rows() -> Vec> { + (0..64).map(|l| { let mut v = vec![0u32; 10]; v[0] = l; v[1] = 15; v[8] = 4 * l; v }).collect() + } + + #[test] + fn a_ps_helper_lane_runs_the_program_but_does_not_store() { + // even lanes covered, odd lanes helper lanes + let launch = 0x5555_5555u64; + let want: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 && l % 2 == 0 { 9 } else { m }).collect(); + let exact = run_graphics(&[SET_V7, STORE_V7, ENDPGM], true, false, 32, launch, &store_rows(), &memory_image()); + assert_eq!(exact, want, "before EXEC is written, the store keeps its guard"); + // whole-quad mode, then back to the launch EXEC before the store (as compiled PSs do) + let wqm32: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + SET_V7, + ("S_AND_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + STORE_V7, + ENDPGM, + ]; + assert_eq!(run_graphics(&wqm32, true, false, 32, launch, &store_rows(), &memory_image()), want); + // the same in wave64, run in 32-lane waves + let wqm64: Vec = vec![ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + SET_V7, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + STORE_V7, + ENDPGM, + ]; + assert_eq!(run_graphics(&wqm64, true, true, 32, launch, &store_rows(), &memory_image()), want); + // a VS: every lane in the launch EXEC stores + let all: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 { 9 } else { m }).collect(); + assert_eq!(run_graphics(&[SET_V7, STORE_V7, ENDPGM], false, false, 32, 0xFFFF_FFFF, &store_rows(), &memory_image()), all); + } + + #[test] + fn whole_quad_instructions_need_every_lane_of_the_quad() { + // v_cmp (lanes above 15); s_and_saveexec s0; s_cbranch_execz L; s_wqm exec, s0; v_mov; + // L: exec |= s0 – the s_wqm of the launch EXEC, in a block only some lanes reach + let p: Vec = vec![ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + SET_V7, + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + let e = lower_graphics(&decode(&p), true, false, false, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("S_WQM_B32: needs whole quads, in a block not every lane reaches")); + // s_wqm of another mask: the lanes of the quad are not read + let other: Vec = vec![("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), SET_V7, ENDPGM]; + let e = lower_graphics(&decode(&other), true, false, false, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("S_WQM_B32 of a mask other than the launch EXEC")); + for (name, quad) in [ + ("IMAGE_SAMPLE", true), + ("IMAGE_SAMPLE_B_CL", true), + ("IMAGE_GATHER4_C", true), + ("IMAGE_GET_LOD", true), + ("S_WQM_B64", true), + ("IMAGE_SAMPLE_L", false), + ("IMAGE_SAMPLE_C_LZ_O", false), + ("IMAGE_SAMPLE_D_G16", false), + ("IMAGE_SAMPLE_CD", false), + ("IMAGE_GATHER4_LZ", false), + ("IMAGE_LOAD", false), + ] { + assert_eq!(whole_quad(name), quad, "{name}"); + } + } + + #[test] + fn a_wave64_vs_in_32_lane_waves_that_reads_upper_lanes_is_refused() { + // whole-wave code writes lanes 32–63 (v6 = 5), then v_readlane of lane 32 + let p: Vec = vec![ + ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 133)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]), + ENDPGM, + ]; + let insts = decode(&p); + assert_eq!(super::super::upper_lanes::analyze(&insts).reads.values().copied().collect::>(), vec![super::super::upper_lanes::Read::Const(5)]); + let e = lower_graphics(&insts, false, true, true, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("wave64 VS / PS in 32-lane waves: a read of lanes 32–63")); + assert!(lower_graphics(&insts, false, true, false, Interp::default()).is_ok(), "in 64-lane waves the lanes are there"); + } + #[test] fn wave64_masks_span_both_words() { // v_cmp_gt_u32 vcc, 40, v0 over 64 lanes: lanes 0–39 From 5d2d65c5fdaa3620967680a83026cdca44824439 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:18:19 -0300 Subject: [PATCH 32/51] Recompiler: s_wqm in a VS / PS keeps the launch-EXEC rule `6ca6b90` lowers `s_wqm` of any mask through the ballot of its bits, and teidenzero's VS / PS commits allow it only of the launch EXEC (whose quads' helper lanes the analysis knows). Both now hold: in a VS / PS and where the analysis found `s_wqm` of the launch EXEC, `salu`'s rule; elsewhere (compute) the ballot. --- crates/xcl/src/gpu/recomp/lower.rs | 3 +++ crates/xcl/src/gpu/recomp/lower/wave.rs | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 6d759f353c..0958d65bc4 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -173,6 +173,8 @@ struct Lower<'a, I: Ir> { dpp_en: Option, /// survey mode (`survey_compute`): every refusal is noted here and the lowering goes on noted: Option>, + /// a VS / PS (`lower_graphics`): `s_wqm` only of the launch EXEC (its quads' helper lanes) + graphics: bool, } /// A vector memory store: a side effect inactive lanes must not have. @@ -1084,6 +1086,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s dpp_src: None, dpp_en: None, noted: survey.then(Vec::new), + graphics, }; // the registers the program names, and the ones the runner reads back let mut sregs: Vec = vec![VCC, VCC + 1, 124, EXEC, EXEC + 1]; diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs index 89e92d5164..28576603ae 100644 --- a/crates/xcl/src/gpu/recomp/lower/wave.rs +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -416,8 +416,9 @@ impl Lower<'_, I> { let (s0, sd) = (fv("SSRC0"), fv("SDST") as u8); // `s_wqm` of a mask (`s_wqm_b64 exec, exec`): a lane's bit is set when any lane of its // quad has its bit; the quad is in the lane's own half of the mask + // (the launch EXEC's, and any in a VS / PS, are `salu`'s) let wqm = if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" }; - if name == wqm { + if name == wqm && !self.graphics && !self.sum.wqm_all.contains(&d.pc) { let Some((r, false)) = self.mask_reg(b, s0) else { return Err(format!("unsupported {name} of a number")) }; let [lo, hi] = self.mask_words(b, r, true)?; let lane = self.lane(); From b1bfd1ea04e2fd765c1825209b5024740063a5ed Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:19:02 -0300 Subject: [PATCH 33/51] Tests: the f32 reference keeps signed zeros on every driver On an RX 9070 XT, `f32_programs_on_the_gpu` failed at lane 16 v10: `floor(-(+0)) * 2` is -0 on the console and in the per-lane DXIL, but the HLSL reference gave +0: DXC's `fast` flags include no-signed-zeros and the AMD driver folds by them. The reference is now compiled with `-Gis`, and `check_f32_rounding` compares v10 bit for bit, so the -0 is asserted rather than hidden by `-0.0 == 0.0`. Diagnosis and fix by Diskuss (#1269); the HLSL path itself still gives +0 there on that driver. --- crates/xcl/src/gpu/recomp/lower.rs | 2 +- crates/xcl/src/gpu/recomp/lower_dxil.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 0958d65bc4..fc19248f25 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -2330,7 +2330,7 @@ pub(crate) mod tests { assert_eq!(r[4 + i], w.to_bits(), "lane {l} v{}", 4 + i); } assert_eq!(r[9], 0x3F7F_FFFF, "fract(-2^-30): below 1.0"); - assert_eq!(f32::from_bits(r[10]), 2.0 * (-x).floor(), "lane {l}"); + assert_eq!(r[10], (2.0 * (-x).floor()).to_bits(), "lane {l} v10"); assert_eq!(f32::from_bits(r[11]), x.abs() - x.abs().floor(), "lane {l}"); } } diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 3bd492b9dc..167e5966b0 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -532,7 +532,7 @@ mod tests { let bytes: Vec = lines.iter().flat_map(encode_line).collect(); let t = translate(&bytes, &Options { wave64: w64, ..Default::default() }).unwrap(); assert!(t.complete(), "{name}: {:?}", t.unsupported_why); - let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), &st, &[]).unwrap(); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &["-Gis"]).unwrap(), &st, &[]).unwrap(); if !w64 { check(&hlsl.sgpr, &hlsl.vgpr[..32]); } From 3aea7a9dca0efdb4570b018b1725c76d7bbad528 Mon Sep 17 00:00:00 2001 From: Vlad Bondarenko <12616782+vladbondarenko97@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:00:03 -0600 Subject: [PATCH 34/51] Tests: f64 programs for the per-lane lowering, on the HLSL path and per lane One program in the shape of the f32 ones (`f64_programs_on_the_gpu`) on x = 1 + lane / 32 + lane * 2^-52: x + 2^-53 (ties to even), x * 2^-1040 (a denormal in and out), x * f64::MAX (infinity from lane 1), fma(x, x, -x * x) (the product's rounding error: nonzero only when fused), NaN into min / max, VOP3 abs / neg / omod / clamp, floor / ceil / trunc / rndne / fract / frexp_mant / frexp_exp of (lane - 16) / 4 (ties, -0 at lane 15), f64 <-> f32 / i32 / u32 (a tie, overflow, saturation, NaN) and rcp / rsq / sqrt (within 1e-12). The HLSL path's registers are checked against values computed in Rust (`check_f64`), and the per-lane DXIL is compared with the HLSL path register for register, as for f32. The GPU loop of `f32_programs_on_the_gpu` is now `programs_on_the_gpu`. Not in it: v_trig_preop_f64 and v_div_*_f64, which the HLSL path does not translate, and a non-default MODE.FP_ROUND for f64, which it refuses. On 3511bb9 (RTX 3080 Ti, wave32) the HLSL path passes every check, and the per-lane form takes the program and agrees with it register for register. The wave64 half is SKIPPED (no 64-lane waves). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 108 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 33 +++++--- 2 files changed, 131 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index fc19248f25..1a6acf7e0e 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -2450,6 +2450,114 @@ pub(crate) mod tests { (0..256).map(|i| 1000 + i).collect() } + // f64 programs, as the f32 ones: `lower_dxil`'s `f64_programs_on_the_gpu` checks the HLSL + // path's registers with `check_f64` and compares the per-lane form with it + + /// f64 on x = 1 + lane / 32 + lane · 2^-52 (v[2:3]): x + 2^-53 (ties to even), x · 2^-1040 + /// (a denormal in and out), x · f64::MAX (∞ from lane 1), fma(x, x, −x · x) (the rounding + /// error: nonzero only fused), NaN into min / max, VOP3 abs / neg / omod / clamp; floor / ceil + /// / trunc / rndne / fract / frexp of q = (lane − 16) / 4 (ties, −0 at lane 15); f64 ↔ f32 / + /// i32 / u32 (a tie, overflow, saturation, NaN); rcp / rsq / sqrt. + pub(crate) const F64_ARITHMETIC: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 143), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 3), ("LITERAL", 0x3FF0_0000)]), + // v[4:5] = 2^-53, v[6:7] = 2^-1040, v[8:9] = f64::MAX, v[10:11] = NaN + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255), ("LITERAL", 0x3CA0_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 132)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0x7FEF_FFFF)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 129)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 255), ("LITERAL", 0x7FF8_0000)]), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", V + 4)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", V + 6)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 2), ("SRC1", V + 8)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", V + 2)]), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 18), ("NEG", 4)]), + ("V_MIN_F64", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 10), ("SRC1", V + 2)]), + ("V_MAX_F64", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 2), ("SRC1", V + 10), ("NEG", 2)]), + // −x · |−4|, (x − 1) · 4, clamp(fma(x, x, −1)) + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 2), ("SRC1", 247), ("ABS", 2), ("NEG", 1)]), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 2), ("SRC1", 243), ("OMOD", 2)]), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", 243), ("CLAMP", 1)]), + // q = ldexp(lane − 16, −2) + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F64_I32", "ENC_VOP1", &[("VDST", 34), ("SRC0", V + 32)]), + ("V_LDEXP_F64", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + 34), ("SRC1", 194)]), + ("V_FLOOR_F64", "ENC_VOP1", &[("VDST", 38), ("SRC0", V + 36)]), + ("V_CEIL_F64", "ENC_VOP1", &[("VDST", 40), ("SRC0", V + 36)]), + ("V_TRUNC_F64", "ENC_VOP1", &[("VDST", 42), ("SRC0", V + 36)]), + ("V_RNDNE_F64", "ENC_VOP1", &[("VDST", 44), ("SRC0", V + 36)]), + ("V_FRACT_F64", "ENC_VOP1", &[("VDST", 46), ("SRC0", V + 36)]), + ("V_FREXP_MANT_F64", "ENC_VOP1", &[("VDST", 48), ("SRC0", V + 36)]), + ("V_FREXP_EXP_I32_F64", "ENC_VOP1", &[("VDST", 50), ("SRC0", V + 36)]), + // f32 of z = 1 + 2^-24 + lane · 2^-52 (a tie at lane 0) and of f64::MAX; i32 of −4x, of + // x · f64::MAX and of NaN, u32 of −4x and of NaN + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 52), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x1000_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 53), ("SRC0", 255), ("LITERAL", 0x3FF0_0000)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 51), ("SRC0", V + 52)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 54), ("SRC0", V + 8)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 55), ("SRC0", V + 26)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 56), ("SRC0", V + 16)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 57), ("SRC0", V + 10)]), + ("V_CVT_U32_F64", "ENC_VOP1", &[("VDST", 58), ("SRC0", V + 26)]), + ("V_CVT_U32_F64", "ENC_VOP1", &[("VDST", 59), ("SRC0", V + 10)]), + // f64 of u32::MAX − lane and of the f32 at v51 + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 193), ("VSRC1", 0)]), + ("V_CVT_F64_U32", "ENC_VOP1", &[("VDST", 60), ("SRC0", V + 1)]), + ("V_CVT_F64_F32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 51)]), + ("V_RCP_F64", "ENC_VOP1", &[("VDST", 64), ("SRC0", V + 2)]), + ("V_RSQ_F64", "ENC_VOP1", &[("VDST", 66), ("SRC0", V + 2)]), + ("V_SQRT_F64", "ENC_VOP1", &[("VDST", 68), ("SRC0", V + 2)]), + ENDPGM, + ]; + + pub(crate) fn check_f64(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f64::from_bits(r[i] as u64 | (r[i + 1] as u64) << 32); + let x = 1.0 + l as f64 / 32.0 + l as f64 * 2f64.powi(-52); + let q = (l as f64 - 16.0) / 4.0; + assert_eq!(f(2).to_bits(), x.to_bits(), "lane {l}"); + let p = x * x; + let e = if q == 0.0 { 0 } else { (q.abs().to_bits() >> 52) as i32 - 1022 }; + let want = [ + x + 2f64.powi(-53), + x * 2f64.powi(-1040), + x * f64::MAX, + p, + x.mul_add(x, -p), + x, + x, + -4.0 * x, + (x - 1.0) * 4.0, + x.mul_add(x, -1.0).clamp(0.0, 1.0), + (l as f64 - 16.0), + q, + q.floor(), + q.ceil(), + q.trunc(), + q.round_ties_even(), + q - q.floor(), + q / 2f64.powi(e), + ]; + for (k, w) in want.iter().enumerate() { + let i = 12 + 2 * k + if k >= 10 { 2 } else { 0 }; + assert_eq!(f(i).to_bits(), w.to_bits(), "lane {l} v[{i}:{}]: {} against {w}", i + 1, f(i)); + } + assert_eq!(r[50], e as u32, "lane {l}: frexp_exp"); + let z = 1.0 + 2f64.powi(-24) + l as f64 * 2f64.powi(-52); + assert_eq!([r[51], r[54]], [(z as f32).to_bits(), f32::INFINITY.to_bits()], "lane {l}: f32 of f64"); + assert_eq!([r[55], r[56], r[57], r[58], r[59]], [(-4.0 * x) as i32 as u32, i32::MAX as u32, 0, 0, 0], "lane {l}: i32 / u32 of f64"); + assert_eq!([f(60), f(62)], [(u32::MAX - l as u32) as f64, z as f32 as f64], "lane {l}: f64 of u32, f32"); + // the GPU's rcp / rsq / sqrt are close, not exact + for (i, w) in [(64, 1.0 / x), (66, 1.0 / x.sqrt()), (68, x.sqrt())] { + assert!((f(i) - w).abs() <= w * 1e-12, "lane {l} v[{i}:{}]: {} against {w}", i + 1, f(i)); + } + } + } + /// A line's bytes; a `("LITERAL", k)` field is the instruction's literal dword. pub(crate) fn encode_line((n, e, f): &I) -> Vec { let lit = f.iter().find(|(k, _)| *k == "LITERAL").map(|&(_, v)| v as u32); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 167e5966b0..33a29e993e 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -499,6 +499,22 @@ mod tests { /// form refuses a program, that half is SKIPPED with the refusal. #[test] fn f32_programs_on_the_gpu() { + programs_on_the_gpu(&[ + ("f32 arithmetic", F32_ARITHMETIC, check_f32_arithmetic, &[]), + ("f32 compares", F32_COMPARES, check_f32_compares, &[]), + ("f32 conversions", F32_CONVERSIONS, check_f32_conversions, &[]), + ("f32 rounding", F32_ROUNDING, check_f32_rounding, &[]), + ("f32 transcendentals", F32_TRANSCENDENTALS, check_f32_transcendentals, &[3, 4]), + ("f32 three-source", F32_THREE_SOURCE, check_f32_three_source, &[]), + ]); + } + + /// A program of `lower`'s tests, the check of its registers on the HLSL path (wave32), and + /// the VGPRs the per-lane form need only match within `f32_close`. + type Program = (&'static str, &'static [I], fn(&[u32], &[Vec]), &'static [usize]); + + /// `f32_programs_on_the_gpu`'s two halves, for any programs. + fn programs_on_the_gpu(programs: &[Program]) { if !gpu() { return; } @@ -506,17 +522,8 @@ mod tests { runner::skip_test("no DXC"); return; } - type Check = fn(&[u32], &[Vec]); - let programs: [(&str, &[I], Check, &[usize]); 6] = [ - ("f32 arithmetic", F32_ARITHMETIC, check_f32_arithmetic, &[]), - ("f32 compares", F32_COMPARES, check_f32_compares, &[]), - ("f32 conversions", F32_CONVERSIONS, check_f32_conversions, &[]), - ("f32 rounding", F32_ROUNDING, check_f32_rounding, &[]), - ("f32 transcendentals", F32_TRANSCENDENTALS, check_f32_transcendentals, &[3, 4]), - ("f32 three-source", F32_THREE_SOURCE, check_f32_three_source, &[]), - ]; let wave64 = runner::wave64_supported() == Ok(true); - for (name, lines, check, approx) in programs { + for &(name, lines, check, approx) in programs { for w64 in [false, true] { let lanes = if w64 { 64 } else { 32 }; if w64 && !wave64 { @@ -596,6 +603,12 @@ mod tests { } } + /// The f64 program of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn f64_programs_on_the_gpu() { + programs_on_the_gpu(&[("f64", F64_ARITHMETIC, check_f64, &[])]); + } + #[test] fn a_per_lane_compute_program_runs_on_the_gpu() { if !gpu() { From 82c875d4e6bb44661f0ace6e6daeb2e8ad851be9 Mon Sep 17 00:00:00 2001 From: Vlad Bondarenko <12616782+vladbondarenko97@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:59:25 -0600 Subject: [PATCH 35/51] Tests: integer programs for the per-lane lowering, on the HLSL path and per lane Two programs in the shape of the f32 ones (`integer_programs_on_the_gpu`) on a = lane * 0x9E3779B9, b = lane - (a >> 13) and c = 0x7FFFFFF0 + lane: - VOP3-only and VOP2 integer ops: mul_hi u32 / i32, the 24-bit multiplies and mads, bfe u32 / i32 with offset + width past 32 and width 0, bfi, bfm, alignbit / alignbyte, xad, sad_u8 / sad_hi_u8 / sad_u16 / sad_u32 / msad_u8, min3 / max3 / med3 u32 / i32, clamped (saturating) add3 / add / sub u32 and add / sub i32, bcnt, ffbh / ffbl / ffbh_i32 of 0 and -1, bfrev, not, xnor, cvt_pk_u16_u32 / cvt_pk_i16_i32 (saturating), and mad_u32_u16 / mad_i32_i16 with OP_SEL halves; - carries: VOP3 carry-outs into s20..s30 and carry-ins from them, a VOP2 chain through VCC, a VOP3 cndmask on s22, v_mad_u64_u32 / v_mad_i64_i32 with their carry-outs, and the 64-bit shifts (by 65 at lane 31). The HLSL path's registers and carry masks are checked against values computed in Rust (`check_int_*`; v_mad_i64_i32's carry-out is left to the per-lane comparison), and the per-lane DXIL is compared with the HLSL path register for register, as for f32. The GPU loop of `f32_programs_on_the_gpu` is now `programs_on_the_gpu`. On 3511bb9 (RTX 3080 Ti, wave32) the HLSL path passes every check; the per-lane form takes the arithmetic and agrees with the HLSL path, and refuses the carries (`V_ADD_CO_CI_U32`: "it reads register 21 the per-lane form did not pass": #1426 reads a carry-in as the SGPR pair, the bridge passes only its low SGPR in wave32), so that half is SKIPPED. On 56102c5, before that check, the carries ran and every carry-in read 0 per lane (v11, v13, v17, v18 one less, lanes 1-31): the kernel form never sets up #1426's lanes (`DxilIr::new` with `Entry::Kernel` calls no `Lw::setup_lanes*`), so `Lw::lane31` stays 0 and `Lw::lane_of` takes every lane's carry-in from bit 0. That is still so on 3511bb9, so this half fails again once the pair is passed unless the kernel form sets up the lanes. The wave64 halves are SKIPPED (no 64-lane waves). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 217 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 6 + 2 files changed, 223 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 1a6acf7e0e..4c5f9b3a18 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -2378,6 +2378,223 @@ pub(crate) mod tests { if s == 1 { -v } else { v } } + // integer programs, as the f32 ones: `lower_dxil`'s `integer_programs_on_the_gpu` checks the + // HLSL path's registers with the `check_int_*` below and compares the per-lane form with it + + /// a = lane · 0x9E3779B9 (v1), b = lane − (a >> 13) (v2, negative but at lane 0) and + /// c = 0x7FFFFFF0 + lane (v3, past i32::MAX from lane 16) + const INT_INPUTS: [I; 5] = [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0x9E37_79B9)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V + 9)]), + ("V_LSHRREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 141), ("VSRC1", 1)]), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x7FFF_FFF0)]), + ]; + + /// Integer VALU on a, b, c (`INT_INPUTS`): high products, 24-bit and 16-bit multiplies (OP_SEL + /// halves), bitfields with offset + width past 32 and width 0, align, SAD, min3 / max3 / med3, + /// clamped (saturating) adds, bit counts and scans of 0 and −1, packs that saturate. + pub(crate) const INT_ARITHMETIC: &[I] = &[ + INT_INPUTS[0], INT_INPUTS[1], INT_INPUTS[2], INT_INPUTS[3], INT_INPUTS[4], + ("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 12), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_HI_U32_U24", "ENC_VOP2", &[("VDST", 13), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_I32_I24", "ENC_VOP2", &[("VDST", 14), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_HI_I32_I24", "ENC_VOP2", &[("VDST", 15), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAD_I32_I24", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + // bfe(a, lane, 8) unsigned and signed, bfe(a, 4, lane), bfi, bfm(lane, 4) + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 1), ("SRC1", V), ("SRC2", 136)]), + ("V_BFE_I32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V), ("SRC2", 136)]), + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 132), ("SRC2", V)]), + ("V_BFI_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_BFM_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 132)]), + ("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 23), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ("V_ALIGNBYTE_B32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ("V_XAD_U32", "ENC_VOP3", &[("VDST", 25), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U8", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_HI_U8", "ENC_VOP3", &[("VDST", 27), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U16", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U32", "ENC_VOP3", &[("VDST", 29), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MSAD_U8", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MIN3_U32", "ENC_VOP3", &[("VDST", 31), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAX3_I32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MED3_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MED3_I32", "ENC_VOP3", &[("VDST", 34), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MIN3_I32", "ENC_VOP3", &[("VDST", 35), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAX3_U32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + // clamp: a + b + c, a + b, b − a (u32); a + c, b − c (i32); a + c without + ("V_ADD3_U32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("CLAMP", 1)]), + ("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 38), ("SRC0", V + 1), ("SRC1", V + 2), ("CLAMP", 1)]), + ("V_SUB_NC_U32", "ENC_VOP3", &[("VDST", 39), ("SRC0", V + 2), ("SRC1", V + 1), ("CLAMP", 1)]), + ("V_ADD_NC_I32", "ENC_VOP3", &[("VDST", 40), ("SRC0", V + 1), ("SRC1", V + 3), ("CLAMP", 1)]), + ("V_SUB_NC_I32", "ENC_VOP3", &[("VDST", 41), ("SRC0", V + 2), ("SRC1", V + 3), ("CLAMP", 1)]), + ("V_ADD_NC_I32", "ENC_VOP3", &[("VDST", 42), ("SRC0", V + 1), ("SRC1", V + 3)]), + // bcnt(a) + lane, ffbh / ffbl / ffbh_i32 (0 and −1 at lane 0), bfrev, not, xnor + ("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 43), ("SRC0", V + 1), ("SRC1", V)]), + ("V_FFBH_U32", "ENC_VOP1", &[("VDST", 44), ("SRC0", V + 1)]), + ("V_FFBL_B32", "ENC_VOP1", &[("VDST", 45), ("SRC0", V + 2)]), + ("V_FFBH_I32", "ENC_VOP1", &[("VDST", 46), ("SRC0", V + 2)]), + ("V_BFREV_B32", "ENC_VOP1", &[("VDST", 47), ("SRC0", V + 1)]), + ("V_NOT_B32", "ENC_VOP1", &[("VDST", 48), ("SRC0", V + 2)]), + ("V_XNOR_B32", "ENC_VOP2", &[("VDST", 49), ("SRC0", V + 1), ("VSRC1", 2)]), + // packs of (a, b) to u16 and (b, c) to i16; 16-bit mads of a.hi · b.lo, a.lo · b.hi + ("V_CVT_PK_U16_U32", "ENC_VOP3", &[("VDST", 50), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_CVT_PK_I16_I32", "ENC_VOP3", &[("VDST", 51), ("SRC0", V + 2), ("SRC1", V + 3)]), + ("V_MAD_U32_U16", "ENC_VOP3", &[("VDST", 52), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("OP_SEL", 1)]), + ("V_MAD_I32_I16", "ENC_VOP3", &[("VDST", 53), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("OP_SEL", 2)]), + ("V_MIN_I32", "ENC_VOP2", &[("VDST", 54), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MAX_U32", "ENC_VOP2", &[("VDST", 55), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 56), ("SRC0", V + 1), ("SRC1", V), ("SRC2", V + 3)]), + ("V_ADD_LSHL_U32", "ENC_VOP3", &[("VDST", 57), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ENDPGM, + ]; + + /// Carries on a, b, c (`INT_INPUTS`): VOP3 carry-outs into s20..s30 and carry-ins from them, + /// a VOP2 chain through VCC, a VOP3 cndmask on s22, v_mad_u64_u32 / v_mad_i64_i32 with their + /// carry-outs (s32, s34) and the 64-bit shifts by 2 · lane + 3 (65 at lane 31: 1). + pub(crate) const INT_CARRIES: &[I] = &[ + INT_INPUTS[0], INT_INPUTS[1], INT_INPUTS[2], INT_INPUTS[3], INT_INPUTS[4], + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 10), ("SDST", 20), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 11), ("SDST", 22), ("SRC0", V + 1), ("SRC1", V + 3), ("SRC2", 20)]), + ("V_SUB_CO_U32", "VOP3_SDST_ENC", &[("VDST", 12), ("SDST", 24), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 13), ("SDST", 26), ("SRC0", V + 3), ("SRC1", V + 2), ("SRC2", 24)]), + ("V_SUBREV_CO_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 28), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 15), ("SDST", 30), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", 28)]), + // vcc = a > b; a + b + vcc, c − a − vcc, a − c − vcc, each into vcc + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 2)]), + ("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 16), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_SUB_CO_CI_U32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 3), ("VSRC1", 1)]), + ("V_SUBREV_CO_CI_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", V + 3), ("VSRC1", 1)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 22)]), + // v[20:21] = a · b + (c | a << 32), v[24:25] the same signed; shifts of them and of v[22:23] + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", V + 3)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 1)]), + ("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 20), ("SDST", 32), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 22)]), + ("V_MAD_I64_I32", "VOP3_SDST_ENC", &[("VDST", 24), ("SDST", 34), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 22)]), + ("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 129), ("SRC2", 131)]), + ("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 20)]), + ("V_LSHRREV_B64", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 4), ("SRC1", V + 22)]), + ("V_ASHRREV_I64", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 4), ("SRC1", V + 24)]), + ENDPGM, + ]; + + /// `INT_INPUTS`' a, b, c of a lane + fn int_inputs(l: usize) -> (u32, u32, u32) { + let a = (l as u32).wrapping_mul(0x9E37_79B9); + (a, (l as u32).wrapping_sub(a >> 13), 0x7FFF_FFF0 + l as u32) + } + + pub(crate) fn check_int_arithmetic(_: &[u32], v: &[Vec]) { + let (u24, i24) = (|x: u32| (x & 0xFF_FFFF) as u64, |x: u32| ((x << 8) as i32 >> 8) as i64); + let i16s = |x: u32| x as u16 as i16 as i32; + let bytes = |x: u32| x.to_le_bytes().map(|b| b as i32); + let first = |n: u32, x: u32| if x == 0 { u32::MAX } else { n }; + for (l, r) in v.iter().enumerate() { + let (a, b, c) = int_inputs(l); + let n = l as u32; + let (ai, bi, ci) = (a as i32, b as i32, c as i32); + assert_eq!((r[1], r[2], r[3]), (a, b, c), "lane {l}"); + let mask = |w: u32| ((1u64 << w) - 1) as u32; + let sext = |x: u32, w: u32| if w == 0 { 0 } else { ((x << (32 - w)) as i32 >> (32 - w)) as u32 }; + let (ba, bb) = (bytes(a), bytes(b)); + let sad8: i32 = (0..4).map(|k| (ba[k] - bb[k]).abs()).sum(); + let msad8: i32 = (0..4).filter(|&k| bb[k] != 0).map(|k| (ba[k] - bb[k]).abs()).sum(); + let sad16 = (i16s(a) as u16 as i32 - b as u16 as i32).abs() + ((a >> 16) as i32 - (b >> 16) as i32).abs(); + let med3 = |x: u32, y: u32, z: u32| x.min(y).max(x.max(y).min(z)); + let med3i = |x: i32, y: i32, z: i32| x.min(y).max(x.max(y).min(z)); + let ffbh_i = |x: u32| if x == 0 || x == u32::MAX { u32::MAX } else { (x ^ (x as i32 >> 31) as u32).leading_zeros() }; + let want = [ + ((a as u64 * b as u64) >> 32) as u32, + ((ai as i64 * bi as i64) >> 32) as u32, + (u24(a) * u24(b)) as u32, + ((u24(a) * u24(b)) >> 32) as u32, + (i24(a) * i24(b)) as u32, + ((i24(a) * i24(b)) >> 32) as u32, + ((u24(a) * u24(b)) as u32).wrapping_add(c), + ((i24(a) * i24(b)) as u32).wrapping_add(c), + a >> (n & 31) & mask(8), + sext((ai >> (n & 31)) as u32 & mask(8), 8), + a >> 4 & mask(n & 31), + a & b | !a & c, + mask(n & 31) << 4, + (((a as u64) << 32 | b as u64) >> (n & 31)) as u32, + (((a as u64) << 32 | b as u64) >> (8 * (n & 3))) as u32, + (a ^ b).wrapping_add(c), + (sad8 as u32).wrapping_add(c), + ((sad8 as u32) << 16).wrapping_add(c), + (sad16 as u32).wrapping_add(c), + a.abs_diff(b).wrapping_add(c), + (msad8 as u32).wrapping_add(c), + a.min(b).min(c), + ai.max(bi).max(ci) as u32, + med3(a, b, c), + med3i(ai, bi, ci) as u32, + ai.min(bi).min(ci) as u32, + a.max(b).max(c), + (a as u64 + b as u64 + c as u64).min(u32::MAX as u64) as u32, + a.saturating_add(b), + b.saturating_sub(a), + ai.saturating_add(ci) as u32, + bi.saturating_sub(ci) as u32, + a.wrapping_add(c), + a.count_ones() + n, + first(a.leading_zeros(), a), + first(b.trailing_zeros(), b), + ffbh_i(b), + a.reverse_bits(), + !b, + !(a ^ b), + a.min(0xFFFF) | b.min(0xFFFF) << 16, + bi.clamp(-32768, 32767) as u32 & 0xFFFF | (ci.clamp(-32768, 32767) as u32) << 16, + (a >> 16).wrapping_mul(b & 0xFFFF).wrapping_add(c), + (i16s(a) * i16s(b >> 16)).wrapping_add(ci) as u32, + ai.min(bi) as u32, + a.max(b), + (a << (n & 31)).wrapping_add(c), + a.wrapping_add(b) << (n & 31), + ]; + for (k, w) in want.iter().enumerate() { + assert_eq!(r[10 + k], *w, "lane {l} v{}: {:#x} against {w:#x}", 10 + k, r[10 + k]); + } + } + } + + pub(crate) fn check_int_carries(s: &[u32], v: &[Vec]) { + let mut masks = [0u32; 8]; + for (l, r) in v.iter().enumerate() { + let (a, b, c) = int_inputs(l); + let (a64, b64, c64) = (a as u64, b as u64, c as u64); + let bit = |m: u32| (m >> l & 1) as u64; + let carry = [a64 + b64 > u32::MAX as u64, a64 + c64 + bit(s[20]) > u32::MAX as u64, b > a, b64 + bit(s[24]) > c64, a > b, b64 + bit(s[28]) > c64]; + let want = [a.wrapping_add(b), (a64 + c64 + bit(s[20])) as u32, a.wrapping_sub(b), (c64.wrapping_sub(b64 + bit(s[24]))) as u32, b.wrapping_sub(a), (c64.wrapping_sub(b64 + bit(s[28]))) as u32]; + for k in 0..6 { + assert_eq!(r[10 + k], want[k], "lane {l} v{}", 10 + k); + masks[k] |= (carry[k] as u32) << l; + } + // the VCC chain + let v0 = (a > b) as u64; + let w16 = a64 + b64 + v0; + let v1 = (w16 >> 32) as u64; + let v2 = (a64 + v1 > c64) as u64; + let v3 = (c64 + v2 > a64) as u64; + assert_eq!([r[16], r[17], r[18]], [w16 as u32, c64.wrapping_sub(a64 + v1) as u32, a64.wrapping_sub(c64 + v2) as u32], "lane {l}: through vcc"); + masks[6] |= (v3 as u32) << l; + assert_eq!(r[19], if bit(s[22]) == 1 { b } else { a }, "lane {l}: cndmask"); + let addend = c64 | a64 << 32; + let (wu, cu) = (a64 * b64).overflowing_add(addend); + let wi = ((a as i32 as i64 * b as i32 as i64) as u64).wrapping_add(addend); + masks[7] |= (cu as u32) << l; + let sh = (2 * l as u32 + 3) & 63; + let pair = |i: usize| r[i] as u64 | (r[i + 1] as u64) << 32; + assert_eq!([pair(20), pair(22), pair(24)], [wu, addend, wi], "lane {l}: mads"); + assert_eq!([pair(26), pair(28), pair(30)], [wu << sh, addend >> sh, ((wi as i64) >> sh) as u64], "lane {l}: 64-bit shifts"); + } + let got = [s[20], s[22], s[24], s[26], s[28], s[30], s[106], s[32]]; + assert_eq!(got, masks, "carry-outs s20..s30, vcc, s32"); + } + pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } } diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 33a29e993e..72a0ebce75 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -493,6 +493,12 @@ mod tests { } } + /// The integer programs of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn integer_programs_on_the_gpu() { + programs_on_the_gpu(&[("integer arithmetic", INT_ARITHMETIC, check_int_arithmetic, &[]), ("integer carries", INT_CARRIES, check_int_carries, &[])]); + } + /// The f32 programs of `lower`'s tests on the GPU: the HLSL path gives the expected /// registers (`check_f32_*`, wave32), and the per-lane DXIL gives the HLSL path's, register /// for register (rcp within `f32_close`: HLSL's `rcp` is a fast fdiv). While the per-lane From 188ee17abf43eea7739b859204f7a2822a4c7821 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:21:00 -0300 Subject: [PATCH 36/51] Recompiler: carry-ins and v_cndmask through #1426 read the right lane bit vladbondarenko97's integer programs found that in the kernel form every carry-in read 0: `DxilIr` never called `Lw::setup_lanes` for a kernel outside the split form, so `Lw::lane31` stayed the constant 0 and #1426's lowering read bit 0 of the mask for every lane. The kernel entry now sets up its lanes. #1426 also reads the mask as an SGPR pair in wave32, so the bridge passes the upper SGPR (0) with this lane's bit in the lower; the "register not passed" check had refused those instructions until now. The integer carry program now runs per lane and agrees with the HLSL path on the GPU (GTX 1650, wave32). --- crates/xcl/src/gpu/recomp/lower.rs | 3 +++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 4c5f9b3a18..5d1d4927a3 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1487,7 +1487,10 @@ impl Lower<'_, I> { inputs.push((Var::S(m as u8), lo)); inputs.push((Var::S(m as u8 + 1), hi)); } else { + // #1426 reads the mask as an SGPR pair in wave32 too: the upper one is 0 + let z = self.ir.int(0); inputs.push((Var::S(m as u8), own)); + inputs.push((Var::S(m as u8 + 1), z)); } } if operand(true, "OPR_SSRC_SPECIAL_SCC") { diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 72a0ebce75..93d8b2e680 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -70,7 +70,9 @@ impl DxilIr { // set up in the entry block (a compute program's come with `compute_ids`) let mut ids = None; let lanes_set = match entry { - Entry::Kernel if lw.split => { + // (a kernel always: `Lw`'s lane bit, `lane31`, is what #1426's lowering of a carry-in or + // a `v_cndmask` reads, and stays 0 without it) + Entry::Kernel => { lw.setup_lanes(); true } From fe8dc8477d35b84c6989cc0f515aee37efd31e0c Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:21:49 -0300 Subject: [PATCH 37/51] Recompiler: f16 products stay on the fallback until #1426 rounds them vladbondarenko97's f16 programs show #1426's v_mul_f16 / v_pk_mul_f16 rounding toward zero (LegacyF32ToF16): x * 65504 gives 0x7BFF where the console and the HLSL path give 0x7C00, and denormal ties round down. They join V_CVT_F16_F32 on DIFFERS_ON_1426 until itsSio's fix on main lands. --- crates/xcl/src/gpu/recomp/lower.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 5d1d4927a3..863e6a5f48 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1450,6 +1450,10 @@ impl Lower<'_, I> { const DIFFERS_ON_1426: &[&str] = &[ // f32 → f16 of a value below the smallest f16 denormal: 0 instead of rounding to it "V_CVT_F16_F32", + // f16 products round toward zero (`LegacyF32ToF16`) where the console rounds to + // nearest even (vladbondarenko97's f16 programs; itsSio is fixing it on `main`) + "V_MUL_F16", + "V_PK_MUL_F16", ]; if DIFFERS_ON_1426.contains(&name) { return Err("its #1426 semantics differ from the console's".into()); From 27751a0b06c311465fdc3cbdae5743a5220f3315 Mon Sep 17 00:00:00 2001 From: Vlad Bondarenko <12616782+vladbondarenko97@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:58:22 -0600 Subject: [PATCH 38/51] Tests: f16 and packed programs for the per-lane lowering, on the HLSL path and per lane Two programs in the shape of the f32 ones (`f16_programs_on_the_gpu`): - f16 VOP1 / VOP2 / VOP3: ties to even, denormal results and their ties, overflow to infinity, a fused fma just below a tie (lane 1: double rounding through f32 lands on the tie), NaN into min / max / med3, OP_SEL source and destination halves, omod and clamp, ldexp into denormals, rndne (-0 at lane 15), f16 <-> i16 / u16; - VOP3P packed math: OP_SEL / OP_SEL_HI swapped and broadcast halves, NEG / NEG_HI, f16 clamp, saturating u16 / i16 (clamp), wrapping sub / mul_lo / mad, and v_cvt_pkrtz_f16_f32 (65504 for the out-of-range values). The HLSL path's registers are checked against values computed in Rust (`check_f16_*`, `f16_bits` rounding to nearest even), and the per-lane DXIL is compared with the HLSL path register for register, as for f32. The GPU loop of `f32_programs_on_the_gpu` is now `programs_on_the_gpu`. Left out of the Rust checks: the f16 results the HLSL path rounds with `f32tof16` (v_add/sub/fma/fmac/ldexp/cvt_f16_u16, v_pk_add/fma). Their rounding is the driver's: on NVIDIA it rounds toward zero, where the console rounds to nearest even (MODE.FP_ROUND = 0), e.g. 0x3C01 + 2^-11 gives 0x3C01 for 0x3C02. The per-lane comparison still covers them. On 3511bb9 (RTX 3080 Ti, wave32) the HLSL path passes every check and the per-lane form takes both programs, but it gives v_mul_f16 and v_pk_mul_f16 rounded toward zero (#1426 writes them through LegacyF32ToF16, the HLSL path through `f32_to_f16_rm`): x * 65504 is 0x7BFF for infinity (lanes 1-31) and the denormal ties of x * 2^-15 go down (lanes 3, 7, ..., 31), so the per-lane half fails there. The wave64 halves are SKIPPED (no 64-lane waves). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 177 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 6 + 2 files changed, 183 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 863e6a5f48..8b5130bed8 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -2247,6 +2247,183 @@ pub(crate) mod tests { ENDPGM, ]; + // f16 and packed programs, as the f32 ones: `lower_dxil`'s `f16_programs_on_the_gpu` checks + // the HLSL path's registers with the `check_f16_*` below and compares the per-lane form with it + + /// f16 VOP1 / VOP2 / VOP3 on x = 1 + lane · 2^-10 (v1, and v6's low half; v6's high half is + /// −2 − lane · 2^-9): ties to even, denormal results and their ties, overflow, a fused fma + /// just below a tie (lane 1), NaN into min / max / med3, OP_SEL halves, omod and clamp, and + /// f16 ↔ i16 / u16. + pub(crate) const F16_ARITHMETIC: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x3C00)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xC000)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 6), ("SRC1", 144), ("SRC2", V + 1)]), + // v2 = 2^-11, v3 = 2^-15 (a denormal), v4 = 65504, v5 = NaN, v7 = 2^-11 · (1 − 2^-10) + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 255), ("LITERAL", 0x1000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 255), ("LITERAL", 0x0200)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 255), ("LITERAL", 0x7BFF)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255), ("LITERAL", 0x7E00)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 255), ("LITERAL", 0x0FFE)]), + // x + 2^-11, 2^-11 − x (ties), x · 2^-15 (denormal ties), x · 65504 (∞ from lane 1), + // fma(x, v7, x) + ("V_ADD_F16", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_SUB_F16", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 1), ("VSRC1", 3)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 1), ("VSRC1", 4)]), + ("V_FMA_F16", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", V + 7), ("SRC2", V + 1)]), + // min(NaN, x), max(x, −NaN); v15's high half = v6's + x, its low half kept + ("V_MIN_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V + 5), ("VSRC1", 1)]), + ("V_MAX_F16", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 5), ("NEG", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V)]), + ("V_ADD_F16", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 6), ("SRC1", V + 1), ("OP_SEL", 9)]), + // omod: (x · 0.5) · 2, (x · x − 1) · 4; clamp of 65504 · 2 + ("V_MUL_F16", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", 240), ("OMOD", 1)]), + ("V_FMA_F16", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 1), ("SRC2", 243), ("OMOD", 2)]), + ("V_MUL_F16", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 4), ("SRC1", 244), ("CLAMP", 1)]), + // ldexp(x, −lane): denormals and their ties from lane 15, 0 from lane 26 + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 128), ("VSRC1", 0)]), + ("V_LDEXP_F16", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 1), ("VSRC1", 20)]), + // fract of v6's high half; q = (lane − 16) / 2 into rndne (ties, −0 at lane 15), i16, u16; + // u16 2049 · lane into f16 (a tie at lane 16) + ("V_FRACT_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 6), ("OP_SEL", 1)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 25), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F16_I16", "ENC_VOP1", &[("VDST", 24), ("SRC0", V + 25)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 26), ("SRC0", 240), ("VSRC1", 24)]), + ("V_RNDNE_F16", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 26)]), + ("V_CVT_I16_F16", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 26)]), + ("V_CVT_U16_F16", "ENC_VOP1", &[("VDST", 28), ("SRC0", V + 26)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V), ("SRC1", 139), ("SRC2", V)]), + ("V_CVT_F16_U16", "ENC_VOP1", &[("VDST", 29), ("SRC0", V + 30)]), + // med3(NaN, x, 2); fmac v32 = x · 2^-11 + x + ("V_MED3_F16", "ENC_VOP3", &[("VDST", 31), ("SRC0", V + 5), ("SRC1", V + 1), ("SRC2", 244)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 32), ("SRC0", V + 1)]), + ("V_FMAC_F16", "ENC_VOP2", &[("VDST", 32), ("SRC0", V + 1), ("VSRC1", 2)]), + ENDPGM, + ]; + + /// VOP3P packed math on v1 = x | y << 16 (x, y as in `F16_ARITHMETIC`), v2 = 2^-11 | 2^-15 << 16, + /// v3 = NaN | 65504 << 16 and the u16 / i16 pairs v4 = 2049 · lane | (0xFFFF − lane) << 16, + /// v5 = (0x8000 + lane << 10) | (0x7FF0 + lane) << 16: OP_SEL / OP_SEL_HI picking swapped and + /// broadcast halves, NEG / NEG_HI, clamp (f16, and saturating u16 / i16), and + /// v_cvt_pkrtz_f16_f32 (toward zero, 65504 for the out-of-range ones). + pub(crate) const F16_PACKED: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x3C00)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xC000)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V + 9), ("SRC1", 144), ("SRC2", V + 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 255), ("LITERAL", 0x0200_1000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 255), ("LITERAL", 0x7BFF_7E00)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 255), ("LITERAL", 0x0FFE_0FFE)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 139), ("SRC2", V)]), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xFFFF)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 11), ("SRC1", 144), ("SRC2", V + 10)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 138), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12), ("LITERAL", 0x8000)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x7FF0)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 13), ("SRC1", 144), ("SRC2", V + 12)]), + // v1 + v2; v1.hi · v2.lo | v1.lo · v2.hi; fma(v1, v7, v1) (v7 as in `F16_ARITHMETIC`) + ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 2), ("OP_SEL_HI", 3)]), + ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2), ("OP_SEL", 1), ("OP_SEL_HI", 2)]), + ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 7), ("SRC2", V + 1), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)]), + // min(v3, v1), max(v1, −v3), v1 + (−lo | hi of v1's high half), clamp(v3.hi · v1) + ("V_PK_MIN_F16", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 3), ("SRC1", V + 1), ("OP_SEL_HI", 3)]), + ("V_PK_MAX_F16", "ENC_VOP3P", &[("VDST", 18), ("SRC0", V + 1), ("SRC1", V + 3), ("OP_SEL_HI", 3), ("NEG", 2), ("NEG_HI", 2)]), + ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("NEG_HI", 1)]), + ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 20), ("SRC0", V + 3), ("SRC1", V + 1), ("OP_SEL", 1), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + // u16 / i16: wrapping, saturating (clamp), v4.lo · v5.hi | v4.hi · v5.hi, v4 · v4 + v5 + ("V_PK_ADD_U16", "ENC_VOP3P", &[("VDST", 21), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3)]), + ("V_PK_ADD_U16", "ENC_VOP3P", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_SUB_U16", "ENC_VOP3P", &[("VDST", 23), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_ADD_I16", "ENC_VOP3P", &[("VDST", 24), ("SRC0", V + 5), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_SUB_I16", "ENC_VOP3P", &[("VDST", 25), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3)]), + ("V_PK_MUL_LO_U16", "ENC_VOP3P", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL", 2), ("OP_SEL_HI", 3)]), + ("V_PK_MAD_U16", "ENC_VOP3P", &[("VDST", 27), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)]), + // pkrtz of 1 + lane · 2^-11 and of 65520 + 16 · lane (f32) + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 31), ("SRC0", 140), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 29), ("SRC0", 255), ("VSRC1", 31), ("LITERAL", 0x3F80_0000)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 255), ("VSRC1", 31), ("LITERAL", 0x477F_F000)]), + ("V_CVT_PKRTZ_F16_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", V + 29), ("VSRC1", 30)]), + ENDPGM, + ]; + + /// binary16 of an f64 (exact: an f16 sum or product), rounded to nearest even: denormals, + /// and ∞ past 65504 + pub(crate) fn f16_bits(x: f64) -> u32 { + let s = (x.is_sign_negative() as u32) << 15; + let a = x.abs(); + if a.is_infinite() { + return s | 0x7C00; + } + let e = ((a.to_bits() >> 52) as i32 - 1023).max(-14); + let q = (a * 2f64.powi(10 - e)).round_ties_even() as u32; + s | ((e + 14) as u32 * 1024 + q).min(0x7C00) + } + + pub(crate) fn check_f16_arithmetic(_: &[u32], v: &[Vec]) { + let h = |b: u32| f16_to_f32(b & 0xFFFF) as f64; + let p = |e: i32| 2f64.powi(e); + for (l, r) in v.iter().enumerate() { + let (x, y) = (0x3C00 + l as u32, 0xC000 + l as u32); + let (fx, fy, q) = (h(x), h(y), (l as f64 - 16.0) / 2.0); + assert_eq!((r[1], r[6]), (x, y << 16 | x), "lane {l}"); + // v8, v9, v12, v17, v19, v29 and v32 round to nearest even on the console (MODE.FP_ROUND + // = 0) and the HLSL path gives them rounded toward zero on NVIDIA (`f32tof16`, whose + // rounding the driver picks), so they are left to the per-lane comparison + let want = [ + (10, f16_bits(fx * p(-15))), + (11, f16_bits(fx * 65504.0)), + (13, x), + (14, x), + (15, f16_bits(fy + fx) << 16 | l as u32), + (16, x), + (18, 0x3C00), + (22, f16_bits(fy - fy.floor())), + (23, f16_bits(q.round_ties_even())), + (24, f16_bits(l as f64 - 16.0)), + (26, f16_bits(q)), + (27, q as i32 as u32 & 0xFFFF), + (28, q as u32), + (31, x), + ]; + for (i, w) in want { + assert_eq!(r[i], w, "lane {l} v{i}: {:#x} against {w:#x}", r[i]); + } + } + } + + pub(crate) fn check_f16_packed(_: &[u32], v: &[Vec]) { + let h = |b: u32| f16_to_f32(b & 0xFFFF) as f64; + let p = |e: i32| 2f64.powi(e); + let pk = |lo: u32, hi: u32| lo & 0xFFFF | hi << 16; + let i16s = |a: u32| a as u16 as i16 as i32; + let sat = |a: i32| a.clamp(-32768, 32767) as u32; + for (l, r) in v.iter().enumerate() { + let n = l as u32; + let (x, y) = (0x3C00 + n, 0xC000 + n); + let (fx, fy) = (h(x), h(y)); + let (a0, a1, c0, c1) = (2049 * n, 0xFFFF - n, 0x8000 + (n << 10), 0x7FF0 + n); + assert_eq!((r[1], r[4], r[5]), (pk(x, y), pk(a0, a1), pk(c0, c1)), "lane {l}"); + // v14 and v16 as v8 and v12 of `check_f16_arithmetic` + let want = [ + (15, pk(f16_bits(fy * p(-11)), f16_bits(fx * p(-15)))), + (17, pk(x, y)), + (18, pk(x, y)), + (19, pk(f16_bits(2.0 * fx), 0)), + (20, pk(0x3C00, 0)), + (21, pk(a0 + c0, a1 + c1)), + (22, pk((a0 + c0).min(0xFFFF), (a1 + c1).min(0xFFFF))), + (23, pk(a0.saturating_sub(c0), a1.saturating_sub(c1))), + (24, pk(sat(2 * i16s(c0)), sat(2 * i16s(c1)))), + (25, pk(a0.wrapping_sub(c0), a1.wrapping_sub(c1))), + (26, pk(a0 * c1, a1 * c1)), + (27, pk(a0 * a0 + c0, a1 * a1 + c1)), + (28, pk(0x3C00 + n / 2, 0x7BFF)), + ]; + for (i, w) in want { + assert_eq!(r[i], w, "lane {l} v{i}: {:#x} against {w:#x}", r[i]); + } + } + } + pub(crate) fn check_f32_arithmetic(_: &[u32], v: &[Vec]) { let sat = |x: f32| x.clamp(0.0, 1.0); for (l, r) in v.iter().enumerate() { diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 93d8b2e680..f269fd08d1 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -456,6 +456,12 @@ mod tests { } } + /// The f16 and packed programs of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn f16_programs_on_the_gpu() { + programs_on_the_gpu(&[("f16 arithmetic", F16_ARITHMETIC, check_f16_arithmetic, &[]), ("f16 packed", F16_PACKED, check_f16_packed, &[])]); + } + /// The per-lane form as real DXIL on the GPU agrees with the lowering run on the CPU (and so /// with the HLSL path, which `lower`'s tests compare it with): registers and memory. #[test] From 3827fb538740ed438f207ba8dc8589f4f73824f0 Mon Sep 17 00:00:00 2001 From: Miguel Machado Date: Tue, 24 Nov 2026 16:22:48 -0300 Subject: [PATCH 39/51] Recompiler: coalesce straight-line guarded runs in the per-lane lowering Coalesce maximal straight-line runs of guarded vector instructions under an unchanged EXEC mask (absorbing pure no-ops like s_waitcnt) into a single per-lane EXEC branch lowered unguarded, merging updated registers with SSA phis at the continuation block. Runs are emitted when they contain a side-effecting instruction (stores, atomics, non-read DS, EXP) or at least two guarded instructions; standalone guarded VALU/loads keep a select. Runs stop at scalar/mask/SCC writes (including V_CMPX and VOP3_SDST_ENC), cross-lane ops, and implicit-derivative image ops. Track block def/use ownership in stale() so splitting a partial console block into multiple runs keeps earlier definitions in the same console block non-stale while keeping definitions inside a run block partial. Assisted-by: Antigravity (Gemini 4 Neon) Reviewed-by: Claude Code (Claude Opus 5.5, xhigh) --- crates/xcl/src/gpu/recomp/lower.rs | 496 +++++++++++++++++++++--- crates/xcl/src/gpu/recomp/lower_dxil.rs | 56 ++- 2 files changed, 503 insertions(+), 49 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 8b5130bed8..41525eb24e 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -165,6 +165,15 @@ struct Lower<'a, I: Ir> { /// per IR block: not every lane that reached one of the program's lane branches gets here /// before they meet again (a loop that lanes leave one by one, an arm some lanes skip) partial: Vec, + /// stale-value ownership for blocks split by a coalesced run: backbone blocks of console + /// block b (`blk(b)` and its continuations) share `blk(b)` for both defs and uses, while a + /// run's inner block keeps its own `def_owner` (any def there is partial to outside reads) + /// and `blk(b)` as its `use_owner` (reads of earlier defs in the same console block stay valid) + def_owner: Vec, + use_owner: Vec, + /// inside a coalesced guarded run's own block: only lanes with EXEC set enter, so writes + /// need no per-instruction guard + unguarded: bool, /// the IR block each mask bit was written in, and the mask bits read (block, value) def_block: std::collections::HashMap, lane_uses: Vec<(usize, I::V)>, @@ -197,6 +206,122 @@ fn whole_quad(name: &str) -> bool { } } +/// Cross-lane and wave-level ops stay out of coalesced guarded runs (they need the parent +/// block's lane participation, e.g. fetch-inactive or whole-wave mask reads). +fn is_cross_lane(d: &Decoded) -> bool { + let n = d.inst.name; + matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) + || n.starts_with("V_PERMLANE") + || n.starts_with("V_MBCNT_") + || n.starts_with("V_READLANE") + || n.starts_with("V_READFIRSTLANE") + || n.starts_with("V_WRITELANE") + || n.starts_with("DS_SWIZZLE") + || n.starts_with("DS_BPERMUTE") + || n.starts_with("DS_PERMUTE") +} + +/// Implicit-derivative image instructions need quad-uniform control flow. +fn needs_quad_convergence(n: &str) -> bool { + n == "IMAGE_GET_LOD" + || ((n.starts_with("IMAGE_SAMPLE") || n.starts_with("IMAGE_GATHER")) + && !n.contains("_L_") + && !n.ends_with("_L") + && !n.contains("_LZ") + && !n.contains("_D_") + && !n.ends_with("_D") + && !n.contains("_CD")) +} + +/// Any write to an SGPR, mask (VCC / EXEC / M0), or SCC must run for all lanes outside a +/// coalesced run (inactive lanes clear their bit in a VALU mask write rather than keeping it). +fn writes_scalar_or_scc(d: &Decoded) -> bool { + let (_, written) = super::x64_masks::uses(d); + let (_, explicit_w) = rdna2::sgpr_uses(d); + let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r) & !(1u128 << 125); + writes != 0 + || d.inst.name.starts_with("V_CMPX") + || d.ienc + .operands + .iter() + .any(|o| o.output && matches!(o.ty, "OPR_VCC" | "OPR_EXEC" | "OPR_SDST_EXEC" | "OPR_SDST_M0" | "OPR_SSRC_SPECIAL_SCC")) +} + +/// Pure no-ops in this lowering: allowed inside a coalesced run without breaking it. +fn is_run_noop(d: &Decoded) -> bool { + matches!( + d.inst.name, + "V_NOP" | "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" + ) +} + +/// Guarded instructions with side effects that inactive lanes must not execute even alone. +fn must_branch(d: &Decoded) -> bool { + let n = d.inst.name; + is_store(d) + || n.contains("_STORE_") + || n.starts_with("IMAGE_STORE") + || n.contains("_ATOMIC_") + || (n.starts_with("DS_") && !n.starts_with("DS_READ") && !n.starts_with("DS_NOP")) + || n == "EXP" +} + +fn can_coalesce(d: &Decoded, guarded: &HashSet) -> bool { + guarded.contains(&d.pc) && !is_cross_lane(d) && !needs_quad_convergence(d.inst.name) && !writes_scalar_or_scc(d) +} + +/// Exclusive end of a block's non-terminator instructions. +fn block_body_end(insts: &[Decoded], range: &std::ops::Range) -> usize { + let mut end = range.end; + if end > range.start { + let d = &insts[end - 1]; + let name = d.inst.name; + if name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM") || d.far_target.is_some() { + end -= 1; + } + } + end +} + +/// Straight-line runs of guarded instructions in one console block that benefit from a single +/// per-lane EXEC branch instead of per-write `select`s (or per-store branches): any run with +/// a `must_branch` instruction or at least two guarded instructions. +fn coalesced_runs(insts: &[Decoded], range: &std::ops::Range, guarded: &HashSet) -> Vec> { + let end = block_body_end(insts, range); + let mut runs = Vec::new(); + let mut start: Option = None; + let mut last_end = 0usize; + let mut inst_count = 0usize; + let mut branch = false; + let mut flush = |start: &mut Option, last_end: usize, inst_count: &mut usize, branch: &mut bool| { + if let Some(s) = start.take() { + if *branch || *inst_count >= 2 { + runs.push(s..last_end); + } + *inst_count = 0; + *branch = false; + } + }; + for i in range.start..end { + let d = &insts[i]; + if is_run_noop(d) { + continue; + } + if can_coalesce(d, guarded) { + if start.is_none() { + start = Some(i); + } + last_end = i + 1; + inst_count += 1; + branch |= must_branch(d); + } else { + flush(&mut start, last_end, &mut inst_count, &mut branch); + } + } + flush(&mut start, last_end, &mut inst_count, &mut branch); + runs +} + /// IR block of analysis block b (block 0 is the prologue). fn blk(b: usize) -> usize { b + 1 @@ -333,7 +458,7 @@ impl<'a, I: Ir> Lower<'a, I> { } None => v, }; - let v = if self.guarded.contains(&d.pc) { + let v = if !self.unguarded && self.guarded.contains(&d.pc) { let old = self.read(b, Var::V(r)); let e = self.read_bit(b, EXEC)?; self.ir.select(e, v, old) @@ -791,9 +916,9 @@ impl<'a, I: Ir> Lower<'a, I> { Ok(()) } - /// `global_` / `flat_` `load` / `store_dword{,x2,x3,x4}` on the flat memory. A guarded load - /// keeps the old register in lanes without their EXEC bit (`write_v`); a guarded store is - /// lowered in a block only those lanes enter (the caller's split). + /// `global_` / `flat_` `load` / `store_dword{,x2,x3,x4}` on the flat memory. A standalone + /// guarded load keeps the old register in lanes without their EXEC bit (`write_v`); guarded + /// stores and coalesced runs are lowered unguarded in a block only those lanes enter (`splits`). fn vmem(&mut self, b: usize, d: &Decoded) -> R<()> { let name = d.inst.name; if self.ir.mem_windows() > 1 { @@ -884,7 +1009,7 @@ impl<'a, I: Ir> Lower<'a, I> { Some(ops) => work.extend_from_slice(ops), None => { if let Some(&b) = self.def_block.get(&v) { - if b != c && self.partial[b] { + if self.def_owner[b] != self.use_owner[c] && self.partial[b] { return true; } } @@ -1012,28 +1137,32 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s } // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores, // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch, - // then for every guarded store (only the lanes with their EXEC bit may write): the block of - // the store and the one the rest of its block continues in. `tail[b]`: the IR block the + // then for every coalesced guarded run (only the lanes with their EXEC bit enter): the run's + // block and the one the rest of its block continues in. `tail[b]`: the IR block the // program's block b ends in. let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4); let guarded: HashSet = sum.guarded.iter().copied().collect(); - let mut splits: Vec> = vec![Vec::new(); n]; // (inst, store, cont) + let mut splits: Vec, usize, usize)>> = vec![Vec::new(); n]; // (run, body, cont) let mut count = n + 5; for (b, block) in sum.blocks.iter().enumerate() { - for i in block.insts.clone() { - if is_store(&insts[i]) && guarded.contains(&insts[i].pc) { - splits[b].push((i, count, count + 1)); - count += 2; - } + for run in coalesced_runs(insts, &block.insts, &guarded) { + splits[b].push((run, count, count + 1)); + count += 2; } } let tail: Vec = (0..n).map(|b| splits[b].last().map_or(blk(b), |s| s.2)).collect(); let mut partial = vec![false; count]; + let mut def_owner: Vec = (0..count).collect(); + let mut use_owner: Vec = (0..count).collect(); for (b, p) in partial_blocks(&sum).into_iter().enumerate() { partial[blk(b)] = p; for &(_, s, c) in &splits[b] { partial[s] = true; partial[c] = p; + def_owner[s] = s; + use_owner[s] = blk(b); + def_owner[c] = blk(b); + use_owner[c] = blk(b); } } let ends: Vec = sum.order.iter().copied().filter(|&b| sum.blocks[b].succ.is_empty()).collect(); @@ -1081,6 +1210,9 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s bit_uses: Vec::new(), lane: None, partial, + def_owner, + use_owner, + unguarded: false, def_block: std::collections::HashMap::new(), lane_uses: Vec::new(), dpp_src: None, @@ -1238,49 +1370,41 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s } let block = &sum.blocks[b]; let last = block.insts.end - 1; + let body_end = block_body_end(insts, &block.insts); let mut cur = ib; let mut split = splits[b].iter().peekable(); - for i in block.insts.clone() { - let d = &insts[i]; - let name = d.inst.name; - if i == last && (name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM") || d.far_target.is_some()) { - break; - } - if matches!(stage, Stage::Pixel) && whole_quad(name) && l.partial[cur] { - l.note_inst(Err(format!("{name}: needs whole quads, in a block not every lane reaches")), cur, d)?; - continue; - } - if let Some(&(_, s, c)) = split.next_if(|x| x.0 == i) { - // a guarded store: only the lanes with their EXEC bit go through its block + let mut i = block.insts.start; + while i < body_end { + if let Some(&(ref run, s, c)) = split.next_if(|x| x.0.start == i) { + // a coalesced guarded run: only the lanes with their EXEC bit enter `s`, + // lowered unguarded; updated registers merge through SSA phis at `c` let e = l.read_bit(cur, EXEC)?; l.ir.br_if(e, s, c); done[cur] = true; l.ir.at(s); l.ssa.seal(&mut l.ir, s); - let r = l.vmem(s, d); - let r = l.or_bridge(r, s, d, true); - l.note_inst(r, s, d)?; + l.unguarded = true; + for j in run.clone() { + let r = l.lower_inst(s, &insts[j]); + l.note_inst(r, s, &insts[j])?; + } + l.unguarded = false; l.ir.br(c); done[s] = true; l.ir.at(c); l.ssa.seal(&mut l.ir, c); cur = c; + i = run.end; } else { - let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { - l.smem(cur, d) - } else if name.starts_with("S_") { - l.salu(cur, d) - } else if name.starts_with("V_") { - l.valu(cur, d) - } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { - l.vmem(cur, d) - } else if name == "DS_SWIZZLE_B32" { - l.swizzle(cur, d) - } else { - Err(format!("unsupported {name}")) - }; - let r = l.or_bridge(r, cur, d, false); - l.note_inst(r, cur, d)?; + let name = insts[i].inst.name; + if matches!(stage, Stage::Pixel) && whole_quad(name) && l.partial[cur] { + l.note_inst(Err(format!("{name}: needs whole quads, in a block not every lane reaches")), cur, &insts[i])?; + i += 1; + continue; + } + let r = l.lower_inst(cur, &insts[i]); + l.note_inst(r, cur, &insts[i])?; + i += 1; } } match block.succ.as_slice() { @@ -1427,12 +1551,12 @@ impl Lower<'_, I> { /// so that a later read does not report a refusal that only follows from this one. /// An instruction this lowering has no semantics of, through `Ir::foreign` (#1426's /// per-instruction lowering) with the lane-mask analysis's guard: `true` where EXEC is proven - /// (or in a guarded store's own block, `in_store_block`), else the lane's EXEC bit. Its SGPR + /// (or inside a coalesced guarded run's block, `in_guarded_run`), else the lane's EXEC bit. Its SGPR /// operands are read as numbers (a mask read whole is refused, as everywhere), the mask a /// VALU reads lane by lane (`v_cndmask_b32`'s selector, a carry-in) as a number holding only /// this lane's bit, and a mask it writes (a compare, a carry-out) comes back as this lane's /// bit of the ballot it makes. Of the instructions writing EXEC, only `v_cmpx_*` is taken. - fn bridge(&mut self, b: usize, d: &Decoded, in_store_block: bool) -> R<()> { + fn bridge(&mut self, b: usize, d: &Decoded, in_guarded_run: bool) -> R<()> { let name = d.inst.name; let (whole, written) = super::x64_masks::uses(d); let (_, explicit_w) = rdna2::sgpr_uses(d); @@ -1526,7 +1650,7 @@ impl Lower<'_, I> { if writes_scc { outputs.push(Var::Scc); } - let guard = if cmpx || in_store_block || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; + let guard = if cmpx || in_guarded_run || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; let vals = self.ir.foreign(d, guard, &inputs, &outputs)?; for (&var, &v) in outputs.iter().zip(&vals) { match var { @@ -1571,10 +1695,29 @@ impl Lower<'_, I> { Ok(()) } + /// Lowers one non-terminator instruction in block `b`, falling back to `bridge`. + fn lower_inst(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { + self.smem(b, d) + } else if name.starts_with("S_") { + self.salu(b, d) + } else if name.starts_with("V_") { + self.valu(b, d) + } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { + self.vmem(b, d) + } else if name == "DS_SWIZZLE_B32" { + self.swizzle(b, d) + } else { + Err(format!("unsupported {name}")) + }; + self.or_bridge(r, b, d, self.unguarded) + } + /// `r`, or an instruction it calls unsupported lowered through `bridge`. - fn or_bridge(&mut self, r: R<()>, b: usize, d: &Decoded, in_store_block: bool) -> R<()> { + fn or_bridge(&mut self, r: R<()>, b: usize, d: &Decoded, in_guarded_run: bool) -> R<()> { match r { - Err(e) if e.starts_with("unsupported ") => match self.bridge(b, d, in_store_block) { + Err(e) if e.starts_with("unsupported ") => match self.bridge(b, d, in_guarded_run) { Ok(()) => Ok(()), Err(f) if f == "no foreign lowering" => Err(e), Err(f) => Err(format!("{e} ({f})")), @@ -1681,6 +1824,12 @@ pub(crate) mod tests { } v } + fn selects(&self) -> usize { + self.blocks.iter().map(|(ins, _)| ins.iter().filter(|(_, op)| matches!(op, Ins::Select(..))).count()).sum() + } + fn br_ifs(&self) -> usize { + self.blocks.iter().filter(|(_, t)| matches!(t, Term::BrIf(..))).count() + } } impl Sink for Interp { @@ -3846,4 +3995,255 @@ pub(crate) mod tests { agrees_with_hlsl("lane reads, wave64", &lane_reads(true), true, &[]); agrees_with_hlsl("waterfall, wave64", &waterfall(true), true, &[2, 4, 5]); } + + /// Guarded straight-line run under narrowed EXEC (no skip branch): VALU ops, a guarded load, + /// `s_waitcnt`, and two guarded stores all coalesce into one per-lane branch with 0 selects. + pub(crate) fn coalesced_run(wave64: bool) -> Vec { + let (cmp, save, restore): (&'static [(&'static str, u64)], &str, &str) = if wave64 { + (&[("SRC0", 168), ("VSRC1", 0)], "S_AND_SAVEEXEC_B64", "S_OR_B64") + } else { + (&[("SRC0", 144), ("VSRC1", 0)], "S_AND_SAVEEXEC_B32", "S_OR_B32") + }; + vec![ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", cmp), + (save, "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 138), ("VSRC1", 0)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", 131)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 0)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 8), ("SADDR", 125), ("OFFSET", 0)]), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 5), ("VSRC1", 2)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 4), ("SADDR", 125), ("OFFSET", 0x100)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 6), ("SADDR", 125), ("OFFSET", 0x200)]), + (restore, "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + ENDPGM, + ] + } + + /// Guarded runs separated by a scalar write, a `v_cmp`, and a cross-lane `v_readlane`, plus + /// `v_cndmask` and a twice-written VGPR inside coalesced runs. + pub(crate) const COALESCED_BREAKS: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 133)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 135), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 1)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 136), ("VSRC1", 0)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 3), ("VSRC1", 4)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 3), ("VSRC1", 6)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 130), ("VSRC1", 7)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + + /// Two coalesced runs separated by a scalar write inside an already-`partial` block (arm of a + /// skipped `if`), reading SGPR `s2` and `vcc` written earlier in that same console block. + pub(crate) const COALESCED_IN_PARTIAL: &[I] = &[ + ("S_AND_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 126), ("SSRC1", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 152), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 10)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 139)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 140), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 2), ("VSRC1", 0)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 1)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 3)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 2), ("VSRC1", 4)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 5)]), + ENDPGM, + ]; + + /// A 4-iteration uniform loop whose body narrows EXEC (no skip branch) around a coalesced run. + pub(crate) const COALESCED_IN_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 2), ("SSRC1", 132)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)]), + ENDPGM, + ]; + + /// Guarded run of f32 instructions lowered through `Ir::foreign` (`Lw::inst_guarded`). + pub(crate) const COALESCED_F32_RUN: &[I] = &[ + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 242), ("VSRC1", 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 244), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 3), ("SRC1", 240), ("SRC2", 242)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 242), ("VSRC1", 4)]), + ENDPGM, + ]; + + #[test] + fn guarded_run_coalesces_into_one_branch_with_no_selects() { + for (wave64, lanes, cut) in [(false, 32usize, 16usize), (true, 64usize, 40usize)] { + let lines = coalesced_run(wave64); + let insts = decode(&lines); + let sum = lane_masks::analyze(&insts, wave64).unwrap(); + assert_eq!(sum.guarded.len(), 7, "wave64={wave64}"); + let (ir, stale) = lower_kernel(&insts, wave64, Interp::default()).unwrap(); + assert!(stale.is_empty(), "{stale:?}"); + // wave64 has 1 prologue select to pick EXEC's lo/hi dword; 0 per-write selects in either mode + assert_eq!(ir.selects(), usize::from(wave64), "wave64={wave64}: coalesced run removes all per-write selects"); + assert_eq!(ir.br_ifs(), 3, "wave64={wave64}: entry + 1 coalesced run + exit"); + + let (s, v) = state(lanes); + let (s, v, mem) = run_mem(&lines, wave64, &s, &v, &memory_image()); + assert_eq!(s[126], u32::MAX); + if wave64 { + assert_eq!(s[127], u32::MAX); + } + for l in 0..lanes { + let l32 = l as u32; + if l < cut { + let (v2, v5) = (l32 + 10, 1000 + l32); + let (v3, v6) = (v2 * 3, v5 + v2); + let v4 = v3 ^ l32; + assert_eq!((v[l][2], v[l][3], v[l][4], v[l][5], v[l][6], v[l][7]), (v2, v3, v4, v5, v6, v4 + v6), "wave64={wave64} lane {l}"); + assert_eq!((mem[64 + l], mem[128 + l]), (v4, v6), "wave64={wave64} lane {l} mem"); + } else { + assert_eq!((v[l][2], v[l][3], v[l][4], v[l][5], v[l][6], v[l][7]), (0, 0, 0, 0, 0, 0), "wave64={wave64} lane {l}"); + assert_eq!((mem[64 + l], mem[128 + l]), (1064 + l32, 1128 + l32), "wave64={wave64} lane {l} mem"); + } + } + } + + // a single guarded VALU or load keeps its select rather than adding a branch + for single_op in [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)][..]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 125), ("OFFSET", 0)][..]), + ] { + let single = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + single_op, + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]); + let (ir, _) = lower_kernel(&single, false, Interp::default()).unwrap(); + assert_eq!((ir.selects(), ir.br_ifs()), (1, 2), "{}", single_op.0); + } + } + + #[test] + fn guard_coalescing_breaks_at_scalar_compare_and_cross_lane_ops() { + let (ir, stale) = lower_kernel(&decode(COALESCED_BREAKS), false, Interp::default()).unwrap(); + assert!(stale.is_empty(), "{stale:?}"); + assert_eq!((ir.selects(), ir.br_ifs()), (1, 6)); // only v_cndmask's select; 4 runs + entry/exit + let (s, v) = state(32); + let (s, v) = run(COALESCED_BREAKS, false, &s, &v); + assert_eq!((s[2], s[3], s[106], s[126]), (8, 10, 0xFF, u32::MAX)); + for l in 0..32usize { + let l32 = l as u32; + let want = if l < 16 { + let (v1, v3) = (l32 + 7, l32 + 15); + let v4 = v3 ^ (v1 + l32); + (v1, v4, 10 + (if l < 8 { v4 } else { v3 }) + 3) + } else { + (0, 0, 0) + }; + assert_eq!((v[l][1], v[l][4], v[l][7]), want, "lane {l}"); + } + + // two coalesced runs inside a partial block (with a scalar write in between) stay non-stale + let (s, v) = state(32); + let (_, v) = run(COALESCED_IN_PARTIAL, false, &s, &v); + for l in 0..32usize { + let l32 = l as u32; + let v4 = if l < 12 { l32 + 24 } else { 0 }; + let v5 = if l < 24 { 12 + v4 } else { 0 }; + assert_eq!((v[l][4], v[l][5], v[l][6]), (v4, v5, v5 + 1), "partial lane {l}"); + } + + // coalesced run inside a loop: 0 selects, SSA phis carry loop values cleanly + let (ir, _) = lower_kernel(&decode(COALESCED_IN_LOOP), false, Interp::default()).unwrap(); + assert_eq!(ir.selects(), 0); + let (s, v) = state(32); + let (s, v) = run(COALESCED_IN_LOOP, false, &s, &v); + assert_eq!((s[2], s[126]), (4, u32::MAX)); + for l in 0..32 { + assert_eq!((v[l][1], v[l][2]), if l < 16 { (4, 10) } else { (0, 0) }, "loop lane {l}"); + } + + // guarded VALU carry-out (VOP3_SDST_ENC) and cross-lane ds_swizzle split runs + let cs = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 1)]), + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 106), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 3)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 130), ("VSRC1", 4)]), + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 5), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 129), ("VSRC1", 6)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 7)]), + ENDPGM, + ]); + let sum = lane_masks::analyze(&cs, false).unwrap(); + let guarded: HashSet = sum.guarded.iter().copied().collect(); + assert_eq!(coalesced_runs(&cs, &sum.blocks[0].insts, &guarded), vec![2..4, 5..7, 8..10]); + } + + #[test] + fn coalesced_guarded_runs_agree_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + return; + } + agrees_with_hlsl("coalesced breaks, wave32", COALESCED_BREAKS, false, &[]); + agrees_with_hlsl("coalesced in partial, wave32", COALESCED_IN_PARTIAL, false, &[]); + agrees_with_hlsl("coalesced in loop, wave32", COALESCED_IN_LOOP, false, &[]); + let check_mem = |wave64: bool| { + let (lines, lanes) = (coalesced_run(wave64), if wave64 { 64 } else { 32 }); + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64, split_wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(&lines, wave64, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "wave64={wave64}: memory"); + for l in 0..lanes { + for r in 0..8 { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "wave64={wave64}: lane {l} v{r}"); + } + } + assert_eq!(cs[126], gpu.sgpr[126]); + if wave64 { + assert_eq!(cs[127], gpu.sgpr[127]); + } + }; + check_mem(false); + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + check_mem(true); + } } diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index f269fd08d1..6bdd9904f9 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -469,7 +469,18 @@ mod tests { if !gpu() { return; } - for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { + let run = coalesced_run(false); + for (name, lines) in [ + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF), + ("leaving loop", LEAVING_LOOP), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY), + ("coalesced run", &run[..]), + ("coalesced breaks", COALESCED_BREAKS), + ("coalesced in partial", COALESCED_IN_PARTIAL), + ("coalesced in loop", COALESCED_IN_LOOP), + ] { let insts = decode(lines); let (dxil, stale) = super::kernel(&insts, false).unwrap_or_else(|e| panic!("{name}: {e}")); let (s, v) = state(32); @@ -663,4 +674,47 @@ mod tests { let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); assert_eq!(&out[..cpu.len()], &cpu[..]); } + + /// Coalesced guarded runs lowered through `Ir::foreign` (`Lw::inst_guarded` with `guard = true` + /// inside the run's block): f32 arithmetic against HLSL, and 4-window memory load/store inside + /// a coalesced run (`Lw` making window-switch blocks inside the run) against the CPU lowering. + #[test] + fn coalesced_foreign_runs_agree_on_the_gpu() { + if !gpu() { + return; + } + // 4-window compute: lanes with tid < 16 run a coalesced load + add + store via `foreign` + let cs = compute_cs(); + let run = coalesced_run(false); + let bytes: Vec = run.iter().flat_map(encode_line).collect(); + let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let mem = memory_image(); + let out = runner::dispatch(&k.dxil, [1, 1, 1], &[0, 0], &mem).unwrap(); + let cpu = run_compute(&run, &cs, 1, &[0, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..], "4-window coalesced memory via foreign"); + + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let bytes: Vec = COALESCED_F32_RUN.iter().flat_map(encode_line).collect(); + let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), &st, &[]).unwrap(); + let (dxil, _) = super::kernel(&decode(COALESCED_F32_RUN), false).unwrap(); + let direct = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..32 { + for r in 0..=5 { + assert_eq!(direct.vgpr[l][r], hlsl.vgpr[l][r], "lane {l} v{r}"); + } + } + assert_eq!((direct.sgpr[106], direct.sgpr[126]), (hlsl.sgpr[106], hlsl.sgpr[126])); + } } From a23b6ff3d1490ba8db7c5c2c452bd374c8b06076 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:28:12 -0300 Subject: [PATCH 40/51] Recompiler: a value copied where some lanes are elsewhere is that block's write `stale()` keys each scalar value by the block that made it. A write in a block some lanes skip of a value made elsewhere (an older mask copied with `s_mov s4, s0`, a constant the builder shares) kept the older block, so a read after the lanes meet was not refused although the console's write reached every lane and each lane here kept its own. Such a write now gets a copy of its own (`or v, 0`) defined in the partial block. Found by MiguelMachado-dev while writing guard coalescing. --- crates/xcl/src/gpu/recomp/lower.rs | 32 +++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 41525eb24e..ff26958982 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -377,8 +377,22 @@ impl<'a, I: Ir> Lower<'a, I> { /// SCC, written and read like an SGPR number: a lane that skipped the block writing it /// keeps its own older value (`stale`). - fn write_scc(&mut self, b: usize, v: I::V) { + /// `v` as written in block b: in a block some lanes skip, a value made elsewhere (an older + /// mask copied, a shared constant) gets a copy of its own, so `stale` sees the write here. + fn own(&mut self, b: usize, v: I::V, bit: bool) -> I::V { + let v = match self.def_block.get(&v) { + Some(&d) if d != b && self.partial[b] => { + let z = if bit { self.ir.boolean(false) } else { self.ir.int(0) }; + self.ir.bin(Bin::Or, v, z) + } + _ => v, + }; self.def_block.entry(v).or_insert(b); + v + } + + fn write_scc(&mut self, b: usize, v: I::V) { + let v = self.own(b, v, true); self.ssa.write(b, Var::Scc, v); } @@ -389,7 +403,7 @@ impl<'a, I: Ir> Lower<'a, I> { } fn write_num(&mut self, b: usize, r: u8, v: I::V) { - self.def_block.entry(v).or_insert(b); + let v = self.own(b, v, false); self.ssa.write(b, Var::S(r), v); self.ssa.write(b, Var::M(r), self.bit_marker); if self.wave64 && r > 0 { @@ -399,9 +413,7 @@ impl<'a, I: Ir> Lower<'a, I> { } fn write_bit(&mut self, b: usize, r: u8, bit: I::V) { - if r != EXEC { - self.def_block.entry(bit).or_insert(b); - } + let bit = if r != EXEC { self.own(b, bit, true) } else { bit }; self.ssa.write(b, Var::M(r), bit); self.ssa.write(b, Var::S(r), self.num_marker); if self.wave64 { @@ -3774,6 +3786,16 @@ pub(crate) mod tests { // a mask written before the lanes split is read after they meet: fine let insts = decode(SKIPPED_IF); assert_eq!(lower_kernel(&insts, false, Interp::default()).unwrap().1, Vec::::new()); + // an older mask copied in the arm some lanes skip (s_mov s4, s0), read after they meet: + // the copy is the arm's write, not the older value's (found by MiguelMachado-dev) + let mut lines = SKIPPED_IF.to_vec(); + lines[2] = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]); + lines.insert(3, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 0)])); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 128), ("SRC1", 129), ("SRC2", 4)])); + // (s4 holds a mask before the lanes split, so the join is mask against mask) + lines.insert(1, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); } #[test] From dd566c0c9eb06aa3950000213bca3217340dfac5 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:31:12 -0300 Subject: [PATCH 41/51] Recompiler: no r - 1 for s0 in the mask-pair check of cross-lane ops `mask_reg` built its upper-dword answer with `then_some((r - 1, true))`, which evaluates `r - 1` even when the condition is false, so a cross-lane scalar op on s0 overflowed in debug builds (`xcl shaders --recomp` panicked). It is lazy now (`then`). Found and fixed by nobodyttk (#1269). --- crates/xcl/src/gpu/recomp/lower.rs | 14 ++++++++++++++ crates/xcl/src/gpu/recomp/lower/wave.rs | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index ff26958982..9d15a31533 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -3140,6 +3140,20 @@ pub(crate) mod tests { out } + /// A cross-lane scalar op on s0 holding a number takes the number path (the check for the + /// upper dword of a mask pair at s must not compute r - 1 for s0: nobodyttk, #1269). + #[test] + fn a_wave_op_on_s0_holding_a_number() { + let lines: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255), ("LITERAL", 0xF0F0)]), + ("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 0)]), + ENDPGM, + ]; + // the CPU lowering has no number form of it (DXIL takes it from #1426): refused, no panic + let err = lower_kernel(&decode(lines), false, Interp::default()).err().expect("refused"); + assert_eq!(err, "unsupported S_BCNT1_I32_B32"); + } + /// `s_wqm` of a mask sets every lane of a quad with a bit; `s_cselect` picks a mask or a /// number by SCC. #[test] diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs index 28576603ae..7d3ceceb77 100644 --- a/crates/xcl/src/gpu/recomp/lower/wave.rs +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -44,7 +44,7 @@ impl Lower<'_, I> { return Some((r, false)); } // the upper dword of a wave64 mask pair - (self.wave64 && r > 0 && self.holds_mask(b, r - 1)).then_some((r - 1, true)) + (self.wave64 && r > 0 && self.holds_mask(b, r - 1)).then(|| (r - 1, true)) } /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits; with `half`, From fdb4c10dce052d32fb827dca51d07c1cb7858017 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:37:22 -0300 Subject: [PATCH 42/51] Recompiler: --lanes runs the per-lane form under the sweep's timeout A few large programs kept the sweep running for over an hour (the adapter's trivial-phi replacement walks the whole module each time). They now count as "timeout: over N s" refusals, as the direct form's do. --- crates/xcl/src/shaders.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 2ada0d332b..92c04341d4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1933,7 +1933,13 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: let time = t.elapsed(); if let (true, recomp::Mode::Compute(cs)) = (lanes, &mode) { lanes_tried.fetch_add(1, Ordering::Relaxed); - match recomp::lower_dxil::compute_with(code, cs, o) { + // under the sweep's timeout too (the thread is left to finish) + let (tx, rx) = std::sync::mpsc::channel(); + let (c, csc) = (code.to_vec(), cs.clone()); + std::thread::spawn(move || { + let _ = tx.send(recomp::lower_dxil::compute_with(&c, &csc, o)); + }); + match rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) { Ok(k) => { lanes_ok.fetch_add(1, Ordering::Relaxed); lanes_bytes.fetch_add(k.dxil.len(), Ordering::Relaxed); From e40ac38816462e41b381e33cbb4d78bb4639a696 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:39:10 -0300 Subject: [PATCH 43/51] Recompiler: the runtime's split compute programs ask for 32-lane waves `compute_with` passed `WaveSize(64)` to `Lw::finish` for a wave64 program in the split form, so on a GPU with 32-lane waves only (the runtime's split path) `CreateComputePipelineState` refused it (0x80070057 on a GTX 1650): no split program reached the GPU through the runtime. The split form now asks for 32-lane waves, as `compute_split` does. Test: the 2-D / 3-D id programs in the split form through `compute_with`, against the CPU lowering's wave64 run. Also: `can_coalesce` uses `whole_quad` instead of its own copy of it. Both found by MiguelMachado-dev, reading the code. --- crates/xcl/src/gpu/recomp/lower.rs | 14 +------------- crates/xcl/src/gpu/recomp/lower_dxil.rs | 23 ++++++++++++++++++++++- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 9d15a31533..2188d42543 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -221,18 +221,6 @@ fn is_cross_lane(d: &Decoded) -> bool { || n.starts_with("DS_PERMUTE") } -/// Implicit-derivative image instructions need quad-uniform control flow. -fn needs_quad_convergence(n: &str) -> bool { - n == "IMAGE_GET_LOD" - || ((n.starts_with("IMAGE_SAMPLE") || n.starts_with("IMAGE_GATHER")) - && !n.contains("_L_") - && !n.ends_with("_L") - && !n.contains("_LZ") - && !n.contains("_D_") - && !n.ends_with("_D") - && !n.contains("_CD")) -} - /// Any write to an SGPR, mask (VCC / EXEC / M0), or SCC must run for all lanes outside a /// coalesced run (inactive lanes clear their bit in a VALU mask write rather than keeping it). fn writes_scalar_or_scc(d: &Decoded) -> bool { @@ -267,7 +255,7 @@ fn must_branch(d: &Decoded) -> bool { } fn can_coalesce(d: &Decoded, guarded: &HashSet) -> bool { - guarded.contains(&d.pc) && !is_cross_lane(d) && !needs_quad_convergence(d.inst.name) && !writes_scalar_or_scc(d) + guarded.contains(&d.pc) && !is_cross_lane(d) && !whole_quad(d.inst.name) && !writes_scalar_or_scc(d) } /// Exclusive end of a block's non-terminator instructions. diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 6bdd9904f9..7fa53dc01d 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -404,7 +404,7 @@ pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> R .stack_size(256 << 20) .spawn(move || { let ir = lower::lower_compute(&insts, &cs, o.wave64, DxilIr::with(&insts, o, &Entry::Compute(cs.clone())))?; - ir.finish(cs.threads, if o.wave64 { 64 } else { 32 }) + ir.finish(cs.threads, if o.wave64 && !o.split { 64 } else { 32 }) }) .map_err(|e| format!("per-lane thread: {e}"))? .join() @@ -628,6 +628,27 @@ mod tests { } } + /// A wave64 program in the split form through `compute_with` (the runtime's path on a GPU + /// with 32-lane waves only): 32-lane hardware waves (`WaveSize(32)`, not 64), the console's + /// wave64 results (MiguelMachado-dev found `compute_with` passing 64). + #[test] + fn the_runtime_path_takes_the_split_form() { + if !gpu() { + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, true); + let cs = ids_cs(threads); + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let o = super::KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&k.dxil, [2, 1, 1], &[100, 0], &mem).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let cpu = run_compute_waves(&lines, &cs, true, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?}"); + } + } + /// The f64 program of `lower`'s tests, as `f32_programs_on_the_gpu`. #[test] fn f64_programs_on_the_gpu() { From 14e367e5563d3b550f2b79f5dd563d669b49aa6d Mon Sep 17 00:00:00 2001 From: teidenzero <8762337+teidenzero@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:33:28 -0500 Subject: [PATCH 44/51] Recompiler: a VS starts with every lane in EXEC in the per-lane form Each D3D vertex invocation is one lane, so no lane of a VS is outside EXEC at launch (gefydev's answer in #1269). The lane-mask analysis now takes a VS's launch EXEC as every lane (`LaunchExec::All`, as for compute), and the lowering sets each lane's EXEC bit at the program's first block, so a VS that never writes EXEC keeps no guard. Only a PS takes the launch EXEC as unknown. Tested on an RTX 4090 (Windows 10 22H2, DXC 1.8.2502): - cargo test -p xcl --lib -- recomp::lower recomp::lane_masks gpu::dxil --test-threads=4: 133 passed, 0 failed, 1 ignored; - cargo test --workspace --no-fail-fast -- --test-threads=4: lib 869 passed, 0 failed, 22 ignored; every other test binary passed; - with the VS's launch EXEC taken as unknown again, a_ps_helper_lane_runs_the_program_but_does_not_store fails (the VS's store keeps its guard). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/lower.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 2188d42543..1cb527afcd 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1128,8 +1128,10 @@ pub fn survey_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, survey: bool) -> R<(I, Vec, Vec)> { let kernel = matches!(stage, Stage::Kernel); let graphics = matches!(stage, Stage::Vertex | Stage::Pixel); - // a VS / PS: lanes may run outside the launch EXEC (a PS's helper lanes) - let launch = if graphics { lane_masks::LaunchExec::Unknown } else { lane_masks::LaunchExec::All }; + // a PS: lanes may run outside the launch EXEC (its helper lanes); a VS has none, each D3D + // vertex invocation being one lane + let pixel = matches!(stage, Stage::Pixel); + let launch = if pixel { lane_masks::LaunchExec::Unknown } else { lane_masks::LaunchExec::All }; let sum = lane_masks::analyze_launch(insts, wave64, launch).map_err(|e| e.to_string())?; let n = sum.blocks.len(); if n == 0 { @@ -1362,9 +1364,9 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s if !sealed[ib] { sealed[ib] = seal_ready(&mut l, &done, ib); } - if b == 0 && !graphics { - // the analysis takes the lanes that start the program as its EXEC (a VS / PS keeps - // the launch EXEC from its start: there the analysis does not know it) + if b == 0 && !pixel { + // the analysis takes the lanes that start the program as its EXEC (a PS keeps the + // launch EXEC from its start: there the analysis does not know it) let t = l.ir.boolean(true); l.write_bit(ib, EXEC, t); } @@ -3366,9 +3368,13 @@ pub(crate) mod tests { ENDPGM, ]; assert_eq!(run_graphics(&wqm64, true, true, 32, launch, &store_rows(), &memory_image()), want); - // a VS: every lane in the launch EXEC stores + // a VS: each D3D vertex invocation is one lane, so every lane that runs is in EXEC at + // launch and stores, whatever bit its start gives it let all: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 { 9 } else { m }).collect(); - assert_eq!(run_graphics(&[SET_V7, STORE_V7, ENDPGM], false, false, 32, 0xFFFF_FFFF, &store_rows(), &memory_image()), all); + assert_eq!(run_graphics(&[SET_V7, STORE_V7, ENDPGM], false, false, 32, launch, &store_rows(), &memory_image()), all); + // … so its store keeps no guard (no block of its own), where a PS's does + let blocks = |pixel: bool| lower_graphics(&decode(&[SET_V7, STORE_V7, ENDPGM]), pixel, false, false, Interp::default()).unwrap().blocks.len(); + assert_eq!(blocks(false) + 2, blocks(true), "a guarded store adds two blocks: the PS's only"); } #[test] From 29eccc018f4e04abbd647e1be2e69a2fa0d920ac Mon Sep 17 00:00:00 2001 From: Itsmetibo <189468068+Itsmetibo@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:46:28 +0100 Subject: [PATCH 45/51] Recompiler: replace the per-lane form's trivial phis in one pass DxilIr's Sink::replace called Module::replace_all_uses for every trivial phi the SSA construction drops, and each call walks every instruction and metadata entry of the module, so the per-lane lowering took time (trivial phis) x (module size), about quadratic in the program's size. A CPU profile (WPR) of one 80 KB retail compute program put replace_all_uses and the heap at the top: survey_compute_code took 18.5 s of the program's 19.3 s, and the CS + MS per-lane survey (XCL_RECOMP_STAGES=CS,MS XCL_RECOMP_NO_HLSL=1) did not finish in 10 minutes on a 12-thread i5-11600. The runtime's per-lane form (XCL_PER_LANE=1) goes through the same adapter. replace now records old -> new, and DxilIr::finish makes all of them in one pass (Module::replace_uses, which follows a chain a -> b -> c as the calls one at a time in order did) before #1426's Lw seals its blocks. Nothing reads an instruction's operands back before then: the SSA construction resolves a replaced phi through its own forward map, and Lw's SSA only compares the values it holds. replace_all_uses stays and goes through replace_uses. Test: a batched map with a chain gives the same container as replace_all_uses one at a time. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module.rs | 14 +++++++-- crates/xcl/src/gpu/dxil/tests.rs | 39 +++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 20 +++++++++---- 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 6baebccdc2..cc37c4fa74 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1110,9 +1110,19 @@ impl Module { /// Replaces every use of `old` by `new` in the entry's instructions and in /// metadata (e.g. to drop a trivial phi). `old` itself stays in its block. pub fn replace_all_uses(&mut self, old: Value, new: Value) { + self.replace_uses(&HashMap::from([(old, new)])); + } + + /// `replace_all_uses` for every `old → new` of `map` in one pass over the module: a use + /// becomes the end of its chain (`a → b`, `b → c`: a use of `a` becomes `c`), as the same + /// calls one at a time in order would leave it. + pub fn replace_uses(&mut self, map: &HashMap) { + if map.is_empty() { + return; + } let r = |v: &mut Value| { - if *v == old { - *v = new; + while let Some(&n) = map.get(v) { + *v = n; } }; for inst in &mut self.insts { diff --git a/crates/xcl/src/gpu/dxil/tests.rs b/crates/xcl/src/gpu/dxil/tests.rs index 67e6baf0dc..af8d2e960e 100644 --- a/crates/xcl/src/gpu/dxil/tests.rs +++ b/crates/xcl/src/gpu/dxil/tests.rs @@ -177,3 +177,42 @@ fn blocks_are_written_in_reverse_post_order() { let want: Vec = (0..64).map(|l| ((l as u32) << 2) + 7 + sgpr[l]).collect(); assert_eq!(&r.raw[..64], &want[..]); } + +/// `replace_uses` makes a whole map of trivial phis in one pass and leaves the module as +/// `replace_all_uses` one at a time in order does, a chain included (`a → b`, then `b → v`, +/// as the SSA construction makes when `b` turns trivial after `a`). +#[test] +fn batched_replacements_match_one_at_a_time() { + let build = |batched: bool| { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let res = s.raw_uav(1, 0); + let lane = s.thread_id_in_group(0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + let next = s.m.new_block(); + let x = s.raw_load(io, off, 1)[0]; + s.m.br(next); + let entry = s.m.entry_block(); + s.m.set_block(next); + let i32 = s.m.i32(); + let b = s.m.phi(i32); + s.m.add_incoming(b, x, entry); + let a = s.m.phi(i32); + s.m.add_incoming(a, b, entry); + let sum = s.m.bin(BinOp::Add, a, b); + s.raw_store(res, off, &[sum]); + if batched { + s.m.replace_uses(&std::collections::HashMap::from([(a, b), (b, x)])); + } else { + s.m.replace_all_uses(a, b); + s.m.replace_all_uses(b, x); + } + s.finish([64, 1, 1], None) + }; + let c = build(true); + assert_eq!(c, build(false)); + if let Err(e) = validate::validate(&c) { + panic!("validator rejected the kernel:\n{e}"); + } +} diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 7fa53dc01d..3fbe8c659a 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -7,8 +7,11 @@ //! #1426's translator state (`gpu::dxil::lower::Lw`, built by `Lw::new` and finished by //! `Lw::finish`), so its per-entry setup (`setup_lanes_compute`) and its instruction //! lowering are reachable from here. A phi the SSA -//! construction finds trivial has its uses replaced (`Module::replace_all_uses`); the phi itself -//! stays in its block, unused. +//! construction finds trivial has its uses replaced (`Module::replace_uses`); the phi itself +//! stays in its block, unused. The replacements are collected and made in one pass in +//! `DxilIr::finish`: one pass over the module per trivial phi made the lowering quadratic in +//! the program's size, and nothing reads an instruction's operands back before then (the +//! SSA construction resolves a replaced phi itself). use super::lower::{self, Bin, Cmp, Ir}; use super::ssa::{Sink, Var}; @@ -17,7 +20,7 @@ use crate::gpu::dxil::lower::Lw; use crate::gpu::dxil::module::{BinOp, Block, CastOp, Pred, Value}; use crate::gpu::dxil::shader::RawUav; use crate::gpu::rdna2::Decoded; -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; struct DxilIr { lw: Lw, @@ -36,6 +39,8 @@ struct DxilIr { /// lowering takes `lane()` before `compute_ids`, and in the split form the console lane /// is not the hardware lane (the upper half's are 32-63) ids: Option<(Value, [Value; 3])>, + /// trivial phis → what replaces their uses, made in the module by `finish` + replaced: HashMap, } impl DxilIr { @@ -85,7 +90,7 @@ impl DxilIr { }; let io = lw.init.io.expect("the I/O buffer"); let (res, mem) = (lw.res, lw.mems[0]); - DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set, ids } + DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set, ids, replaced: HashMap::new() } } fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { @@ -99,6 +104,8 @@ impl DxilIr { /// the lowering's blocks are sealed for `Lw`'s variables (every edge into them is known once /// the lowering is done), then `Lw::finish`. fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + // the trivial phis' uses first, as `replace` would have left them + self.lw.s.m.replace_uses(&self.replaced); let first = *self.blocks.first().ok_or("no blocks")?; self.lw.s.m.set_block(Block(0)); self.lw.br(first); @@ -127,8 +134,9 @@ impl Sink for DxilIr { self.lw.s.m.add_incoming(phi, value, self.tails[pred]); } fn replace(&mut self, old: Value, new: Value) { - // every use of the trivial phi becomes `new`; the phi stays in its block, unused - self.lw.s.m.replace_all_uses(old, new); + // every use of the trivial phi becomes `new` (in `finish`); the phi stays in its + // block, unused + self.replaced.insert(old, new); } fn undef(&mut self, var: Var) -> Value { let t = self.ty(var); From f2517621f2bc374daa206e24634f29414005e0c8 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:53:40 -0300 Subject: [PATCH 46/51] Recompiler: the per-lane form takes heap memory windows #1693 put memory windows through the descriptor heap in #1426's lowering (XCL_HEAP_WINDOWS), so compute_with no longer refuses them: with several windows the per-lane form's memory instructions go through Lw, which now reads the window from the heap. --- crates/xcl/src/gpu/recomp/lower_dxil.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 3fbe8c659a..8447575743 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -394,9 +394,6 @@ pub fn enabled() -> bool { /// A compute program in its per-lane form with the runtime's options `o` (`pso::direct_compute`): /// the container and its static samplers. pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> Result { - if o.mem_windows & super::HEAP_WINDOWS != 0 { - return Err("heap memory windows".into()); - } let mut insts = Vec::new(); let mut off = 0usize; while off + 4 <= code.len() { @@ -685,15 +682,12 @@ mod tests { /// With the runtime's four memory windows (`compute_with`), the memory instructions go /// through #1426's window switch (blocks of its own in the `Ir` block) and the program - /// still gives the CPU lowering's memory; heap memory windows are refused. + /// still gives the CPU lowering's memory. #[test] fn a_per_lane_program_with_four_memory_windows_runs_on_the_gpu() { let cs = compute_cs(); let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; - let heap = super::KernelOptions { mem_windows: 4 | super::super::HEAP_WINDOWS, ..o }; - let heap = super::compute_with(&bytes, &cs, heap).err().unwrap_or_default(); - assert!(heap.contains("heap"), "{heap}"); if !gpu() { return; } From 4e057cb91ee83aa0873eeccdedf14f163cfeb18a Mon Sep 17 00:00:00 2001 From: Miguel Machado Date: Tue, 24 Nov 2026 16:49:54 -0300 Subject: [PATCH 47/51] Tests: cover split wave64 coalesced runs on the GPU Extend coalesced_foreign_runs_agree_on_the_gpu to also run coalesced_run(true) through compute_with with wave64=true, split=true and 4 memory windows (cut = 40, spanning both wave32 halves) so wave64 coalesced runs are checked on 32-lane hardware too. Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/lower_dxil.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 8447575743..b9da7a7dc8 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -700,22 +700,26 @@ mod tests { /// Coalesced guarded runs lowered through `Ir::foreign` (`Lw::inst_guarded` with `guard = true` /// inside the run's block): f32 arithmetic against HLSL, and 4-window memory load/store inside - /// a coalesced run (`Lw` making window-switch blocks inside the run) against the CPU lowering. + /// a coalesced run (wave32 and split wave64, `Lw` making window-switch blocks inside the run) + /// against the CPU lowering. #[test] fn coalesced_foreign_runs_agree_on_the_gpu() { if !gpu() { return; } - // 4-window compute: lanes with tid < 16 run a coalesced load + add + store via `foreign` + // 4-window compute: lanes below the cut (16 in wave32; 40 in split wave64, spanning both + // wave32 halves) run a coalesced load + add + store via `foreign` let cs = compute_cs(); - let run = coalesced_run(false); - let bytes: Vec = run.iter().flat_map(encode_line).collect(); - let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; - let k = super::compute_with(&bytes, &cs, o).unwrap(); let mem = memory_image(); - let out = runner::dispatch(&k.dxil, [1, 1, 1], &[0, 0], &mem).unwrap(); - let cpu = run_compute(&run, &cs, 1, &[0, 0], &mem); - assert_eq!(&out[..cpu.len()], &cpu[..], "4-window coalesced memory via foreign"); + for (wave64, split) in [(false, false), (true, true)] { + let run = coalesced_run(wave64); + let bytes: Vec = run.iter().flat_map(encode_line).collect(); + let o = super::KernelOptions { wave64, split, mem_windows: 4, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let out = runner::dispatch(&k.dxil, [1, 1, 1], &[0, 0], &mem).unwrap(); + let cpu = run_compute_waves(&run, &cs, wave64, 1, &[0, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..], "4-window coalesced memory via foreign (wave64={wave64}, split={split})"); + } if dxc::location().is_err() { runner::skip_test("no DXC"); From 9e27370765adfcdcc153fc24d2f18e70ee47502b Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:19:51 -0300 Subject: [PATCH 48/51] Tests: the per-lane GPU tests skip on adapters without 32-lane waves On CI the adapter is WARP, which has neither 32- nor 64-lane waves, and every per-lane GPU test failed there in CreateComputePipelineState (0x80070057) instead of skipping. They now require a GPU that runs `[WaveSize(32)]` programs, as `recomp::tests::gpu_ready` does, and skip with "no GPU with 32-lane waves" otherwise. With XCL_ADAPTER=warp the lib runs 876 passed, 0 failed, 22 ignored. --- crates/xcl/src/gpu/recomp/lower.rs | 35 +++++++++++++++---------- crates/xcl/src/gpu/recomp/lower_dxil.rs | 4 +-- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 1cb527afcd..1ea45a732b 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -2131,6 +2131,13 @@ pub(crate) mod tests { } pub(crate) type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + /// A GPU that runs `[WaveSize(32)]` programs, as the per-lane tests need (WARP, the CI + /// adapter, has neither 32 nor 64: skipped, as `recomp::tests::gpu_ready` does). + pub(crate) fn gpu_waves() -> bool { + use super::super::runner; + runner::adapter().is_ok() && runner::wave32_supported() == Ok(true) + } + pub(crate) const V: u64 = 256; pub(crate) const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); @@ -3442,8 +3449,8 @@ pub(crate) mod tests { #[test] fn the_lowering_agrees_with_the_hlsl_path_on_the_gpu() { use super::super::{dxc, runner, translate, Options}; - if runner::adapter().is_err() || dxc::location().is_err() { - runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { @@ -3534,8 +3541,8 @@ pub(crate) mod tests { #[test] fn the_wave64_lowering_agrees_with_the_hlsl_path_on_the_gpu() { use super::super::{dxc, runner, translate, Options}; - if runner::adapter().is_err() || dxc::location().is_err() { - runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } if runner::wave64_supported() != Ok(true) { @@ -3592,8 +3599,8 @@ pub(crate) mod tests { #[test] fn the_split_form_agrees_with_the_wave64_lowering_on_the_gpu() { use super::super::{lower_dxil, runner}; - if runner::adapter().is_err() { - runner::skip_test("no GPU"); + if !gpu_waves() { + runner::skip_test("no GPU with 32-lane waves"); return; } let reads = lane_reads(true); @@ -3736,8 +3743,8 @@ pub(crate) mod tests { #[test] fn a_2d_or_3d_group_agrees_with_the_hlsl_path_on_the_gpu() { use super::super::{dxc, runner, translate, Mode, Options}; - if runner::adapter().is_err() || dxc::location().is_err() { - runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } for wave64 in [false, true] { @@ -3764,8 +3771,8 @@ pub(crate) mod tests { #[test] fn a_compute_program_agrees_with_the_hlsl_path_on_the_gpu() { use super::super::{dxc, runner, translate, Mode, Options}; - if runner::adapter().is_err() || dxc::location().is_err() { - runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); @@ -4010,8 +4017,8 @@ pub(crate) mod tests { #[test] fn cross_lane_reads_agree_with_the_hlsl_path_on_the_gpu() { use super::super::{dxc, runner}; - if runner::adapter().is_err() || dxc::location().is_err() { - runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } agrees_with_hlsl("lane reads, wave32", &lane_reads(false), false, &[]); @@ -4236,8 +4243,8 @@ pub(crate) mod tests { #[test] fn coalesced_guarded_runs_agree_with_the_hlsl_path_on_the_gpu() { use super::super::{dxc, runner, translate, Options}; - if runner::adapter().is_err() || dxc::location().is_err() { - runner::skip_test(if runner::adapter().is_err() { "no GPU" } else { "no DXC" }); + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } agrees_with_hlsl("coalesced breaks, wave32", COALESCED_BREAKS, false, &[]); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index b9da7a7dc8..4fcb0a13e6 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -425,8 +425,8 @@ mod tests { use super::super::{dxc, runner, translate, Mode, Options}; fn gpu() -> bool { - if runner::adapter().is_err() { - runner::skip_test("no GPU"); + if !gpu_waves() { + runner::skip_test("no GPU with 32-lane waves"); return false; } true From 66879efc7d958cd18eaab93cb379492a85583d2b Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:46:28 -0300 Subject: [PATCH 49/51] Recompiler: the per-lane form refuses whole-wave mask decisions and modes it drops Two correctness gaps on programs the per-lane form took, found by Kalmarv's review of #1745 with GPU programs against the HLSL path: - A branch on whether any lane of a mask is set (`s_cbranch_vccz` / `vccnz`, `s_cbranch_scc*` after a mask op or `s_cmp_lg` of a mask) and a scalar read of such an SCC (`s_cselect`, `s_cmov`, `s_addc`, `s_subb`) decide for the whole wave on the console. The analysis took each lane's own bit, which differs in the lanes in EXEC that lack the bit (VCC = lanes 0-15, EXEC = all 32: 7 where the console gives 0). They are now taken only where the condition is the same in every lane that reaches with its EXEC bit (`s_and_saveexec` then `s_cbranch_execz`, or VCC equal to EXEC), and refused otherwise. The analysis test that stated the old assumption (a vccz branch is a lane branch) now states the rule. - `s_setreg` of MODE was a no-op, so a non-default rounding mode was dropped where #1426 and the HLSL path refuse the program. MODE writes now go to #1426's lowering, and the adapter sets `dyn_rm` / `has_f64_round_op` as #1426's translator does, so `s_round_mode` and `s_setreg` refuse what they cannot honour. Denormal-only writes are still taken. Tests: Kalmarv's five branch / select programs are refused, and a uniform one is taken; f32 by `s_setreg` and f64 by `s_round_mode` / `s_setreg` are refused (the f32 one was taken before the fix), and a denormal-only write is taken. --- crates/xcl/src/gpu/recomp/lane_masks.rs | 46 ++++++++++++++++++++++--- crates/xcl/src/gpu/recomp/lower.rs | 35 ++++++++++++++----- crates/xcl/src/gpu/recomp/lower_dxil.rs | 24 +++++++++++++ 3 files changed, 93 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 29d64f725c..51eefc53d5 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -599,6 +599,20 @@ impl<'a> Lanes<'a> { } } + /// Whether `c` is the same in every lane that reaches with its EXEC bit (`reach` and `e`): + /// then a lane deciding by its own bit decides as the whole wave does. Unknown (too large + /// to build) is no. + fn uniform_over(&mut self, reach: B, e: B, c: B) -> bool { + let Some(re) = self.bdd.within(|bdd| bdd.and(reach, e)) else { return false }; + if self.bdd.implies(re, c) { + return true; + } + match self.bdd.within(|bdd| bdd.not(c)) { + Some(nc) => self.bdd.implies(re, nc), + None => false, + } + } + /// The condition under which a lane takes the branch ending a block, and whether it is a /// lane mask's. fn cond(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { @@ -800,6 +814,17 @@ impl<'a> Lanes<'a> { sum.guarded.push(d.pc); } } + // an SCC a mask op set, read by a scalar instruction: the console reads the whole + // wave's, each lane here its own bit, the same only where it is constant over EXEC + let n = d.inst.name; + if ["S_CSELECT", "S_CMOV", "S_ADDC", "S_SUBB"].iter().any(|p| n.starts_with(p)) { + if let Some((c, true)) = st.scc { + let e = st.regs[EXEC].unwrap(); + if !self.uniform_over(reach[b], e, c) { + return Err("a scalar read of the SCC of a mask op, with lanes in EXEC without its bit"); + } + } + } if d.inst.name == if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" } { let s0 = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0); if self.mask_src(&st, d, s0).and_then(|a| self.wqm(a)) == Some(TRUE) { @@ -810,6 +835,13 @@ impl<'a> Lanes<'a> { } let last = &self.insts[end - 1]; if self.succ[b].iter().any(|s| s.1 != Edge::Always) { + let (c, lane) = self.cond_bounded(&st, last, b)?; + // a lane branch is each lane's only where the condition is constant over the lanes + // in EXEC (`s_and_saveexec` then `s_cbranch_execz`); `s_cbranch_vccz` on a mask some + // lanes in EXEC lack takes the whole wave's way on the console (Kalmarv, #1745) + if lane && !self.uniform_over(reach[b], st.regs[EXEC].unwrap(), c) { + return Err("a branch on whether any lane of a mask is set, with lanes in EXEC without its bit"); + } let (_, lane) = self.cond_bounded(&st, last, b)?; if lane { sum.lane_branches += 1; @@ -967,10 +999,16 @@ mod tests { } #[test] - fn a_vccz_branch_is_a_lane_branch() { - // v_cmp; s_cbranch_vccz L; v_mov (lanes with the bit only); L: v_mov - let s = run(&[CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).unwrap(); - assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 0, 1)); + fn a_vccz_branch_is_a_lane_branch_only_where_vcc_is_the_exec() { + // v_cmp; s_cbranch_vccz L: the console skips only when no lane in EXEC has the bit, so + // lanes in EXEC without it run the v_mov too; deciding per lane would skip it: refused + let err = run(&[CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).err(); + assert_eq!(err, Some("a branch on whether any lane of a mask is set, with lanes in EXEC without its bit")); + // v_cmp; s_and_saveexec s0, vcc; s_cbranch_vccz L: VCC ∧ EXEC is the new EXEC, the same + // as each lane's bit for every lane in it: a lane branch + let save: I = ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); + let s = run(&[CMP, save, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 1, 1)); } #[test] diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 1ea45a732b..c8156a91d8 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -715,9 +715,6 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_scc(b, v); } "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" => {} - // MODE (float rounding / denormals): only float instructions read it, and the - // lowering refuses every float instruction so far – revisit when floats come in - "S_SETREG_IMM32_B32" | "S_SETREG_B32" if self.sets_mode_only(d) => {} "S_SETREG_IMM32_B32" | "S_SETREG_B32" => { let s = fv("SIMM16").unwrap_or(0); return Err(format!("unsupported {name} hwreg {} offset {} size {}", s & 0x3F, (s >> 6) & 0x1F, ((s >> 11) & 0x1F) + 1)); @@ -870,11 +867,6 @@ impl<'a, I: Ir> Lower<'a, I> { self.write_v(b, d, vdst as u16, v) } - /// `s_setreg*` writing `HW_REG_MODE` (id 1 of its `SIMM16`) and nothing else. - fn sets_mode_only(&self, d: &Decoded) -> bool { - rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) & 0x3F == 1 - } - /// `s_load_dword{,x2,x4,x8,x16}`: dwords of the flat memory into SGPRs, from /// `s[sbase] + offset + soffset` (one memory window, as `emit::smem` with `mem_windows` 1). fn smem(&mut self, b: usize, d: &Decoded) -> R<()> { @@ -3137,6 +3129,33 @@ pub(crate) mod tests { out } + /// A branch or a scalar select on whether any lane of a mask is set decides for the whole + /// wave on the console: with lanes in EXEC that lack the bit (VCC = lanes 0–15, EXEC = all), + /// each lane deciding by its own bit would differ in lanes 16–31, so the program is refused + /// (Kalmarv's five programs on #1745); where the mask is constant over EXEC it is taken. + #[test] + fn a_whole_wave_decision_on_a_mask_some_lanes_lack_is_refused() { + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]); + const MOV7: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]); + const AND: I = ("S_AND_B32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 106), ("SSRC1", 126)]); + let programs: [(&str, Vec); 5] = [ + ("vccnz", vec![CMP, ("S_CBRANCH_VCCNZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("vccz", vec![CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("and + scc1", vec![CMP, AND, ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("cmp_lg + scc1", vec![CMP, ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 106), ("SSRC1", 128)]), ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("and + cselect", vec![CMP, AND, ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 133), ("SSRC1", 135)]), ENDPGM]), + ]; + for (name, p) in programs { + let err = lower_kernel(&decode(&p), false, Interp::default()).err().unwrap_or_else(|| panic!("{name}: taken")); + assert!(err.contains("any lane of a mask") || err.contains("SCC of a mask op"), "{name}: {err}"); + } + // VCC = EXEC: the same in every lane in EXEC, so each lane decides as the wave does + let uniform: [I; 4] = [("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 126)]), ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]; + let (s, v) = state(32); + let (_, v) = run(&uniform, false, &s, &v); + assert!(v.iter().all(|r| r[1] == 7)); + } + /// A cross-lane scalar op on s0 holding a number takes the number path (the check for the /// upper dword of a mask pair at s must not compute r - 1 for s0: nobodyttk, #1269). #[test] diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 4fcb0a13e6..7107e53854 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -71,6 +71,10 @@ impl DxilIr { } } let mut lw = Lw::new(insts, &leaders, o, entry); + // the rounding modes the program sets, as `kernel::translate_on_this_thread` finds them: + // #1426's `s_round_mode` / `s_setreg` refuse a mode they cannot honour from these + let branchy = insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); + (lw.dyn_rm, lw.has_f64_round_op) = crate::gpu::dxil::lower::round_modes(insts, !branchy); // a kernel's lanes in the split form: the console lane each hardware lane stands for, // set up in the entry block (a compute program's come with `compute_ids`) let mut ids = None; @@ -432,6 +436,26 @@ mod tests { true } + /// A rounding mode #1426's lowering cannot honour refuses the program, as #1426 and the HLSL + /// path do, instead of the per-lane form computing with the default mode (Kalmarv, #1745): + /// f32 toward zero by `s_setreg`, f64 by `s_round_mode` and by `s_setreg`. + #[test] + fn a_rounding_mode_the_lowering_cannot_honour_is_refused() { + let add_f32: I = ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)]); + let add_f64: I = ("V_ADD_F64", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 2)]); + let programs: [(&str, Vec); 3] = [ + ("f32 by s_setreg", vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x801), ("LITERAL", 3)]), add_f32, ENDPGM]), + ("f64 by s_round_mode", vec![("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 0xC)]), add_f64, ENDPGM]), + ("f64 by s_setreg", vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x881), ("LITERAL", 3)]), add_f64, ENDPGM]), + ]; + for (name, p) in programs { + assert!(super::kernel(&decode(&p), false).is_err(), "{name}: taken"); + } + // denormal bits only (MODE[7:4]): the default rounding, taken + let denorm: Vec = vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x1901), ("LITERAL", 0xF)]), add_f32, ENDPGM]; + super::kernel(&decode(&denorm), false).unwrap(); + } + /// An instruction lowered by #1426 that writes to `Lw`'s entry block after the program's /// blocks are written (scratch) gives a container, and runs. #[test] From 9dcf2f6916436aad162069127c8e68586862cc3b Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:03:47 -0300 Subject: [PATCH 50/51] Recompiler: a mask op's SCC carried around a loop stays a lane's thehollowedone's program on #1745: `s_and_b32 s0, vcc, exec` sets SCC in a loop's body and the next iteration's `s_cselect_b32` reads it. The loop head's join counted only the edges whose masks it uses, and back edges do not count there, so the SCC came out a uniform value and the per-lane form selected by each lane's bit: 7 where the console gives 5 in lanes 16-31. The mask-op flag now comes from every incoming edge, back edges included, and an unknown SCC that is a lane's on some edge is an unknown lane condition, so the whole-wave rule refuses it. Test: his program is refused (it was taken before the fix). --- crates/xcl/src/gpu/recomp/lane_masks.rs | 11 ++++++++++- crates/xcl/src/gpu/recomp/lower.rs | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 51eefc53d5..bdb04fb157 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -701,9 +701,13 @@ impl<'a> Lanes<'a> { if edges.is_empty() { return Ok((reach, st)); } + // an SCC a mask op set on any incoming edge, back edges included (their masks may not + // count here, but a lane's own SCC carried around a loop is still a lane's: thehollowedone, + // #1745) + let scc_lane = self.preds[b].iter().any(|&(p, k)| outs[p].get(k).is_some_and(|(f, s)| *f != FALSE && s.scc.is_some_and(|x| x.1))); for slot in 0..=SCC { let get = |s: &State| if slot == SCC { s.scc.map(|x| x.0) } else { s.regs[slot] }; - let lane = edges.iter().any(|(_, s)| s.scc.is_some_and(|x| x.1)); + let lane = scc_lane; let v = if forced.contains(&(b, slot)) { Some(self.atom(Atom::Join(b, slot), b)?) } else if edges.iter().any(|(_, s)| get(s).is_none()) { @@ -721,6 +725,11 @@ impl<'a> Lanes<'a> { }) }; if slot == SCC { + // unknown but a lane's on some edge: an unknown lane condition, not a uniform one + let v = match v { + None if lane => Some(self.atom(Atom::Join(b, SCC), b)?), + v => v, + }; st.scc = v.map(|v| (v, lane)); } else { st.regs[slot] = v; diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index c8156a91d8..1b5942dea4 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -3149,6 +3149,23 @@ pub(crate) mod tests { let err = lower_kernel(&decode(&p), false, Interp::default()).err().unwrap_or_else(|| panic!("{name}: taken")); assert!(err.contains("any lane of a mask") || err.contains("SCC of a mask op"), "{name}: {err}"); } + // the mask op's SCC reaching the `s_cselect` only around the loop's back edge + // (thehollowedone's program on #1745: 7 where the console gives 5 in lanes 16–31) + let around: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 130)]), + CMP, + ("S_CMP_GT_U32", "ENC_SOPC", &[("SSRC0", 129), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 133), ("SSRC1", 135)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)]), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 128)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 2)]), + AND, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFF9)]), + ENDPGM, + ]; + let err = lower_kernel(&decode(&around), false, Interp::default()).err().expect("around the loop: taken"); + assert!(err.contains("SCC of a mask op") || err.contains("any lane of a mask"), "around the loop: {err}"); // VCC = EXEC: the same in every lane in EXEC, so each lane decides as the wave does let uniform: [I; 4] = [("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 126)]), ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]; let (s, v) = state(32); From bfb8133d36df38c3de381f9d99203568b32aa765 Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:03:47 -0300 Subject: [PATCH 51/51] Recompiler: per-lane cache entries change when the per-lane sources do Pipodi's review of #1745: the translated-cache identity of `XCL_PER_LANE` entries did not include the per-lane form's sources, so a cached container outlived a change to the lowering. build.rs hashes them into XCL_PER_LANE_SOURCE_ID, which only the per-lane entries' identity includes (the HLSL path's entries keep theirs). --- crates/xcl/build.rs | 19 +++++++++++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index caf2ef4c7e..64a6b08bd3 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -20,6 +20,16 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/xbox.rs", ]; +/// The per-lane form's sources (`XCL_PER_LANE`): part of only its own cache entries' identity, +/// so editing them does not invalidate the HLSL path's. +const PER_LANE_SOURCES: &[&str] = &[ + "src/gpu/recomp/lane_masks.rs", + "src/gpu/recomp/lower.rs", + "src/gpu/recomp/lower/wave.rs", + "src/gpu/recomp/lower_dxil.rs", + "src/gpu/recomp/ssa.rs", +]; + fn add(h: &mut u64, bytes: &[u8]) { for &byte in bytes { *h ^= byte as u64; @@ -48,4 +58,13 @@ fn main() { add(&mut h, &[0]); } println!("cargo:rustc-env=XCL_TRANSLATOR_SOURCE_ID={h:016x}"); + let mut p = 0xcbf2_9ce4_8422_2325u64; + for relative in PER_LANE_SOURCES { + println!("cargo:rerun-if-changed={relative}"); + add(&mut p, relative.as_bytes()); + add(&mut p, &[0]); + add(&mut p, &std::fs::read(root.join(relative)).expect("read per-lane source")); + add(&mut p, &[0]); + } + println!("cargo:rustc-env=XCL_PER_LANE_SOURCE_ID={p:016x}"); } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index cca24d7c89..5360dde638 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -243,7 +243,7 @@ mod translated { ); // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { - identity_for(&id.to_string(), "xcl-per-lane") + identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) } else { id }