From 94ab523cf6f9975327cf8da623f46d267ec29185 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:54:07 -0500 Subject: [PATCH 1/7] Recompiler: share direct DXIL scalar-load bodies in compute shaders Emit an internal function for each scalar load shape when XCL_DXIL_OUTLINE=1. Reuse the carry-aware window calculation and the existing per-word bounds. Copy helper definitions and rebuild wide return storage for dispatch pieces. --- README.md | 2 + crates/xcl/src/gpu/dxil/core_tests.rs | 46 ++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 11 +- crates/xcl/src/gpu/dxil/lower.rs | 1 + crates/xcl/src/gpu/dxil/lower_mem.rs | 134 ++++++++++++++++++------ crates/xcl/src/gpu/dxil/lower_window.rs | 2 +- crates/xcl/src/gpu/dxil/module.rs | 103 +++++++++++++++++- crates/xcl/src/gpu/dxil/module/opt.rs | 4 +- crates/xcl/src/gpu/dxil/module/split.rs | 47 +++++++-- crates/xcl/src/gpu/recomp/pso.rs | 4 +- 10 files changed, 305 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 321cc03a9e..cc470d264c 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,8 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups made up of complete native waves can use the per-lane form for branches on whole-wave masks. + With direct DXIL, `XCL_DXIL_OUTLINE=1` makes compute shaders call a shared function for each scalar + load shape. The switch defaults to off while native size and dispatch times are being measured. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..1d26b9310d 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -831,3 +831,49 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +fn scalar_load_fixture() -> Vec { + prog(&[ + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 4), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 32), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None), + ]) +} + +#[test] +fn outlined_scalar_loads_validate() { + for windows in [1, 4, 0x104] { + let opts = KernelOptions { wave64: true, split: true, mem_windows: windows, sampler_base: 0 }; + let blob = super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, true).unwrap(); + super::validate::validate(&blob).unwrap(); + let ir = super::validate::disassemble(&blob).unwrap(); + assert!(ir.contains("define internal") && ir.contains("@xcl_buffer_load_4")); + } +} + +#[test] +fn outlined_scalar_loads_match_inline_at_view_end() { + use crate::gpu::recomp::runner::{self, KernelState}; + let (wave32, native64) = match (runner::wave32_supported(), runner::wave64_supported()) { + (Ok(a), Ok(b)) => (a, b), + (Err(e), _) | (_, Err(e)) => return runner::skip_test(&e), + }; + if !wave32 && !native64 { + return runner::skip_test("no wave32 or wave64 GPU"); + } + let memory: Vec = (0..32).map(|i| 0xabc0_0000 + i).collect(); + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if (wave64 && !split && !native64) || ((!wave64 || split) && !wave32) { continue; } + let opts = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let blobs = [false, true].map(|enabled| super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, enabled).unwrap()); + for (lo, hi) in [(u32::MAX, 0), (0, 0x7f), (1, 0)] { + let mut state = KernelState::default(); + state.sgpr[126..128].copy_from_slice(&[lo, hi]); + state.sgpr[8..12].copy_from_slice(&[16, 0, 10, 0]); + let [a, b] = blobs.each_ref().map(|dxil| runner::run(dxil, &state, &memory).unwrap()); + assert_eq!(a.raw, b.raw); + assert_eq!(&b.sgpr[24..28], &[memory[4], memory[5], memory[6], 0]); + assert_eq!(&b.sgpr[32..36], &[memory[5], memory[6], 0, 0]); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..4a31b8f1e6 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -158,11 +158,12 @@ fn translate_entry( ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs + let outline = std::env::var("XCL_DXIL_OUTLINE").is_ok_and(|v| v == "1"); let code = code.to_vec(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, outline)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -186,6 +187,11 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec ((0..n).map(|k| if coherent { s.raw_uav_coherent(2 + k, 0) } else { s.raw_uav(2 + k, 0) }).collect(), None) } +#[cfg(test)] +pub(super) fn translate_outline_fixture(code: &[u8], o: KernelOptions, outline: bool) -> Result, String> { + translate_on_this_thread(code, o, Entry::Kernel, Some(false), None, 0, outline).map(|k| k.dxil) +} + fn translate_on_this_thread( code: &[u8], o: KernelOptions, @@ -193,6 +199,7 @@ fn translate_on_this_thread( compact: Option, nest: Option, tables: usize, + outline: bool, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -209,6 +216,7 @@ fn translate_on_this_thread( let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + lw.outline_smem = outline && (kernel || compute); let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); @@ -553,6 +561,7 @@ impl Lw { guard_override: None, mask_override: None, local_masks: false, + outline_smem: false, exchange_error: None, pc: 0, }; diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..f6678eb227 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -264,6 +264,7 @@ pub struct Lw { /// when it is never read whole. Set by a caller that reads back only each lane's own bit /// (the per-lane form's bridge), so no exchange meets the other half. pub local_masks: bool, + pub outline_smem: bool, } impl Lw { diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..22ee7c1ba5 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1154,28 +1154,8 @@ impl Lw { let imm = Self::fv(d, "OFFSET") as u32; let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); let soff = if soff == 125 { self.c(0) } else { self.code32(soff, None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? }; - let mut vals = if name.starts_with("s_buffer_load") { - let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2)); - let k = self.c(imm); - let off = self.add(k, soff); - self.buffer_window(d0, d1, &[Ea::U(k), Ea::U(soff)], false); - let st = self.lshrc(d1, 16); - let st = self.andc(st, 0x3FFF); - let sz = self.cmpc(Pred::Eq, st, 0); - let lim = self.mul(d2, st); - let lim = self.sel(sz, d2, lim); - let base = self.add(d0, off); - let base_aligned = self.andc(base, !3); - let raw = self.mem_ld_chunks(base_aligned, count); - let z = self.c(0); - (0..count) - .map(|i| { - let o = self.addc(off, 4 * i); - let ok = self.cmp(Pred::ULt, o, lim); - self.sel(ok, raw[i as usize], z) - }) - .collect::>() - } else { + let buffer = name.starts_with("s_buffer_load"); + if !buffer { // a repeat of a load nothing has changed since: its values (`reload`) let slot = self.reload.map(|r| super::reload::VAR_RELOAD + 16 * r.slot); if let (Some(var), Some(true)) = (slot, self.reload.map(|r| r.available)) { @@ -1185,15 +1165,16 @@ impl Lw { } return Ok(()); } - let imm = ((imm << 11) as i32 >> 11) as u32; - let b = self.sreg(sbase); - let hi = self.sreg(sbase + 1); - let k = self.c(imm); - self.window_at(hi, b, &[Ea::S(k), Ea::U(soff)], false); - let a = self.add(b, k); - let a = self.add(a, soff); - let base_aligned = self.andc(a, !3); - self.mem_ld_chunks(base_aligned, count) + } + let lo = self.sreg(sbase); + let hi = self.sreg(sbase + 1); + let size = if buffer { self.sreg(sbase + 2) } else { self.c(0) }; + let imm = self.c(if buffer { imm } else { ((imm << 11) as i32 >> 11) as u32 }); + let args = [lo, hi, size, imm, soff]; + let mut vals = if self.outline_smem { + self.call_scalar_load(count, buffer, args) + } else { + self.scalar_load(count, buffer, args) }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { @@ -1216,6 +1197,97 @@ impl Lw { Ok(()) } + fn scalar_load(&mut self, count: u32, buffer: bool, [d0, d1, d2, k, soff]: [Value; 5]) -> Vec { + if buffer { + let off = self.add(k, soff); + self.buffer_window(d0, d1, &[Ea::U(k), Ea::U(soff)], false); + let st = self.lshrc(d1, 16); + let st = self.andc(st, 0x3FFF); + let sz = self.cmpc(Pred::Eq, st, 0); + let lim = self.mul(d2, st); + let lim = self.sel(sz, d2, lim); + let base = self.add(d0, off); + let base_aligned = self.andc(base, !3); + let raw = self.mem_ld_chunks(base_aligned, count); + let z = self.c(0); + (0..count) + .map(|i| { + let o = self.addc(off, 4 * i); + let ok = self.cmp(Pred::ULt, o, lim); + self.sel(ok, raw[i as usize], z) + }) + .collect::>() + } else { + self.window_at(d1, d0, &[Ea::S(k), Ea::U(soff)], false); + let a = self.add(d0, k); + let a = self.add(a, soff); + let base_aligned = self.andc(a, !3); + self.mem_ld_chunks(base_aligned, count) + } + } + + fn call_scalar_load(&mut self, count: u32, buffer: bool, inputs: [Value; 5]) -> Vec { + use super::module::{FnAttrs, Block}; + use super::ssa::Ssa; + + let name = format!("xcl_{}_load_{count}", if buffer { "buffer" } else { "scalar" }); + let uma = if self.windowed() { self.uma_base() } else { self.c(0) }; + let mut args = vec![inputs[0], inputs[1], inputs[2], inputs[3], inputs[4], uma]; + let slot = (count > 1).then(|| self.s.m.return_slot()); + args.extend(slot); + let f = if let Some(f) = self.s.m.function(&name) { + f + } else { + let word = self.s.m.i32(); + let params: Vec<_> = args.iter().map(|&a| self.s.m.type_of(a)).collect(); + let signature = self.s.m.func_ty(word, ¶ms); + let f = self.s.m.declare(&name, signature, FnAttrs::NoInline); + let body = self.s.m.declarations(); + let caller = std::mem::replace(&mut self.s.m, body); + let ssa = std::mem::replace(&mut self.ssa, Ssa::new(word)); + let old_base = self.uma_base_val.replace(Value::Param(word, 5)); + let old_mems = self.mems.clone(); + // Root-bound handles belong to a function. Re-create the same bindings locally. + for mem in &mut self.mems { + if let Some(index) = mem.binding { + let bind = self.s.bindings[index].clone(); + let h = self.s.handle_from_binding(bind.class, bind.lower, bind.lower, bind.space, bind.lower); + mem.handle = self.s.annotate(h, bind.kind | 0x1000 | if bind.coherent { 0x4000 } else { 0 }, 0); + } + } + self.ssa.expect_preds(&mut self.s, Block(0), 0, &mut |s, v| self.init.load(s, v)); + let results = self.scalar_load(count, buffer, std::array::from_fn(|i| Value::Param(word, i as u32))); + if slot.is_some() { + let out = Value::Param(params[6], 6); + let z = self.c(0); + for (i, &v) in results.iter().enumerate().skip(1) { + let k = self.c(i as u32); + let at = self.s.m.gep(out, &[z, k]); + self.s.m.store(at, v, 4); + } + } + self.s.m.return_word(results[0]); + self.s.m.optimize(); + self.mems = old_mems; + self.uma_base_val = old_base; + self.ssa = ssa; + let body = std::mem::replace(&mut self.s.m, caller); + self.s.m.finish_helper(f, body); + f + }; + let r = self.s.m.call(f, &args); + let mut results = vec![r]; + if let Some(slot) = slot { + let z = self.c(0); + for i in 1..count { + let k = self.c(i); + let at = self.s.m.gep(slot, &[z, k]); + results.push(self.s.m.load(at, 4)); + } + } + results + } + // ------------------------------------------------------------ MUBUF / MTBUF pub fn mubuf(&mut self, d: &Decoded, name: &str) -> LResult<()> { diff --git a/crates/xcl/src/gpu/dxil/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 1f41e5817d..9db239d635 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -28,7 +28,7 @@ impl Lw { /// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`), /// hoisted to the entry block so multi-window shaders load it once rather than on every /// memory operation. - fn uma_base(&mut self) -> Value { + pub(super) fn uma_base(&mut self) -> Value { if let Some(v) = self.uma_base_val { return v; } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..d8359c5f43 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -43,6 +43,7 @@ enum TypeDef { /// A value: global variable, function, module constant or instruction result. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Value { + Param(Ty, u32), Global(u32), Func(u32), Const(u32), @@ -80,12 +81,14 @@ pub enum FnAttrs { NoUnwind, /// `noduplicate nounwind` (barriers) NoDuplicate, + NoInline, } impl FnAttrs { /// Index into the PARAMATTR table (+1; 0 = none). fn index(self) -> u64 { match self { + FnAttrs::NoInline => 5, FnAttrs::None => 0, FnAttrs::ReadNone => 1, FnAttrs::ReadOnly => 2, @@ -197,6 +200,7 @@ enum Op { Cmp(Pred, Value, Value), Select(Value, Value, Value), Extract(Value, u32), + Return(Value), Call(u32, Vec), Phi(Vec<(Value, Block)>), Load(Value, u32), @@ -248,6 +252,8 @@ pub struct Module { type_ids: HashMap, consts: Vec, const_ids: HashMap, + return_slot: Option, + helpers: std::collections::BTreeMap>, funcs: Vec, func_ids: HashMap, globals: Vec, @@ -276,6 +282,8 @@ impl Module { type_ids: HashMap::new(), consts: Vec::new(), const_ids: HashMap::new(), + return_slot: None, + helpers: Default::default(), funcs: Vec::new(), func_ids: HashMap::new(), globals: Vec::new(), @@ -509,6 +517,7 @@ impl Module { Value::Const(c) => match &self.consts[c as usize] { ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, }, + Value::Param(ty, _) => ty, Value::Inst(i) => self.insts[i as usize].ty, } } @@ -549,7 +558,7 @@ impl Module { /// Whether the current block already ends in a terminator. pub fn terminated(&self) -> bool { self.blocks[self.cur.0 as usize].last().is_some_and(|&i| { - matches!(self.insts[i as usize].op, Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Unreachable) + matches!(self.insts[i as usize].op, Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Return(_) | Op::Unreachable) }) } @@ -623,6 +632,45 @@ impl Module { let t = self.struct_elem(at, idx); self.push(Op::Extract(agg, idx), t) } + pub fn return_word(&mut self, v: Value) { + let void = self.void(); + self.push(Op::Return(v), void); + } + + /// Calls consume and read their scratch in one basic block. Every piece may + /// therefore have its own entry-block allocation for wide SMEM returns. + pub fn return_slot(&mut self) -> Value { + if let Some(slot) = self.return_slot { return slot; } + let word = self.i32(); + let words = self.array(16, word); + let current = self.current_block(); + self.set_block(Block(0)); + let old = self.set_insert_before_term(true); + let slot = self.alloca(words, 4); + self.set_insert_before_term(old); + self.set_block(current); + self.return_slot = Some(slot); + slot + } + + pub fn function(&self, name: &str) -> Option { + self.func_ids.get(name).copied() + } + + /// A helper owns its local instructions. Its symbol indices start with the caller's + /// tables and those tables grow only while the caller is suspended. + pub fn finish_helper(&mut self, f: u32, mut body: Module) { + if let Some(err) = body.error() { self.fail(err); } + self.types.clone_from(&body.types); + self.type_ids.clone_from(&body.type_ids); + self.consts.clone_from(&body.consts); + self.const_ids.clone_from(&body.const_ids); + self.funcs.clone_from(&body.funcs); + self.func_ids.clone_from(&body.func_ids); + body.helpers.clear(); + self.helpers.insert(f, std::rc::Rc::new(body)); + } + pub fn call(&mut self, f: u32, args: &[Value]) -> Value { let ret = match &self.types[self.funcs[f as usize].ty.0 as usize] { TypeDef::Func(r, p) => { @@ -858,6 +906,13 @@ impl Module { } } } + for (&f, helper) in &self.helpers { + if !fused[f as usize] { continue; } + for def in &helper.insts { + if let Op::Call(callee, _) = def.op { fused[callee as usize] = true; } + def.op.for_each_operand(|v| if let Value::Global(g) = v { gused[g as usize] = true; }); + } + } let mut gmap: Vec> = vec![None; self.globals.len()]; let mut n_globals = 0u64; for (g, used) in gused.iter().enumerate() { @@ -895,6 +950,7 @@ impl Module { } let abs = |v: Value| -> u64 { match v { + Value::Param(..) => unreachable!("parameter in entry"), Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), Value::Const(c) => const_base + c as u64, @@ -920,9 +976,13 @@ impl Module { w.record(PARAMATTR_GRP_CODE_ENTRY, &[2, FN, 0, ATTR_NOUNWIND, 0, ATTR_READONLY]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[3, FN, 0, ATTR_NOUNWIND]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[4, FN, 0, ATTR_NODUPLICATE, 0, ATTR_NOUNWIND]); + let groups = if self.helpers.is_empty() { 4 } else { + w.record(PARAMATTR_GRP_CODE_ENTRY, &[5, FN, 0, 14, 0, ATTR_NOUNWIND]); + 5 + }; w.end_block(); w.enter_block(BLOCK_PARAMATTR); - for g in 1..=4 { + for g in 1..=groups { w.record(PARAMATTR_CODE_ENTRY, &[g]); } w.end_block(); @@ -942,12 +1002,13 @@ impl Module { &[g.ty.0 as u64, ((g.addrspace as u64) << 2) | 2 | g.constant as u64, init, linkage, align, 0, 0, 0, 0, 0, 0, 0], ); } - for f in self.funcs.iter().enumerate().filter(|(i, _)| fused[*i]).map(|x| x.1) { + for (idx, f) in self.funcs.iter().enumerate().filter(|(i, _)| fused[*i]) { + let helper = self.helpers.contains_key(&(idx as u32)); // [type, cc, isproto, linkage, paramattr, align, section, visibility, // gc, unnamed_addr, prologue, dllstorage, comdat, prefix, personality] w.record( MODULE_CODE_FUNCTION, - &[f.ty.0 as u64, 0, (!f.defined) as u64, LINKAGE_EXTERNAL, f.attrs.index(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + &[f.ty.0 as u64, 0, (!(f.defined || helper)) as u64, if helper { LINKAGE_INTERNAL } else { LINKAGE_EXTERNAL }, f.attrs.index(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ); } @@ -1028,6 +1089,35 @@ impl Module { } w.end_block(); + for (&f, helper) in &self.helpers { + if !fused[f as usize] { continue; } + let TypeDef::Func(_, params) = &self.types[self.funcs[f as usize].ty.0 as usize] else { unreachable!() }; + let (blocks, positions) = helper.block_layout(); + let first = inst_base + params.len() as u64; + let mut next = first; + let mut ids = vec![0; helper.insts.len()]; + for &block in &blocks { + for &id in &helper.blocks[block] { + ids[id as usize] = next; + if !helper.is_void(helper.insts[id as usize].ty) { next += 1; } + } + } + let local_id = |v| match v { + Value::Param(_, i) => inst_base + u64::from(i), + Value::Inst(i) => ids[i as usize], + _ => abs(v), + }; + w.enter_block(BLOCK_FUNCTION); + w.record(FUNC_CODE_DECLAREBLOCKS, &[blocks.len() as u64]); + for block in blocks { + for &id in &helper.blocks[block] { + helper.write_inst(&mut w, id as usize, ids[id as usize], &local_id, &positions, &mut operands); + } + } + if let Some(err) = helper.error() { self.fail(err); } + w.end_block(); + } + w.end_block(); // module w.finish() } @@ -1145,7 +1235,7 @@ impl Module { r(a); r(b) } - Op::Cast(_, a, _) | Op::Extract(a, _) | Op::Load(a, _) | Op::CondBr(a, _, _) | Op::Alloca(_, a, _) => r(a), + Op::Return(a) | Op::Cast(_, a, _) | Op::Extract(a, _) | Op::Load(a, _) | Op::CondBr(a, _, _) | Op::Alloca(_, a, _) => r(a), Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { r(a); r(b); @@ -1208,6 +1298,7 @@ impl Module { Op::Cast(op, v, t) => w.record(FUNC_CODE_INST_CAST, &[rel(*v), t.0 as u64, *op as u64]), Op::Cmp(p, a, b) => w.record(FUNC_CODE_INST_CMP2, &[rel(*a), rel(*b), *p as u64]), Op::Select(c, t, f) => w.record(FUNC_CODE_INST_VSELECT, &[rel(*t), rel(*f), rel(*c)]), + Op::Return(v) => w.record(FUNC_CODE_INST_RET, &[rel(*v)]), Op::Extract(a, idx) => w.record(FUNC_CODE_INST_EXTRACTVAL, &[rel(*a), *idx as u64]), Op::Call(f, args) => { let fd = &self.funcs[*f as usize]; @@ -1276,6 +1367,7 @@ impl Module { Value::Const(c) => match &self.consts[c as usize] { ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, }, + Value::Param(ty, _) => ty, Value::Inst(i) => self.insts[i as usize].ty, } } @@ -1401,6 +1493,7 @@ impl Module { Op::Br(b) => InstInfo::Term(None, vec![*b]), Op::CondBr(c, t, f) => InstInfo::Term(Some(*c), vec![*t, *f]), Op::Switch(v, d, cases) => InstInfo::Term(Some(*v), std::iter::once(*d).chain(cases.iter().map(|c| c.1)).collect()), + Op::Return(v) => InstInfo::Term(Some(*v), Vec::new()), Op::Ret | Op::Unreachable => InstInfo::Term(None, Vec::new()), } } diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 230a59f9f9..5a07d6fff3 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -20,7 +20,7 @@ impl Op { f(*a); f(*b) } - Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => f(*v), + Op::Return(v) | Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => f(*v), Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { f(*a); f(*b); @@ -47,7 +47,7 @@ impl Op { *a = f(*a); *b = f(*b) } - Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => *v = f(*v), + Op::Return(v) | Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => *v = f(*v), Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { *a = f(*a); *b = f(*b); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7a88b9ae11..594dff1f0c 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -112,6 +112,8 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::Alloca(..) if self.m.return_slot == Some(Value::Inst(i)) => {} + Op::Load(ptr, _) if self.m.is_return_pointer(*ptr) => {} 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) => {} @@ -158,6 +160,12 @@ impl Shader { let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); let slab = Slab::new(&mut dst); + for &block in &plan.blocks[stage] { + for &id in &src.blocks[block.0 as usize] { + let v = Value::Inst(id); + if src.is_return_pointer(v) { src.rebuild_static(v, &mut dst.m, &mut values)?; } + } + } for &id in prefix { let def = &src.insts[id as usize]; let mut op = def.op.clone(); @@ -214,7 +222,7 @@ impl Shader { 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; } + if src.is_return_pointer(Value::Inst(i)) || (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); @@ -288,12 +296,18 @@ impl Shader { Op::Call(f, args) if self.m.funcs[*f as usize].name.starts_with("dx.op.textureLoad") && uav_load(args, &self.m))) { self.features.remove(&Feature::TypedUavLoadAdditionalFormats); } - 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 }); + let mut called = BTreeSet::new(); + for &i in self.m.blocks.iter().flatten() { + if let Op::Call(f, _) = self.m.insts[i as usize].op { called.insert(f); } + } + for m in std::iter::once(&self.m).chain(called.iter().filter_map(|f| self.m.helpers.get(f).map(|h| h.as_ref()))) { + for &i in m.blocks.iter().flatten() { + if let Op::Call(f, args) = &m.insts[i as usize].op { + if m.funcs[*f as usize].name == "dx.op.createHandleFromHeap" { + self.features.insert(if m.const_u64(args[2]) == Some(0) { + Feature::ResourceHeapIndexing + } else { Feature::SamplerHeapIndexing }); + } } } } @@ -502,7 +516,16 @@ impl Module { None } + fn is_return_pointer(&self, v: Value) -> bool { + if self.return_slot.is_none() { return false; } + if Some(v) == self.return_slot { return true; } + let Value::Inst(i) = v else { return false }; + matches!(&self.insts[i as usize].op, Op::Gep(base, indices) + if Some(*base) == self.return_slot && indices.iter().all(|i| matches!(i, Value::Const(_)))) + } + fn transport_words(&self, v: Value) -> Option { + if self.is_return_pointer(v) { return Some(0); } let def = &self.insts[inst(v)?]; match &self.types[def.ty.0 as usize] { TypeDef::Int(1..=32) | TypeDef::Float => Some(1), @@ -526,6 +549,15 @@ impl Module { 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); } + if self.is_return_pointer(v) { + let slot = dst.return_slot(); + let value = match &self.insts[id as usize].op { + Op::Gep(_, indices) => dst.gep(slot, indices), + _ => slot, + }; + map.insert(v, value); + return Some(value); + } 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); @@ -586,6 +618,7 @@ impl Module { type_ids: self.type_ids.clone(), consts: self.consts.clone(), const_ids: self.const_ids.clone(), + helpers: self.helpers.clone(), funcs: self.funcs.clone(), func_ids: self.func_ids.clone(), globals: self.globals.clone(), diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8b0cde0f1..6baec1dd7d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -905,7 +905,7 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT", "XCL_DXIL_OUTLINE"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -1997,7 +1997,7 @@ mod shader_cache_tests { #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT", "XCL_DXIL_OUTLINE"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); From a42b50e11cb2d0c7d00b96522c67016240edfa95 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:20:08 -0500 Subject: [PATCH 2/7] Recompiler: mark the private scalar-load output parameter noalias Wide outlined loads write through one pointer into caller-owned storage. Record that guarantee on the seventh parameter so DXIL-to-SPIR-V translation can pass it in the logical addressing model. --- crates/xcl/src/gpu/dxil/core_tests.rs | 5 ++++- crates/xcl/src/gpu/dxil/lower_mem.rs | 3 ++- crates/xcl/src/gpu/dxil/module.rs | 15 ++++++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 1d26b9310d..0e30d2fd1c 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -847,7 +847,10 @@ fn outlined_scalar_loads_validate() { let blob = super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, true).unwrap(); super::validate::validate(&blob).unwrap(); let ir = super::validate::disassemble(&blob).unwrap(); - assert!(ir.contains("define internal") && ir.contains("@xcl_buffer_load_4")); + for name in ["@xcl_buffer_load_4(", "@xcl_scalar_load_2("] { + let definition = ir.lines().find(|l| l.starts_with("define internal") && l.contains(name)).expect("wide load helper"); + assert!(definition.contains("[16 x i32]* noalias"), "{definition}"); + } } } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 22ee7c1ba5..af44a47d5a 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1241,7 +1241,8 @@ impl Lw { let word = self.s.m.i32(); let params: Vec<_> = args.iter().map(|&a| self.s.m.type_of(a)).collect(); let signature = self.s.m.func_ty(word, ¶ms); - let f = self.s.m.declare(&name, signature, FnAttrs::NoInline); + let attrs = if slot.is_some() { FnAttrs::NoInlineScalarLoadOut } else { FnAttrs::NoInline }; + let f = self.s.m.declare(&name, signature, attrs); let body = self.s.m.declarations(); let caller = std::mem::replace(&mut self.s.m, body); let ssa = std::mem::replace(&mut self.ssa, Ssa::new(word)); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d8359c5f43..d9e2325620 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -82,6 +82,8 @@ pub enum FnAttrs { /// `noduplicate nounwind` (barriers) NoDuplicate, NoInline, + /// A wide scalar load takes six words and a private, non-aliasing output pointer. + NoInlineScalarLoadOut, } impl FnAttrs { @@ -89,6 +91,7 @@ impl FnAttrs { fn index(self) -> u64 { match self { FnAttrs::NoInline => 5, + FnAttrs::NoInlineScalarLoadOut => 6, FnAttrs::None => 0, FnAttrs::ReadNone => 1, FnAttrs::ReadOnly => 2, @@ -976,15 +979,23 @@ impl Module { w.record(PARAMATTR_GRP_CODE_ENTRY, &[2, FN, 0, ATTR_NOUNWIND, 0, ATTR_READONLY]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[3, FN, 0, ATTR_NOUNWIND]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[4, FN, 0, ATTR_NODUPLICATE, 0, ATTR_NOUNWIND]); + let scalar_out = self.funcs.iter().zip(&fused).any(|(f, used)| *used && f.attrs == FnAttrs::NoInlineScalarLoadOut); let groups = if self.helpers.is_empty() { 4 } else { - w.record(PARAMATTR_GRP_CODE_ENTRY, &[5, FN, 0, 14, 0, ATTR_NOUNWIND]); + w.record(PARAMATTR_GRP_CODE_ENTRY, &[5, FN, 0, ATTR_NOINLINE, 0, ATTR_NOUNWIND]); 5 }; + if scalar_out { + // LLVM attribute index 0 is the return value, 1 is the first parameter. + w.record(PARAMATTR_GRP_CODE_ENTRY, &[6, 7, 0, ATTR_NOALIAS]); + } w.end_block(); w.enter_block(BLOCK_PARAMATTR); for g in 1..=groups { w.record(PARAMATTR_CODE_ENTRY, &[g]); } + if scalar_out { + w.record(PARAMATTR_CODE_ENTRY, &[6, 5]); + } w.end_block(); self.write_types(&mut w); @@ -1391,7 +1402,9 @@ const MODULE_CODE_FUNCTION: u32 = 8; const PARAMATTR_CODE_ENTRY: u32 = 2; const PARAMATTR_GRP_CODE_ENTRY: u32 = 3; +const ATTR_NOALIAS: u64 = 9; const ATTR_NODUPLICATE: u64 = 12; +const ATTR_NOINLINE: u64 = 14; const ATTR_NOUNWIND: u64 = 18; const ATTR_READNONE: u64 = 20; const ATTR_READONLY: u64 = 21; From 62658dfc16fd595d346c7adbc4a7a11dfc156c17 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:56:55 -0500 Subject: [PATCH 3/7] Recompiler: outline repeated load shapes and scan emitted DXIL helpers Count lowered sites per scalar-load form and width, excluding available reloads and counting compact representatives once. Four sites retain the size reduction while substantially reducing the programs that grow. Use reachable helper instructions for feature detection and symbol use. Keep globals and nested helper definitions when transferring the completed body. Validate a shader whose only wide arithmetic and FMad occur in a nested helper. --- README.md | 4 +- crates/xcl/src/gpu/dxil/core_tests.rs | 26 +++++ crates/xcl/src/gpu/dxil/kernel.rs | 19 +++- crates/xcl/src/gpu/dxil/lower.rs | 2 +- crates/xcl/src/gpu/dxil/lower_mem.rs | 31 ++++-- crates/xcl/src/gpu/dxil/module.rs | 128 ++++++++++++++++-------- crates/xcl/src/gpu/dxil/module/split.rs | 31 +++--- crates/xcl/src/gpu/dxil/shader.rs | 19 +--- 8 files changed, 170 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index cc470d264c..db25d0e83a 100644 --- a/README.md +++ b/README.md @@ -213,8 +213,8 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups made up of complete native waves can use the per-lane form for branches on whole-wave masks. - With direct DXIL, `XCL_DXIL_OUTLINE=1` makes compute shaders call a shared function for each scalar - load shape. The switch defaults to off while native size and dispatch times are being measured. + With direct DXIL, `XCL_DXIL_OUTLINE=1` lets compute shaders share a scalar-load function when its + addressing form and width occur at four or more emitted sites. The switch defaults to off while native size and dispatch times are being measured. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 0e30d2fd1c..aa71eeeb2f 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -837,9 +837,35 @@ fn scalar_load_fixture() -> Vec { ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("SOFFSET", 125)], None), ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 4), ("SOFFSET", 125)], None), ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 32), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 40), ("SBASE", 4), ("OFFSET", 8), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 44), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 48), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 50), ("SBASE", 4), ("OFFSET", 8), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 52), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None), ]) } +#[test] +fn scalar_load_threshold_counts_emitted_sites_per_shape() { + let threshold = super::lower_mem::MIN_OUTLINE_SITES; + let opts = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + for n in [threshold - 1, threshold] { + let mut code = Vec::new(); + for site in 0..n { + for _ in 0..2 { + // The second load of the same address is a reload hit. + code.extend(encode("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), + ("OFFSET", u64::from(site) * 4), ("SOFFSET", 125)], None).unwrap()); + } + } + code.extend(prog(&[("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 36), ("SBASE", 4), ("SOFFSET", 125)], None)])); + let blob = super::kernel::translate_outline_fixture(&code, opts, true).unwrap(); + let ir = super::validate::disassemble(&blob).unwrap(); + assert_eq!(ir.contains("@xcl_scalar_load_2("), n == threshold); + assert!(!ir.contains("@xcl_buffer_load_2(")); + } +} + #[test] fn outlined_scalar_loads_validate() { for windows in [1, 4, 0x104] { diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 4a31b8f1e6..ed8ad196c4 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -216,7 +216,6 @@ fn translate_on_this_thread( let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); - lw.outline_smem = outline && (kernel || compute); let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); @@ -344,6 +343,22 @@ fn translate_on_this_thread( // scalar loads the program repeats keep their first values (compute programs and kernels: // the other stages enter their code by edges the CFG does not hold) let reloads = if follow_loads { super::reload::analyze(&cfg) } else { Default::default() }; + if outline && follow_loads { + // Compact lowering emits each representative once and does not substitute reloads. + let mut count_block = |b: usize| { + for &i in &cfg.blocks[b].insts { + if plan.is_none() && reloads.get(b, i).is_some_and(|r| r.available) { continue; } + if let Some((buffer, words)) = super::lower_mem::scalar_load_shape(cfg.insts[i].inst.name) { + lw.scalar_load_sites[buffer as usize][words.ilog2() as usize] += 1; + } + } + }; + if let Some(p) = &plan { + for &r in &p.rep { count_block(p.order[r]); } + } else { + for &b in &cfg.rpo { count_block(b); } + } + } let mut gs_entry: Option = None; if let Some(p) = &plan { match nest { @@ -561,7 +576,7 @@ impl Lw { guard_override: None, mask_override: None, local_masks: false, - outline_smem: false, + scalar_load_sites: [[0; 5]; 2], exchange_error: None, pc: 0, }; diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index f6678eb227..b41c428f1c 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -264,7 +264,7 @@ pub struct Lw { /// when it is never read whole. Set by a caller that reads back only each lane's own bit /// (the per-lane form's bridge), so no exchange meets the other half. pub local_masks: bool, - pub outline_smem: bool, + pub scalar_load_sites: [[u32; 5]; 2], } impl Lw { diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index af44a47d5a..e1b77602f1 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -151,6 +151,25 @@ pub struct FmtComp1 { pub dflt: Value, } +pub(super) const MIN_OUTLINE_SITES: u32 = 4; + +pub(super) fn scalar_load_shape(name: &str) -> Option<(bool, u32)> { + let (buffer, width) = if let Some(width) = name.strip_prefix("S_BUFFER_LOAD_") { + (true, width) + } else { + (false, name.strip_prefix("S_LOAD_")?) + }; + let count = match width { + "DWORD" => 1, + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => return None, + }; + Some((buffer, count)) +} + impl Lw { /// Runs `f` on the active memory window (`mem`, `mem1`.. at u2.., or descriptor heap /// when `self.heap_mem` is set via `XCL_HEAP_WINDOWS`), returning `out_tys.len()` values @@ -1141,20 +1160,12 @@ impl Lw { self.write64(&Dst::S(sdata), z, z); return Ok(()); } - let count = match name.trim_start_matches("s_buffer_load_").trim_start_matches("s_load_") { - "dword" => 1, - "dwordx2" => 2, - "dwordx4" => 4, - "dwordx8" => 8, - "dwordx16" => 16, - _ => return err(d, "SMEM"), - }; + let Some((buffer, count)) = scalar_load_shape(d.inst.name) else { return err(d, "SMEM") }; let sdata = Self::field(d, "SDATA"); let sbase = Self::field(d, "SBASE"); let imm = Self::fv(d, "OFFSET") as u32; let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); let soff = if soff == 125 { self.c(0) } else { self.code32(soff, None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? }; - let buffer = name.starts_with("s_buffer_load"); if !buffer { // a repeat of a load nothing has changed since: its values (`reload`) let slot = self.reload.map(|r| super::reload::VAR_RELOAD + 16 * r.slot); @@ -1171,7 +1182,7 @@ impl Lw { let size = if buffer { self.sreg(sbase + 2) } else { self.c(0) }; let imm = self.c(if buffer { imm } else { ((imm << 11) as i32 >> 11) as u32 }); let args = [lo, hi, size, imm, soff]; - let mut vals = if self.outline_smem { + let mut vals = if self.scalar_load_sites[buffer as usize][count.ilog2() as usize] >= MIN_OUTLINE_SITES { self.call_scalar_load(count, buffer, args) } else { self.scalar_load(count, buffer, args) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d9e2325620..9305b48076 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -670,7 +670,8 @@ impl Module { self.const_ids.clone_from(&body.const_ids); self.funcs.clone_from(&body.funcs); self.func_ids.clone_from(&body.func_ids); - body.helpers.clear(); + self.globals.clone_from(&body.globals); + self.helpers = std::mem::take(&mut body.helpers); self.helpers.insert(f, std::rc::Rc::new(body)); } @@ -889,15 +890,11 @@ impl Module { Value::Func(f) => fused[f as usize] = true, _ => {} }; - for &b in &order { - for &i in &self.blocks[b] { - let op = &self.insts[i as usize].op; - if let Op::Call(f, _) = op { - mark(Value::Func(*f)); - } - op.for_each_operand(&mut mark); - } - } + self.any_emitted_inst(|_, op, _| { + if let Op::Call(f, _) = op { mark(Value::Func(*f)); } + op.for_each_operand(&mut mark); + false + }); for c in &self.consts { if let ConstDef::Aggregate(_, e) = c { e.iter().copied().for_each(&mut mark); @@ -909,13 +906,6 @@ impl Module { } } } - for (&f, helper) in &self.helpers { - if !fused[f as usize] { continue; } - for def in &helper.insts { - if let Op::Call(callee, _) = def.op { fused[callee as usize] = true; } - def.op.for_each_operand(|v| if let Value::Global(g) = v { gused[g as usize] = true; }); - } - } let mut gmap: Vec> = vec![None; self.globals.len()]; let mut n_globals = 0u64; for (g, used) in gused.iter().enumerate() { @@ -1510,40 +1500,54 @@ impl Module { Op::Ret | Op::Unreachable => InstInfo::Term(None, Vec::new()), } } - /// Whether an instruction of the entry function produces or consumes a - /// value of type `t` (the shader-flag rules key off instruction types). /// The 64-bit integer and double types, if already interned (lookup /// without adding them to the type table). pub fn existing_i64_f64(&self) -> (Option, Option) { (self.type_ids.get(&TypeDef::Int(64)).copied(), self.type_ids.get(&TypeDef::Double).copied()) } - /// Whether the entry uses a D3D11.1 double extension through plain - /// instructions: double `fdiv`, or conversions between double and - /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). + /// Visit instructions in reachable blocks, following calls into emitted helpers. + fn any_emitted_inst(&self, mut test: impl FnMut(&Module, &Op, Ty) -> bool) -> bool { + let mut pending = vec![self]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(body) = pending.pop() { + for block in body.block_layout().0 { + for &i in &body.blocks[block] { + let d = &body.insts[i as usize]; + if test(body, &d.op, d.ty) { return true; } + if let Op::Call(f, _) = &d.op { + if let Some(helper) = self.helpers.get(f) { + if seen.insert(*f) { pending.push(helper.as_ref()); } + } + } + } + } + } + false + } + + pub fn uses_fmad(&self) -> bool { + self.any_emitted_inst(|m, op, _| matches!(op, Op::Call(f, args) + if m.funcs[*f as usize].name.starts_with("dx.op.tertiary.") + && args.first().and_then(|&v| m.const_u64(v)) == Some(46))) + } + + /// D3D11.1 double extensions include double division and integer conversions. pub fn uses_double_extensions(&self) -> bool { - let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; - self.insts.iter().any(|d| match &d.op { - Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, - Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + let Some(&f64) = self.type_ids.get(&TypeDef::Double) else { return false }; + self.any_emitted_inst(|m, op, ty| match op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => m.value_ty(*v) == f64, Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, _ => false, }) } + pub fn insts_use_type(&self, t: Ty) -> bool { - self.blocks.iter().flatten().any(|&i| { - let d = &self.insts[i as usize]; - if d.ty == t { - return true; - } - let ops: Vec = match self.inst_info(i) { - InstInfo::Call(_, a) => a.to_vec(), - InstInfo::Phi(l) => l.iter().map(|p| p.0).collect(), - InstInfo::Load(p) => vec![p], - InstInfo::Store(p, v) => vec![p, v], - InstInfo::Other(v) => v, - InstInfo::Term(c, _) => c.into_iter().collect(), - }; - ops.into_iter().any(|v| self.value_ty(v) == t) + self.any_emitted_inst(|m, op, ty| { + if ty == t { return true; } + let mut used = false; + op.for_each_operand(|v| used |= m.value_ty(v) == t); + used }) } /// True if any surviving `dx.op.annotateHandle` call carries the `IsROV` flag (`0x2000`). @@ -1648,6 +1652,50 @@ impl Module { mod tests { use super::*; + #[test] + fn feature_scans_follow_only_reachable_helper_code() { + use crate::gpu::dxil::{container::Stage, shader::{Feature, Shader}, validate}; + let mut shader = Shader::new(Stage::Compute, (6, 6)); + shader.require(Feature::DisableMathRefactoring); + let m = &mut shader.m; + let (word, wide, double, float) = (m.i32(), m.i64(), m.f64(), m.f32()); + let sig = m.func_ty(word, &[word]); + let outer = m.declare("outer", sig, FnAttrs::NoInline); + let mut outer_body = m.declarations(); + let inner = outer_body.declare("inner", sig, FnAttrs::NoInline); + let mut body = outer_body.declarations(); + let p = Value::Param(word, 0); + let w = body.cast(CastOp::ZExt, p, wide); + let d = body.cast(CastOp::UIToFP, w, double); + let v = body.cast(CastOp::FPTrunc, d, float); + let fm_ty = body.func_ty(float, &[word, float, float, float]); + let fm = body.declare("dx.op.tertiary.f32", fm_ty, FnAttrs::ReadNone); + let opcode = body.i32c(46); + let mad = body.call(fm, &[opcode, v, v, v]); + let result = body.bitcast(mad, word); + let shared = body.global("helper_word", word, 3, None, false, 4); + body.store(shared, result, 4); + body.return_word(result); + outer_body.finish_helper(inner, body); + let v = outer_body.call(inner, &[p]); + outer_body.return_word(v); + m.finish_helper(outer, outer_body); + let dead = m.new_block(); + m.set_block(dead); + let arg = m.i32c(1); + m.call(outer, &[arg]); + m.ret(); + m.set_block(m.entry_block()); + assert!(!m.insts_use_type(wide) && !m.uses_double_extensions() && !m.uses_fmad()); + m.call(outer, &[arg]); + m.ret(); + assert!(m.insts_use_type(wide) && m.insts_use_type(double)); + assert!(m.uses_double_extensions() && m.uses_fmad()); + let blob = shader.try_finish([1, 1, 1], None).unwrap(); + validate::validate(&blob).unwrap(); + } + + #[test] fn sign_extension_does_not_intern_unrelated_integer_types() { let mut wide = Module::new(); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 594dff1f0c..3b8372004e 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -292,25 +292,22 @@ impl Shader { // typed UAV loads (`texture_load` without a mip): the whole program's flag stays only on // the pieces that have one, the validator wants flags to match usage let uav_load = |args: &[Value], m: &Module| args.get(2).is_some_and(|&mip| matches!(mip, Value::Const(c) if matches!(m.consts[c as usize], super::ConstDef::Undef(_)))); - if !self.m.blocks.iter().flatten().any(|&i| matches!(&self.m.insts[i as usize].op, - Op::Call(f, args) if self.m.funcs[*f as usize].name.starts_with("dx.op.textureLoad") && uav_load(args, &self.m))) { - self.features.remove(&Feature::TypedUavLoadAdditionalFormats); - } - let mut called = BTreeSet::new(); - for &i in self.m.blocks.iter().flatten() { - if let Op::Call(f, _) = self.m.insts[i as usize].op { called.insert(f); } - } - for m in std::iter::once(&self.m).chain(called.iter().filter_map(|f| self.m.helpers.get(f).map(|h| h.as_ref()))) { - for &i in m.blocks.iter().flatten() { - if let Op::Call(f, args) = &m.insts[i as usize].op { - if m.funcs[*f as usize].name == "dx.op.createHandleFromHeap" { - self.features.insert(if m.const_u64(args[2]) == Some(0) { - Feature::ResourceHeapIndexing - } else { Feature::SamplerHeapIndexing }); - } + let mut typed_load = false; + self.m.any_emitted_inst(|m, op, _| { + if let Op::Call(f, args) = op { + let name = &m.funcs[*f as usize].name; + if name.starts_with("dx.op.textureLoad") && uav_load(args, m) { + typed_load = true; + } + if name == "dx.op.createHandleFromHeap" { + self.features.insert(if m.const_u64(args[2]) == Some(0) { + Feature::ResourceHeapIndexing + } else { Feature::SamplerHeapIndexing }); } } - } + false + }); + if !typed_load { self.features.remove(&Feature::TypedUavLoadAdditionalFormats); } } } diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..ce58efa8be 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -601,7 +601,7 @@ impl Shader { /// `dx.op.tertiary.*` `FMad` (op 46), since DXIL validation forbids `FMad` /// together with `DisableMathRefactoring`. pub(super) fn feature_flags(&self) -> (u64, u64) { - let drop_no_refactor = self.features.contains(&Feature::DisableMathRefactoring) && self.uses_fmad(); + let drop_no_refactor = self.features.contains(&Feature::DisableMathRefactoring) && self.m.uses_fmad(); let mut flags = 0u64; let mut sfi0 = 0u64; for &f in &self.features { @@ -613,23 +613,6 @@ impl Shader { } (flags, sfi0) } - - /// True if any surviving instruction calls `dx.op.tertiary.*` with opcode - /// `46` (`Tertiary::FMad`). - fn uses_fmad(&self) -> bool { - use super::module::{Block, InstInfo}; - for b in 0..self.m.block_count() { - for &inst in self.m.block_insts(Block(b as u32)) { - let InstInfo::Call(name, args) = self.m.inst_info(inst) else { continue }; - if name.starts_with("dx.op.tertiary.") - && args.first().and_then(|&v| self.m.const_u64(v)) == Some(46) - { - return true; - } - } - } - false - } } /// The function attributes DXC gives each `dx.op` declaration (DXC 1.9 From e94780e594b98635f6c7ca7650af6e385a8ed11b Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:00:47 -0500 Subject: [PATCH 4/7] Recompiler: keep graphics shader caches active during compute outlining --- crates/xcl/src/gpu/recomp/pso.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 6baec1dd7d..3ebb03ce91 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -905,9 +905,10 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT", "XCL_DXIL_OUTLINE"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] .iter() .any(|name| present(name)) + && (stage != Stage::Compute || !present("XCL_DXIL_OUTLINE")) && (stage != Stage::Pixel || ![ "XCL_DEBUG_MAGENTA", @@ -1997,11 +1998,15 @@ mod shader_cache_tests { #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT", "XCL_DXIL_OUTLINE"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); } + assert!(!cache_allowed(Stage::Compute, |v| v == "XCL_DXIL_OUTLINE")); + for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert!(cache_allowed(stage, |v| v == "XCL_DXIL_OUTLINE")); + } for name in [ "XCL_DEBUG_MAGENTA", "XCL_DEBUG_LOD0", From 534cceea3679938d2126bd7951da000d72a09acd Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:27:55 -0500 Subject: [PATCH 5/7] Recompiler: preserve live scalar-load results across helper calls --- crates/xcl/src/gpu/dxil/core_tests.rs | 46 +++++++++++++++++++++++++- crates/xcl/src/gpu/dxil/lower_mem.rs | 47 ++++++++++++--------------- crates/xcl/src/gpu/dxil/module.rs | 39 ++++++++-------------- crates/xcl/src/gpu/dxil/module/opt.rs | 4 +-- 4 files changed, 82 insertions(+), 54 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index aa71eeeb2f..4b03f56edd 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -874,7 +874,7 @@ fn outlined_scalar_loads_validate() { super::validate::validate(&blob).unwrap(); let ir = super::validate::disassemble(&blob).unwrap(); for name in ["@xcl_buffer_load_4(", "@xcl_scalar_load_2("] { - let definition = ir.lines().find(|l| l.starts_with("define internal") && l.contains(name)).expect("wide load helper"); + let definition = ir.lines().find(|l| l.starts_with("define internal void") && l.contains(name)).expect("wide load helper"); assert!(definition.contains("[16 x i32]* noalias"), "{definition}"); } } @@ -906,3 +906,47 @@ fn outlined_scalar_loads_match_inline_at_view_end() { } } } + +#[test] +fn outlined_scalar_loads_preserve_distinct_image_descriptors() { + use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT; + + if !runner::wave32_supported().unwrap_or(false) { + return runner::skip_test("no wave32 GPU"); + } + + // Keep four different descriptor indices live across calls to the same eight-word helper. + let mut code = Vec::new(); + let mut memory = Vec::new(); + for i in 0..4 { + code.extend(encode("S_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 16 + 8 * i), ("SBASE", 4), ("OFFSET", 32 * i), ("SOFFSET", 125)], None).unwrap()); + memory.extend_from_slice(&[2 * i as u32, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]); + } + for i in 0..4 { + code.extend(encode("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 4 + i), ("VADDR", 0), ("SRSRC", 4 + 2 * i), ("DMASK", 1), ("DIM", 1), ("UNORM", 1)], None).unwrap()); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let textures: Vec<_> = (0..4).map(|_| TestTexture { + dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 32, height: 1, depth: 1, + texel_bytes: 4, data: vec![0; 128], uav: true, + }).collect(); + let mut state = KernelState::default(); + for (lane, vgprs) in state.vgpr.iter_mut().enumerate() { + vgprs[0] = lane as u32; + for i in 0..4 { vgprs[4 + i] = 0x12340000 + (i as u32) * 32 + lane as u32; } + } + let opts = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for outline in [false, true] { + let dxil = super::kernel::translate_outline_fixture(&code, opts, outline).unwrap(); + let result = runner::run_with(&dxil, &state, &memory, &textures, &[]).unwrap(); + assert_eq!(result.textures.len(), textures.len()); + for (i, bytes) in result.textures.iter().enumerate() { + assert_eq!(bytes.len(), 32 * 4); + for (lane, texel) in bytes.chunks_exact(4).enumerate() { + let expected = 0x12340000 + i as u32 * 32 + lane as u32; + assert_eq!(u32::from_le_bytes(texel.try_into().unwrap()), expected, "outline={outline} texture={i} lane={lane}"); + } + } + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index e1b77602f1..e9ac60e448 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1243,17 +1243,16 @@ impl Lw { let name = format!("xcl_{}_load_{count}", if buffer { "buffer" } else { "scalar" }); let uma = if self.windowed() { self.uma_base() } else { self.c(0) }; - let mut args = vec![inputs[0], inputs[1], inputs[2], inputs[3], inputs[4], uma]; - let slot = (count > 1).then(|| self.s.m.return_slot()); - args.extend(slot); + let slot = self.s.m.return_slot(); + let args = [inputs[0], inputs[1], inputs[2], inputs[3], inputs[4], uma, slot]; let f = if let Some(f) = self.s.m.function(&name) { f } else { let word = self.s.m.i32(); let params: Vec<_> = args.iter().map(|&a| self.s.m.type_of(a)).collect(); - let signature = self.s.m.func_ty(word, ¶ms); - let attrs = if slot.is_some() { FnAttrs::NoInlineScalarLoadOut } else { FnAttrs::NoInline }; - let f = self.s.m.declare(&name, signature, attrs); + let void = self.s.m.void(); + let signature = self.s.m.func_ty(void, ¶ms); + let f = self.s.m.declare(&name, signature, FnAttrs::NoInlineScalarLoadOut); let body = self.s.m.declarations(); let caller = std::mem::replace(&mut self.s.m, body); let ssa = std::mem::replace(&mut self.ssa, Ssa::new(word)); @@ -1269,16 +1268,16 @@ impl Lw { } self.ssa.expect_preds(&mut self.s, Block(0), 0, &mut |s, v| self.init.load(s, v)); let results = self.scalar_load(count, buffer, std::array::from_fn(|i| Value::Param(word, i as u32))); - if slot.is_some() { - let out = Value::Param(params[6], 6); - let z = self.c(0); - for (i, &v) in results.iter().enumerate().skip(1) { - let k = self.c(i as u32); - let at = self.s.m.gep(out, &[z, k]); - self.s.m.store(at, v, 4); - } + // Consecutive calls may feed distinct live descriptor indices. Passing every word + // through caller storage avoids a native driver reusing the later call's scalar return. + let out = Value::Param(params[6], 6); + let z = self.c(0); + for (i, v) in results.into_iter().enumerate() { + let k = self.c(i as u32); + let at = self.s.m.gep(out, &[z, k]); + self.s.m.store(at, v, 4); } - self.s.m.return_word(results[0]); + self.s.m.ret(); self.s.m.optimize(); self.mems = old_mems; self.uma_base_val = old_base; @@ -1287,17 +1286,13 @@ impl Lw { self.s.m.finish_helper(f, body); f }; - let r = self.s.m.call(f, &args); - let mut results = vec![r]; - if let Some(slot) = slot { - let z = self.c(0); - for i in 1..count { - let k = self.c(i); - let at = self.s.m.gep(slot, &[z, k]); - results.push(self.s.m.load(at, 4)); - } - } - results + self.s.m.call(f, &args); + let z = self.c(0); + (0..count).map(|i| { + let k = self.c(i); + let at = self.s.m.gep(slot, &[z, k]); + self.s.m.load(at, 4) + }).collect() } // ------------------------------------------------------------ MUBUF / MTBUF diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 9305b48076..64009f367e 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -81,8 +81,7 @@ pub enum FnAttrs { NoUnwind, /// `noduplicate nounwind` (barriers) NoDuplicate, - NoInline, - /// A wide scalar load takes six words and a private, non-aliasing output pointer. + /// A scalar load takes six words and a private, non-aliasing output pointer. NoInlineScalarLoadOut, } @@ -90,8 +89,7 @@ impl FnAttrs { /// Index into the PARAMATTR table (+1; 0 = none). fn index(self) -> u64 { match self { - FnAttrs::NoInline => 5, - FnAttrs::NoInlineScalarLoadOut => 6, + FnAttrs::NoInlineScalarLoadOut => 5, FnAttrs::None => 0, FnAttrs::ReadNone => 1, FnAttrs::ReadOnly => 2, @@ -203,7 +201,6 @@ enum Op { Cmp(Pred, Value, Value), Select(Value, Value, Value), Extract(Value, u32), - Return(Value), Call(u32, Vec), Phi(Vec<(Value, Block)>), Load(Value, u32), @@ -561,7 +558,7 @@ impl Module { /// Whether the current block already ends in a terminator. pub fn terminated(&self) -> bool { self.blocks[self.cur.0 as usize].last().is_some_and(|&i| { - matches!(self.insts[i as usize].op, Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Return(_) | Op::Unreachable) + matches!(self.insts[i as usize].op, Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Unreachable) }) } @@ -635,13 +632,9 @@ impl Module { let t = self.struct_elem(at, idx); self.push(Op::Extract(agg, idx), t) } - pub fn return_word(&mut self, v: Value) { - let void = self.void(); - self.push(Op::Return(v), void); - } /// Calls consume and read their scratch in one basic block. Every piece may - /// therefore have its own entry-block allocation for wide SMEM returns. + /// therefore have its own entry-block allocation for SMEM results. pub fn return_slot(&mut self) -> Value { if let Some(slot) = self.return_slot { return slot; } let word = self.i32(); @@ -970,17 +963,14 @@ impl Module { w.record(PARAMATTR_GRP_CODE_ENTRY, &[3, FN, 0, ATTR_NOUNWIND]); w.record(PARAMATTR_GRP_CODE_ENTRY, &[4, FN, 0, ATTR_NODUPLICATE, 0, ATTR_NOUNWIND]); let scalar_out = self.funcs.iter().zip(&fused).any(|(f, used)| *used && f.attrs == FnAttrs::NoInlineScalarLoadOut); - let groups = if self.helpers.is_empty() { 4 } else { - w.record(PARAMATTR_GRP_CODE_ENTRY, &[5, FN, 0, ATTR_NOINLINE, 0, ATTR_NOUNWIND]); - 5 - }; if scalar_out { + w.record(PARAMATTR_GRP_CODE_ENTRY, &[5, FN, 0, ATTR_NOINLINE, 0, ATTR_NOUNWIND]); // LLVM attribute index 0 is the return value, 1 is the first parameter. w.record(PARAMATTR_GRP_CODE_ENTRY, &[6, 7, 0, ATTR_NOALIAS]); } w.end_block(); w.enter_block(BLOCK_PARAMATTR); - for g in 1..=groups { + for g in 1..=4 { w.record(PARAMATTR_CODE_ENTRY, &[g]); } if scalar_out { @@ -1236,7 +1226,7 @@ impl Module { r(a); r(b) } - Op::Return(a) | Op::Cast(_, a, _) | Op::Extract(a, _) | Op::Load(a, _) | Op::CondBr(a, _, _) | Op::Alloca(_, a, _) => r(a), + Op::Cast(_, a, _) | Op::Extract(a, _) | Op::Load(a, _) | Op::CondBr(a, _, _) | Op::Alloca(_, a, _) => r(a), Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { r(a); r(b); @@ -1299,7 +1289,6 @@ impl Module { Op::Cast(op, v, t) => w.record(FUNC_CODE_INST_CAST, &[rel(*v), t.0 as u64, *op as u64]), Op::Cmp(p, a, b) => w.record(FUNC_CODE_INST_CMP2, &[rel(*a), rel(*b), *p as u64]), Op::Select(c, t, f) => w.record(FUNC_CODE_INST_VSELECT, &[rel(*t), rel(*f), rel(*c)]), - Op::Return(v) => w.record(FUNC_CODE_INST_RET, &[rel(*v)]), Op::Extract(a, idx) => w.record(FUNC_CODE_INST_EXTRACTVAL, &[rel(*a), *idx as u64]), Op::Call(f, args) => { let fd = &self.funcs[*f as usize]; @@ -1496,7 +1485,6 @@ impl Module { Op::Br(b) => InstInfo::Term(None, vec![*b]), Op::CondBr(c, t, f) => InstInfo::Term(Some(*c), vec![*t, *f]), Op::Switch(v, d, cases) => InstInfo::Term(Some(*v), std::iter::once(*d).chain(cases.iter().map(|c| c.1)).collect()), - Op::Return(v) => InstInfo::Term(Some(*v), Vec::new()), Op::Ret | Op::Unreachable => InstInfo::Term(None, Vec::new()), } } @@ -1659,10 +1647,11 @@ mod tests { shader.require(Feature::DisableMathRefactoring); let m = &mut shader.m; let (word, wide, double, float) = (m.i32(), m.i64(), m.f64(), m.f32()); - let sig = m.func_ty(word, &[word]); - let outer = m.declare("outer", sig, FnAttrs::NoInline); + let void = m.void(); + let sig = m.func_ty(void, &[word]); + let outer = m.declare("outer", sig, FnAttrs::NoUnwind); let mut outer_body = m.declarations(); - let inner = outer_body.declare("inner", sig, FnAttrs::NoInline); + let inner = outer_body.declare("inner", sig, FnAttrs::NoUnwind); let mut body = outer_body.declarations(); let p = Value::Param(word, 0); let w = body.cast(CastOp::ZExt, p, wide); @@ -1675,10 +1664,10 @@ mod tests { let result = body.bitcast(mad, word); let shared = body.global("helper_word", word, 3, None, false, 4); body.store(shared, result, 4); - body.return_word(result); + body.ret(); outer_body.finish_helper(inner, body); - let v = outer_body.call(inner, &[p]); - outer_body.return_word(v); + outer_body.call(inner, &[p]); + outer_body.ret(); m.finish_helper(outer, outer_body); let dead = m.new_block(); m.set_block(dead); diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 5a07d6fff3..230a59f9f9 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -20,7 +20,7 @@ impl Op { f(*a); f(*b) } - Op::Return(v) | Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => f(*v), + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => f(*v), Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { f(*a); f(*b); @@ -47,7 +47,7 @@ impl Op { *a = f(*a); *b = f(*b) } - Op::Return(v) | Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => *v = f(*v), + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => *v = f(*v), Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { *a = f(*a); *b = f(*b); From 89e1a91d348967997afefdea2eb29f71a254c057 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:02:20 -0500 Subject: [PATCH 6/7] Recompiler: gate scalar-load outlining on the selected NVIDIA adapter --- README.md | 4 ++-- crates/xcl/src/gpu/adapter.rs | 13 +++++++++++++ crates/xcl/src/gpu/dxil/core_tests.rs | 14 ++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 20 +++++++++++++++++++- crates/xcl/src/gpu/recomp/pso.rs | 11 +++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 3 +++ crates/xcl/tests/gpu_compute_e2e.rs | 2 +- 7 files changed, 61 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index db25d0e83a..ce77c714fa 100644 --- a/README.md +++ b/README.md @@ -213,8 +213,8 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups made up of complete native waves can use the per-lane form for branches on whole-wave masks. - With direct DXIL, `XCL_DXIL_OUTLINE=1` lets compute shaders share a scalar-load function when its - addressing form and width occur at four or more emitted sites. The switch defaults to off while native size and dispatch times are being measured. + With direct DXIL on NVIDIA, `XCL_DXIL_OUTLINE=1` lets compute shaders share a scalar-load function when its + addressing form and width occur at four or more emitted sites. The switch defaults to off. Other adapters keep scalar loads inline. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61fd85..5bb1df7b1e 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -13,6 +13,7 @@ //! (`gpu::recomp::runner`), so the GPU tests can be run on each adapter of a machine in turn. use std::fmt; +use std::sync::OnceLock; use windows::Win32::Graphics::Dxgi::*; @@ -115,6 +116,18 @@ pub(crate) fn select_indices>(names: &[S], sel: &Selector) -> Vec< Vec::new() } +/// The title may fall back to another adapter while opening its D3D12 device. +pub(crate) static TITLE_VENDOR: OnceLock = OnceLock::new(); + +/// Offline shaders and the test runner select the first matching hardware adapter. +pub(crate) fn shader_vendor() -> Option { + static OFFLINE_VENDOR: OnceLock> = OnceLock::new(); + TITLE_VENDOR.get().copied().or_else(|| *OFFLINE_VENDOR.get_or_init(|| { + let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.ok()?; + candidates(&factory, &Selector::from_env_or("auto")).first().map(|(_, d)| d.VendorId) + })) +} + /// The adapter's name from its description. pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 4b03f56edd..20ee7bab3a 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -866,6 +866,14 @@ fn scalar_load_threshold_counts_emitted_sites_per_shape() { } } +#[test] +fn scalar_load_outlining_requires_nvidia() { + assert!(super::kernel::outline_supported(Some(0x10de))); + for vendor in [Some(0x1002), Some(0x8086), Some(0x1414), None] { + assert!(!super::kernel::outline_supported(vendor)); + } +} + #[test] fn outlined_scalar_loads_validate() { for windows in [1, 4, 0x104] { @@ -882,6 +890,9 @@ fn outlined_scalar_loads_validate() { #[test] fn outlined_scalar_loads_match_inline_at_view_end() { + if !super::kernel::outline_supported(crate::gpu::adapter::shader_vendor()) { + return crate::gpu::recomp::runner::skip_test("scalar-load outlining requires an NVIDIA adapter"); + } use crate::gpu::recomp::runner::{self, KernelState}; let (wave32, native64) = match (runner::wave32_supported(), runner::wave64_supported()) { (Ok(a), Ok(b)) => (a, b), @@ -909,6 +920,9 @@ fn outlined_scalar_loads_match_inline_at_view_end() { #[test] fn outlined_scalar_loads_preserve_distinct_image_descriptors() { + if !super::kernel::outline_supported(crate::gpu::adapter::shader_vendor()) { + return crate::gpu::recomp::runner::skip_test("scalar-load outlining requires an NVIDIA adapter"); + } use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT; diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index ed8ad196c4..c22dfeee0f 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -148,6 +148,24 @@ pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wav translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) } +pub(super) fn outline_supported(vendor: Option) -> bool { + vendor == Some(0x10de) // NVIDIA +} + +pub(crate) fn outline_enabled() -> bool { + if !std::env::var("XCL_DXIL_OUTLINE").is_ok_and(|v| v == "1") { + return false; + } + if outline_supported(crate::gpu::adapter::shader_vendor()) { + return true; + } + static WARN: std::sync::Once = std::sync::Once::new(); + WARN.call_once(|| { + crate::xlog_warn!("XCL_DXIL_OUTLINE=1 requires an NVIDIA adapter. Using inline scalar loads."); + }); + false +} + fn translate_entry( code: &[u8], o: KernelOptions, @@ -158,7 +176,7 @@ fn translate_entry( ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs - let outline = std::env::var("XCL_DXIL_OUTLINE").is_ok_and(|v| v == "1"); + let outline = matches!(entry, Entry::Kernel | Entry::Compute(_)) && outline_enabled(); let code = code.to_vec(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 3ebb03ce91..120b5ba341 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -154,7 +154,7 @@ fn shader_cache() -> &'static Mutex { /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); - if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { + if !cache_allowed(stage, translation_override_active) { return compile_one().map(|(c, _)| c); } let key = ShaderKey { @@ -904,6 +904,13 @@ fn cached_shader( Ok(shader) } +fn translation_override_active(name: &str) -> bool { + match name { + "XCL_DXIL_OUTLINE" => crate::gpu::dxil::kernel::outline_enabled(), + _ => std::env::var_os(name).is_some(), + } +} + fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] .iter() @@ -1146,7 +1153,7 @@ fn console_mesh_with( let compile_one = || compile(code, ms, wave64); // Cache the mesh compute pass in RAM (`ShaderCache` + in-flight coalescing) and on disk // (`translated/v2`, namespaced by backend) across all `(MS, PS)` pipelines that share it. - let cs = if cache_allowed(Stage::Mesh, |name| std::env::var_os(name).is_some()) { + let cs = if cache_allowed(Stage::Mesh, translation_override_active) { let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), stage: Stage::Mesh, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..f2ddbd90d3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -513,6 +513,7 @@ pub fn init() -> Result { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option = None; let mut name = String::new(); + let mut vendor_id = 0; // WARP fallback let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); if sel != crate::gpu::adapter::Selector::Warp { let mut list = crate::gpu::adapter::candidates(&factory, &sel); @@ -523,6 +524,7 @@ pub fn init() -> Result { for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); + vendor_id = desc.VendorId; name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } @@ -545,6 +547,7 @@ pub fn init() -> Result { let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie); } } + let _ = crate::gpu::adapter::TITLE_VENDOR.set(vendor_id); open_uma(&device); super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 5ffa519a96..6343194c73 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -188,7 +188,7 @@ fn offline_compute_pipeline_is_reused_by_a_second_process() { let run = |enabled: bool| { let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input) .args(["--precompile", "--pipelines"]).env("XCL_DXIL_CACHE", &cache) - .env("TMP", &dir).env("TEMP", &dir).env("XCL_DXIL_DUMP", "all") + .env("TMP", &dir).env("TEMP", &dir).env("XCL_DXIL_DUMP", "all").env_remove("XCL_DXIL_OUTLINE") .env("XCL_PSO_DISK_CACHE", if enabled { "1" } else { "0" }).output().unwrap(); let text = String::from_utf8_lossy(&out.stdout).into_owned(); assert!(out.status.success() && text.contains("pipelines made on the GPU 1, refused 0"), "{text}\n{}", String::from_utf8_lossy(&out.stderr)); From 3c0fc4b96a6b3706d8bac16492760bef6bb5ff12 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:42:22 -0500 Subject: [PATCH 7/7] Tests: exclude known non-NVIDIA adapters from strict outline fixtures --- crates/xcl/src/gpu/dxil/core_tests.rs | 42 ++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 20ee7bab3a..e38eb6b485 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -888,10 +888,44 @@ fn outlined_scalar_loads_validate() { } } +fn outline_fixture_applies(vendor: Option) -> bool { + if vendor.is_none() { + crate::gpu::recomp::runner::skip_test("could not identify the GPU for scalar-load outlining"); + return false; + } + if !super::kernel::outline_supported(vendor) { + use std::io::Write; + let thread = std::thread::current(); + let _ = writeln!(std::io::stderr(), "SKIPPED {}: NVIDIA-only scalar-load fixture", thread.name().unwrap_or("?")); + return false; + } + true +} + +#[test] +fn outlined_scalar_loads_strict_vendor_exclusion() { + // Isolate XCL_REQUIRE_GPU from the other tests running in this process. + const CHILD: &str = "XCL_TEST_OUTLINE_VENDOR_CHILD"; + if std::env::var_os(CHILD).is_some() { + assert!(!outline_fixture_applies(Some(0x1002))); + assert!(outline_fixture_applies(Some(0x10de))); + assert!(std::panic::catch_unwind(|| outline_fixture_applies(None)).is_err()); + return; + } + for mode in ["wave64", "mesh"] { + let test = std::thread::current(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test.name().unwrap()]) + .env(CHILD, "1").env("XCL_REQUIRE_GPU", mode) + .output().unwrap(); + assert!(output.status.success(), "{mode}: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + } +} + #[test] fn outlined_scalar_loads_match_inline_at_view_end() { - if !super::kernel::outline_supported(crate::gpu::adapter::shader_vendor()) { - return crate::gpu::recomp::runner::skip_test("scalar-load outlining requires an NVIDIA adapter"); + if !outline_fixture_applies(crate::gpu::adapter::shader_vendor()) { + return; } use crate::gpu::recomp::runner::{self, KernelState}; let (wave32, native64) = match (runner::wave32_supported(), runner::wave64_supported()) { @@ -920,8 +954,8 @@ fn outlined_scalar_loads_match_inline_at_view_end() { #[test] fn outlined_scalar_loads_preserve_distinct_image_descriptors() { - if !super::kernel::outline_supported(crate::gpu::adapter::shader_vendor()) { - return crate::gpu::recomp::runner::skip_test("scalar-load outlining requires an NVIDIA adapter"); + if !outline_fixture_applies(crate::gpu::adapter::shader_vendor()) { + return; } use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT;