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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,9 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o
masks and lane values ([`docs/wave64-on-wave32.md`](docs/wave64-on-wave32.md)) – slower than
64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63
can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups
made up of complete native waves can use the per-lane form for branches on whole-wave masks.
made up of complete native waves can use the per-lane form for branches on whole-wave masks;
split-wave64 programs that access LDS stay on the HLSL path to preserve instruction order
between their two hardware wave32 halves.
Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42).

```powershell
Expand Down
13 changes: 12 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,14 @@ pub enum Entry {
Geometry(GsInterface),
}

/// Whether `d` accesses the group's LDS rather than using the DS encoding for a cross-lane
/// operation. GDS is separate global memory and is refused by the instruction lowering itself.
pub(crate) fn real_lds_access(d: &Decoded) -> bool {
d.enc.name == "ENC_DS"
&& crate::gpu::rdna2::field_value(d.enc, &d.words, "GDS") != Some(1)
&& !matches!(d.inst.name, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP")
}

/// 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(), None)
Expand Down Expand Up @@ -226,6 +234,9 @@ fn translate_on_this_thread(
let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_));
let compute = matches!(entry, Entry::Compute(_));
let split = o.wave64 && o.split && !gfx;
if split && !matches!(entry, Entry::Geometry(_)) && cfg.insts.iter().any(real_lds_access) {
return Err("split wave64 LDS access needs the HLSL path".into());
}
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);
let uses_lds = lw.lds.is_some();
Expand Down Expand Up @@ -592,7 +603,7 @@ impl Lw {
let mut slot = 1u32;
for d in insts {
let n = d.inst.name;
if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") {
if real_lds_access(d) {
uses_lds = true;
}
if n == "DS_BPERMUTE_B32" {
Expand Down
32 changes: 32 additions & 0 deletions crates/xcl/src/gpu/dxil/robustness_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,38 @@ fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() {
kernel::translate_mesh(&code, o(false, false), &ms(32)).expect("a mesh pass of one 32-lane wave");
}

#[test]
fn split_wave64_real_lds_is_left_to_the_hlsl_path() {
let write = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]);
let swizzle = prog(&[("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 4)], None)]);
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 };
let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };

let e = kernel::translate_compute(&write, o(true, true), &cs).err().expect("split LDS translated");
assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}");
kernel::translate_compute(&write, o(true, false), &cs).expect("native wave64 LDS");
kernel::translate_compute(&write, o(false, false), &cs).expect("native wave32 LDS");
kernel::translate_compute(&swizzle, o(true, true), &cs).expect("split cross-lane DS");
}

#[test]
fn real_lds_classification_excludes_cross_lane_ds_and_gds() {
let one = |name, fields: &[(&str, u64)]| {
let bytes = encode(name, "ENC_DS", fields, None).unwrap();
crate::gpu::rdna2::decode(&bytes, 0).unwrap()
};
assert!(kernel::real_lds_access(&one("DS_READ_B32", &[("VDST", 1), ("ADDR", 0)])));
assert!(!kernel::real_lds_access(&one("DS_READ_B32", &[("VDST", 1), ("ADDR", 0), ("GDS", 1)])));
for (name, fields) in [
("DS_SWIZZLE_B32", &[("VDST", 1), ("ADDR", 0)][..]),
("DS_BPERMUTE_B32", &[("VDST", 1), ("ADDR", 0), ("DATA0", 1)][..]),
("DS_PERMUTE_B32", &[("VDST", 1), ("ADDR", 0), ("DATA0", 1)][..]),
("DS_NOP", &[][..]),
] {
assert!(!kernel::real_lds_access(&one(name, fields)), "{name}");
}
}

// ---- builder misuse: recorded as the first error, finish fails instead of panicking

use super::container::Stage;
Expand Down
68 changes: 67 additions & 1 deletion crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@ pub(super) struct Em {
img_writes: Vec<u64>,
/// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`)
pub coherent_mem: bool,
/// split wave64: what lies between the basic block's previous LDS access and here
x64_lds: LdsGap,
/// first instructions of the basic blocks (branch targets, after branches)
block_starts: BTreeSet<u64>,
}

/// Split wave64 (`x64_lds_meet`): since the basic block's previous LDS access
#[derive(Clone, Copy, PartialEq)]
enum LdsGap {
/// that was a write or an atomic, or there was none in the block
Open,
/// that was a read, and no exchange since
Read,
/// the halves met in an exchange since
Met,
}

