Skip to content
Draft
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o
size of 1.9's for translated compute programs and took an NVIDIA driver 1.4–2.2 times as long to build
pipelines from ([#156](https://github.com/ivall/xcl/issues/156)). `xcl run` prints the DXC it loaded, and
`report.json` has it under `dxc`.
- With direct DXIL and multiple memory windows, vector-buffer loads, stores and atomics respect
byte-addressed descriptor limits even when their offset crosses 4 GiB into another bound window.
- **GPU:** developed on AMD RDNA4. The console's geometry and NGG programs run as a compute pass plus a
mesh pass, so a GPU without mesh shaders draws none of them. On GPUs with 32-lane waves only
(NVIDIA) console wave64 compute, geometry and mesh programs run as two 32-lane halves that exchange
Expand Down
3 changes: 2 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct KernelOptions {
/// Version of the direct translator's output, part of the on-disk translation cache's
/// identity (`recomp::pso`): bump it on any change that alters the emitted containers
/// (the `gpu/dxil` sources are not in build.rs's translator source hash).
pub const TRANSLATOR_VERSION: u32 = 5;
pub const TRANSLATOR_VERSION: u32 = 6;

/// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this
/// translator, with the HLSL path as the fallback for what it cannot translate yet.
Expand Down Expand Up @@ -166,6 +166,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu
upper: z,
half: z,
mems,
uma_base_hi: None,
heap_mem,
res,
fmt_table: None,
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ pub struct Lw {
pub half: Value,
/// the memory windows `mem`, `mem1`.. (u2..)
pub mems: Vec<RawUav>,
/// The immutable ABI window base loaded in the entry block on first use.
pub uma_base_hi: Option<Value>,
/// the windows come from the descriptor heap (`lower_window`; `mems` only counts them):
/// Some(globallycoherent)
pub heap_mem: Option<bool>,
Expand Down
86 changes: 72 additions & 14 deletions crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,53 @@ impl Lw {
}
r
}
/// A byte always fits in one aligned word. A halfword needs the next word
/// only when it starts in the last byte of the first.
fn buffer_subword(&mut self, a: Value, bytes: u32, in_range: Value) -> LResult<Value> {
let zero = self.c(0);
// Clamp invalid accesses before the read, then mask their result. Like
// dword loads this avoids a separate branch around each buffer access.
let a = self.sel(in_range, a, zero);
let word = self.mem_ld(a);
let byte = self.andc(a, 3);
let shift = self.shlc(byte, 3);
let low = self.bin(BinOp::LShr, word, shift);
let low = self.sel(in_range, low, zero);
if bytes == 1 {
return Ok(low);
}
let slot = self.tmp_var();
self.wr(slot, low);
let crosses = self.cmpc(Pred::Eq, byte, 3);
self.guarded(crosses, &mut |lw| {
let next = lw.addc(a, 1);
let next_word = lw.mem_ld(next);
let high = lw.shlc(next_word, 8);
let result = lw.or(low, high);
lw.wr(slot, result);
Ok(())
})?;
Ok(self.rd(slot))
}

/// An invalid buffer descriptor returns zero before issuing the unaligned reads.
fn checked_ld_raw(&mut self, a: Value, in_range: Value) -> LResult<[Value; 4]> {
let zero = self.c(0);
let slots: [u32; 4] = std::array::from_fn(|_| {
let slot = self.tmp_var();
self.wr(slot, zero);
slot
});
self.guarded(in_range, &mut |lw| {
let words = lw.ld_raw(a);
for (slot, word) in slots.into_iter().zip(words) {
lw.wr(slot, word);
}
Ok(())
})?;
Ok(slots.map(|slot| self.rd(slot)))
}

/// `st_part`: atomically replace the bits `m` of the dword at `b` by `v`.
fn st_part(&mut self, b: Value, m: Value, v: Value) {
let nm = self.not(m);
Expand Down Expand Up @@ -694,6 +741,21 @@ impl Lw {

// ------------------------------------------------------------ MUBUF / MTBUF

/// A byte-addressed descriptor bounds the complete offset, even when the
/// physical effective address is inside a different bound window.
fn buffer_bytes_in_range(&mut self, voff: Value, off: Value, bytes: Value, records: Value) -> Value {
let end = self.add(off, bytes);
let valid = self.cmp(Pred::ULe, end, records);
if !self.windowed() {
return valid;
}
// off = voff + immediate. Reject carry from either unsigned addition.
let offset_fits = self.cmp(Pred::UGe, off, voff);
let end_fits = self.cmp(Pred::UGe, end, off);
let fits = self.land(offset_fits, end_fits);
self.land(valid, fits)
}

pub fn mubuf(&mut self, d: &Decoded, name: &str) -> LResult<()> {
if name.starts_with("buffer_atomic_") {
return self.buffer_atomic(d, name);
Expand Down Expand Up @@ -737,8 +799,7 @@ impl Lw {
let szero = self.cmpc(Pred::Eq, stride, 0);
let idx_ok = self.cmp(Pred::ULt, index, d2);
let in_range = |lw: &mut Lw, bytes: Value| -> Value {
let e = lw.add(off, bytes);
let ok = lw.cmp(Pred::ULe, e, d2);
let ok = lw.buffer_bytes_in_range(voff, off, bytes, d2);
lw.sel(szero, ok, idx_ok)
};
if let Some((n, signed, store, half)) = d16s {
Expand All @@ -753,9 +814,7 @@ impl Lw {
return self.guarded(c, &mut |lw| lw.st_bytes(a, [data, z, z, z], nv));
}
return self.guarded(act, &mut |lw| {
let r = lw.ld_raw(a);
let z = lw.c(0);
let raw = lw.sel(ok, r[0], z);
let raw = lw.buffer_subword(a, n, ok)?;
let nv = lw.d16_merge(v, raw, n, signed, half);
lw.vset(vdata, nv);
Ok(())
Expand All @@ -772,16 +831,14 @@ impl Lw {
return self.guarded(c, &mut |lw| lw.st_bytes(a, [v, z, z, z], nv));
}
return self.guarded(act, &mut |lw| {
let r = lw.ld_raw(a);
let raw = lw.buffer_subword(a, n, ok)?;
let bits = 8 * n;
let val = if signed {
let x = lw.shlc(r[0], 32 - bits);
let x = lw.shlc(raw, 32 - bits);
lw.ashrc(x, 32 - bits)
} else {
lw.andc(r[0], ((1u64 << bits) - 1) as u32)
lw.andc(raw, ((1u64 << bits) - 1) as u32)
};
let z = lw.c(0);
let val = lw.sel(ok, val, z);
lw.vset(vdata, val);
Ok(())
});
Expand All @@ -795,8 +852,9 @@ impl Lw {
self.guarded(act, &mut |lw| {
for i in 0..count {
let at = lw.addc(a, 4 * i as u32);
let v = lw.mem_ld(at);
let z = lw.c(0);
let at = lw.sel(oks[i as usize], at, z);
let v = lw.mem_ld(at);
let v = lw.sel(oks[i as usize], v, z);
lw.vset(vdata + i, v);
}
Expand Down Expand Up @@ -841,7 +899,7 @@ impl Lw {
let ok = self.land(has, rng);
let cur: Vec<Value> = (0..count).map(|i| self.vreg(vdata + i)).collect();
self.guarded(act, &mut |lw| {
let r = lw.ld_raw(a);
let r = lw.checked_ld_raw(a, ok)?;
let c = [lw.fmt_comp(&r, info, 0), lw.fmt_comp(&r, info, 1), lw.fmt_comp(&r, info, 2), lw.fmt_comp(&r, info, 3)];
let z = lw.c(0);
if let Some((_, components, high)) = d16_format {
Expand Down Expand Up @@ -1210,8 +1268,8 @@ impl Lw {
self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(f("OFFSET") as u32), Ea::Mul(stride, index)], true);
let a = self.andc(a, !(bytes - 1));
let szero = self.cmpc(Pred::Eq, stride, 0);
let e = self.addc(off, bytes);
let r1 = self.cmp(Pred::ULe, e, d2);
let size = self.c(bytes);
let r1 = self.buffer_bytes_in_range(voff, off, size, d2);
let r2 = self.cmp(Pred::ULt, index, d2);
let ok = self.sel(szero, r1, r2);
let act = self.act();
Expand Down
24 changes: 21 additions & 3 deletions crates/xcl/src/gpu/dxil/lower_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,14 @@ impl Lw {

/// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`).
fn uma_base(&mut self) -> Value {
let io = self.init.io.expect("io");
let off = self.c(crate::gpu::recomp::IO_UMA_BASE_HI as u32 * 4);
self.s.raw_load(io, off, 1)[0]
*self.uma_base_hi.get_or_insert_with(|| {
let current = self.s.m.current_block();
self.s.m.set_block(self.init.entry);
let off = self.s.m.i32c(crate::gpu::recomp::IO_UMA_BASE_HI as u32 * 4);
let base = self.s.raw_load(self.init.io.expect("io"), off, 1)[0];
self.s.m.set_block(current);
base
})
}

/// Selects the window of an access whose 64-bit effective address is `hi:lo` plus
Expand All @@ -42,6 +47,15 @@ impl Lw {
if !self.windowed() {
return;
}
// With no displacement, the low dword cannot carry into the window selector.
let zero = |v| self.s.m.const_u64(v) == Some(0);
if adds.iter().all(|term| match *term {
Ea::K(k) => k == 0,
Ea::U(v) | Ea::S(v) => zero(v),
Ea::Mul(a, b) => zero(a) || zero(b),
}) {
return self.window_hi(hi, write);
}
let mut ea = self.pack64(lo, hi);
for &t in adds {
let x = match t {
Expand All @@ -64,6 +78,10 @@ impl Lw {
if !self.windowed() {
return;
}
if !write && self.s.m.const_u64(hi) == Some(0) {
self.wr(VAR_WIN, hi);
return;
}
let base = self.uma_base();
let mut w = self.sub(hi, base);
if !write {
Expand Down
54 changes: 50 additions & 4 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3331,7 +3331,8 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
if !gpu_ready() {
return;
}
let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap();
let windows = 4;
let arena = crate::gpu::uma::Uma::with_windows(windows, 1 << 20).unwrap();
let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64);
assert_eq!(w1 - w0, 1 << 32);
let base_hi = (w0 >> 32) as u32;
Expand All @@ -3350,6 +3351,16 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
*word(w0 + 0x4000) = 0xABCD_0123; // 32-bit hi=0 descriptor-table style read target
*word(w1 + 0x5000) = 0x5566_7788; // valid strided V# buffer_load target
*word(w1 + 0x0010) = 0x99AA_BBCC; // 64-bit carry target: (w0 + 0xFFFF_FFF0) + 0x20 == w1 + 0x10
*word(w1 + 0x18) = CANARY1;
*word(w1 + 0x14) = 0xfe;
*word(w1 + 0x1c) = CANARY1;
let counter = |win: usize, lane: usize| arena.window(win).0 as u64 + 0x7000 + 4 * lane as u64;
let initial = |win: usize, lane: usize| (win * 1000 + lane + 1) as u32;
for win in 0..windows {
for lane in 0..64 {
*word(counter(win, lane)) = initial(win, lane);
}
}

let glbl = |n: &'static str, f: &[(&str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option<u32>) {
(n, "ENC_FLAT_GLBL", f.iter().map(|&(a, b)| (unsafe { std::mem::transmute::<&str, &'static str>(a) }, b)).collect(), None)
Expand Down Expand Up @@ -3378,13 +3389,24 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 17), ("ADDR", 16), ("SADDR", 20), ("OFFSET", 0)]),
// 11. 64-bit signed borrow out of UMA: s[22:23] = w0 + 0x0 + (-16) -> (base_hi - 1, 0xFFFF_FFF0) -> dropped, reads 0 (v18)
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 18), ("ADDR", 0), ("SADDR", 22), ("OFFSET", 0xFF0)]),
glbl("GLOBAL_ATOMIC_ADD", &[("VDST", 35), ("ADDR", 32), ("DATA", 34), ("SADDR", 0x7D), ("GLC", 1)]),
("BUFFER_LOAD_UBYTE", "ENC_MUBUF", vec![("VDATA", 39), ("VADDR", 38), ("SRSRC", 11), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 20)], None),
("BUFFER_STORE_DWORD", "ENC_MUBUF", vec![("VDATA", 1), ("VADDR", 38), ("SRSRC", 11), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 28)], None),
("BUFFER_ATOMIC_ADD", "ENC_MUBUF", vec![("VDATA", 41), ("VADDR", 38), ("SRSRC", 12), ("SOFFSET", 128), ("OFFEN", 1), ("GLC", 1)], None),
// Read the crossing halfword twice at the same instruction, shrinking the
// descriptor from 64 to 0 between iterations. Keep both results observable.
("V_MOV_B32", "ENC_VOP1", vec![("VDST", 43), ("SRC0", V + 42)], None),
("BUFFER_LOAD_USHORT", "ENC_MUBUF", vec![("VDATA", 42), ("SRSRC", 13), ("SOFFSET", 128), ("OFFSET", 3)], None),
("S_SUB_U32", "ENC_SOP2", vec![("SDST", 54), ("SSRC0", 54), ("SSRC1", 192)], None),
("S_CBRANCH_SCC0", "ENC_SOPP", vec![("SIMM16", 0xfffb)], None), // repeat until subtraction borrows
];
let refs: Vec<(&str, &str, &[(&str, u64)], Option<u32>)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect();
let p = prog(&refs);
let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap();
let opt = on_gpu(Options { mem_windows: windows as u32, heap_windows: heap, ..Default::default() });
let t = translate(&p, &opt).unwrap();
assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap);
let hlsl_dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil);
let dxil = direct_or(&p, &opt, hlsl_dxil);

let mut st = KernelState::default();
st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + 4]); // s[2:3]: out-of-UMA hi = base_hi + 4
Expand All @@ -3394,7 +3416,11 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + 4) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3)
st.sgpr[20..22].copy_from_slice(&[0xFFFF_FFF0, base_hi]); // carry base
st.sgpr[22..24].copy_from_slice(&[0, base_hi]); // borrow base (0 - 16 borrows into base_hi - 1)
for r in st.vgpr.iter_mut() {
st.sgpr[44..48].copy_from_slice(&[0, base_hi, 64, 0]);
st.sgpr[48..52].copy_from_slice(&[0x20, base_hi, 64, 0]);
st.sgpr[52..56].copy_from_slice(&[0x10, base_hi + 1, 64, 0]);
st.sgpr[126..128].fill(0x5555_5555);
for (lane, r) in st.vgpr.iter_mut().enumerate() {
r[0] = 0; // index 0
r[1] = 0xBAD0_DEAD; // poison value to store
r[2] = 0x7777_7777; // sentinel overwritten to 0 by out-of-UMA buffer_load
Expand All @@ -3411,6 +3437,14 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
r[13] = 0xFFFF_FFFF; // out-of-UMA global_atomic_inc CAS loop
r[16] = 0x20; // carry offset: 0xFFFF_FFF0 + 0x20 = 0x1_0000_0010 -> w1 + 0x10
r[18] = 0x7777_7777;
r[32] = 0x7000 + 4 * lane as u32;
r[33] = base_hi + ((lane / 2) % (windows + 1)) as u32;
r[34] = 1;
r[35] = 0x7777_7777;
// Lane zero crosses 4 GiB into valid memory beyond the 64-byte descriptor.
r[38] = if lane == 0 { u32::MAX - 3 } else { 64 };
r[39] = 0x7777_7777;
r[41] = 7;
}

let r = runner::run_in_arena(&dxil, &st, &arena).unwrap();
Expand All @@ -3423,6 +3457,18 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
assert_eq!(r.vgpr[0][14], 0, "out-of-UMA buffer_atomic_add GLC must return 0");
assert_eq!(r.vgpr[0][17], 0x99AA_BBCC, "64-bit carry global_load must cross from w0 into w1");
assert_eq!(r.vgpr[0][18], 0, "64-bit signed borrow below window 0 must be rejected and read 0");
assert_eq!((r.vgpr[0][43], r.vgpr[0][42]), (0xfe99, 0), "crossing halfword, then zero after the descriptor shrinks");
assert_eq!((r.vgpr[0][39], *word(w1 + 0x18), r.vgpr[0][41], *word(w1 + 0x1c)), (0, CANARY1, 0, CANARY1),
"descriptor offset or access width wrapping across 4 GiB must reject the load, store and atomic");
for lane in 0..64 {
let selected = (lane / 2) % (windows + 1);
let active = lane % 2 == 0;
let expected = if !active { st.vgpr[lane][35] } else if selected < windows { initial(selected, lane) } else { 0 };
assert_eq!(r.vgpr[lane][35], expected, "atomic return for lane {lane}");
for win in 0..windows {
assert_eq!(*word(counter(win, lane)), initial(win, lane) + u32::from(active && win == selected), "window {win}, lane {lane}");
}
}

assert_eq!(*word(w0 + 0x1000), CANARY0, "out-of-UMA global_store must not clobber w0");
assert_eq!(*word(w1 + 0x1000), CANARY1, "out-of-UMA buffer_store must not clobber w1");
Expand Down
Loading