Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 43 additions & 24 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,34 @@ pub struct Plan {
pub next: Vec<(u32, u32)>,
/// the distinct pairs of offsets from a block to its two successors, sorted
pub steps: Vec<(u32, u32)>,
/// an entry holds the block's taken successor itself; the other one is the next block
pub inline: bool,
}

/// Most 32-bit words of tables a program may need to take the form by itself.
const MAX_TABLE_WORDS: usize = 8192;
pub const TABLE_WORDS: usize = 8192;
/// `TABLE_WORDS` on a GPU that runs only 32-lane waves.
pub const TABLE_WORDS_WAVE32: usize = 12288;

impl Plan {
/// Bits of a table entry: the class, and the index of the pair of offsets.
/// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets.
fn widths(&self) -> (u32, u32) {
(bits(self.rep.len()), bits(self.steps.len()))
(bits(self.rep.len()), if self.inline { bits(self.order.len()) } else { bits(self.steps.len()) })
}

/// 32-bit words of the two tables.
/// 32-bit words of the 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
(self.order.len() * (cb + pb) as usize).div_ceil(32) + 1 + if self.inline { 0 } else { 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 {
pub fn wanted(cfg: &Cfg, p: &Plan, tables: usize) -> 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
large(cfg) && once * 10 < all * 3 && p.words() <= tables
}

/// Whether a program is large enough for `wanted` to be asked.
Expand All @@ -60,6 +64,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
}
let mut ids: HashMap<(Vec<u64>, &'static str), u32> = HashMap::new();
let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new());
let mut falls = true;
for (n, &b) in order.iter().enumerate() {
let blk = &cfg.blocks[b];
let mut key = vec![cfg.headers.contains(&b) as u64];
Expand All @@ -68,9 +73,9 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
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));
}
let sampler = lw.static_samplers.get(&d.pc);
key.push(sampler.is_some() as u64);
key.extend(sampler.into_iter().flatten().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"));
Expand All @@ -84,7 +89,10 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
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])),
Term::Cond(i, t, f) => {
falls &= number[f] == n as u32 + 1;
(cfg.insts[i].inst.name, (number[t], number[f]))
}
};
let fresh = ids.len() as u32;
let c = *ids.entry((key, end)).or_insert(fresh);
Expand All @@ -95,7 +103,10 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
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 mut p = Plan { order, class, rep, next, steps: steps.into_iter().collect(), inline: false };
let pairs = p.words();
p.inline = falls;
p.inline = falls && p.words() < pairs;
let (cb, pb) = p.widths();
(cb + pb <= 32).then_some(p)
}
Expand Down Expand Up @@ -134,17 +145,21 @@ pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResu
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];
let mut packed = vec![0u32; (n * width as usize).div_ceil(32) + 1];
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 field = match (p.inline, to.0) {
(true, END) => 0,
(true, t) => t,
_ => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32,
};
let e = (p.class[b] | field << 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<u32> = 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 steps: Vec<u32> = p.steps.iter().flat_map(|&(t, f)| [t, f]).collect();
let steps = (!p.inline).then(|| 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));
Expand All @@ -164,13 +179,17 @@ pub fn emit(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block) -> LResu
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 field = lw.lshrc(e, cb);
let field = lw.andc(field, (1u32 << pb) - 1);
let (taken, not_taken) = if let Some(steps) = steps {
let pi = lw.shlc(field, 1);
let step_t = word(lw, steps, pi);
let pi1 = lw.addc(pi, 1);
let step_f = word(lw, steps, pi1);
(lw.add(b, step_t), lw.add(b, step_f))
} else {
(field, lw.addc(b, 1))
};
let cases: Vec<Block> = 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();
Expand Down
123 changes: 123 additions & 0 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,50 @@ fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() {
assert_eq!(&c.sgpr[..2], &p.sgpr[..2]);
}

fn early_outs(copies: usize) -> Vec<u8> {
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 k in 0..copies {
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)]));
v.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 2)]));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", ((copies - 1 - k) * 3 + 1) as u64)]));
}
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 129)]));
v.extend(i("S_ENDPGM", "ENC_SOPP", &[]));
v
}

#[test]
fn branches_to_many_places_keep_their_target_in_the_entry() {
let code = early_outs(1000);
let cfg = super::cfg::Cfg::build(&code).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(), p.steps.len()), (1002, 1002));
assert!(p.words() < 500, "{} words", p.words());
}

#[test]
fn gpu_compact_form_with_targets_in_the_entry_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);
let code = early_outs(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[..4], &[12, 3, 12, 0]);
assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc));
}

#[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}"));
Expand All @@ -124,3 +168,82 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
assert_eq!(p.order.len(), 4);
assert_ne!(p.class[0], p.class[2]);
}