/// The T# SGPRs (SRSRC) of a program's image stores and atomics, at most 16, sorted. An
Expand Down Expand Up @@ -595,7 +610,9 @@ fn to_f16_rounded_expr(dynamic_rm: bool, e: &str) -> String {
}

impl Em {
pub fn new(opt: Options) -> Self {
/// `block_starts`: the first instructions of the program's basic blocks (branch targets and
/// the instructions after branches): split wave64 elides no LDS meeting across them.
pub fn new(opt: Options, block_starts: BTreeSet<u64>) -> Self {
Em {
opt,
reductions: Default::default(),
Expand Down Expand Up @@ -629,6 +646,8 @@ impl Em {
has_s_barrier: false,
img_writes: Vec::new(),
coherent_mem: false,
x64_lds: LdsGap::Open,
block_starts,
}
}

Expand Down Expand Up @@ -986,6 +1005,9 @@ impl Em {
ballot = "ballot_px_local";
}
}
if ballot == "xcl_x_ballot" {
self.x64_met();
}
match if ballot == "ballot_px" { quad_bits(a, cond, &m) } else { None } {
Some((reads, q)) => {
if !reads.is_empty() {
Expand Down Expand Up @@ -1143,6 +1165,7 @@ impl Em {
self.line(&format!("uint {t}_m = WaveReadLaneAt({v}, {lane32}u);"));
self.line(&format!("xcl_x_put(0u, {t}_m);"));
self.line(&format!("uint {t}_o = xcl_x_meet() ? xcl_x_get(0u) : 0u;"));
self.x64_met();
self.line(&format!("uint {t}_r1 = xcl_half == {}u ? {t}_m : {t}_o;", l1 >> 5));
self.line(&format!("uint {t}_r2 = xcl_half == {}u ? {t}_m : {t}_o;", l2 >> 5));
self.write32(&dst1, &format!("{t}_r1"));
Expand All @@ -1167,6 +1190,7 @@ impl Em {
self.line(&format!("uint {t}_m = WaveReadLaneAt({v}, {lane32}u);"));
self.line(&format!("xcl_x_put(0u, {t}_m);"));
self.line(&format!("uint {t}_o = xcl_x_meet() ? xcl_x_get(0u) : 0u;"));
self.x64_met();
self.line(&format!("uint {r1} = xcl_half == {}u ? {t}_m : {t}_o;", l1 >> 5));
self.line(&format!("uint {r2} = xcl_half == {}u ? {t}_m : {t}_o;", l2 >> 5));
self.write32(&Dst::S(s1), &r1);
Expand Down Expand Up @@ -1218,6 +1242,7 @@ impl Em {
self.line(&format!("uint {t}_mh = WaveReadLaneAt({vh}, {lane32}u);"));
self.line(&format!("xcl_x_put(0u, {t}_ml); xcl_x_put(1u, {t}_mh);"));
self.line(&format!("bool {t}_ok = xcl_x_meet();"));
self.x64_met();
self.line(&format!("uint {t}_ol = {t}_ok ? xcl_x_get(0u) : 0u;"));
self.line(&format!("uint {t}_oh = {t}_ok ? xcl_x_get(1u) : 0u;"));
let (h1, h2) = (l1 >> 5, l2 >> 5);
Expand Down Expand Up @@ -1255,6 +1280,9 @@ impl Em {
let text = rdna2::format(d);
self.line(&format!("// {:04x}: {text}", d.pc));
self.cur_pc = d.pc;
if self.block_starts.contains(&d.pc) {
self.x64_lds = LdsGap::Open;
}
// a far jump (`rdna2::resolve_far_jumps`) is an unconditional branch
if let Some(t) = d.far_target {
return Flow::Jump(t);
Expand Down Expand Up @@ -1994,6 +2022,7 @@ impl Em {
}
let get: Vec<String> = vals.iter().enumerate().map(|(i, v)| format!("{v} = xcl_x_get({i}u);")).collect();
self.line(&format!("if (xcl_x_meet() && xcl_half != 0u) {{ {} }}", get.join(" ")));
self.x64_met();
}
for (i, v) in vals.iter().enumerate() {
let s = self.sreg(sdata + i as u64);
Expand Down Expand Up @@ -4094,6 +4123,7 @@ impl Em {
let rla = self.rla_uniform_fn();
// (a live lane of EXEC where there is one: `first_lane_live`)
self.line(&format!("uint {t} = {rla}({a}, first_lane_live({el}, {eh}));"));
self.x64_met();
self.write32(&dst, &t);
return Ok(());
}
Expand Down Expand Up @@ -4121,6 +4151,8 @@ impl Em {
(Some(Read::Shadow), Some((v, l))) => self.line(&format!("uint {t} = xcl_sh{v}_{l}; if (!xcl_hw32) {t} = {read};")),
_ => self.line(&format!("uint {t} = {read};")),
}
// split wave64 (no `upper` there): the last arm, an exchange
self.x64_met();
self.write32(&dst, &t);
return Ok(());
}
Expand Down Expand Up @@ -4526,6 +4558,33 @@ impl Em {
}

/// LDS (`groupshared`, compute only) and the DS cross-lane permutes.
/// Split wave64: the console runs an instruction in all 64 lanes before the next, so a lane
/// reads the LDS the other half wrote an instruction earlier with no s_barrier – the halves
/// meet before every LDS access (nothing exchanged: the meeting is the order). Called once
/// the access is known to be translated. Not in geometry mode: ES lanes write their own
/// items and read no other lane's before the barrier where the phases meet.
/// No meeting for a read right after a read of the same basic block, nor when the halves
/// met in an exchange since the block's previous access (`LdsGap`). Still in order: for
/// accesses j < i of the stream, one a write, the halves meet between them (the access
/// after a write and every write meet, or an exchange lies before them; a block's first
/// access meets), and both halves pass the same meetings: the other half's j is done
/// before this half's i. Two reads need no order.
fn x64_lds_meet(&mut self, write: bool) {
if self.x64() && !matches!(self.opt.mode, Mode::Geometry(_)) {
if self.x64_lds == LdsGap::Open || (write && self.x64_lds == LdsGap::Read) {
self.line("xcl_x_meet();");
}
self.x64_lds = if write { LdsGap::Open } else { LdsGap::Read };
}
}

/// An exchange (`xcl_x_meet`) the current instruction always runs, in the split form.
fn x64_met(&mut self) {
if self.x64() {
self.x64_lds = LdsGap::Met;
}
}

fn ds(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
let act = self.act();
Expand Down Expand Up @@ -4557,6 +4616,7 @@ impl Em {
self.line(&format!("uint {t}_l = (({a} + {off16}u) >> 2) & {m}u;"));
let rla = if self.x64() {
self.x64_words = 32;
self.x64_met();
"xcl_x_rla_any"
} else {
"rla"
Expand Down Expand Up @@ -4587,6 +4647,7 @@ impl Em {
}
// ADDTID forms have no ADDR VGPR: byte address = M0[15:0] + offset16 + 4 * lane_id.
if matches!(name, "ds_write_addtid_b32" | "ds_read_addtid_b32") {
self.x64_lds_meet(name == "ds_write_addtid_b32");
self.uses_lds = true;
let m0 = self.sreg(124);
let at = format!("(({m0} & 0xFFFFu) + {off16}u + 4u * lane_id)");
Expand Down Expand Up @@ -4651,6 +4712,7 @@ impl Em {
};
// d16 8 / 16-bit LDS accesses (half of the VGPR)
if let Some((bits, signed, write, half)) = ds_d16(name) {
self.x64_lds_meet(write);
let at = format!("{a} + {off16}u");
let slot = lds(at.clone());
let sh = format!("((({at}) & 3u) * 8u)");
Expand All @@ -4676,6 +4738,7 @@ impl Em {
_ => None,
};
if let Some((bits, signed, write)) = small {
self.x64_lds_meet(write);
let at = format!("{a} + {off16}u");
let slot = lds(at.clone());
let sh = format!("((({at}) & 3u) * 8u)");
Expand All @@ -4697,6 +4760,7 @@ impl Em {
return Ok(());
}
if let Some((write, n, stride, two)) = rw(name) {
self.x64_lds_meet(write);
let addrs: Vec<String> = if two {
vec![format!("{a} + {}u", o0 * stride), format!("{a} + {}u", o1 * stride)]
} else {
Expand Down Expand Up @@ -4729,6 +4793,7 @@ impl Em {
};
// two exchanges (ds_wrxchg2(st64)_rtn_b32): old values to VDST, VDST + 1
if op == "wrxchg2_b32" || op == "wrxchg2st64_b32" {
self.x64_lds_meet(true);
let stride = if op == "wrxchg2_b32" { 4 } else { 256 };
let (s0, s1) = (lds(format!("{a} + {}u", o0 * stride)), lds(format!("{a} + {}u", o1 * stride)));
let (v0, v1) = (self.vreg(f("DATA0")), self.vreg(f("DATA1")));
Expand All @@ -4744,6 +4809,7 @@ impl Em {
let (v, v2) = if op.starts_with("cmpst_") { (d1, d0) } else { (d0, d1) };
let slot = lds(format!("{a} + {off16}u"));
let body = rmw32(&op, &At::Ref(slot), &v, &v2, &format!("{t}_o"), &t).ok_or("DS")?;
self.x64_lds_meet(true);
self.line(&format!("uint {t}_o = 0u; if ({act}) {{ {body} }}"));
if rtn {
let r = self.vreg(f("VDST"));
Expand Down
37 changes: 37 additions & 0 deletions crates/xcl/src/gpu/recomp/lower_dxil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,17 +352,26 @@ pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec<u8>, Vec<u8>), Str
Ok((ir.finish([lanes, 1, 1], lanes)?.dxil, stale))
}

fn refuse_split_real_lds(insts: &[Decoded]) -> Result<(), String> {
if insts.iter().any(crate::gpu::dxil::kernel::real_lds_access) {
return Err("split wave64 LDS access needs the HLSL path".into());
}
Ok(())
}

/// `kernel` in the split form: a wave64 program as two hardware wave32s (`DxilIr::split`).
/// EXEC at launch must be the whole console wave, as the CPU interpreter and the HLSL path
/// start it.
pub fn kernel_split(insts: &[Decoded]) -> Result<(Vec<u8>, Vec<u8>), String> {
refuse_split_real_lds(insts)?;
let (ir, stale) = lower::lower_kernel(insts, true, DxilIr::split(insts, &Entry::Kernel))?;
Ok((ir.finish([64, 1, 1], 32)?.dxil, stale))
}

/// `compute` in the split form: each console wave64 as two hardware wave32s, threads numbered
/// by arrival (`Lw::setup_lanes_compute`).
pub fn compute_split(insts: &[Decoded], cs: &super::CsInterface) -> Result<Vec<u8>, String> {
refuse_split_real_lds(insts)?;
let ir = lower::lower_compute(insts, cs, true, DxilIr::split(insts, &Entry::Compute(cs.clone())))?;
Ok(ir.finish(cs.threads, 32)?.dxil)
}
Expand Down Expand Up @@ -421,6 +430,9 @@ pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> R
insts.push(d);
}
crate::gpu::rdna2::resolve_far_jumps(&mut insts);
if o.wave64 && o.split {
refuse_split_real_lds(&insts)?;
}
// as `kernel::translate_entry`: a thread with a large stack, a panic is a refusal
let cs = cs.clone();
std::thread::Builder::new()
Expand Down Expand Up @@ -799,6 +811,31 @@ mod tests {
}
}

#[test]
fn the_runtime_path_leaves_split_wave64_lds_to_hlsl() {
let bytes = crate::gpu::rdna2::encode("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None).unwrap();
let cs = compute_cs();
let o = |wave64, split| super::KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };

let e = super::compute_with(&bytes, &cs, o(true, true)).err().expect("split LDS translated");
assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}");
let insts = [crate::gpu::rdna2::decode(&bytes, 0).unwrap()];
let e = super::kernel_split(&insts).err().expect("split kernel LDS translated");
assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}");
let e = super::compute_split(&insts, &cs).err().expect("split compute LDS translated");
assert!(e.contains("split wave64 LDS access needs the HLSL path"), "{e}");
super::compute_with(&bytes, &cs, o(true, false)).expect("native wave64 LDS");
super::compute_with(&bytes, &cs, o(false, false)).expect("native wave32 LDS");

let swizzle = crate::gpu::rdna2::encode(
"DS_SWIZZLE_B32",
"ENC_DS",
&[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 4)],
None,
).unwrap();
super::compute_with(&swizzle, &cs, o(true, true)).expect("split cross-lane DS");
}

/// The f64 program of `lower`'s tests, as `f32_programs_on_the_gpu`.
#[test]
fn f64_programs_on_the_gpu() {
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1571,7 +1571,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result<Translation, String> {
leaders.insert(next);
}
}
let mut em = emit::Em::new(opt.clone());
let mut em = emit::Em::new(opt.clone(), leaders.clone());
em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts);
em.configure_round_modes(&insts, branches == 0);
em.static_ss = constant_samplers(&insts, &leaders);
Expand Down
Loading
Loading