From 28fbf06e62b404b2b286aeb6c35a2826e47828f1 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:52:02 -0500 Subject: [PATCH 1/7] Recompiler: split large direct compute pipelines at CFG edges Keep control-flow cycles in one pipeline, pass edge-live values through per-dispatch scratch and compile the pieces on the PSO workers. Direct dispatch records the chain with UAV ordering. Indirect dispatch builds the whole form on demand. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + crates/xcl/src/gpu/dxil/kernel.rs | 25 +- crates/xcl/src/gpu/dxil/module.rs | 3 + crates/xcl/src/gpu/dxil/module/opt.rs | 2 +- crates/xcl/src/gpu/dxil/module/split.rs | 595 ++++++++++++++++++ crates/xcl/src/gpu/dxil/shader.rs | 18 + crates/xcl/src/gpu/recomp/pso.rs | 100 ++- crates/xcl/src/gpu/recomp/runner.rs | 35 +- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 4 +- crates/xcl/src/hle/d3d12x/bind.rs | 14 +- crates/xcl/src/hle/d3d12x/console_list.rs | 2 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 51 +- crates/xcl/src/hle/d3d12x/real.rs | 97 +-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 148 +++++ crates/xcl/src/host.rs | 4 + crates/xcl/src/shaders.rs | 2 +- 16 files changed, 1032 insertions(+), 71 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/module/split.rs create mode 100644 crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs diff --git a/README.md b/README.md index 0075066ea..570466dd9 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - **The game folder is never modified** – writes go to the overlay. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. +- Direct compute dispatches can split large programs into pipelines built in parallel. + `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, + zero disables splitting). Loops stay in one piece. Indirect dispatches use the whole pipeline. - Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 94ce0b37d..9a1819449 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -65,6 +65,13 @@ pub fn translate(code: &[u8], o: KernelOptions) -> Result, String> { pub struct Kernel { pub dxil: Vec, pub static_samplers: Vec<([u32; 4], bool)>, + pub dispatch_chain: Option>, +} + +pub use super::module::split::DispatchChain; + +pub fn dispatch_piece_limit() -> usize { + std::env::var("XCL_DIRECT_SPLIT_INSTRUCTIONS").ok().and_then(|s| s.parse().ok()).unwrap_or(12_500) } /// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset leaves it to `compact::wanted`. @@ -173,6 +180,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); + let mut split_tid = None; let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -185,6 +193,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); + if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } compute_init(&mut lw, cs, tid, gtid); cs.threads } @@ -390,7 +399,8 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact lw.s.m.set_block(Block(0)); lw.s.m.br(h0); let hw = if split || !o.wave64 { 32 } else { 64 }; - lw.finish(numthreads, hw) + let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; + lw.finish_dispatch(numthreads, hw, limit, split_tid) } /// True when a pixel shader uses RDNA2 Primitive Ordered Pixel Shading (POPS): @@ -554,15 +564,24 @@ impl Lw { /// 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 { + pub fn finish(self, numthreads: [u32; 3], hw: u32) -> Result { + self.finish_dispatch(numthreads, hw, 0, None) + } + + fn finish_dispatch(mut self, numthreads: [u32; 3], hw: u32, limit: usize, split_tid: Option) -> Result { if let Some(e) = self.exchange_error.take() { return Err(e); } let stage = self.s.stage; + let mut dispatch_chain = None; 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 if limit > 0 && (numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32 { + self.s.m.optimize(); + dispatch_chain = self.s.split_compute(numthreads, split_tid, limit).map(std::sync::Arc::new); + self.s.finish_optimized(numthreads, Some(hw)) } else { self.s.try_finish(numthreads, Some(hw)) } @@ -573,7 +592,7 @@ impl Lw { 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: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect(), dispatch_chain }) } } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index f2930cd7e..cc85589f5 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; use super::bitstream::{signed, BitWriter}; mod opt; +pub(super) mod split; // ---------------------------------------------------------------- types @@ -59,6 +60,7 @@ enum ConstDef { Aggregate(Ty, Vec), } +#[derive(Clone)] struct FuncDecl { name: String, ty: Ty, @@ -93,6 +95,7 @@ impl FnAttrs { } } +#[derive(Clone)] struct GlobalDef { name: String, /// Value type (the global itself is a pointer to it). diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index c9b4f1a6d..94a6ebe1b 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -41,7 +41,7 @@ impl Op { } /// Rewrites every value operand through `f`. - fn map_operands(&mut self, mut f: impl FnMut(Value) -> Value) { + pub(super) fn map_operands(&mut self, mut f: impl FnMut(Value) -> Value) { match self { Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::Store(a, b, _) | Op::AtomicRmw(_, a, b) => { *a = f(*a); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs new file mode 100644 index 000000000..52642859c --- /dev/null +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -0,0 +1,595 @@ +//! Partition the optimized compute entry at CFG edges. A dispatch cannot +//! jump back to an earlier dispatch, so a strongly connected component is +//! indivisible. Each crossing edge has its own compact state layout. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use super::{BinOp, Block, CastOp, Module, Op, TypeDef, Value}; +use crate::gpu::dxil::shader::{Feature, RawUav, Shader}; + +#[derive(Debug)] +pub(crate) struct Edge { + pub from: Block, + pub to: Block, + pub live: Vec, +} + +pub(crate) struct Plan { + pub blocks: Vec>, + pub edges: Vec, +} + +#[derive(Clone)] +pub struct DispatchChain { + pub pieces: Vec>, + pub dwords_per_group: u32, +} + +struct Scratch { + uav: RawUav, + base: Value, +} + +impl Scratch { + fn new(s: &mut Shader, stride: u32, threads: u32, lane: Value) -> Self { + let uav = s.raw_uav(0, 2); + let cb = s.cbv(0, 2, 16); + let zero = s.m.i32c(0); + let ty = s.m.i32(); + let [width, height, _, _] = s.cbuffer_load_legacy(cb, zero, ty); + let [x, y, z] = [0, 1, 2].map(|axis| s.group_id(axis)); + let row = s.m.bin(BinOp::Mul, z, height); + let row = s.m.bin(BinOp::Add, row, y); + let first = s.m.bin(BinOp::Mul, row, width); + let group = s.m.bin(BinOp::Add, first, x); + let n = s.m.i32c(threads); + let first = s.m.bin(BinOp::Mul, group, n); + let index = s.m.bin(BinOp::Add, first, lane); + let bytes = s.m.i32c(stride * 4); + Self { uav, base: s.m.bin(BinOp::Mul, index, bytes) } + } + + fn at(&self, m: &mut Module, slot: u32) -> Value { + let offset = m.i32c(slot * 4); + m.bin(BinOp::Add, self.base, offset) + } +} + +impl Shader { + /// Start with full native wave32 groups. A fresh dispatch can assign a + /// different physical wave to a group; wave-lane index identifies the + /// continuation within a full, single-wave group. + pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { + if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { + return None; + } + if self.m.blocks.iter().map(Vec::len).sum::() <= limit { return None; } + let mut prefix = Vec::new(); + if let Some(tid) = split_tid { + let end = self.m.blocks[0].iter().position(|&i| Value::Inst(i) == tid)?; + prefix.extend_from_slice(&self.m.blocks[0][..=end]); + } + let mut consumed = HashSet::new(); + for &i in self.m.blocks.iter().flatten() { + self.m.insts[i as usize].op.for_each_operand(|v| { consumed.insert(v); }); + } + for (b, block) in self.m.blocks.iter().enumerate() { + // In a single split console wave each inter-half exchange begins + // with TGSM stores, one rendezvous, peer loads and a rendezvous. + // A block ending anywhere inside that sequence cannot be a cut. + let mut exchange = 0; + for &i in block { + if b == 0 && prefix.contains(&i) { continue; } + match &self.m.insts[i as usize].op { + Op::Alloca(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => return None, + Op::Store(..) if split_tid.is_some() && exchange <= 1 => exchange = 1, + Op::Load(p, _) if self.m.global_root(*p).is_some_and(|g| self.m.globals[g].constant) => {} + Op::Load(..) if split_tid.is_some() && matches!(exchange, 2 | 3) => exchange = 3, + Op::Load(..) | Op::Store(..) => return None, + Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.barrier" + && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64) => { + exchange = match exchange { 1 => 2, 3 => 0, _ => return None }; + } + // Sub-dword stores use interlocked AND/OR. They return an + // old word that nobody observes; every write stays in place. + Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.atomicBinOp.i32" + && matches!(self.m.const_u64(args[2]), Some(1 | 2)) + && !consumed.contains(&Value::Inst(i)) => {} + Op::Call(f, _) if ["dx.op.barrier", "dx.op.atomic"].iter().any(|p| self.m.funcs[*f as usize].name.starts_with(p)) => return None, + _ => {} + } + } + if exchange != 0 { return None; } + } + let plan = self.m.dispatch_plan(limit)?; + let mut stride = 1; + for edge in &plan.edges { + let mut words = 1; + for &v in &edge.live { + words += self.m.transport_words(v)?; + } + stride = stride.max(words); + } + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix)).collect::>>()?; + Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) + } + + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, threads: [u32; 3], prefix: &[u32]) -> Option> { + let src = &self.m; + let mut dst = self.dispatch_piece(); + let mut values = HashMap::new(); + for &id in prefix { + let def = &src.insts[id as usize]; + let mut op = def.op.clone(); + op.map_operands(|v| *values.get(&v).unwrap_or(&v)); + values.insert(Value::Inst(id), dst.m.push(op, def.ty)); + } + let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); + let scratch = Scratch::new(&mut dst, stride, threads[0], lane); + let local: HashMap<_, _> = plan.blocks[stage].iter().map(|&b| (b, dst.m.new_block())).collect(); + let mut hops = HashMap::new(); + let mut exits = HashMap::new(); + let mut cases = Vec::new(); + let mut paths = Vec::new(); + let mut incoming = std::collections::BTreeMap::, Block)>>::new(); + let mut statics = BTreeSet::new(); + let merge = dst.m.new_block(); + let done = dst.m.new_block(); + let selector = if stage != 0 { Some(dst.raw_load(scratch.uav, scratch.base, 1)[0]) } else { None }; + for (index, edge) in plan.edges.iter().enumerate() { + let tag = dst.m.i32c(index as u32 + 1); + if local.contains_key(&edge.from) { + exits.insert((edge.from, edge.to), (dst.m.new_block(), tag)); + } + if let Some(&target) = local.get(&edge.to) { + let bridge = dst.m.new_block(); + dst.m.set_block(bridge); + let mut slot = 1; + for &v in &edge.live { + let n = src.transport_words(v)?; + if n == 0 { + statics.insert(v); + continue; + } + let at = scratch.at(&mut dst.m, slot); + let words = dst.raw_load(scratch.uav, at, if n == 2 { 3 } else { 1 }); + incoming.entry(v).or_default().push((words, bridge)); + slot += n; + } + dst.m.br(merge); + let hop = dst.m.new_block(); + dst.m.set_block(hop); + dst.m.br(target); + cases.push((tag, bridge)); + paths.push((bridge, tag, hop)); + hops.insert((edge.from, edge.to), hop); + } + } + dst.m.set_block(Block(0)); + if let Some(sel) = selector { + dst.m.switch(sel, done, &cases); + dst.m.set_block(merge); + let word = dst.m.i32(); + let mut unpack = Vec::new(); + for (original, inc) in incoming { + let mut words = Vec::new(); + for k in 0..inc[0].0.len() { + let phi = dst.m.phi(word); + for &(pred, _, _) in &paths { + let v = inc.iter().find(|p| p.1 == pred).map(|p| p.0[k]).unwrap_or_else(|| dst.m.undef(word)); + dst.m.add_incoming(phi, v, pred); + } + words.push(phi); + } + unpack.push((original, words)); + } + for (original, words) in unpack { + values.insert(original, src.unpack(original, &words, &mut dst.m)); + } + for handle in statics { + src.rebuild_static(handle, &mut dst.m, &mut values)?; + } + let routes: Vec<_> = paths.iter().map(|&(_, tag, hop)| (tag, hop)).collect(); + dst.m.switch(sel, done, &routes); + } else { + dst.m.br(local[&Block(0)]); + } + dst.m.set_block(done); + dst.m.ret(); + + // Assign all instruction identities before fixing operands. A loop's + // phi can use an instruction in a block copied later. + let mut copied = Vec::new(); + for &block in &plan.blocks[stage] { + dst.m.set_block(local[&block]); + for &i in &src.blocks[block.0 as usize] { + if block == Block(0) && prefix.contains(&i) { continue; } + let old = &src.insts[i as usize]; + if matches!(old.op, Op::Ret) && stage + 1 < plan.blocks.len() { + let zero = dst.m.i32c(0); + dst.raw_store(scratch.uav, scratch.base, &[zero]); + } + let v = dst.m.push(old.op.clone(), old.ty); + values.insert(Value::Inst(i), v); + copied.push((block, inst(v)?)); + } + } + for (block, id) in copied { + let op = &mut dst.m.insts[id].op; + let mut complete = true; + op.map_operands(|v| match v { + Value::Inst(_) => values.get(&v).copied().unwrap_or_else(|| { complete = false; v }), + _ => v, + }); + if !complete { return None; } + let target = |b: Block| local.get(&b).copied().or_else(|| exits.get(&(block, b)).map(|p| p.0)); + match op { + Op::Phi(inc) => for (_, p) in inc { + *p = *local.get(p).or_else(|| hops.get(&(*p, block)))?; + }, + Op::Br(b) => *b = target(*b)?, + Op::CondBr(_, t, f) => { *t = target(*t)?; *f = target(*f)?; } + Op::Switch(_, d, cases) => { + *d = target(*d)?; + for (_, t) in cases { *t = target(*t)?; } + } + _ => {} + } + } + for edge in &plan.edges { + let Some(&(b, tag)) = exits.get(&(edge.from, edge.to)) else { continue }; + dst.m.set_block(b); + let mut slot = 1; + for &v in &edge.live { + let n = src.transport_words(v)?; + if n != 0 { + let words = src.pack(v, *values.get(&v)?, &mut dst.m); + let at = scratch.at(&mut dst.m, slot); + dst.raw_store(scratch.uav, at, &words); + slot += n; + } + } + dst.raw_store(scratch.uav, scratch.base, &[tag]); + dst.m.ret(); + } + dst.infer_piece_features(); + let blob = dst.try_finish(threads, Some(32)).ok()?; + crate::gpu::dxil::validate::validate(&blob).ok()?; + Some(blob) + } + + fn infer_piece_features(&mut self) { + for f in [Feature::Doubles, Feature::Int64Ops, Feature::DoubleExtensions, + Feature::ResourceHeapIndexing, Feature::SamplerHeapIndexing] { + self.features.remove(&f); + } + for def in &self.m.insts { + if let Op::Call(f, args) = &def.op { + if self.m.funcs[*f as usize].name == "dx.op.createHandleFromHeap" { + self.features.insert(if self.m.const_u64(args[2]) == Some(0) { + Feature::ResourceHeapIndexing + } else { Feature::SamplerHeapIndexing }); + } + } + } + } +} + +fn inst(v: Value) -> Option { + if let Value::Inst(i) = v { Some(i as usize) } else { None } +} + +impl Module { + fn global_root(&self, v: Value) -> Option { + match v { + Value::Global(g) => Some(g as usize), + Value::Inst(i) => match &self.insts[i as usize].op { + Op::Gep(p, _) => self.global_root(*p), + _ => None, + }, + _ => None, + } + } + + /// Only an index is transported. Resource handles and TGSM pointers are + /// created inside the receiving dispatch, using their original properties. + fn indexed(&self, v: Value) -> Option { + let op = &self.insts[inst(v)?].op; + if let Op::Gep(Value::Global(g), indices) = op { + if self.globals[*g as usize].name == "xcl_xs" && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { + return Some(indices[1]); + } + } + if let Op::Call(f, a) = op { + if self.funcs[*f as usize].name == "dx.op.annotateHandle" && matches!(a[2], Value::Const(_)) { + if let Op::Call(create, args) = &self.insts[inst(a[1])?].op { + if self.funcs[*create as usize].name == "dx.op.createHandleFromHeap" && args[2..].iter().all(|v| matches!(v, Value::Const(_))) { + return Some(args[1]); + } + } + } + } + None + } + + fn transport_words(&self, v: Value) -> Option { + let def = &self.insts[inst(v)?]; + match &self.types[def.ty.0 as usize] { + TypeDef::Int(1..=32) | TypeDef::Float => Some(1), + TypeDef::Int(64) => Some(2), + TypeDef::Struct(..) if self.static_handle(v) => Some(0), + _ if self.indexed(v).is_some() => Some(1), + _ => None, + } + } + + fn static_handle(&self, v: Value) -> bool { + let Value::Inst(i) = v else { return true }; + let Op::Call(f, args) = &self.insts[i as usize].op else { return false }; + match self.funcs[*f as usize].name.as_str() { + "dx.op.createHandleFromBinding" => args.iter().all(|v| matches!(v, Value::Const(_))), + "dx.op.annotateHandle" => args.iter().all(|&v| self.static_handle(v)), + _ => false, + } + } + + fn rebuild_static(&self, v: Value, dst: &mut Module, map: &mut HashMap) -> Option { + let Value::Inst(id) = v else { return Some(v) }; + if let Some(&old) = map.get(&v) { return Some(old); } + let Op::Call(f, args) = &self.insts[id as usize].op else { return None }; + let args: Vec<_> = args.iter().map(|&a| self.rebuild_static(a, dst, map)).collect::>()?; + let new = dst.call(*f, &args); + map.insert(v, new); + Some(new) + } + + fn pack(&self, original: Value, v: Value, dst: &mut Module) -> Vec { + if let Some(index) = dst.indexed(v) { return vec![index]; } + let ty = self.insts[inst(original).unwrap()].ty; + let word = dst.i32(); + match self.types[ty.0 as usize] { + TypeDef::Int(32) => vec![v], + TypeDef::Int(64) => { + let shift = dst.const_int(ty, 32); + let high = dst.bin(BinOp::LShr, v, shift); + vec![dst.cast(CastOp::Trunc, v, word), dst.cast(CastOp::Trunc, high, word)] + } + TypeDef::Float => vec![dst.bitcast(v, word)], + _ => vec![dst.cast(CastOp::ZExt, v, word)], + } + } + + fn unpack(&self, original: Value, words: &[Value], dst: &mut Module) -> Value { + if self.indexed(original).is_some() { + match &self.insts[inst(original).unwrap()].op { + Op::Gep(base, indices) => return dst.gep(*base, &[indices[0], words[0]]), + Op::Call(f, annotate) => { + let Op::Call(create, args) = &self.insts[inst(annotate[1]).unwrap()].op else { unreachable!() }; + let handle = dst.call(*create, &[args[0], words[0], args[2], args[3]]); + return dst.call(*f, &[annotate[0], handle, annotate[2]]); + } + _ => unreachable!(), + } + } + let ty = self.insts[inst(original).unwrap()].ty; + match self.types[ty.0 as usize] { + TypeDef::Int(32) => words[0], + TypeDef::Int(64) => { + let low = dst.cast(CastOp::ZExt, words[0], ty); + let high = dst.cast(CastOp::ZExt, words[1], ty); + let shift = dst.const_int(ty, 32); + let shifted = dst.bin(BinOp::Shl, high, shift); + dst.bin(BinOp::Or, low, shifted) + } + TypeDef::Float => dst.bitcast(words[0], ty), + _ => dst.cast(CastOp::Trunc, words[0], ty), + } + } +} + +impl Module { + /// Preserve symbol and type indices when copying instructions into a + /// piece. The destination has its own blocks, instructions and metadata. + pub(in crate::gpu::dxil) fn declarations(&self) -> Self { + Self { + types: self.types.clone(), + type_ids: self.type_ids.clone(), + consts: self.consts.clone(), + const_ids: self.const_ids.clone(), + funcs: self.funcs.clone(), + func_ids: self.func_ids.clone(), + globals: self.globals.clone(), + ..Self::new() + } + } + + pub(crate) fn dispatch_plan(&self, limit: usize) -> Option { + let (order, _) = self.block_layout(); + let count = |b: usize| self.blocks[b].len(); + if limit == 0 || order.iter().copied().map(count).sum::() <= limit { + return None; + } + let mut predecessors = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + for target in self.successors(b) { + predecessors[target.0 as usize].push(b); + } + } + + // In reverse postorder of the original graph, flooding the transpose + // visits one component at a time in topological order (Kosaraju). + let mut visited = vec![false; self.blocks.len()]; + let mut blocks = vec![Vec::new()]; + let mut stages = vec![usize::MAX; self.blocks.len()]; + let mut used = 0; + for &root in &order { + if visited[root] { + continue; + } + let mut component = Vec::new(); + let mut cost = 0; + let mut stack = vec![root]; + visited[root] = true; + while let Some(b) = stack.pop() { + cost += count(b); + component.push(b); + for &p in &predecessors[b] { + if !visited[p] { + visited[p] = true; + stack.push(p); + } + } + } + if cost > limit { + return None; + } + if used + cost > limit { + blocks.push(Vec::new()); + used = 0; + } + used += cost; + for b in component { + stages[b] = blocks.len() - 1; + } + } + + let mut crossing = BTreeSet::new(); + for &b in &order { + let from = Block(b as u32); + blocks[stages[b]].push(from); + for to in self.successors(b) { + if stages[b] != stages[to.0 as usize] { + debug_assert!(stages[b] < stages[to.0 as usize]); + crossing.insert((from, to)); + } + } + } + let mut live_in = vec![HashSet::new(); self.blocks.len()]; + let mut phi_input = HashMap::<_, BTreeSet<_>>::new(); + let mut work = Vec::new(); + for &b in &order { + for &inst in &self.blocks[b] { + let op = &self.insts[inst as usize].op; + // A phi reads each operand on its incoming edge, including + // when the definition is its predecessor's last instruction. + if let Op::Phi(inputs) = op { + for &(value, pred) in inputs { + if let Value::Inst(i) = value { + let edge = (pred, Block(b as u32)); + if crossing.contains(&edge) { + phi_input.entry(edge).or_default().insert(value); + } + if self.def_block[i as usize] != pred { + work.push((pred.0 as usize, i)); + } + } + } + } else { + op.for_each_operand(|v| { + if let Value::Inst(i) = v { + if self.def_block[i as usize].0 as usize != b { + work.push((b, i)); + } + } + }); + } + } + } + while let Some((b, value)) = work.pop() { + if live_in[b].insert(value) { + for &p in &predecessors[b] { + if self.def_block[value as usize].0 as usize != p { + work.push((p, value)); + } + } + } + } + let edges = crossing.into_iter().map(|(from, to)| { + let mut live = phi_input.remove(&(from, to)).unwrap_or_default(); + live.extend(live_in[to.0 as usize].iter().copied().map(Value::Inst)); + Edge { from, to, live: live.into_iter().collect() } + }).collect(); + Some(Plan { blocks, edges }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::{ + dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::Pred}, + recomp::{runner, CsInterface}, + }; + + fn compare(threads: u32) { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [threads, 1, 1]; + let split = threads == 64; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.s.raw_uav(2, 0); + let group = lw.s.group_id(0); + let count = lw.c(threads); + let base = lw.mul(group, count); + let index = lw.add(base, tid); + let offset = lw.shlc(index, 2); + let original = lw.s.raw_load(mem, offset, 1)[0]; + let trips = lw.andc(tid, 3); + let trips = lw.addc(trips, 1); + let mut value = original; + let i32 = lw.s.m.i32(); + let zero = lw.c(0); + + // Each loop both consumes the previous loop's result and reuses + // the original per-lane input. All lanes eventually reconverge. + for round in 1..=16 { + let pred = lw.cur(); + let body = lw.s.m.new_block(); + let exit = lw.s.m.new_block(); + lw.s.m.br(body); + lw.s.m.set_block(body); + let counter = lw.s.m.phi(i32); + let acc = lw.s.m.phi(i32); + lw.s.m.add_incoming(counter, zero, pred); + lw.s.m.add_incoming(acc, value, pred); + let next = lw.addc(counter, 1); + value = lw.add(acc, original); + value = lw.addc(value, round); + lw.s.m.add_incoming(counter, next, body); + lw.s.m.add_incoming(acc, value, body); + let again = lw.cmp(Pred::ULt, next, trips); + lw.s.m.cond_br(again, body, exit); + lw.s.m.set_block(exit); + if split && round == 8 { + let other_half = lw.exchange(lw.half); + value = lw.add(value, other_half); + } + } + lw.s.raw_store(mem, offset, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 40).expect("split the synthetic program"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + let initial: Vec<_> = (1..=threads * 3).collect(); + let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { + let n = (i as u32 % 4) + 1; + v + n * (16 * v + 136) + u32::from(split && i as u32 % threads < 32) + }).collect(); + let reference = runner::dispatch(&whole, [3, 1, 1], &[], &initial).unwrap(); + assert_eq!(reference, expected); + let result = runner::dispatch_split(&chain, [3, 1, 1], &initial).unwrap(); + assert_eq!(result, reference); + } + + #[test] + fn dispatch_chain_wave32_live_loops() { compare(32); } + + #[test] + fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64); } +} diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index 35f36c319..c1a35ff0f 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -155,6 +155,20 @@ pub struct RawUav { } impl Shader { + pub(super) fn dispatch_piece(&self) -> Self { + Self { + m: self.m.declarations(), + stage: self.stage, + sm: self.sm, + entry: self.entry, + features: self.features.clone(), + bindings: self.bindings.clone(), + handle_ty: self.handle_ty, + props_ty: self.props_ty, + rov: self.rov, + } + } + pub fn new(stage: Stage, sm: (u32, u32)) -> Shader { let mut m = Module::new(); let entry = m.define_entry("main"); @@ -514,6 +528,10 @@ impl Shader { self.m.ret(); } self.m.optimize(); + self.finish_optimized(numthreads, wave_size) + } + + pub(super) fn finish_optimized(mut self, numthreads: [u32; 3], wave_size: Option) -> Result, String> { self.infer_type_features(); let flags: u64 = self.features.iter().map(|f| f.metadata_bit()).fold(0, |a, b| a | b); let sfi0: u64 = self.features.iter().map(|f| f.container_bit()).fold(0, |a, b| a | b); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b6dd120ff..cf9292a6f 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -121,6 +121,7 @@ pub type StaticSampler = ([u32; 4], bool); /// A console shader as PC DXIL and the static samplers it needs in its root signature. #[derive(Clone)] pub struct Compiled { + pub dispatch_chain: Option>, pub dxil: Vec, pub samplers: Vec, } @@ -256,6 +257,9 @@ mod translated { Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), _ => id, }; + let id = if Backend::current() != Backend::Hlsl { + identity_for(&id.to_string(), &format!("dispatch-split-{}", crate::gpu::dxil::kernel::dispatch_piece_limit())) + } else { id }; // `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(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) @@ -303,7 +307,26 @@ mod translated { samplers.push((s, cmp != 0)); } let len = u32_(&mut r)? as usize; - (r.len() == len && len > 0).then(|| Compiled { dxil: r.to_vec(), samplers }) + if len == 0 { return None; } + let (whole, mut rest) = r.split_at_checked(len)?; + let dispatch_chain = if rest.is_empty() { + None + } else { + let dwords_per_group = u32_(&mut rest)?; + let count = u32_(&mut rest)?; + if dwords_per_group == 0 || count < 2 || count as usize > rest.len() / 4 { return None; } + let mut pieces = Vec::new(); + for _ in 0..count { + let len = u32_(&mut rest)? as usize; + if len == 0 { return None; } + let (piece, next) = rest.split_at_checked(len)?; + pieces.push(piece.to_vec()); + rest = next; + } + if !rest.is_empty() { return None; } + Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) + }; + Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -315,6 +338,14 @@ mod translated { } b.extend_from_slice(&(c.dxil.len() as u32).to_le_bytes()); b.extend_from_slice(&c.dxil); + if let Some(chain) = &c.dispatch_chain { + b.extend_from_slice(&chain.dwords_per_group.to_le_bytes()); + b.extend_from_slice(&(chain.pieces.len() as u32).to_le_bytes()); + for piece in &chain.pieces { + b.extend_from_slice(&(piece.len() as u32).to_le_bytes()); + b.extend_from_slice(piece); + } + } let Some(dir) = path.parent() else { return }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); // written whole, then renamed: a reader never sees half a file @@ -423,7 +454,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok(Compiled { dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -510,6 +541,7 @@ impl ShaderEntry { self.blob.len() + self.key.cache_dir.capacity() + self.shader.dxil.capacity() + + self.shader.dispatch_chain.as_ref().map_or(0, |chain| chain.pieces.iter().map(Vec::capacity).sum()) + self.shader.samplers.capacity() * std::mem::size_of::() } } @@ -726,7 +758,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo 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 }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -736,7 +768,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } 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 }) + Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -771,7 +803,7 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - _ => return Err("the shader stage does not match its slot in the PSO".into()), }; dump_direct(blob, &k.dxil); - Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) } pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { @@ -846,7 +878,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dxil: cs, samplers: t.static_samplers }, record, ps) + finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) } fn compile_console_mesh( @@ -872,7 +904,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); } Err(e) => direct_fallback("MS", &e), } @@ -883,7 +915,7 @@ fn compile_console_mesh( return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) } fn console_mesh_with( @@ -1044,10 +1076,38 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA /// The ABI root signature with the pipeline's static samplers (registers 0.., space 1). pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result { + abi_signature(dev, graphics, samplers, false) +} + +/// Record all piece dispatches after the six common root views have been bound. +pub(crate) unsafe fn record_dispatch_chain<'a>( + list: &ID3D12GraphicsCommandList, grid: [u32; 3], scratch: &ID3D12Resource, + pieces: impl IntoIterator, +) { + let [x, y, z] = grid; + list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); + for (i, piece) in pieces.into_iter().enumerate() { + if i != 0 { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + } + let constants = [x, y, z, i as u32]; + list.SetComputeRoot32BitConstants(7, 4, constants.as_ptr().cast(), 0); + list.SetPipelineState(piece); + list.Dispatch(x, y, z); + } + +} + +pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result { + abi_signature(dev, false, samplers, true) +} + +fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { // u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding) - let params: Vec = (0..6) + let mut params: Vec = (0..6) .map(|i| D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -1056,6 +1116,22 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }) .collect(); + if split { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, RegisterSpace: 2, Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 4, + } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } let mut flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; if graphics { flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; @@ -1118,7 +1194,7 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dxil: vec![1, 2, 3, 4, 5], samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let c = Compiled { dispatch_chain: None, dxil: vec![1, 2, 3, 4, 5], samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone())); @@ -1242,6 +1318,7 @@ mod shader_cache_tests { fn compiled(marker: u8) -> Compiled { Compiled { + dispatch_chain: None, dxil: vec![marker; 16], samplers: vec![([marker as u32; 4], false)], } @@ -1317,6 +1394,7 @@ mod shader_cache_tests { cached_shader(&cache, key(1), b"a", || { let dxil = dxc::compile_cached_in(&dir, "probe", "main", "cs_6_6")?.0; Ok(Compiled { + dispatch_chain: None, dxil, samplers: Vec::new(), }) @@ -1350,6 +1428,7 @@ mod shader_cache_tests { key(4), b"d", Arc::new(Compiled { + dispatch_chain: None, dxil: vec![0; limit + 1], samplers: Vec::new(), }), @@ -1524,6 +1603,7 @@ mod shader_cache_tests { let dxil = dxc::compile_cached_in(&dir, "pending probe", "main", "cs_6_6")?.0; Ok(Compiled { + dispatch_chain: None, dxil, samplers: Vec::new(), }) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ed683350f..a8b13fcf4 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1613,7 +1613,25 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false, None).map(|(m, _)| m) +} + +#[cfg(test)] +pub(crate) fn dispatch_split( + chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], mem: &[u32], +) -> Result, String> { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; + let rs = super::pso::dispatch_chain_root_signature(&gpu.dev, &[])?; + let pieces: Vec = chain.pieces.iter().map(|dxil| unsafe { + gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }).map_err(e) + }).collect::>()?; + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, groups, &[], mem, 1, false, + Some((&pieces, chain.dwords_per_group))).map(|(m,_)| m) } /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not @@ -1630,7 +1648,7 @@ pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true).map(|(_, t)| t) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true, None).map(|(_, t)| t) } /// Dispatch with an existing compute pipeline on `dev` (its own queue), e.g. one the D3D12.X @@ -1640,7 +1658,7 @@ pub fn dispatch_on(dev: &ID3D12Device, pso: &ID3D12PipelineState, rs: &ID3D12Roo unsafe { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; - dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) + dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false, None).map(|(m, _)| m) } } @@ -1657,6 +1675,7 @@ fn dispatch_with( mem: &[u32], reps: usize, timed: bool, + chain: Option<(&[ID3D12PipelineState], u32)>, ) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); io.resize(KERNEL_SGPRS, 0); @@ -1708,6 +1727,10 @@ fn dispatch_with( list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + let scratch = chain.map(|(_, words)| { + let bytes = groups.iter().fold(4 * u64::from(words), |n, &g| n * u64::from(g)); + buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true) + }).transpose()?; // `reps` dispatches, each between two timestamps when `timed` let stamps = 2 * reps as u32; let queries = if timed { @@ -1726,7 +1749,11 @@ fn dispatch_with( if let Some((heap, _)) = &queries { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); } - list.Dispatch(groups[0], groups[1], groups[2]); + if let (Some((pieces, _)), Some(scratch)) = (chain, &scratch) { + super::pso::record_dispatch_chain(&list, groups, scratch, pieces); + } else { + list.Dispatch(groups[0], groups[1], groups[2]); + } if let Some((heap, _)) = &queries { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k + 1); } diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index f5ed20cec..ae630107d 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -102,7 +102,9 @@ pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) } #[cfg(test)] -pub(super) fn recording_backing_for_test(list: usize) -> Option { +pub(super) use recording_backing as recording_backing_for_test; + +pub(super) fn recording_backing(list: usize) -> Option { STATE.lock().unwrap().as_ref()?.of_list.get(&list).copied() } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index da5b15ef4..06f8eb29e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -299,6 +299,17 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; match bind_abi(this, list, pso, gfx) { Ok(()) => { + if compute { + match super::real::dispatch_chain::whole(pso) { + Ok(Some(whole)) => list.SetPipelineState(&whole), + Ok(None) => {} + Err(e) => { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + count(DISPATCHES_SKIPPED); + return; + } + } + } count(if gfx { DRAWS } else { DISPATCHES }); fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } @@ -935,8 +946,7 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis trace_fullscreen(this, pso, [x, y, z]); } bind_abi(this, list, pso, false)?; - list.Dispatch(x, y, z); - Ok(()) + super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]) } /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3a3480f18..a3348a168 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -854,7 +854,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let raw = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); - list.Dispatch(x, y, z); + super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; out.dispatches += 1; } _ => out.skipped_dispatches += 1, diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 39f338143..f4b91cf5d 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -169,10 +169,12 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -fn queue() -> &'static Mutex>> { - static Q: OnceLock>>> = OnceLock::new(); +type Work = Box; + +fn queue() -> &'static Mutex> { + static Q: OnceLock>> = OnceLock::new(); Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::>(); + let (tx, rx) = mpsc::channel::(); let rx = Arc::new(Mutex::new(rx)); // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); @@ -180,18 +182,43 @@ fn queue() -> &'static Mutex>> { let rx = rx.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { let next = rx.lock().unwrap().recv(); - let Ok(p) = next else { return }; - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, false); - } + let Ok(work) = next else { return }; + work(); }); } Mutex::new(tx) }) } +fn enqueue(p: Arc) { + let _ = queue().lock().unwrap().send(Box::new(move || { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + build(&p, job, false); + } + })); +} + +/// The caller also drains its batch. Multiple workers can therefore build +/// different chains without ever waiting for a free worker to start a piece. +pub(super) fn build_pieces(jobs: Vec) -> Vec { + let count = jobs.len(); + let jobs = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::>())); + let (send, recv) = mpsc::channel(); + let drain = move || loop { + let job = jobs.lock().unwrap().pop(); + let Some((i, job)) = job else { return }; + let _ = send.send((i, job())); + }; + for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { + let _ = queue().lock().unwrap().send(Box::new(drain.clone())); + } + drain(); + let mut results = vec![0; count]; + for (i, result) in recv.iter().take(count) { results[i] = result; } + results +} + /// Release a pipeline state XCL owns (raw pointer, 0 = none). pub fn release(p: usize) { if p != 0 { @@ -240,7 +267,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - let _ = queue().lock().unwrap().send(p); + enqueue(p); } else if used::known(key) { if let Some(q) = preload() { q.list.lock().unwrap().push_back(p); @@ -527,7 +554,7 @@ pub fn resolve(pso: usize) -> usize { 0 => { // a lazy one is wanted now: to the workers if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p); + enqueue(p); } pso } @@ -586,7 +613,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> return built(p); } if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); + enqueue(p.clone()); } if p.late.load(Ordering::Acquire) { return pso; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18..1c0da137d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1751,6 +1751,7 @@ pub(super) fn forget_pso_for_test(pso: usize) { } fn forget_pso(pso: usize) { + dispatch_chain::forget(pso); if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); } @@ -3866,18 +3867,70 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if big && crate::gpu::recomp::dxc::defer() { return Some(Err(())); } + let record = crate::gpu::shader::fnv64(cs); + if let Some(plan) = compiled.dispatch_chain { + if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) { + LAST_COMPUTE_RS.with(|c| c.set(rs)); + note_pso_rs(*ppv, rs as *mut c_void); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(0, ppv); + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + return Some(Ok(0)); + } + } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); + let (hr, in_driver, reused) = compute_container(this, f, d, rs, &dxil, record, riid, ppv); + if hr < 0 { + // A huge program's verdict in the log itself: `note_translation_error` goes to the + // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program + // took an AMD driver 15 – 23 s and ~15 GB to refuse with E_OUTOFMEMORY in every run, and + // the log showed only its `driver compile finish` and the dispatches skipped after it. + if dxil.len() >= huge_pso_bytes() { + // (the record hash is the console program's, as in `driver compile start` and + // `xcl shaders --measure-pso`; the driver-cache name is the translated DXIL's) + crate::xlog_warn!( + "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", + dxil.len(), + driver_cache::name(&dxil, d.Flags.0), + in_driver.as_millis() + ); + } + note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); + return Some(Err(())); + } + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(hr, ppv); + crate::xlog_info!( + "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", + dxil.len(), + in_driver.as_millis(), + if reused { ", the driver's blob of an earlier build" } else { "" } + ); + Some(Ok(hr)) +} + +pub(super) mod dispatch_chain; +pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; + +unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, + dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); - copy.CS = bytecode(&dxil); + copy.CS = bytecode(dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. - let key = compute_blob_key(&dxil, rs as usize, copy.Flags.0); + let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path(&dxil, copy.Flags.0); + let disk = driver_cache::path(dxil, copy.Flags.0); let from_disk = cached.is_none(); if from_disk { cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); @@ -3886,7 +3939,6 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } // in the background, a few at a time and within the commit headroom the program asks for - let record = crate::gpu::shader::fnv64(cs); let (mut hr, mut in_driver) = driver_compile_identified( "compute", dxil.len(), @@ -3920,37 +3972,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if reused && from_disk { driver_cache::note(true, None); } - if hr < 0 { - // A huge program's verdict in the log itself: `note_translation_error` goes to the - // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program - // took an AMD driver 15 – 23 s and ~15 GB to refuse with E_OUTOFMEMORY in every run, and - // the log showed only its `driver compile finish` and the dispatches skipped after it. - if dxil.len() >= huge_pso_bytes() { - // (the record hash is the console program's, as in `driver compile start` and - // `xcl shaders --measure-pso`; the driver-cache name is the translated DXIL's) - crate::xlog_warn!( - "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", - dxil.len(), - driver_cache::name(&dxil, copy.Flags.0), - in_driver.as_millis() - ); - } - note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); - return Some(Err(())); - } - TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); - note_pso_rs(*ppv, rs); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); - } - note_translated_compute(hr, ppv); - crate::xlog_info!( - "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", - dxil.len(), - in_driver.as_millis(), - if reused { ", the driver's blob of an earlier build" } else { "" } - ); - Some(Ok(hr)) + (hr, in_driver, reused) } /// The blobs of `COMPUTE_BLOBS`, kept on disk between runs. @@ -5977,6 +5999,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { + dispatch_chain::allocator_reset(this as usize); super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); } @@ -5987,7 +6010,9 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); - f(raw) + let hr = f(raw); + if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs new file mode 100644 index 000000000..b4d2f8a52 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -0,0 +1,148 @@ +//! PSOs for a split compute entry. The first piece is the real PSO returned +//! to the caller. Other pieces and the lazily built whole form belong to it. +use super::*; +use crate::gpu::{dxil::kernel::DispatchChain, recomp::pso}; +use std::sync::{Arc, LazyLock, OnceLock}; + +static PROGRAMS: AtomicU64 = AtomicU64::new(0); +static PIECES: AtomicU64 = AtomicU64::new(0); +static DISPATCHES: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn log_counts() { + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued", + PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed)); +} + +struct PipelineBuilder { + device: ID3D12Device, + create: PsoFn, + signature: ID3D12RootSignature, + flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, + record: u64, +} + +impl PipelineBuilder { + unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), + dxil, self.record, iid, &mut raw); + (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + } +} + +struct Chain { + builder: Arc, + tail: Vec, + words: u32, + whole_code: Vec, + whole: OnceLock, + build_whole: Mutex<()>, +} + +impl Chain { + unsafe fn whole(&self) -> Result { + if let Some(p) = self.whole.get() { return Ok(p.clone()); } + let _guard = self.build_whole.lock().unwrap(); + if let Some(p) = self.whole.get() { return Ok(p.clone()); } + let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; + let _ = self.whole.set(p.clone()); + Ok(p) + } +} + +static CHAINS: LazyLock>>> = LazyLock::new(Default::default); + +pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], + plan: Arc) -> Option { + if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } + let dev = ID3D12Device::from_raw_borrowed(&this)?; + let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; + let rs = signature.as_raw() as usize; + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, + flags: desc.Flags, node: desc.NodeMask, record }); + let jobs = (0..plan.pieces.len()).map(|i| { + let plan = plan.clone(); + let builder = builder.clone(); + let iid = if i == 0 { *iid } else { pc_iid(Kind::PipelineState) }; + Box::new(move || builder.pipeline(&plan.pieces[i], &iid).map_or(0, |p| p.into_raw() as usize)) as super::super::pso_async::Job + }).collect(); + // Take ownership of every success, including when a different piece failed. + let built: Vec<_> = super::super::pso_async::build_pieces(jobs).into_iter() + .map(|p| (p != 0).then(|| ID3D12PipelineState::from_raw(p as *mut c_void))).collect(); + let mut pieces = built.into_iter().collect::>>()?.into_iter(); + let first = pieces.next()?; + let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, + whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()) }); + PROGRAMS.fetch_add(1, Ordering::Relaxed); + PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); + *result = first.into_raw(); + CHAINS.lock().unwrap().insert(*result as usize, chain); + Some(rs) +} + +pub(super) fn forget(pso: usize) { + let gone = CHAINS.lock().unwrap().remove(&pso); + drop(gone); // releasing a tail PSO also goes through forget_pso +} + +pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + chain.map(|c| c.whole()).transpose() +} + +struct Recording { + scratch: ID3D12Resource, + first: ID3D12PipelineState, + chain: Arc, +} + +static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); + +pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { + let recordings = RECORDINGS.lock().unwrap().remove(&allocator); + drop(recordings); +} + +unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }; + let mut resource = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +/// Called with the original six ABI views bound. The extended signature is +/// common to every piece and the whole fallback. Choose before recording any +/// part of the dispatch, including when scratch allocation fails. +pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, grid: [u32; 3]) -> Result<(), String> { + let [x, y, z] = grid; + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { list.Dispatch(x, y, z); return Ok(()) }; + if grid.contains(&0) { return Ok(()); } + // A title Reset can switch to a different PC allocator while this + // recording is still submitted on the old one. Retain by backing. + let allocator = if super::super::alloc_pool::enabled() { + super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) + } else { allocator }; + let size = grid.into_iter().try_fold(u64::from(chain.words) * 4, |s, n| s.checked_mul(n as u64)); + let scratch = size.filter(|&n| n <= u32::MAX as u64 + 1 && allocator != 0 && list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) + .and_then(|n| scratch_buffer(&chain.builder.device, n)); + let Some(scratch) = scratch else { + list.SetPipelineState(&chain.whole()?); + list.Dispatch(x, y, z); + return Ok(()); + }; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + let held = Arc::new(Recording { scratch, first, chain }); + RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); + DISPATCHES.fetch_add(1, Ordering::Relaxed); + pso::record_dispatch_chain(list, grid, &held.scratch, std::iter::once(&held.first).chain(&held.chain.tail)); + Ok(()) +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f3e57ce5f..71a25c7c1 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -35,6 +35,10 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + let _ = std::thread::Builder::new().name("xcl-split-counts".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_secs(10)); + crate::hle::d3d12x::real::log_dispatch_chain_counts(); + }); // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) if std::env::var_os("XCL_ACTIVITY").is_some() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee30332..ff9ac68b2 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1189,7 +1189,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); From 510621e6d1439b23cddcf99bed099ad6eab320bf Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:57:46 -0500 Subject: [PATCH 2/7] Tests: use the compute fixture's existing memory window The synthetic split fixture declared u2 twice with different coherence flags. Bind its existing memory window and validate the whole fixture before checking the cut. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module/split.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 52642859c..2b16df3b3 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -515,7 +515,6 @@ impl Module { #[cfg(test)] mod tests { - use super::*; use crate::gpu::{ dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::Pred}, recomp::{runner, CsInterface}, @@ -532,7 +531,7 @@ mod tests { let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); let (tid, _) = lw.setup_lanes_compute(geometry, false); - let mem = lw.s.raw_uav(2, 0); + let mem = lw.mems[0]; let group = lw.s.group_id(0); let count = lw.c(threads); let base = lw.mul(group, count); @@ -573,9 +572,11 @@ mod tests { lw.s.raw_store(mem, offset, &[value]); lw.s.m.ret(); lw.s.m.optimize(); - let chain = lw.s.split_compute(geometry, split.then_some(tid), 40).expect("split the synthetic program"); - assert!(chain.pieces.len() >= 3); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 40); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); + let chain = chain.expect("split the synthetic program"); + assert!(chain.pieces.len() >= 3); let initial: Vec<_> = (1..=threads * 3).collect(); let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { let n = (i as u32 % 4) + 1; From f90a90781e9a459afba10ed9091664b5ab406762 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:05:49 -0500 Subject: [PATCH 3/7] Recompiler: pack consecutive lanes into each dispatch scratch slot Adjacent lanes previously accessed ef008c0f's continuation data 1,612 bytes apart. Store the tag and each live dword in a separate lane-contiguous plane; transport both halves of i64 values through their own planes. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module/split.rs | 42 ++++++++++++++++++------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 2b16df3b3..c4cfe66e1 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -28,6 +28,7 @@ pub struct DispatchChain { struct Scratch { uav: RawUav, base: Value, + bytes_per_slot: u32, } impl Scratch { @@ -42,15 +43,17 @@ impl Scratch { let row = s.m.bin(BinOp::Add, row, y); let first = s.m.bin(BinOp::Mul, row, width); let group = s.m.bin(BinOp::Add, first, x); - let n = s.m.i32c(threads); - let first = s.m.bin(BinOp::Mul, group, n); + // Give consecutive logical lanes consecutive words for a slot, including + // the continuation tag in slot zero. A workgroup owns all its slots. + let group_words = s.m.i32c(stride * threads); + let first = s.m.bin(BinOp::Mul, group, group_words); let index = s.m.bin(BinOp::Add, first, lane); - let bytes = s.m.i32c(stride * 4); - Self { uav, base: s.m.bin(BinOp::Mul, index, bytes) } + let four = s.m.i32c(4); + Self { uav, base: s.m.bin(BinOp::Mul, index, four), bytes_per_slot: threads * 4 } } fn at(&self, m: &mut Module, slot: u32) -> Value { - let offset = m.i32c(slot * 4); + let offset = m.i32c(slot * self.bytes_per_slot); m.bin(BinOp::Add, self.base, offset) } } @@ -151,8 +154,10 @@ impl Shader { statics.insert(v); continue; } - let at = scratch.at(&mut dst.m, slot); - let words = dst.raw_load(scratch.uav, at, if n == 2 { 3 } else { 1 }); + let words = (slot..slot + n).map(|word| { + let at = scratch.at(&mut dst.m, word); + dst.raw_load(scratch.uav, at, 1)[0] + }).collect(); incoming.entry(v).or_default().push((words, bridge)); slot += n; } @@ -244,8 +249,10 @@ impl Shader { let n = src.transport_words(v)?; if n != 0 { let words = src.pack(v, *values.get(&v)?, &mut dst.m); - let at = scratch.at(&mut dst.m, slot); - dst.raw_store(scratch.uav, at, &words); + for (k, word) in words.into_iter().enumerate() { + let at = scratch.at(&mut dst.m, slot + k as u32); + dst.raw_store(scratch.uav, at, &[word]); + } slot += n; } } @@ -516,7 +523,7 @@ impl Module { #[cfg(test)] mod tests { use crate::gpu::{ - dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::Pred}, + dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::{BinOp, CastOp, Pred}}, recomp::{runner, CsInterface}, }; @@ -538,6 +545,14 @@ mod tests { let index = lw.add(base, tid); let offset = lw.shlc(index, 2); let original = lw.s.raw_load(mem, offset, 1)[0]; + // Two different dynamic dwords cross every cut as one i64. With + // slot-major scratch the high word is a wave width past the low word. + let i64_ty = lw.s.m.i64(); + let lo = lw.s.m.cast(CastOp::ZExt, original, i64_ty); + let hi = lw.s.m.cast(CastOp::ZExt, tid, i64_ty); + let shift = lw.s.m.const_int(i64_ty, 32); + let hi = lw.s.m.bin(BinOp::Shl, hi, shift); + let pair = lw.s.m.bin(BinOp::Or, lo, hi); let trips = lw.andc(tid, 3); let trips = lw.addc(trips, 1); let mut value = original; @@ -569,6 +584,11 @@ mod tests { value = lw.add(value, other_half); } } + let pair_lo = lw.s.m.cast(CastOp::Trunc, pair, i32); + let high = lw.s.m.bin(BinOp::LShr, pair, shift); + let pair_hi = lw.s.m.cast(CastOp::Trunc, high, i32); + let both = lw.xor(pair_lo, pair_hi); + value = lw.add(value, both); lw.s.raw_store(mem, offset, &[value]); lw.s.m.ret(); lw.s.m.optimize(); @@ -580,7 +600,7 @@ mod tests { let initial: Vec<_> = (1..=threads * 3).collect(); let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { let n = (i as u32 % 4) + 1; - v + n * (16 * v + 136) + u32::from(split && i as u32 % threads < 32) + v + n * (16 * v + 136) + u32::from(split && i as u32 % threads < 32) + (v ^ (i as u32 % threads)) }).collect(); let reference = runner::dispatch(&whole, [3, 1, 1], &[], &initial).unwrap(); assert_eq!(reference, expected); From 141b2b319375bbf181b9e32651508b9537d95c4d Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:57:20 -0500 Subject: [PATCH 4/7] Tests: exercise divergent forward edges across compute dispatch pieces Adopt WebIdentity1's fixture from #2080. Lanes return early, skip ahead over a piece, or run different numbers of loop iterations. Check the whole and split outputs against the CPU model and guard words on a 2 x 3 x 2 dispatch grid for native wave32 and split wave64. Source: https://github.com/xcl-dev/xcl/pull/2080#issuecomment-7152187595 Assisted-by: OpenAI Codex (GPT-6) Co-authored-by: WebIdentity1 <212448219+WebIdentity1@users.noreply.github.com> --- crates/xcl/src/gpu/dxil/module/split.rs | 118 ++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index c4cfe66e1..7af0f2aa2 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -613,4 +613,122 @@ mod tests { #[test] fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64); } + /// Early exits and forward skips retain their own continuation tags; group + /// indexing must keep every lane separate across all three dispatch axes. + #[test] + fn dispatch_chain_divergent_forward_edges_3d() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + println!("CHAIN_GPU={}", runner::adapter().unwrap()); + for threads in [32, 64] { + let geometry = [threads, 1, 1]; + let split = threads == 64; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let [x, y, z] = [0, 1, 2].map(|axis| lw.s.group_id(axis)); + let three = lw.c(3); + let row = lw.mul(z, three); + let row = lw.add(row, y); + let row = lw.shlc(row, 1); + let group = lw.add(row, x); + let count = lw.c(threads); + let base = lw.mul(group, count); + let index = lw.add(base, tid); + let offset = lw.shlc(index, 2); + let original = lw.s.raw_load(mem, offset, 1)[0]; + let mode = lw.andc(tid, 3); + let trips = lw.addc(mode, 1); + let zero = lw.c(0); + let one = lw.c(1); + let i32 = lw.s.m.i32(); + let early = lw.s.m.new_block(); + let choose = lw.s.m.new_block(); + let first = lw.s.m.new_block(); + let middle = lw.s.m.new_block(); + let second = lw.s.m.new_block(); + let done = lw.s.m.new_block(); + let exits = lw.cmp(Pred::Eq, mode, zero); + lw.s.m.cond_br(exits, early, choose); + lw.s.m.set_block(early); + let marker = lw.addc(index, 100_000); + lw.s.raw_store(mem, offset, &[marker]); + lw.s.m.ret(); + lw.s.m.set_block(choose); + let skips = lw.cmp(Pred::Eq, mode, one); + lw.s.m.cond_br(skips, middle, first); + lw.s.m.set_block(first); + let mut value = original; + let mut middle_value = None; + for round in 1..=16 { + if round == 9 { + let previous = lw.cur(); + lw.s.m.br(middle); + lw.s.m.set_block(middle); + let joined = lw.s.m.phi(i32); + lw.s.m.add_incoming(joined, original, choose); + lw.s.m.add_incoming(joined, value, previous); + value = joined; + middle_value = Some(joined); + let stops = lw.cmp(Pred::Eq, mode, three); + lw.s.m.cond_br(stops, done, second); + lw.s.m.set_block(second); + } + let pred = lw.cur(); + let body = lw.s.m.new_block(); + let exit = lw.s.m.new_block(); + lw.s.m.br(body); + lw.s.m.set_block(body); + let counter = lw.s.m.phi(i32); + let acc = lw.s.m.phi(i32); + lw.s.m.add_incoming(counter, zero, pred); + lw.s.m.add_incoming(acc, value, pred); + let next = lw.addc(counter, 1); + value = lw.add(acc, original); + value = lw.addc(value, round); + lw.s.m.add_incoming(counter, next, body); + lw.s.m.add_incoming(acc, value, body); + let again = lw.cmp(Pred::ULt, next, trips); + lw.s.m.cond_br(again, body, exit); + lw.s.m.set_block(exit); + } + let last = lw.cur(); + lw.s.m.br(done); + lw.s.m.set_block(done); + let final_value = lw.s.m.phi(i32); + lw.s.m.add_incoming(final_value, middle_value.unwrap(), middle); + lw.s.m.add_incoming(final_value, value, last); + lw.s.raw_store(mem, offset, &[final_value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let plan = lw.s.m.dispatch_plan(64).expect("partition branch fixture"); + let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); + assert!(plan.edges.iter().any(|edge| stage(edge.to) > stage(edge.from) + 1), "exercise a forward skip over an intermediate piece"); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 64).expect("split branch fixture"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); + let words = (threads * 12) as usize; + let initial: Vec<_> = (0..words + 16).map(|i| if i < words { i as u32 + 17 } else { 0xdeadbeef }).collect(); + let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { + if i >= words { return v; } + match i as u32 % 4 { + 0 => 100_000 + i as u32, + 1 => v + 2 * (8 * v + 100), + 2 => v + 3 * (16 * v + 136), + _ => v + 4 * (8 * v + 36), + } + }).collect(); + let reference = runner::dispatch(&whole, [2, 3, 2], &[], &initial).unwrap(); + assert_eq!(reference, expected, "unsplit {threads}"); + let result = runner::dispatch_split(&chain, [2, 3, 2], &initial).unwrap(); + assert_eq!(result, expected, "split {threads}"); + println!("CHAIN_BRANCH threads={threads} pieces={} scratch_words_per_group={} checked_words={words} guards=16", chain.pieces.len(), chain.dwords_per_group); + } + } + } From 8eefdefcf2283f1ae7ff524ed66de43356b82060 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:22:10 -0500 Subject: [PATCH 5/7] Tests: verify native wave64 compute keeps its whole pipeline Compile and validate a partitionable CFG through the native-wave64 admission gate. On a wave64 adapter, run the whole pipeline and check its lane count and output. Identify the existing compare(64) case as two hardware waves. Assisted-by: OpenAI Codex (GPT-6) --- crates/xcl/src/gpu/dxil/kernel.rs | 39 +++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/module/split.rs | 1 + 2 files changed, 40 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 9a1819449..d40070d30 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -596,6 +596,45 @@ impl Lw { } } +#[cfg(test)] +#[test] +fn dispatch_chain_native_wave64_builds_whole() { + use crate::gpu::recomp::runner; + + let threads = [64, 1, 1]; + let cs = CsInterface { threads, ..Default::default() }; + let options = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(threads, false); + let offset = lw.shlc(tid, 2); + let width = lw.s.wave_lane_count(); + let mem = lw.mems[0]; + for _ in 0..40 { + let block = lw.s.m.new_block(); + lw.s.m.br(block); + lw.s.m.set_block(block); + let old = lw.s.raw_load(mem, offset, 1)[0]; + let new = lw.add(old, width); + lw.s.raw_store(mem, offset, &[new]); + } + lw.s.m.ret(); + lw.s.m.optimize(); + // Exercise the native-wave admission gate with an otherwise partitionable CFG. + assert!(lw.s.m.dispatch_plan(64).is_some()); + let program = lw.finish_dispatch(threads, 64, 64, None).unwrap(); + assert!(program.dispatch_chain.is_none()); + super::validate::validate(&program.dxil).expect("valid native wave64 whole shader"); + + if !runner::wave64_supported().unwrap_or(false) { + runner::skip_test("no wave64"); + return; + } + let initial: Vec = (1..=64).collect(); + let expected: Vec<_> = initial.iter().map(|v| v + 40 * 64).collect(); + let result = runner::dispatch(&program.dxil, [1, 1, 1], &[], &initial).unwrap(); + assert_eq!(result, expected); +} + /// The kernel's epilogue: SGPRs and SCC from lane 0, every touched VGPR per lane. fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { let touched: Vec = lw.init.touched.iter().copied().collect(); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7af0f2aa2..b7d6669a4 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -611,6 +611,7 @@ mod tests { #[test] fn dispatch_chain_wave32_live_loops() { compare(32); } + /// A guest wave64 split across two hardware wave32s. #[test] fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64); } /// Early exits and forward skips retain their own continuation tags; group From c4178b3754078a3eb3ad0c1704bbc5994c5bff00 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:39:09 -0500 Subject: [PATCH 6/7] Recompiler: carry wave64 partner exchanges across dispatch pieces Use the workgroup's flat logical thread ID for the continuation of each wave32 half. Keep each counter signal with its peer wait, and transfer the per-half arrival counters and double-buffered exchange slots at a group-wide rendezvous between pieces. Wave allocation starts afresh in each piece. Leave guest LDS and partial guest waves on the whole path. Exercise four wave64s with different exchange epochs across repeated cuts and compare every output word to the whole shader and a CPU oracle. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/lanes.rs | 2 + crates/xcl/src/gpu/dxil/module.rs | 10 ++ crates/xcl/src/gpu/dxil/module/split.rs | 185 +++++++++++++++++++++--- docs/wave64-on-wave32.md | 7 + 5 files changed, 187 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d40070d30..1a3969edd 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -193,7 +193,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); - if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } + if split && !uses_lds && cs.threads.iter().product::() % 64 == 0 { split_tid = Some(tid); } compute_init(&mut lw, cs, tid, gtid); cs.threads } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 04491ba07..02940dbba 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -300,6 +300,7 @@ impl Lw { let alive = self.cmpc(Pred::Eq, dead, 0); let has = self.cmpc(Pred::Ne, xn, 0); let go = self.land(alive, has); + let region = (self.cur(), self.s.m.block_count()); let _ = self.guarded(go, &mut |lw| { lw.s.barrier(barrier::TGSM_FENCE); let t = lw.s.m.i1c(true); @@ -354,6 +355,7 @@ impl Lw { }); let one = self.c(1); let ho = self.xor(h, one); + self.s.m.finish_spin_region(region.0, region.1); let theirs = at(self, ho); let metv = self.rd(met); let ok = self.nz(metv); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index cc85589f5..84ceed241 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -254,6 +254,7 @@ pub struct Module { insts: Vec, def_block: Vec, blocks: Vec>, + spin_regions: Vec>, cur: Block, insert_before_term: bool, md: Vec, @@ -282,6 +283,7 @@ impl Module { insts: Vec::new(), def_block: Vec::new(), blocks: vec![Vec::new()], + spin_regions: Vec::new(), cur: Block(0), insert_before_term: false, md: Vec::new(), @@ -519,6 +521,14 @@ impl Module { self.blocks.push(Vec::new()); Block(self.blocks.len() as u32 - 1) } + /// Keep both halves' signal and wait in the same dispatch. The join can + /// begin the next piece since the exchange slots are checkpointed. + pub(super) fn finish_spin_region(&mut self, start: Block, first_new: usize) { + let mut region = vec![start]; + region.extend((first_new..self.blocks.len()).map(|i| Block(i as u32)).filter(|&b| b != self.cur)); + self.spin_regions.push(region); + } + pub fn entry_block(&self) -> Block { Block(0) } diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index b7d6669a4..1ce9fa69a 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -52,6 +52,45 @@ impl Scratch { Self { uav, base: s.m.bin(BinOp::Mul, index, four), bytes_per_slot: threads * 4 } } + /// Every logical thread participates, including threads whose guest path + /// skipped this piece. Exactly one thread owns each shared word. + fn transfer_shared(&self, s: &mut Shader, lane: Value, lanes: u32, arrays: &[(Value, u32, u32)], restore: bool) { + use crate::gpu::dxil::ops::barrier::GROUP_SYNC; + if !restore { s.barrier(GROUP_SYNC); } + for &(global, count, slot) in arrays { + for page in 0..count.div_ceil(lanes) { + let remaining = count - page * lanes; + let mut join = None; + if remaining < lanes { + let n = s.m.i32c(remaining); + let active = s.m.cmp(super::Pred::ULt, lane, n); + let body = s.m.new_block(); + let next = s.m.new_block(); + s.m.cond_br(active, body, next); + s.m.set_block(body); + join = Some(next); + } + let zero = s.m.i32c(0); + let base = s.m.i32c(page * lanes); + let index = s.m.bin(BinOp::Add, base, lane); + let ptr = s.m.gep(global, &[zero, index]); + let addr = self.at(&mut s.m, slot + page); + if restore { + let v = s.raw_load(self.uav, addr, 1)[0]; + s.m.store(ptr, v, 4); + } else { + let v = s.m.load(ptr, 4); + s.raw_store(self.uav, addr, &[v]); + } + if let Some(next) = join { + s.m.br(next); + s.m.set_block(next); + } + } + } + if restore { s.barrier(GROUP_SYNC); } + } + fn at(&self, m: &mut Module, slot: u32) -> Value { let offset = m.i32c(slot * self.bytes_per_slot); m.bin(BinOp::Add, self.base, offset) @@ -59,11 +98,16 @@ impl Scratch { } impl Shader { - /// Start with full native wave32 groups. A fresh dispatch can assign a - /// different physical wave to a group; wave-lane index identifies the - /// continuation within a full, single-wave group. + /// Native wave32 uses the hardware lane in a single full wave. Split + /// wave64 recreates the flat console thread ID on every dispatch, including + /// when the hardware schedules the waves in a different order. pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { - if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { + let lanes: u32 = threads.into_iter().try_fold(1u32, u32::checked_mul)?; + let multi = split_tid.is_some() && lanes > 64; + if self.m.globals.iter().any(|g| !g.constant + && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs")) + && !(multi && g.name == "xcl_xc")) + { return None; } if self.m.blocks.iter().map(Vec::len).sum::() <= limit { return None; } @@ -76,6 +120,8 @@ impl Shader { for &i in self.m.blocks.iter().flatten() { self.m.insts[i as usize].op.for_each_operand(|v| { consumed.insert(v); }); } + let root_is = |v, name| self.m.global_root(v).is_some_and(|g| self.m.globals[g].name == name); + let spins: HashSet<_> = self.m.spin_regions.iter().flatten().copied().collect(); for (b, block) in self.m.blocks.iter().enumerate() { // In a single split console wave each inter-half exchange begins // with TGSM stores, one rendezvous, peer loads and a rendezvous. @@ -84,10 +130,15 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::AtomicRmw(super::RmwOp::Add, p, _) if multi && root_is(*p, "xcl_xc") => {} + Op::Load(p, _) | Op::Store(p, _, _) if multi && root_is(*p, "xcl_xs") => {} + Op::Call(f, args) if multi && spins.contains(&Block(b as u32)) + && self.m.funcs[*f as usize].name == "dx.op.barrier" + && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::TGSM_FENCE as u64) => {} Op::Alloca(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => return None, - Op::Store(..) if split_tid.is_some() && exchange <= 1 => exchange = 1, + Op::Store(..) if split_tid.is_some() && !multi && exchange <= 1 => exchange = 1, Op::Load(p, _) if self.m.global_root(*p).is_some_and(|g| self.m.globals[g].constant) => {} - Op::Load(..) if split_tid.is_some() && matches!(exchange, 2 | 3) => exchange = 3, + Op::Load(..) if split_tid.is_some() && !multi && matches!(exchange, 2 | 3) => exchange = 3, Op::Load(..) | Op::Store(..) => return None, Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.barrier" && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64) => { @@ -113,11 +164,19 @@ impl Shader { } stride = stride.max(words); } - let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix)).collect::>>()?; - Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) + let mut shared = Vec::new(); + if multi { + for (i, g) in self.m.globals.iter().enumerate().filter(|(_, g)| matches!(g.name.as_str(), "xcl_xc" | "xcl_xs")) { + let TypeDef::Array(n, _) = self.m.types[g.ty.0 as usize] else { return None }; + shared.push((Value::Global(i as u32), u32::try_from(n).ok()?, stride)); + stride = stride.checked_add(u32::try_from(n).ok()?.div_ceil(lanes))?; + } + } + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix, &shared)).collect::>>()?; + Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(lanes)? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, threads: [u32; 3], prefix: &[u32], shared: &[(Value, u32, u32)]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -128,7 +187,12 @@ impl Shader { values.insert(Value::Inst(id), dst.m.push(op, def.ty)); } let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); - let scratch = Scratch::new(&mut dst, stride, threads[0], lane); + let lanes = threads.iter().product(); + let scratch = Scratch::new(&mut dst, stride, lanes, lane); + if stage > 0 && !shared.is_empty() { + scratch.transfer_shared(&mut dst, lane, lanes, shared, true); + } + let dispatch_entry = dst.m.current_block(); let local: HashMap<_, _> = plan.blocks[stage].iter().map(|&b| (b, dst.m.new_block())).collect(); let mut hops = HashMap::new(); let mut exits = HashMap::new(); @@ -170,7 +234,7 @@ impl Shader { hops.insert((edge.from, edge.to), hop); } } - dst.m.set_block(Block(0)); + dst.m.set_block(dispatch_entry); if let Some(sel) = selector { dst.m.switch(sel, done, &cases); dst.m.set_block(merge); @@ -200,6 +264,8 @@ impl Shader { dst.m.br(local[&Block(0)]); } dst.m.set_block(done); + let checkpoint = !shared.is_empty() && stage + 1 < plan.blocks.len(); + if checkpoint { scratch.transfer_shared(&mut dst, lane, lanes, shared, false); } dst.m.ret(); // Assign all instruction identities before fixing operands. A loop's @@ -213,6 +279,7 @@ impl Shader { if matches!(old.op, Op::Ret) && stage + 1 < plan.blocks.len() { let zero = dst.m.i32c(0); dst.raw_store(scratch.uav, scratch.base, &[zero]); + if checkpoint { dst.m.br(done); continue; } } let v = dst.m.push(old.op.clone(), old.ty); values.insert(Value::Inst(i), v); @@ -257,7 +324,7 @@ impl Shader { } } dst.raw_store(scratch.uav, scratch.base, &[tag]); - dst.m.ret(); + if checkpoint { dst.m.br(done); } else { dst.m.ret(); } } dst.infer_piece_features(); let blob = dst.try_finish(threads, Some(32)).ok()?; @@ -303,7 +370,7 @@ impl Module { fn indexed(&self, v: Value) -> Option { let op = &self.insts[inst(v)?].op; if let Op::Gep(Value::Global(g), indices) = op { - if self.globals[*g as usize].name == "xcl_xs" && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { + if matches!(self.globals[*g as usize].name.as_str(), "xcl_xs" | "xcl_xc") && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { return Some(indices[1]); } } @@ -428,7 +495,7 @@ impl Module { let mut visited = vec![false; self.blocks.len()]; let mut blocks = vec![Vec::new()]; let mut stages = vec![usize::MAX; self.blocks.len()]; - let mut used = 0; + let mut components = Vec::new(); for &root in &order { if visited[root] { continue; @@ -447,16 +514,40 @@ impl Module { } } } - if cost > limit { - return None; + for &b in &component { + stages[b] = components.len(); } + components.push((cost, component)); + } + // A wait polling the peer's counter cannot complete if the peer's + // signal was deferred to another dispatch. Pack these SCCs together. + let mut through: Vec = (0..components.len()).collect(); + for region in &self.spin_regions { + let mut span = region.iter().map(|b| stages[b.0 as usize]).filter(|&i| i != usize::MAX); + if let Some(i) = span.next() { + let (lo, hi) = span.fold((i, i), |(lo, hi), i| (lo.min(i), hi.max(i))); + through[lo] = through[lo].max(hi); + } + } + let mut i = 0; + let mut used = 0; + while i < components.len() { + let first = i; + let mut last = i; + let mut cost = 0; + while i <= last { + last = last.max(through[i]); + cost += components[i].0; + i += 1; + } + if cost > limit { return None; } if used + cost > limit { blocks.push(Vec::new()); used = 0; } used += cost; - for b in component { - stages[b] = blocks.len() - 1; + for (_, component) in &components[first..i] { + for &b in component { stages[b] = blocks.len() - 1; } } } @@ -608,6 +699,64 @@ mod tests { assert_eq!(result, reference); } + #[test] + fn dispatch_chain_four_wave64s_preserves_partner_epochs() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [16, 16, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let half = lw.lshrc(tid, 5); + let group = lw.s.group_id(0); + let group_base = lw.shlc(group, 8); + let index = lw.add(group_base, tid); + let addr = lw.shlc(index, 2); + let mem = lw.mems[0]; + let initial = lw.s.raw_load(mem, addr, 1)[0]; + let acc = lw.tmp_var(); + lw.wr(acc, initial); + let odd_wave = lw.andc(tid, 64); + let odd_wave = lw.nz(odd_wave); + // Only odd guest waves perform every exchange. A single common + // exchange count for all guest waves would corrupt their results. + for round in 1..=12 { + let mut exchange = |lw: &mut Lw| { + let payload = lw.addc(half, round); + let peer = lw.exchange(payload); + let old = lw.rd(acc); + let sum = lw.add(old, peer); + lw.wr(acc, sum); + Ok(()) + }; + if round % 2 == 1 { lw.guarded(odd_wave, &mut exchange).unwrap(); } + else { exchange(&mut lw).unwrap(); } + let next = lw.block(Some(1)); + lw.br(next); + lw.s.m.set_block(next); + } + let v = lw.rd(acc); + lw.s.raw_store(mem, addr, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 160).expect("split four guest waves"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + let input: Vec = (1..=512).collect(); + let expected: Vec<_> = input.iter().enumerate().map(|(i, v)| { + let tid = i as u32 % 256; + v + (1..=12).filter(|round| round % 2 == 0 || tid & 64 != 0) + .map(|round| ((tid / 32) ^ 1) + round).sum::() + }).collect(); + let groups = [2, 1, 1]; + let reference = runner::dispatch(&whole, groups, &[], &input).unwrap(); + assert_eq!(reference, expected); + assert_eq!(runner::dispatch_split(&chain, groups, &input).unwrap(), reference); + } + #[test] fn dispatch_chain_wave32_live_loops() { compare(32); } diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d20353..8b84fb48b 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -72,6 +72,13 @@ SGPRs of both halves and the tests fail if they ever differ. are resident on one SM / CU) but not necessarily on WARP. `XCL_WAVE64_SPIN=1` forces this variant everywhere (the test suite passes with it too). +For direct compute dispatches split across pipelines, a group of full console waves can +carry the exchange state through scratch. A signal and its bounded wait stay in one piece. +All threads meet at the piece exit and copy the arrival counters and both banks of slots. +The next piece assigns logical thread IDs again, restores the shared words and synchronises +before following each lane's continuation. Each console wave keeps its own exchange count, +including when other waves skip the piece. Programs using guest LDS stay on the whole pipeline. + A console wave whose upper half does not exist (group of 32 or 96 threads) exchanges with nobody: the missing lanes count as inactive (ballot bits 0), exactly as on the console. The GS phase of ES+GS runs in the lower half only (≤ 21 primitives), likewise without a partner. From eafe39f1a5329b08204cc423238456bedddd8557 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:03:57 -0500 Subject: [PATCH 7/7] Tests: keep exited guest waves in dispatch checkpoints Adopt WebIdentity1's four-wave fixture. Two guest waves return at different points while the other waves keep exchanging. Compare the whole shader and the dispatch chain to the CPU oracle across a 3D grid. Source: https://github.com/xcl-dev/xcl/pull/2097#issuecomment-7152422936 Assisted-by: OpenAI Codex (GPT-6) Co-authored-by: WebIdentity1 <212448219+WebIdentity1@users.noreply.github.com> --- crates/xcl/src/gpu/dxil/module/split.rs | 85 +++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 1ce9fa69a..2b35d9b62 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -757,6 +757,91 @@ mod tests { assert_eq!(runner::dispatch_split(&chain, groups, &input).unwrap(), reference); } + /// Guest waves that returned still participate in the checkpoint rendezvous + /// while other waves keep advancing their partner counters and slot banks. + #[test] + fn dispatch_chain_exited_waves_preserve_other_waves_3d() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + println!("CHAIN_EXIT_GPU={}", runner::adapter().unwrap()); + let geometry = [16, 16, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let half = lw.lshrc(tid, 5); + let wave = lw.lshrc(tid, 6); + let [x, y, z] = [0, 1, 2].map(|axis| lw.s.group_id(axis)); + let z = lw.shlc(z, 1); + let row = lw.add(z, y); + let row = lw.shlc(row, 1); + let group = lw.add(row, x); + let base = lw.shlc(group, 8); + let index = lw.add(base, tid); + let addr = lw.shlc(index, 2); + let mem = lw.mems[0]; + let initial = lw.s.raw_load(mem, addr, 1)[0]; + let acc = lw.tmp_var(); + lw.wr(acc, initial); + let not_second_wave = lw.cmpc(Pred::Ne, wave, 1); + for round in 1..=12 { + if round == 1 || round == 7 { + let exit = lw.block(Some(1)); + let live = lw.block(Some(1)); + let stops = lw.cmpc(Pred::Eq, wave, if round == 1 { 0 } else { 2 }); + lw.cond_br(stops, exit, live); + lw.s.m.set_block(exit); + let old = lw.rd(acc); + let value = if round == 1 { lw.addc(old, 100_000) } else { old }; + lw.s.raw_store(mem, addr, &[value]); + lw.s.m.ret(); + lw.s.m.set_block(live); + } + let mut exchange = |lw: &mut Lw| { + let payload = lw.addc(half, round); + let peer = lw.exchange(payload); + let old = lw.rd(acc); + let value = lw.add(old, peer); + lw.wr(acc, value); + Ok(()) + }; + if round % 2 == 1 { lw.guarded(not_second_wave, &mut exchange).unwrap(); } + else { exchange(&mut lw).unwrap(); } + let next = lw.block(Some(1)); + lw.br(next); + lw.s.m.set_block(next); + } + let value = lw.rd(acc); + lw.s.raw_store(mem, addr, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 160).expect("split with exited guest waves"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid whole shader"); + let input: Vec<_> = (0..2064u32).map(|i| if i < 2048 { i + 17 } else { 0xdeadbeef }).collect(); + let expected: Vec<_> = input.iter().enumerate().map(|(i, &v)| { + if i >= 2048 { return v; } + let tid = i as u32 % 256; + let peer = (tid / 32) ^ 1; + match tid / 64 { + 0 => v + 100_000, + 1 => v + 6 * peer + 42, + 2 => v + 6 * peer + 21, + _ => v + 12 * peer + 78, + } + }).collect(); + println!("CHAIN_EXIT_STAGE whole pieces={} scratch_dwords_per_group={}", chain.pieces.len(), chain.dwords_per_group); + let reference = runner::dispatch(&whole, [2, 2, 2], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program CPU oracle"); + println!("CHAIN_EXIT_STAGE split"); + let result = runner::dispatch_split(&chain, [2, 2, 2], &input).unwrap(); + assert_eq!(result, expected, "split program CPU oracle"); + println!("CHAIN_EXIT checked_words=2048 guards=16 pieces={} scratch_dwords_per_group={}", chain.pieces.len(), chain.dwords_per_group); + } + #[test] fn dispatch_chain_wave32_live_loops() { compare(32); }