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
38 changes: 36 additions & 2 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,41 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option<Plan> {
repeated.then_some(p)
}

/// `XCL_DIRECT_COMPACT_MIN=<instructions>` (unset: off): a compute program of at least that
/// many reachable non-terminator instructions takes the compact form whenever it has one whose
/// table fits (`sized_plan`), however little of it repeats. The automatic choice is about size;
/// this one is about speed: on a big program the driver's register allocation of the plain
/// form can spill most of the program's values (a retail title's 6,000-instruction shadow-mask
/// program: 256 VGPRs and 18 KB of scratch a lane on RDNA4), and the compact form's blocks,
/// each lowered on its own, need none.
pub fn compact_min() -> Option<usize> {
#[cfg(test)]
if let Some(v) = COMPACT_MIN_FOR_TEST.with(|c| c.get()) {
return v;
}
static V: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
*V.get_or_init(|| std::env::var("XCL_DIRECT_COMPACT_MIN").ok().and_then(|v| v.trim().parse::<usize>().ok()).filter(|&n| n > 0))
}

#[cfg(test)]
thread_local! {
/// `compact_min` for the translations of this test thread
pub(crate) static COMPACT_MIN_FOR_TEST: std::cell::Cell<Option<Option<usize>>> = const { std::cell::Cell::new(None) };
}

/// The compact form of a program of at least `min` reachable instructions whose table fits
/// (`compact_min`).
pub fn sized_plan(cfg: &Cfg, lw: &Lw, min: usize) -> Option<Plan> {
if insts(cfg) < min {
return None;
}
plan(cfg, lw).filter(|p| p.words() <= MAX_TABLE_WORDS)
}

fn insts(cfg: &Cfg) -> usize {
cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum()
}

/// Reachable non-terminator instruction count threshold for trying the compact form.
const LARGE_INSTS: usize = 10_000;
/// Reachable basic-block count threshold for trying the compact form: branch-heavy
Expand All @@ -280,8 +315,7 @@ const LARGE_BLOCKS: usize = 2_000;

/// Whether to consider compaction based on the reachable instruction and block counts.
pub fn large(cfg: &Cfg) -> bool {
cfg.rpo.len() >= LARGE_BLOCKS
|| cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::<usize>() >= LARGE_INSTS
cfg.rpo.len() >= LARGE_BLOCKS || insts(cfg) >= LARGE_INSTS
}

pub const END: u32 = u32::MAX;
Expand Down
77 changes: 77 additions & 0 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,3 +479,80 @@ fn gpu_nested_compact_matches_plain_and_flat() {
.expect("nested budget GPU run");
assert_eq!((got3.sgpr, got3.vgpr, got3.scc), (plain3.sgpr, plain3.vgpr, plain3.scc), "nested loop budget");
}

/// `f` with `XCL_DIRECT_COMPACT_MIN` taken as `min` by the translations of this thread.
fn with_compact_min<R>(min: Option<usize>, f: impl FnOnce() -> R) -> R {
let before = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(min)));
let r = f();
super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(before));
r
}

/// `XCL_DIRECT_COMPACT_MIN`: a compute program of at least that many instructions takes the
/// compact form, below the automatic choice's size; a smaller one, or a kernel, keeps the plain
/// form.
#[test]
fn a_compute_program_from_the_compact_size_takes_the_compact_form() {
if compact_mode().is_some() {
return;
}
use crate::gpu::recomp::CsInterface;
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() };
let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
// 100 copies: 900 instructions, below the automatic thresholds
let code = repeated(100);
let compute = |min| with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap().dxil.len();
let plain = compute(None);
assert!(compute(Some(500)) * 3 < plain, "compact {} B, plain {plain} B", compute(Some(500)));
assert_eq!(compute(Some(5000)), plain, "below the size");
let kernel = |min| with_compact_min(min, || translate_full(&code, o)).unwrap().dxil;
assert_eq!(kernel(Some(500)), kernel(None), "a kernel keeps its form");
}