fn two_segments(copies: usize) -> Vec<u8> {
let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"));
let mut code = Vec::new();
code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)]));
for r in [2, 3] {
code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", r), ("SRC0", 256 + r)]));
}
for marker in [3, 4] {
for k in 0..copies {
code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)]));
code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256), ("VSRC1", 1)]));
let offset = (copies - 1 - k) * 3 + 1;
assert!(offset <= i16::MAX as usize);
code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", offset as u64)]));
}
code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", marker), ("SSRC0", 129)]));
}
code.extend(i("S_ENDPGM", "ENC_SOPP", &[]));
code
}

#[test]
fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() {
if compact_mode().is_some() {
return;
}
let code = two_segments(8192);
let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 };
let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 };
let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len();
let (compact, plain) = (size(true), size(false));
assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves");
}

#[test]
fn gpu_compact_inline_table_above_old_cap_checks_late_entries() {
if compact_mode().is_some() {
return;
}
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" }),
}
const COPIES: usize = 8192;
let code = two_segments(COPIES);
let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };
let cfg = super::cfg::Cfg::build(&code).unwrap();
let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
let p = super::compact::plan(&cfg, &lw).unwrap();
assert!(p.inline && p.words() > 8192 && p.words() <= 12288);
assert!(super::compact::wanted(&cfg, &p, super::compact::TABLE_WORDS_WAVE32));
let k = translate_full(&code, o).unwrap();
for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] {
let mut st = KernelState::default();
st.sgpr[0] = initial;
st.sgpr[1] = 1;
st.sgpr[2] = 0x1234;
for lane in 0..KERNEL_LANES {
st.vgpr[lane][..4].copy_from_slice(&[lane as u32, 17, 0x12345678, 0x87654321]);
}
let (mut value, mut count, mut marks, mut carry) = (initial, 0u32, [0u32; 2], false);
for mark in &mut marks {
for n in 0..COPIES {
(value, carry) = value.overflowing_add(1);
count += 1;
if carry { break; }
if n + 1 == COPIES { *mark = 1; }
}
}
let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("GPU run");
assert_eq!(&out.sgpr[..5], &[value, 1, 0x1234, marks[0], marks[1]], "initial {initial:#x}");
assert_eq!(out.scc, carry as u32);
for lane in 0..KERNEL_LANES {
assert_eq!(&out.vgpr[lane][..4], &[lane as u32, 17 + count * lane as u32, 0x12345678, 0x87654321], "initial {initial:#x} lane {lane}");
}
}
}
28 changes: 17 additions & 11 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,33 +79,33 @@ pub fn compact_mode() -> Option<bool> {
/// `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<Kernel, String> {
translate_entry(code, o, Entry::Kernel, Some(compact))
translate_entry(code, o, Entry::Kernel, Some(compact), super::compact::TABLE_WORDS_WAVE32)
}

pub fn translate_full(code: &[u8], o: KernelOptions) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Kernel, compact_mode())
translate_entry(code, o, Entry::Kernel, compact_mode(), super::compact::TABLE_WORDS_WAVE32)
}

/// 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<Kernel, String> {
translate_entry(code, o, Entry::Mesh(ms.clone()), None)
translate_entry(code, o, Entry::Mesh(ms.clone()), None, 0)
}

/// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent).
pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Vertex(vs.clone()), None)
translate_entry(code, o, Entry::Vertex(vs.clone()), None, 0)
}

/// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent).
pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Pixel(ps.clone()), None)
translate_entry(code, o, Entry::Pixel(ps.clone()), None, 0)
}

/// 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<Kernel, String> {
translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None)
translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, 0)
}

/// The entry ABI.
Expand All @@ -121,17 +121,23 @@ pub enum Entry {

/// A compute-mode program (the CS ABI of `cs`).
pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode())
translate_compute_on(code, o, cs, true)
}

fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry, compact: Option<bool>) -> Result<Kernel, String> {
/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables.
pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result<Kernel, String> {
let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS };
translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), tables)
}

fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry, compact: Option<bool>, tables: usize) -> Result<Kernel, String> {
// 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, compact))
.spawn(move || translate_on_this_thread(&code, o, entry, compact, tables))
.map_err(|e| format!("translator thread: {e}"))?
.join()
.map_err(|e| {
Expand All @@ -155,7 +161,7 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec<RawUav>
((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, compact: Option<bool>) -> Result<Kernel, String> {
fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact: Option<bool>, tables: usize) -> Result<Kernel, String> {
let geo = match &entry {
Entry::Geometry(g) => Some(g.clone()),
_ => None,
Expand Down Expand Up @@ -238,7 +244,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact
}

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)));
let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p, tables)));
if let Some(p) = &plan {
crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len());
}
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo
}
}
}
let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?;
let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?;
dump_direct(blob, &k.dxil);
Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers })
}
Expand Down
Loading