From e591a8c8971206c854b0d6c5f8f21362182ed12d Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:35:40 -0700 Subject: [PATCH] Recompiler: direct DXIL lowers a repeating compute program's blocks once The two largest compute programs of a retail pack are about 14,000 blocks of about 600 kinds: one code many times, each copy lowered again, 4.3 MB of DXIL each. A program of at least 20,000 instructions with under 30 % of them in its distinct blocks (the HLSL compact form's thresholds) now takes a compact form: each distinct block once, inside one loop that reads the block's class and its two successors from constant tables and switches to the class. The two come out under 0.5 MB each. Two blocks are of one class when the lowering would emit the same for both: the same instruction words, the same kind of end, and the same of what it looks up by address (static samplers, whether a mask written there is read whole in the split form, s_getpc_b64). Registers are local variables across the loop; as SSA values each was a phi with an edge from every class, and the form came out larger than the plain one for programs with little repetition. The tables are constant data the driver has to take, and #1316 measured an RTX 5070 Ti accepting a table of 12,288 words and refusing one of 15,360, so a program takes the form by itself only when its two tables are at most 8,192 words together (the HLSL compact form's limit). The third largest program repeats itself too, but its branches go to thousands of different offsets and its tables would be about 24,000 words: it keeps the plain form. XCL_DIRECT_COMPACT=1 forces the form on every compute program and 0 turns it off. Part of #1269. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/gpu/dxil/compact.rs | 228 +++++++++++++++++++++++ crates/xcl/src/gpu/dxil/compact_tests.rs | 126 +++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 48 +++-- crates/xcl/src/gpu/dxil/lower.rs | 33 ++++ crates/xcl/src/gpu/dxil/mod.rs | 3 + crates/xcl/src/gpu/recomp/pso.rs | 5 + 6 files changed, 431 insertions(+), 12 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/compact.rs create mode 100644 crates/xcl/src/gpu/dxil/compact_tests.rs diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs new file mode 100644 index 000000000..064f851c3 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -0,0 +1,228 @@ +//! The compact form: each distinct block of a program lowered once, in a loop over a table. + +use super::cfg::{Cfg, Term}; +use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET}; +use super::lower_mem::VAR_TMP; +use super::module::{Block, Pred, Value}; +use std::collections::{BTreeSet, HashMap}; + +pub struct Plan { + /// the reachable blocks in address order: the loop's block numbers + pub order: Vec, + /// the class of each + pub class: Vec, + /// a block of each class (a block number) + pub rep: Vec, + /// where each block goes: (branch taken or jump, branch not taken), as block numbers + pub next: Vec<(u32, u32)>, + /// the distinct pairs of offsets from a block to its two successors, sorted + pub steps: Vec<(u32, u32)>, +} + +/// Most 32-bit words of tables a program may need to take the form by itself. +const MAX_TABLE_WORDS: usize = 8192; + +impl Plan { + /// Bits of a table entry: the class, and the index of the pair of offsets. + fn widths(&self) -> (u32, u32) { + (bits(self.rep.len()), bits(self.steps.len())) + } + + /// 32-bit words of the two tables. + pub fn words(&self) -> usize { + let (cb, pb) = self.widths(); + (self.order.len() * (cb + pb) as usize).div_ceil(32) + 1 + self.steps.len() * 2 + } +} + +/// Whether a program takes the form by itself: large, mostly repeated blocks, small tables. +pub fn wanted(cfg: &Cfg, p: &Plan) -> bool { + let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); + let all: usize = (0..p.order.len()).map(insts).sum(); + let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); + large(cfg) && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS +} + +/// Whether a program is large enough for `wanted` to be asked. +pub fn large(cfg: &Cfg) -> bool { + cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= 20_000 +} + +pub const END: u32 = u32::MAX; + +/// Sorts the reachable blocks into classes the lowering would emit the same for. +pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { + let mut order = cfg.rpo.clone(); + order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); + let mut number = vec![END; cfg.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + number[b] = n as u32; + } + let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); + let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new()); + for (n, &b) in order.iter().enumerate() { + let blk = &cfg.blocks[b]; + let mut key = vec![cfg.headers.contains(&b) as u64]; + for &i in &blk.insts { + let d = &cfg.insts[i]; + key.push(d.words.len() as u64); + key.extend(d.words.iter().map(|&w| w as u64)); + key.push(d.literal.map_or(u64::MAX, |l| l as u64)); + if let Some(s) = lw.static_samplers.get(&d.pc) { + key.extend(s.iter().map(|&w| w as u64)); + } + // what `Lw::write_mask` asks of this address, for any register a mask can go to + if let Some(&l) = lw.whole_live.get(&d.pc) { + let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); + let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); + key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + } + if d.inst.name == "S_GETPC_B64" { + key.push(d.pc); + } + } + let (end, to) = match blk.term { + Term::End => ("end", (END, END)), + Term::Jump(t) => ("jump", (number[t], number[t])), + Term::Cond(i, t, f) => (cfg.insts[i].inst.name, (number[t], number[f])), + }; + let fresh = ids.len() as u32; + let c = *ids.entry((key, end)).or_insert(fresh); + if c == fresh { + rep.push(n); + } + class.push(c); + next.push(to); + } + let steps: BTreeSet<(u32, u32)> = next.iter().enumerate().map(|(b, &to)| offsets(b, to)).collect(); + let p = Plan { order, class, rep, next, steps: steps.into_iter().collect() }; + let (cb, pb) = p.widths(); + (cb + pb <= 32).then_some(p) +} + +/// A block's successors as offsets from its own number. +fn offsets(b: usize, (t, f): (u32, u32)) -> (u32, u32) { + if t == END { (0, 0) } else { (t.wrapping_sub(b as u32), f.wrapping_sub(b as u32)) } +} + +fn bits(n: usize) -> u32 { + (usize::BITS - n.saturating_sub(1).leading_zeros()).max(1) +} + +/// A constant table of 32-bit words. +fn table(lw: &mut Lw, name: &str, words: &[u32]) -> Value { + let vals: Vec = words.iter().map(|&w| lw.c(w)).collect(); + let i32 = lw.s.m.i32(); + let at = lw.s.m.array(words.len() as u64, i32); + let init = lw.s.m.aggregate(at, &vals); + lw.s.m.global(name, at, 0, Some(init), true, 4) +} + +fn word(lw: &mut Lw, table: Value, i: Value) -> Value { + let z = lw.c(0); + let p = lw.s.m.gep(table, &[z, i]); + lw.s.m.load(p, 4) +} + +fn slot(lw: &mut Lw, var: u32) -> Value { + let Lw { s, init, .. } = lw; + init.slot(s, var) +} + +/// Lowers the program as one loop from `head` to `exit` that switches to each block's class. +pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResult<()> { + let n = p.order.len(); + let (cb, pb) = p.widths(); + let width = cb + pb; + let mut packed = vec![0u32; p.words() - p.steps.len() * 2]; + for (b, &to) in p.next.iter().enumerate() { + let pair = p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32; + let e = (p.class[b] | pair << cb) as u64; + let at = b * width as usize; + packed[at / 32] |= (e << (at % 32)) as u32; + packed[at / 32 + 1] |= (e << (at % 32) >> 32) as u32; + } + let steps: Vec = p.steps.iter().flat_map(|&(t, f)| [t, f]).collect(); + let blocks = table(lw, "xcl_blocks", &packed); + let steps = table(lw, "xcl_steps", &steps); + + let (at, to) = (lw.tmp_var(), lw.tmp_var()); + let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET)); + lw.s.m.set_block(head); + let b = lw.s.m.load(at, 4); + let w = lw.c(width); + let bit = lw.mul(b, w); + let i = lw.lshrc(bit, 5); + let sh = lw.andc(bit, 31); + let lo = word(lw, blocks, i); + let i1 = lw.addc(i, 1); + let hi = word(lw, blocks, i1); + let lo = lw.lshr(lo, sh); + let hi = lw.shlc(hi, 1); + let k31 = lw.c(31); + let up = lw.sub(k31, sh); + let hi = lw.shl(hi, up); + let e = lw.or(lo, hi); + let class = lw.andc(e, (1u32 << cb) - 1); + let pair = lw.lshrc(e, cb); + let pair = lw.andc(pair, (1u32 << pb) - 1); + let pi = lw.shlc(pair, 1); + let step_t = word(lw, steps, pi); + let pi1 = lw.addc(pi, 1); + let step_f = word(lw, steps, pi1); + let (taken, not_taken) = (lw.add(b, step_t), lw.add(b, step_f)); + let cases: Vec = p.rep.iter().map(|_| lw.block(Some(0))).collect(); + let latch = lw.block(Some(0)); + let arms: Vec<(Value, Block)> = cases.iter().enumerate().skip(1).map(|(k, &c)| (lw.c(k as u32), c)).collect(); + lw.s.m.switch(class, cases[0], &arms); + for (&c, &r) in cases.iter().zip(&p.rep) { + lw.s.m.set_block(c); + lw.init.mem = Some(c); + lw.ssa.begin_log(); + let blk = &cfg.blocks[p.order[r]]; + if cfg.headers.contains(&p.order[r]) { + // a loop head spends the loop budget + let left = lw.s.m.load(budget, 4); + let none = lw.cmpc(Pred::Eq, left, 0); + let (out, body) = (lw.block(Some(1)), lw.block(Some(1))); + lw.cond_br(none, out, body); + lw.s.m.set_block(out); + let end = lw.c(END); + lw.s.m.store(to, end, 4); + lw.s.m.br(latch); + lw.s.m.set_block(body); + let one = lw.c(1); + let l = lw.sub(left, one); + lw.s.m.store(budget, l, 4); + } + for &i in &blk.insts { + lw.inst(&cfg.insts[i])?; + } + let next = match blk.term { + Term::End => lw.c(END), + Term::Jump(_) => taken, + Term::Cond(i, ..) => { + let c = lw.branch_cond(&cfg.insts[i])?; + lw.sel(c, taken, not_taken) + } + }; + for var in lw.ssa.end_log().into_iter().filter(|&v| v < VAR_TMP) { + let (v, p) = (lw.rd(var), slot(lw, var)); + lw.s.m.store(p, v, 4); + } + lw.s.m.store(to, next, 4); + lw.s.m.br(latch); + } + // the epilogue's reads load here + lw.init.mem = Some(latch); + lw.s.m.set_block(latch); + let next = lw.s.m.load(to, 4); + let stop = lw.cmpc(Pred::UGe, next, n as u32); + let cont = lw.block(Some(1)); + lw.cond_br(stop, exit, cont); + lw.s.m.set_block(cont); + lw.s.m.store(at, next, 4); + lw.br(head); + lw.seal(head); + Ok(()) +} diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs new file mode 100644 index 000000000..c88ead868 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -0,0 +1,126 @@ +//! The compact form (`compact`) against the plain one. + +use super::kernel::{compact_mode, translate_full, translate_full_as, KernelOptions}; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState}; +use crate::gpu::recomp::KERNEL_LANES; + +fn repeated(copies: usize) -> Vec { + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut v = Vec::new(); + for _ in 0..copies { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)])); + v.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256), ("VSRC1", 1)])); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 5), ("SSRC1", 130)])); + v.extend(i("V_CMP_LT_U32", "ENC_VOPC", &[("SRC0", 5), ("VSRC1", 0)])); + v.extend(i("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)])); + v.extend(i("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)])); + v.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 256), ("VSRC1", 3)])); + v.extend(i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 6)])); + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 2)])); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)])); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)])); + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 133)])); + v.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 256), ("VSRC1", 2)])); + v.extend(i("S_SUB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)])); + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 128)])); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)])); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + v +} + +fn size(copies: usize, o: KernelOptions, compact: bool) -> usize { + translate_full_as(&repeated(copies), o, compact).unwrap_or_else(|e| panic!("{copies} copies, compact {compact}: {e}")).dxil.len() +} + +#[test] +fn the_compact_form_lowers_a_repeated_block_once() { + for (wave64, split) in [(false, false), (true, true), (true, false)] { + let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let (compact, plain) = (size(128, o, true) - size(64, o, true), size(128, o, false) - size(64, o, false)); + assert!(compact * 20 < plain, "wave64 {wave64} split {split}: 64 more copies cost {compact} B compact, {plain} B plain"); + } +} + +#[test] +fn a_large_program_that_repeats_itself_takes_the_compact_form() { + if compact_mode().is_some() { + return; + } + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + for (copies, compact) in [(2500, true), (2000, false)] { + assert_eq!(translate_full(&repeated(copies), o).unwrap().dxil.len(), size(copies, o, compact), "{copies} copies"); + } +} + +#[test] +fn gpu_compact_form_runs_as_the_plain_form() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let mut st = KernelState::default(); + (st.sgpr[1], st.sgpr[2]) = (3, 12); + for lane in 0..KERNEL_LANES { + st.vgpr[lane][0] = lane as u32; + } + let code = repeated(40); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!(&c.sgpr[..6], &[120, 3, 12, 1, 0, 80]); + for lane in 0..KERNEL_LANES as u32 { + let masked = lane * (lane.saturating_sub(1) / 2); + assert_eq!(&c.vgpr[lane as usize][..4], &[lane, 40 * lane, 5 * lane, masked], "lane {lane}"); + } + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); +} + +#[test] +fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let mut v = Vec::new(); + v.extend(encode("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None).unwrap()); + v.extend(encode("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(super::lower::LOOP_BUDGET + 1)).unwrap()); + v.extend(encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None).unwrap()); + v.extend(encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 129)], None).unwrap()); + v.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let run = |compact: bool| { + let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!(&c.sgpr[..2], &[super::lower::LOOP_BUDGET, 0]); + assert_eq!(&c.sgpr[..2], &p.sgpr[..2]); +} + +#[test] +fn a_mask_read_whole_after_one_copy_only_splits_the_class() { + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let cmp = |v: &mut Vec| { + v.extend(i("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)])); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)])); + }; + let mut v = Vec::new(); + cmp(&mut v); + v.extend(i("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 128), ("VSRC1", 3)])); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)])); + cmp(&mut v); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)])); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let cfg = super::cfg::Cfg::build(&v).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let p = super::compact::plan(&cfg, &lw).unwrap(); + assert_eq!(p.order.len(), 4); + assert_ne!(p.class[0], p.class[2]); +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 5694c1f98..5a86180c1 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -67,30 +67,45 @@ pub struct Kernel { pub static_samplers: Vec<([u32; 4], bool)>, } +/// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset leaves it to `compact::wanted`. +pub fn compact_mode() -> Option { + match std::env::var("XCL_DIRECT_COMPACT").as_deref() { + Ok("1") => Some(true), + Ok("0") => Some(false), + _ => None, + } +} + +/// `translate_full` in the compact form (`compact = true`) or the plain one. +#[cfg(test)] +pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result { + translate_entry(code, o, Entry::Kernel, Some(compact)) +} + pub fn translate_full(code: &[u8], o: KernelOptions) -> Result { - translate_entry(code, o, Entry::Kernel) + translate_entry(code, o, Entry::Kernel, compact_mode()) } /// A mesh-mode (NGG) program: the first pass that writes one record per group into /// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result { - translate_entry(code, o, Entry::Mesh(ms.clone())) + translate_entry(code, o, Entry::Mesh(ms.clone()), None) } /// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result { - translate_entry(code, o, Entry::Vertex(vs.clone())) + translate_entry(code, o, Entry::Vertex(vs.clone()), None) } /// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result { - translate_entry(code, o, Entry::Pixel(ps.clone())) + translate_entry(code, o, Entry::Pixel(ps.clone()), None) } /// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per /// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result { - translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone())) + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None) } /// The entry ABI. @@ -106,17 +121,17 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { - translate_entry(code, o, Entry::Compute(cs.clone())) + translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode()) } -fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry) -> Result { +fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry, compact: Option) -> 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 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)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -139,7 +154,7 @@ 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) } -fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Result { +fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact: Option) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), _ => None, @@ -150,6 +165,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu }; let kernel = matches!(entry, Entry::Kernel); let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); + let compute = matches!(entry, Entry::Compute(_)); 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); @@ -220,6 +236,11 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu } } + let plan = if (compute || kernel) && compact.unwrap_or_else(|| super::compact::large(&cfg)) { super::compact::plan(&cfg, &lw) } else { None }; + let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p))); + if let Some(p) = &plan { + crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); + } let n = cfg.blocks.len(); let mut heads: Vec> = vec![None; n]; let entry = *cfg.rpo.first().ok_or("empty program")?; @@ -253,7 +274,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu lw.partner = Partner::Missing; lw.xn = lw.c(0); } - let h0 = head(&mut lw, entry); + let h0 = if plan.is_some() { lw.block(None) } else { head(&mut lw, entry) }; let exit = lw.block(None); if gs_only { // the GS alone: in the lower hardware wave only @@ -267,7 +288,10 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu } let switch = if two_phase { Some(lw.block(None)) } else { None }; let mut gs_entry: Option = None; - for &b in &cfg.rpo { + if let Some(p) = &plan { + super::compact::emit(&mut lw, &cfg, p, h0, exit)?; + } + for &b in cfg.rpo.iter().filter(|_| plan.is_none()) { let h = head(&mut lw, b); lw.s.m.set_block(h); let es_block = two_phase && !in_gs(b); @@ -403,7 +427,7 @@ impl Lw { let mut lw = Lw { s, ssa: Ssa::new(i32), - init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, + init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new(), slots: HashMap::new(), mem: None }, wave64: o.wave64, split, lane: z, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index f91b431ed..67d0bdf7d 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -72,10 +72,43 @@ pub struct Init { pub vgpr_base: Option, pub entry: Block, pub touched: BTreeSet, + /// the compact form: each register's local variable, and the block that loads them now + pub slots: HashMap, + pub mem: Option, } impl Init { pub fn load(&mut self, s: &mut Shader, var: u32) -> Value { + let Some(b) = self.mem else { return self.first(s, var) }; + let p = self.slot(s, var); + let cur = s.m.current_block(); + let before = s.m.set_insert_before_term(true); + s.m.set_block(b); + let v = s.m.load(p, 4); + s.m.set_block(cur); + s.m.set_insert_before_term(before); + v + } + + /// The local variable of `var`, made in the entry block with the register's first value. + pub fn slot(&mut self, s: &mut Shader, var: u32) -> Value { + if let Some(&p) = self.slots.get(&var) { + return p; + } + let v = self.first(s, var); + let cur = s.m.current_block(); + let before = s.m.set_insert_before_term(false); + s.m.set_block(self.entry); + let i32 = s.m.i32(); + let p = s.m.alloca(i32, 4); + s.m.store(p, v, 4); + s.m.set_block(cur); + s.m.set_insert_before_term(before); + self.slots.insert(var, p); + p + } + + fn first(&mut self, s: &mut Shader, var: u32) -> Value { if var == VAR_BUDGET { return s.m.i32c(LOOP_BUDGET); } diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 6fe75d575..f8ce75650 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -13,6 +13,7 @@ pub mod bitstream; pub mod cfg; +mod compact; pub mod container; pub mod coverage; pub mod graphics; @@ -35,6 +36,8 @@ pub mod shader; pub mod ssa; pub mod validate; +#[cfg(test)] +mod compact_tests; #[cfg(test)] mod core_tests; #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b313881eb..5dc794205 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -251,6 +251,11 @@ mod translated { Backend::current(), direct_version(crate::gpu::dxil::kernel::TRANSLATOR_VERSION, env!("XCL_DIRECT_DXIL_SOURCE_ID")), ); + // `XCL_DIRECT_COMPACT=0` or `1`: the compact form forced off or on is another output + let id = match crate::gpu::dxil::kernel::compact_mode() { + Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), + _ => 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")))