/// A compute program in the compact form `XCL_DIRECT_COMPACT_MIN` gives it runs as in the plain
/// one: every thread of a 2-D wave32 group stores its own (group, y, x).
#[test]
fn gpu_compute_compact_form_from_the_size_runs_as_the_plain_form() {
use crate::gpu::recomp::{CsInterface, KERNEL_SGPRS};
match runner::wave32_supported() {
Ok(true) => {}
Ok(false) => return runner::skip_test("no wave32"),
Err(e) => return runner::skip_test(&e),
}
const V: u64 = 256;
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("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)])); // y · 8
code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)])); // + x
code.extend(i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 134)])); // gid · 64
code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)])); // i
// v3 = x · (y + 1): a loop of y + 1 passes, each lane leaving EXEC after its own
code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)]));
code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)]));
code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)])); // loop: v3 += x
code.extend(i("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 129), ("VSRC1", 5)])); // v5 -= 1
code.extend(i("V_CMP_GT_I32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 5)])); // vcc = 0 > v5
code.extend(i("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)])); // exec &= !vcc
code.extend(i("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]));
code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); // exec = all
code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)])); // 4i
code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)]));
code.extend(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 3), ("SADDR", 0x7D)]));
code.extend(i("S_ENDPGM", "ENC_SOPP", &[]));
let cs = CsInterface { threads: [8, 4, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, ..Default::default() };
let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 };
let groups = 4u32;
let mut want = vec![0xFFFF_FFFFu32; 64 * groups as usize];
for g in 0..groups {
for y in 0..4 {
for x in 0..8 {
want[(g * 64 + y * 8 + x) as usize] = x * (y + 1);
}
}
}
for min in [None, Some(1)] {
let k = with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap_or_else(|e| panic!("{min:?}: {e}"));
let mem = runner::dispatch(&k.dxil, [groups, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; want.len()]).expect("GPU run");
assert_eq!(&mem[..want.len()], &want[..], "compact size {min:?}");
}
}
17 changes: 16 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ pub fn compact_mode() -> Option<bool> {
}
}

/// `XCL_DIRECT_COMPACT_MIN` (`compact::compact_min`), for the caches' identities.
pub fn compact_min() -> Option<usize> {
super::compact::compact_min()
}

#[cfg(test)]
pub(crate) use super::compact::COMPACT_MIN_FOR_TEST;

/// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity.
pub fn compact_nest_tag() -> Option<String> {
super::compact::nest_mode().cache_tag()
Expand Down Expand Up @@ -251,11 +259,15 @@ fn translate_entry_with(
// a register's definition and its use): a thread with a large stack for big programs
let code = code.to_vec();
#[cfg(test)]
let compact_min = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.get());
#[cfg(test)]
let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get());
std::thread::Builder::new()
.name("xcl-dxil-translate".into())
.stack_size(256 << 20)
.spawn(move || {
#[cfg(test)]
super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(compact_min));
#[cfg(test)]
super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold));
translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask)
Expand Down Expand Up @@ -424,7 +436,10 @@ fn translate_on_this_thread(
_ if !compute && !kernel => None,
Some(false) => None,
Some(true) => super::compact::plan(&cfg, &lw),
None => super::compact::automatic_plan(&cfg, &lw, compute && split),
None => match super::compact::compact_min() {
Some(min) if compute => super::compact::sized_plan(&cfg, &lw, min).or_else(|| super::compact::automatic_plan(&cfg, &lw, split)),
_ => super::compact::automatic_plan(&cfg, &lw, compute && split),
},
};
if let Some(p) = &plan {
crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len());
Expand Down
22 changes: 22 additions & 0 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,11 @@ mod translated {
Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }),
_ => id,
};
// `XCL_DIRECT_COMPACT_MIN`: compute programs from that size take the compact form
let id = match crate::gpu::dxil::kernel::compact_min() {
Some(n) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")),
_ => id,
};
// `XCL_DIRECT_COMPACT_NEST`: a non-default nesting policy changes the compact IR
let id = match crate::gpu::dxil::kernel::compact_nest_tag() {
Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag),
Expand Down Expand Up @@ -690,6 +695,10 @@ mod translated {
Some(tag) => identity_for(&id.to_string(), tag),
None => id,
};
let id = match crate::gpu::dxil::kernel::compact_min() {
Some(n) => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")),
None => id,
};
let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}"));
if crate::gpu::recomp::lower_dxil::enabled() {
identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID")))
Expand Down Expand Up @@ -2127,6 +2136,19 @@ mod slab_tests {
mod shader_cache_tests {
use super::*;

/// `XCL_DIRECT_COMPACT_MIN` translations are other entries of the direct translator's caches.
#[test]
fn a_compact_size_is_another_direct_output() {
let with = |n| {
let before = crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(n)));
let id = translated::direct_output_identity(None, 1);
crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.set(before));
id
};
assert_ne!(with(None), with(Some(4096)));
assert_ne!(with(Some(4096)), with(Some(8192)));
}

/// The switch form (no heap windows, or a pipeline retried in it) has 4 root UAVs: a wider
/// count there is 4, which every translator takes; the heap form keeps all of them.
#[test]
Expand Down
Loading