Skip to content
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 66 additions & 3 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ pub fn translate(code: &[u8], o: KernelOptions) -> Result<Vec<u8>, String> {
pub struct Kernel {
pub dxil: Vec<u8>,
pub static_samplers: Vec<([u32; 4], bool)>,
pub dispatch_chain: Option<std::sync::Arc<DispatchChain>>,
}

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`.
Expand Down Expand Up @@ -197,6 +204,7 @@ fn translate_on_this_thread(
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();
Expand All @@ -209,6 +217,7 @@ fn translate_on_this_thread(
}
Entry::Compute(cs) => {
let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds);
if split && !uses_lds && cs.threads.iter().product::<u32>() % 64 == 0 { split_tid = Some(tid); }
compute_init(&mut lw, cs, tid, gtid);
cs.threads
}
Expand Down Expand Up @@ -422,7 +431,8 @@ fn translate_on_this_thread(
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):
Expand Down Expand Up @@ -588,15 +598,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<Kernel, String> {
pub fn finish(self, numthreads: [u32; 3], hw: u32) -> Result<Kernel, String> {
self.finish_dispatch(numthreads, hw, 0, None)
}

fn finish_dispatch(mut self, numthreads: [u32; 3], hw: u32, limit: usize, split_tid: Option<Value>) -> Result<Kernel, String> {
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))
}
Expand All @@ -607,8 +626,52 @@ 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 })
}
}

#[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];
// conditional updates: blocks the optimiser cannot merge into one
for _ in 0..40 {
let update = lw.s.m.new_block();
let join = lw.s.m.new_block();
let taken = lw.cmp(Pred::ULt, tid, width);
lw.s.m.cond_br(taken, update, join);
lw.s.m.set_block(update);
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.br(join);
lw.s.m.set_block(join);
}
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, None).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<u32> = (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.
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
13 changes: 13 additions & 0 deletions crates/xcl/src/gpu/dxil/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::collections::HashMap;
use super::bitstream::{signed, BitWriter};

mod opt;
pub(super) mod split;

// ---------------------------------------------------------------- types

Expand Down Expand Up @@ -59,6 +60,7 @@ enum ConstDef {
Aggregate(Ty, Vec<Value>),
}

#[derive(Clone)]
struct FuncDecl {
name: String,
ty: Ty,
Expand Down Expand Up @@ -93,6 +95,7 @@ impl FnAttrs {
}
}

#[derive(Clone)]
struct GlobalDef {
name: String,
/// Value type (the global itself is a pointer to it).
Expand Down Expand Up @@ -251,6 +254,7 @@ pub struct Module {
insts: Vec<InstDef>,
def_block: Vec<Block>,
blocks: Vec<Vec<u32>>,
spin_regions: Vec<Vec<Block>>,
cur: Block,
insert_before_term: bool,
md: Vec<MdDef>,
Expand Down Expand Up @@ -279,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(),
Expand Down Expand Up @@ -516,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)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/dxil/module/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading