Skip to content
Closed
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
112 changes: 112 additions & 0 deletions crates/xcl/src/gpu/dxil/dispatchx_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use super::kernel::{self, KernelOptions};
use crate::gpu::{rdna2::encode, recomp::{self, runner, CsInterface}};

// An unguarded store at the 3-D global thread index: only EXEC can suppress excess lanes.
fn stores(threads: [u32; 3], groups: [u32; 3]) -> Vec<u8> {
let mut code = Vec::new();
let mut emit = |name, enc, fields: &[(&str, u64)], literal| {
code.extend(encode(name, enc, fields, literal).unwrap());
};
for k in 0..3u64 {
emit("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3 + k), ("SRC0", k), ("SRC1", 255)], Some(threads[k as usize]));
emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3 + k), ("SRC0", 259 + k), ("VSRC1", k)], None);
}
emit("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 261), ("SRC1", 255)], Some(threads[1] * groups[1]));
emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 261), ("VSRC1", 4)], None);
emit("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 260), ("SRC1", 255)], Some(threads[0] * groups[0]));
emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 260), ("VSRC1", 3)], None);
emit("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 3)], None);
emit("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None);
emit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 129), ("VSRC1", 3)], None);
emit("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 8), ("SADDR", 0x7D)], None);
emit("S_ENDPGM", "ENC_SOPP", &[], None);
code
}

fn interface(threads: [u32; 3]) -> CsInterface {
CsInterface { threads, user_sgprs: 0, tgid: [true; 3], tg_size: false, tid_components: 3 }
}

pub(crate) fn wave32_store_container(groups: [u32; 3]) -> Vec<u8> {
use crate::gpu::xbox::tests::{fssm, sample};
let mut header = fssm(&stores([32, 1, 1], groups), &[(6, 1)]);
header[0xd4] = 1 << 5; // wave32
for (word, value) in header[0x138..0x148].chunks_exact_mut(4).zip([0x1380u32, 32, 1, 1]) {
word.copy_from_slice(&value.to_le_bytes());
}
sample(5, &[header])
}

fn masked_stores(wave64: bool, split: bool) {
if recomp::dxc::location().is_err() { runner::skip_test("no DXC"); return; }
let supported = if wave64 && !split { runner::wave64_supported() } else { runner::wave32_supported() };
if supported != Ok(true) { runner::skip_test("required wave size unavailable"); return; }
let x = if wave64 { 64 } else { 32 };
let square = if wave64 { [8, 8, 1] } else { [8, 4, 1] };
let cube = if wave64 { [4, 4, 4] } else { [4, 4, 2] };
let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };
for (threads, groups, limits) in [
([x, 1, 1], [128 / x, 1, 1], [100, 0, 0]),
([x, 1, 1], [128 / x, 1, 1], [10, 0, 0]),
([x, 1, 1], [128 / x, 1, 1], [0, 0, 0]),
(square, [2, 2, 1], [13, square[1] + 1, 0]),
(cube, [2, 2, 2], [7, 6, cube[2] * 2 - 1]),
] {
let shape = std::array::from_fn::<_, 3, _>(|k| threads[k] * groups[k]);
let size = shape.iter().product::<u32>() as usize;
let code = stores(threads, groups);
let cs = interface(threads);
let mut io = vec![0; recomp::KERNEL_SGPRS];
for k in 0..3 { io[recomp::IO_THREAD_LIMIT[k]] = limits[k]; }
let untouched = 0xDEAD_BEEF;
let input = vec![untouched; size];
let base = kernel::translate_compute_on(&code, options, &cs, true).unwrap();
let plain = runner::dispatch(&base.dxil, groups, &io, &input).unwrap();
assert_eq!(plain, (1..=size as u32).collect::<Vec<_>>(), "base ignores thread limits");
let masked = kernel::translate_compute_with_thread_limits(&code, options, &cs, true).unwrap();
let got = runner::dispatch(&masked.dxil, groups, &io, &input).unwrap();
let mut expected = input;
for z in 0..shape[2] {
for y in 0..shape[1] {
for x in 0..shape[0] {
if [x, y, z].iter().zip(limits).all(|(&v, limit)| limit == 0 || v < limit) {
let i = ((z * shape[1] + y) * shape[0] + x) as usize;
expected[i] = i as u32 + 1;
}
}
}
}
assert_eq!(got, expected, "threads={threads:?}, groups={groups:?}, limits={limits:?}");
}
}

#[test]
fn dispatchx_wave32_masks_excess_lanes() { masked_stores(false, false); }
#[test]
fn dispatchx_split_wave64_masks_excess_lanes() { masked_stores(true, true); }
#[test]
fn dispatchx_native_wave64_masks_excess_lanes() { masked_stores(true, false); }

#[test]
fn dispatchx_base_translation_stays_byte_identical() {
if recomp::dxc::location().is_err() { runner::skip_test("no DXC"); return; }
let cs = interface([64, 1, 1]);
let code = stores(cs.threads, [2, 1, 1]);
for (wave64, split) in [(false, false), (true, true), (true, false)] {
let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };
let base = kernel::translate_compute_on(&code, options, &cs, true).unwrap().dxil;
// The window's red/green harness records original-base bytes before installing the
// implementation, then compares them here (same toolchain, no brittle golden hash).
if let Some(dir) = std::env::var_os("XCL_TEST_DISPATCHX_BASELINE") {
let path = std::path::PathBuf::from(dir).join(format!("{wave64}-{split}.dxil"));
if std::env::var_os("XCL_TEST_DISPATCHX_RECORD").is_some() {
std::fs::write(&path, &base).unwrap();
} else {
assert_eq!(std::fs::read(path).unwrap(), base, "original base translation changed");
}
}
let _masked = kernel::translate_compute_with_thread_limits(&code, options, &cs, true).unwrap();
assert_eq!(kernel::translate_compute_on(&code, options, &cs, true).unwrap().dxil, base,
"building a masked entry must not mutate subsequent base translations");
}
}
48 changes: 43 additions & 5 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res
pub enum Entry {
Kernel,
Compute(CsInterface),
/// On-demand DispatchX variant; ordinary compute keeps its original prologue.
ComputeMasked(CsInterface),
Mesh(MsInterface),
Vertex(VsInterface),
Pixel(PsInterface),
Expand All @@ -148,6 +150,12 @@ pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wav
translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables)
}

/// A partial DispatchX group: IO_THREAD_LIMIT bounds each axis (0 means unbounded).
pub fn translate_compute_with_thread_limits(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::ComputeMasked(cs.clone()), compact_mode(), None, tables)
}

fn translate_entry(
code: &[u8],
o: KernelOptions,
Expand Down Expand Up @@ -203,9 +211,9 @@ fn translate_on_this_thread(
None => Cfg::build(code)?,
};
let kernel = matches!(entry, Entry::Kernel);
let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_));
let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_) | Entry::ComputeMasked(_));
let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_));
let compute = matches!(entry, Entry::Compute(_));
let compute = matches!(entry, Entry::Compute(_) | Entry::ComputeMasked(_));
let split = o.wave64 && o.split && !gfx;
let leaders: BTreeSet<u64> = 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);
Expand All @@ -223,10 +231,13 @@ fn translate_on_this_thread(
lw.init.vgpr_base = Some(base);
[if o.wave64 { 64 } else { 32 }, 1, 1]
}
Entry::Compute(cs) => {
Entry::Compute(cs) | Entry::ComputeMasked(cs) => {
let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds);
if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); }
compute_init(&mut lw, cs, tid, gtid);
if matches!(entry, Entry::ComputeMasked(_)) {
mask_compute_threads(&mut lw, cs, gtid);
}
cs.threads
}
Entry::Mesh(ms) => {
Expand Down Expand Up @@ -477,7 +488,7 @@ impl Lw {
let split = o.wave64 && o.split;
let kernel = matches!(entry, Entry::Kernel);
let cs = match entry {
Entry::Compute(cs) => Some(cs.clone()),
Entry::Compute(cs) | Entry::ComputeMasked(cs) => Some(cs.clone()),
_ => None,
};
let ms = match entry {
Expand Down Expand Up @@ -584,7 +595,7 @@ impl Lw {
let group_threads: Option<u32> = match entry {
Entry::Vertex(_) | Entry::Pixel(_) => None,
Entry::Kernel => None,
Entry::Compute(cs) => Some(cs.threads.iter().product()),
Entry::Compute(cs) | Entry::ComputeMasked(cs) => Some(cs.threads.iter().product()),
Entry::Mesh(ms) => Some(ms.threads),
Entry::Geometry(_) => Some(64),
};
Expand Down Expand Up @@ -749,6 +760,33 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3])
lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero });
}

/// Apply the thread bounds after the existing padding-lane mask. Ballot exchanges the
/// two halves of a split wave64 before EXEC disables either half's out-of-range lanes.
fn mask_compute_threads(lw: &mut Lw, cs: &CsInterface, gtid: [Value; 3]) {
let io = lw.init.io.expect("compute I/O");
let mut inside = lw.s.m.i1c(true);
let zero = lw.c(0);
for k in 0..3 {
let offset = lw.c((crate::gpu::recomp::IO_THREAD_LIMIT[k] * 4) as u32);
let limit = lw.s.raw_load(io, offset, 1)[0];
let group = lw.s.group_id(k as u32);
let size = lw.c(cs.threads[k]);
let base = lw.mul(group, size);
let global = lw.add(base, gtid[k]);
let unbounded = lw.s.m.cmp(Pred::Eq, limit, zero);
let in_range = lw.s.m.cmp(Pred::ULt, global, limit);
let axis = lw.or(unbounded, in_range);
inside = lw.and(inside, axis);
}
let (mask_lo, mask_hi) = lw.ballot(inside);
let init = lw.init.compute.as_ref().expect("compute entry");
let (lo, hi) = (init.sgpr[&126], init.sgpr[&127]);
let (lo, hi) = (lw.and(lo, mask_lo), lw.and(hi, mask_hi));
let init = lw.init.compute.as_mut().unwrap();
init.sgpr.insert(126, lo);
init.sgpr.insert(127, hi);
}

/// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the
/// wave index in s3[27:24], SCC 0, EXEC = the wave's threads, v5 = group · threads + slot,
/// other VGPRs 0; and the record slots.
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ mod compact_tests;
#[cfg(test)]
mod core_tests;
#[cfg(test)]
pub(crate) mod dispatchx_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod ops_tests;
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,11 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21;
pub const IO_GS_PRIMS: usize = 110;
pub const IO_GS_VERTICES: usize = 111;
pub const IO_UMA_BASE_HI: usize = 112;
/// io slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis
/// when it is not a whole number of groups (0: the last group is whole), so the program can leave
/// the lanes past it out of EXEC. Written by D3D12.X now; read by the compute prologue later.
/// (113 is left for the group-limit slot of #1428.)
pub const IO_THREAD_LIMIT: [usize; 3] = [114, 115, 116];

impl GsInterface {
/// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register)
Expand Down
31 changes: 26 additions & 5 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -920,13 +920,19 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool {
/// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in
/// registers. None: not a console compute shader.
pub fn compute_user_sgprs(blob: &[u8]) -> Option<u32> {
compute_interface(blob).map(|cs| cs.user_sgprs)
}

/// The dispatch ABI of a console compute program: its user SGPRs and the console's group shape
/// (`numthreads`). None: not a console compute program.
pub fn compute_interface(blob: &[u8]) -> Option<super::CsInterface> {
if let Some(f) = fspx(blob) {
return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs);
return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2));
}
let sh = xbox::parse(blob)?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?;
match interface(blob, &sh, f)? {
Mode::Compute(cs) => Some(cs.user_sgprs),
Mode::Compute(cs) => Some(cs),
_ => None,
}
}
Expand All @@ -948,6 +954,15 @@ fn direct_fallback(stage: &str, err: &str) {
/// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`).
/// FSPX (driver) containers are left to the HLSL path.
fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
direct_compute_entry(blob, sampler_base, windows, split_wave64, false)
}

/// DispatchX's distinct direct entry. A failed translation must not fall back to an unmasked shader.
pub(crate) fn masked_compute(blob: &[u8], windows: u32, split_wave64: bool) -> Result<Compiled, String> {
direct_compute_entry(blob, 0, windows, split_wave64, true)
}

fn direct_compute_entry(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool, masked: bool) -> Result<Compiled, String> {
let sh = xbox::parse(blob).ok_or("not a console shader container")?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?;
let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) };
Expand All @@ -956,7 +971,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo
let wave64 = super::fssm_wave64(f, code);
let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base };
// `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses
if super::lower_dxil::enabled() {
if !masked && super::lower_dxil::enabled() {
match super::lower_dxil::compute_with(code, &cs, o) {
Ok(k) => {
crate::gpu::dxil::coverage::record_translated("CS per-lane");
Expand All @@ -969,8 +984,14 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo
}
}
}
let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?;
dump_direct(blob, &k.dxil);
use crate::gpu::dxil::kernel;
let k = if masked {
kernel::translate_compute_with_thread_limits(code, o, &cs, split_wave64)?
} else {
let k = kernel::translate_compute_on(code, o, &cs, split_wave64)?;
dump_direct(blob, &k.dxil);
k
};
Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers })
}

Expand Down
Loading
Loading