From 6494b6318ee61f9645aad29430600df6a63e41db Mon Sep 17 00:00:00 2001 From: Rex <38073041+not-rex@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:23:20 +1030 Subject: [PATCH 1/3] Recompiler: split wave64 halves meet before each LDS access On a 32-lane GPU a console wave64 program runs as two 32-lane halves. The split form orders cross-lane exchanges between the halves but not LDS accesses, so a half could read LDS before the other half's earlier write (or after its later one) landed. The new GPU test gpu_split_wave64_lds_follows_instruction_order (upper half writes, lower half reads, and the reverse; 1,024 groups) failed 60 of 60 runs on an RTX 5070 Ti (26,048-50,688 of 65,536 threads wrong, in the spin form, with XCL_WAVE64_SPIN=0, and under load) and passed 60 of 60 with this change. Those runs were of its first form, groups of one console wave. It now also runs groups of four (256 threads, the counter-paired form): without the meetings 237,824-239,936 of 262,144 threads were wrong there in 5 of 5 runs; with them the split_wave64 tests pass 5 of 5 runs. The halves now meet (xcl_x_meet(), nothing exchanged) before each LDS access in kernel / compute / mesh mode, once the access is known to be translated. The meeting orders instructions, not the lanes of one instruction. Cost: one exchange per LDS instruction on 32-lane GPUs; the test program goes from 1 exchange to 7 (spin form 0.046 -> 0.120 ms for 16,384 groups, barrier form unchanged). Native wave64 HLSL is unchanged. docs/wave64-on-wave32.md states the rule. split_wave64_meets_before_each_lds_access checks the emitted HLSL without a GPU: six meetings for the test program in the split form, none natively, in a wave32 program or for an access that is not translated (GDS). Assisted-by: Claude Code (Claude Fable 5.2) --- crates/xcl/src/gpu/recomp/emit.rs | 17 +++++ crates/xcl/src/gpu/recomp/tests.rs | 101 +++++++++++++++++++++++++++++ docs/wave64-on-wave32.md | 13 +++- 3 files changed, 130 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 3a7a0348e5..db1c331346 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4444,6 +4444,17 @@ 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. + fn x64_lds_meet(&mut self) { + if self.x64() && !matches!(self.opt.mode, Mode::Geometry(_)) { + self.line("xcl_x_meet();"); + } + } + 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(); @@ -4505,6 +4516,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(); self.uses_lds = true; let m0 = self.sreg(124); let at = format!("(({m0} & 0xFFFFu) + {off16}u + 4u * lane_id)"); @@ -4569,6 +4581,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(); let at = format!("{a} + {off16}u"); let slot = lds(at.clone()); let sh = format!("((({at}) & 3u) * 8u)"); @@ -4594,6 +4607,7 @@ impl Em { _ => None, }; if let Some((bits, signed, write)) = small { + self.x64_lds_meet(); let at = format!("{a} + {off16}u"); let slot = lds(at.clone()); let sh = format!("((({at}) & 3u) * 8u)"); @@ -4615,6 +4629,7 @@ impl Em { return Ok(()); } if let Some((write, n, stride, two)) = rw(name) { + self.x64_lds_meet(); let addrs: Vec = if two { vec![format!("{a} + {}u", o0 * stride), format!("{a} + {}u", o1 * stride)] } else { @@ -4647,6 +4662,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(); 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"))); @@ -4662,6 +4678,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(); self.line(&format!("uint {t}_o = 0u; if ({act}) {{ {body} }}")); if rtn { let r = self.vreg(f("VDST")); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 9be60bf7f6..22777035a2 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7250,6 +7250,107 @@ fn gpu_split_wave64_waves_diverge() { } } +/// The program of the two tests below. A console wave64 runs an instruction in all 64 lanes +/// before the next one, so a lane reads the LDS word a lane of the other half wrote an +/// instruction earlier with no `s_barrier` between them – and not what that lane writes an +/// instruction later. Each half writes a word per lane, the other half reads it, the writer +/// overwrites it: under constant EXEC masks, so nothing else makes the two hardware wave32s of +/// the split form meet between the six accesses. The values carry the group, so a word another +/// group left in the LDS is not the right one. s1 = log2 of the threads per group. +fn lds_order_program() -> Vec { + prog(&[ + // v0 = thread in the group, s4 = group: n = (group << s1) + thread, the values k << 28 | n + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 1)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 5), ("VSRC1", 0)], None), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 10)], Some(0x1000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 10)], Some(0x2000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 255), ("VSRC1", 10)], Some(0x3000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 255), ("VSRC1", 10)], Some(0x4000_0000)), + // v1 = the thread's own word, v2 = the word of thread ^ 32 (the same lane of the other half) + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 160), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)], None), + // lanes 32..63: a[own] = 1 << 28 | n + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 193)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 6)], None), + // lanes 0..31: v4 = a[other], b[own] = 2 << 28 | n (b: 1024 bytes on) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 7), ("OFFSET1", 4)], None), + // lanes 32..63: v5 = b[other], a[own] = 3 << 28 | n (after the other half read it) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 193)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 5), ("ADDR", 2), ("OFFSET1", 4)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 8)], None), + // lanes 0..31: b[own] = 4 << 28 | n (after the other half read it) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 9), ("OFFSET1", 4)], None), + // every lane: out[n] = (v4, v5) + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 131), ("VSRC1", 10)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 0), ("VSRC1", 12)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 12), ("DATA", 4), ("SADDR", 0x7D)], None), + ]) +} + +fn lds_order_cs(threads: u32) -> super::CsInterface { + super::CsInterface { threads: [threads, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 } +} + +/// Without a GPU: the split form of `lds_order_program` meets before each of its six LDS +/// accesses (constant masks: nowhere else), and only the split form does – not a native wave64 +/// translation, not a wave32 program, and not an access that is not translated. +#[test] +fn split_wave64_meets_before_each_lds_access() { + let meets = |code: &[u8], wave64: bool, split_wave64: bool| { + let t = translate(code, &Options { mode: Mode::Compute(lds_order_cs(64)), wave64, split_wave64, ..Default::default() }).unwrap(); + (t.hlsl.matches("xcl_x_meet();").count(), t.complete()) + }; + let p = lds_order_program(); + assert_eq!(meets(&p, true, true), (6, true)); + assert_eq!(meets(&p, true, false), (0, true), "native wave64"); + assert_eq!(meets(&p, false, true), (0, true), "a wave32 program"); + let gds = prog(&[("DS_READ_ADDTID_B32", "ENC_DS", &[("VDST", 3), ("GDS", 1)], None)]); + assert_eq!(meets(&gds, true, true), (0, false), "GDS: not translated"); +} + +/// `lds_order_program` on the GPU, in groups of one console wave and of four (split, the +/// counter-paired form): every read gets the word written an instruction before it. +#[test] +fn gpu_split_wave64_lds_follows_instruction_order() { + if !gpu_ready() { + return; + } + let p = lds_order_program(); + for threads in [64usize, 256] { + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(lds_order_cs(threads as u32)), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + if runner::split_wave64() { + assert!(t.hlsl.contains("[WaveSize(32)]")); + } + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let (groups, base) = (1024usize, 0x100usize); + let mut io = vec![0u32; 128]; + io[0] = base as u32; + io[1] = threads.trailing_zeros(); + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * threads * 8) / 4]).unwrap(); + let mut wrong = Vec::new(); + for n in 0..groups * threads { + let (at, lane, other) = ((base + n * 8) / 4, n % 64, (n ^ 32) as u32); + // lanes 0..31 read a (v4), lanes 32..63 read b (v5): the first value written there + let want = if lane < 32 { [0x1000_0000 | other, 0] } else { [0, 0x2000_0000 | other] }; + if out[at..at + 2] != want { + wrong.push(format!("group {} thread {}: read {:x?}, not {want:x?}", n / threads, n % threads, &out[at..at + 2])); + } + } + assert!(wrong.is_empty(), "{threads} threads per group: {} of {} threads read LDS out of instruction order: {}", wrong.len(), groups * threads, wrong[..wrong.len().min(4)].join("; ")); + } +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d203537..1fae024948 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -43,6 +43,7 @@ whole-wave: | `ds_bpermute` (any lane) | 32 words: each half gives its lanes | | DPP16, DPP8, `ds_swizzle`, `v_permlane(x)16` | none: the ISA keeps them inside a 32-lane half (`WaveReadLaneAt(v, l & 31)`) | | `s_load*` / `s_buffer_load*` with GLC (or DLC) | up to 16 words: half 0's values for both (memory another wave writes may change between the two halves' loads; without GLC the console's scalar cache is not coherent either, so plain loads are read by both halves) | +| an LDS access (`ds_read*`, `ds_write*`, the LDS atomics) in kernel, compute and mesh mode | no words: the halves meet before it, so each half's earlier instructions are done (hazard 6) | So both halves hold the full 64-bit EXEC / VCC / masks and identical SGPRs; every branch is taken the same way by both, and the existing scalar code (`s_bcnt1_i32_b64`, `s_ff1`, @@ -100,6 +101,16 @@ it. A program that really uses the whole 32 KB of LDS therefore loses its top dw without the remap). 4. **`WaveReadLaneAt` with a per-lane index** – used inside a half as before. 5. **Forward progress** – only the multi-wave variant spins; see above. +6. **LDS order** – a console wave runs an instruction in all 64 lanes before the next one, + so a lane reads the LDS another lane wrote an instruction earlier with no `s_barrier`. + Two halves that meet only at exchanges read such a word before it is written, or after a + later write (`gpu_split_wave64_lds_follows_instruction_order`: up to three quarters of + the threads on an RTX 5070 Ti). The halves therefore meet before every LDS access. The + meeting orders instructions, not the lanes of one instruction: when lanes of both halves + write or atomically update the same word in one instruction, which half goes first is not + the console's order. Geometry mode has no meetings: it assumes ES code reads no other + lane's item before the `s_barrier` (ES lanes write their own items, and the phases meet + at a group barrier). ### Masks read lane by lane @@ -139,7 +150,7 @@ destination, 0 in every lane), which are the same in both halves either way. A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` feeding `s_and_saveexec`, `s_cbranch_vccz`, `s_bcnt1`, …) and per readlane / readfirstlane / -ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP instruction, nor for +ds_bpermute / coherent scalar load / LDS access, nothing per ALU, global memory or DPP instruction, nor for masks read lane by lane (selects, 64-bit carry chains). Wave32 programs and everything on GPUs with 64-lane waves are unchanged (the HLSL of every native translation the test suite makes is byte-identical). A wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant (the lane read is skipped) and From 73be6b39aa4dca9aa158f3a8a6a2d2758a9c4372 Mon Sep 17 00:00:00 2001 From: Rex <38073041+not-rex@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:35:45 +1030 Subject: [PATCH 2/3] Recompiler: split wave64 halves skip LDS meetings that order nothing The meeting before every LDS access (previous commit) made a heavy-LDS world stall on an RTX 3060 (PR #1252). Two cases need no meeting: - a read right after a read in the same basic block (two reads need no order; the meeting before the run's first read orders it after the other half's earlier writes, and the next write's meeting waits for this half's reads); - an access when an exchange (ballot, readlane, readfirstlane, bpermute, coherent scalar load) lies between it and the block's previous LDS access: the exchange is a meeting. A mask kept in its half (xcl_x_ballot_local) is no exchange. A block's first access, every write / atomic and a read after a write still meet, so for any two accesses of the stream, one a write, the halves meet between them. Em::new takes the block starts (the branch leaders), so no caller can elide across blocks by leaving them out. Meetings: lds_order_program stays at 6 (every access is a write or a read after a write); the new lds_read_run_program (2 writes, 4 reads, 2 writes) goes from 8 to 5, and to 3 with an exchange after the writes and after the reads. split_wave64_meets_once_per_read_run, ..._lds_local_mask_is_no_meeting and ..._lds_meets_at_loop_head check the rule without a GPU (they fail with a local mask counted as a meeting or without the block-start reset); gpu_split_wave64_lds_read_run_follows_instruction_order checks on the GPU that the reads without a meeting see the other half's writes before the run and not those after it (64 / 256-thread groups, with meetings and with exchanges). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 64 ++++++++++++--- crates/xcl/src/gpu/recomp/mod.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 120 +++++++++++++++++++++++++++++ docs/wave64-on-wave32.md | 14 ++-- 4 files changed, 184 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index db1c331346..5d097ef3bb 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -74,6 +74,21 @@ pub(super) struct Em { safe_barrier: bool, /// the T# SGPRs of the program's image stores and atomics (`image_write_srsrcs`) img_writes: Vec, + /// 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, +} + +/// 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 @@ -591,7 +606,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) -> Self { Em { opt, reductions: Default::default(), @@ -623,6 +640,8 @@ impl Em { track_frexp_denorm: false, safe_barrier: false, img_writes: Vec::new(), + x64_lds: LdsGap::Open, + block_starts, } } @@ -979,6 +998,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() { @@ -1248,6 +1270,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); @@ -1987,6 +2012,7 @@ impl Em { } let get: Vec = 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); @@ -4012,6 +4038,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(()); } @@ -4039,6 +4066,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(()); } @@ -4449,9 +4478,25 @@ impl Em { /// 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. - fn x64_lds_meet(&mut self) { + /// 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(_)) { - self.line("xcl_x_meet();"); + 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; } } @@ -4486,6 +4531,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" @@ -4516,7 +4562,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(); + 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)"); @@ -4581,7 +4627,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(); + self.x64_lds_meet(write); let at = format!("{a} + {off16}u"); let slot = lds(at.clone()); let sh = format!("((({at}) & 3u) * 8u)"); @@ -4607,7 +4653,7 @@ impl Em { _ => None, }; if let Some((bits, signed, write)) = small { - self.x64_lds_meet(); + self.x64_lds_meet(write); let at = format!("{a} + {off16}u"); let slot = lds(at.clone()); let sh = format!("((({at}) & 3u) * 8u)"); @@ -4629,7 +4675,7 @@ impl Em { return Ok(()); } if let Some((write, n, stride, two)) = rw(name) { - self.x64_lds_meet(); + self.x64_lds_meet(write); let addrs: Vec = if two { vec![format!("{a} + {}u", o0 * stride), format!("{a} + {}u", o1 * stride)] } else { @@ -4662,7 +4708,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(); + 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"))); @@ -4678,7 +4724,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(); + self.x64_lds_meet(true); self.line(&format!("uint {t}_o = 0u; if ({act}) {{ {body} }}")); if rtn { let r = self.vreg(f("VDST")); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index a4ce051df8..8ed69eccb5 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1506,7 +1506,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { leaders.insert(next); } } - let mut em = emit::Em::new(opt.clone()); + let mut em = emit::Em::new(opt.clone(), leaders.clone()); em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 22777035a2..df22eaa8f0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7311,6 +7311,8 @@ fn split_wave64_meets_before_each_lds_access() { (t.hlsl.matches("xcl_x_meet();").count(), t.complete()) }; let p = lds_order_program(); + // still six with the read-run rule (`x64_lds_meet`): each access is a write or a read + // right after a write, and no exchange lies between them assert_eq!(meets(&p, true, true), (6, true)); assert_eq!(meets(&p, true, false), (0, true), "native wave64"); assert_eq!(meets(&p, false, true), (0, true), "a wave32 program"); @@ -7351,6 +7353,124 @@ fn gpu_split_wave64_lds_follows_instruction_order() { } } +type LdsInst = (&'static str, &'static str, &'static [(&'static str, u64)], Option); +const LDS_W: LdsInst = ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 6)], None); +const LDS_R: LdsInst = ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None); +const LANE_X: LdsInst = ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)], None); + +/// A run of reads between writes: every lane writes a[own] = 1 << 28 | n and b[own] = +/// 2 << 28 | n, reads the other half's a, b, a, b (one meeting for the four), then overwrites +/// a and b – which the other half must not see. With `exchange`, a v_readfirstlane after the +/// writes and one after the reads stand in for meetings. s1 = log2 of the threads per group. +fn lds_read_run_program(exchange: bool) -> Vec { + let head: [LdsInst; 11] = [ + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 4), ("SSRC1", 1)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 5), ("VSRC1", 0)], None), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 10)], Some(0x1000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 10)], Some(0x2000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 255), ("VSRC1", 10)], Some(0x3000_0000)), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 15), ("SRC0", 255), ("VSRC1", 10)], Some(0x4000_0000)), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 160), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 12)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 13), ("OFFSET1", 4)], None), + ]; + let reads: [LdsInst; 4] = [ + ("DS_READ_B32", "ENC_DS", &[("VDST", 4), ("ADDR", 2)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 5), ("ADDR", 2), ("OFFSET1", 4)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 2)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 7), ("ADDR", 2), ("OFFSET1", 4)], None), + ]; + let tail: [LdsInst; 5] = [ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 14)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 15), ("OFFSET1", 4)], None), + // out[n] = v4..v7 + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 16), ("SRC0", 132), ("VSRC1", 10)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 16), ("SRC0", 0), ("VSRC1", 16)], None), + ("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 16), ("DATA", 4), ("SADDR", 0x7D)], None), + ]; + let x = exchange.then_some(LANE_X); + prog(&head.into_iter().chain(x).chain(reads).chain(x).chain(tail).collect::>()) +} + +/// The split form's HLSL of a compute program (64 threads) and its meetings before LDS accesses. +fn x64_lds_meets(code: &[u8]) -> (usize, String) { + let t = translate(code, &Options { mode: Mode::Compute(lds_order_cs(64)), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + (t.hlsl.matches("xcl_x_meet();").count(), t.hlsl) +} + +/// Without a GPU: a read right after a read in the same block does not meet; a write, a read +/// after a write and a block's first access do, unless an exchange (v_readfirstlane here) +/// lies between the access and the previous one. +#[test] +fn split_wave64_meets_once_per_read_run() { + let meets = |l: &[LdsInst]| x64_lds_meets(&prog(l)).0; + let (w, r, x) = (LDS_W, LDS_R, LANE_X); + let br: LdsInst = ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)], None); + assert_eq!(x64_lds_meets(&lds_read_run_program(false)).0, 5, "two writes, four reads, two writes: 8 before"); + assert_eq!(x64_lds_meets(&lds_read_run_program(true)).0, 3, "the same with two exchanges"); + assert_eq!(meets(&[w, r, r, r, r]), 2, "four reads after a write: one meeting"); + assert_eq!(meets(&[r, r, w]), 2, "a write after reads: one"); + assert_eq!(meets(&[w, x, r, x, w]), 1, "an exchange since the previous access"); + assert_eq!(meets(&[w, x, w, w]), 2, "the exchange counts for the next access only"); + assert_eq!(meets(&[r, br, r]), 2, "a branch target starts a block"); +} + +/// Without a GPU: a mask kept in its half (v_cmp into VCC, never read whole: +/// `xcl_x_ballot_local`) is no exchange, so the read after the write still meets; read whole +/// (s_bcnt1) the mask is exchanged, and that exchange is the read's meeting. +#[test] +fn split_wave64_lds_local_mask_is_no_meeting() { + let cmp: LdsInst = ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 0)], None); + let bcnt: LdsInst = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 9), ("SSRC0", 106)], None); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, cmp, LDS_R])); + assert!(hlsl.contains("xcl_x_ballot_local(and("), "{hlsl}"); + assert_eq!(n, 2); + let (n, hlsl) = x64_lds_meets(&prog(&[LDS_W, cmp, bcnt, LDS_R])); + assert!(hlsl.contains("xcl_x_ballot(and("), "{hlsl}"); + assert_eq!(n, 1); +} + +/// Without a GPU: a loop head starts a block, so its read meets although a read precedes it +/// in the code (`r; L: r; s_cbranch_scc1 L`: the back edge arrives from after the read). +#[test] +fn split_wave64_lds_meets_at_loop_head() { + let back: LdsInst = ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None); + assert_eq!(x64_lds_meets(&prog(&[LDS_R, LDS_R, back])).0, 2); +} + +/// `lds_read_run_program` on the GPU (64 and 256 threads per group), with meetings and with +/// exchanges in their place: the reads without a meeting see the other half's writes before +/// the run and not its writes after it. +#[test] +fn gpu_split_wave64_lds_read_run_follows_instruction_order() { + if !gpu_ready() { + return; + } + for (exchange, threads) in [(false, 64usize), (false, 256), (true, 64), (true, 256)] { + let p = lds_read_run_program(exchange); + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(lds_order_cs(threads as u32)), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let (groups, base) = (1024usize, 0x100usize); + let mut io = vec![0u32; 128]; + io[0] = base as u32; + io[1] = threads.trailing_zeros(); + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * threads * 16) / 4]).unwrap(); + let mut wrong = Vec::new(); + for n in 0..groups * threads { + let (at, o) = ((base + n * 16) / 4, (n ^ 32) as u32); + let want = [0x1000_0000 | o, 0x2000_0000 | o, 0x1000_0000 | o, 0x2000_0000 | o]; + if out[at..at + 4] != want { + wrong.push(format!("group {} thread {}: read {:x?}, not {want:x?}", n / threads, n % threads, &out[at..at + 4])); + } + } + assert!(wrong.is_empty(), "exchange {exchange}, {threads} threads per group: {} of {} threads wrong: {}", wrong.len(), groups * threads, wrong[..wrong.len().min(4)].join("; ")); + } +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 1fae024948..dbc87e46da 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -105,12 +105,14 @@ it. A program that really uses the whole 32 KB of LDS therefore loses its top dw so a lane reads the LDS another lane wrote an instruction earlier with no `s_barrier`. Two halves that meet only at exchanges read such a word before it is written, or after a later write (`gpu_split_wave64_lds_follows_instruction_order`: up to three quarters of - the threads on an RTX 5070 Ti). The halves therefore meet before every LDS access. The - meeting orders instructions, not the lanes of one instruction: when lanes of both halves - write or atomically update the same word in one instruction, which half goes first is not - the console's order. Geometry mode has no meetings: it assumes ES code reads no other - lane's item before the `s_barrier` (ES lanes write their own items, and the phases meet - at a group barrier). + the threads on an RTX 5070 Ti). The halves therefore meet before an LDS access, except a + read right after a read in the same basic block (two reads need no order) or an access + after an exchange that lies between it and the block's previous access (the exchange is + a meeting). The meeting orders instructions, not the lanes of one instruction: when + lanes of both halves write or atomically update the same word in one instruction, which + half goes first is not the console's order. Geometry mode has no meetings: it assumes ES + code reads no other lane's item before the `s_barrier` (ES lanes write their own items, + and the phases meet at a group barrier). ### Masks read lane by lane From ec00d67e5075a1484b186bb870280e62ea5c0999 Mon Sep 17 00:00:00 2001 From: Rex <38073041+not-rex@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:36:08 +1030 Subject: [PATCH 3/3] Recompiler: XCL_WAVE64_LDS_ORDER=0 leaves out the split LDS meetings A switch to compare a title with and without the split wave64 meetings before LDS accesses (the RTX 3060 report on PR #1252). Default on: the meetings are a correctness fix. Set, it bypasses the shader caches like XCL_WAVE64_SPIN; unset, the HLSL is unchanged. With it at 0 the LDS order tests fail as expected (no meetings; the GPU tests read out of order), which shows the switch takes effect. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 7 +++++-- crates/xcl/src/gpu/recomp/pso.rs | 4 ++-- docs/wave64-on-wave32.md | 3 ++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 5d097ef3bb..2bc0dcd862 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -76,6 +76,8 @@ pub(super) struct Em { img_writes: Vec, /// split wave64: what lies between the basic block's previous LDS access and here x64_lds: LdsGap, + /// `XCL_WAVE64_LDS_ORDER=0`: no meetings before LDS accesses (to compare in a title) + x64_lds_order: bool, /// first instructions of the basic blocks (branch targets, after branches) block_starts: BTreeSet, } @@ -641,6 +643,7 @@ impl Em { safe_barrier: false, img_writes: Vec::new(), x64_lds: LdsGap::Open, + x64_lds_order: std::env::var("XCL_WAVE64_LDS_ORDER").map_or(true, |v| v.trim() != "0"), block_starts, } } @@ -4483,9 +4486,9 @@ impl Em { /// 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. + /// before this half's i. Two reads need no order. `XCL_WAVE64_LDS_ORDER=0`: no meetings. fn x64_lds_meet(&mut self, write: bool) { - if self.x64() && !matches!(self.opt.mode, Mode::Geometry(_)) { + if self.x64() && !matches!(self.opt.mode, Mode::Geometry(_)) && self.x64_lds_order { if self.x64_lds == LdsGap::Open || (write && self.x64_lds == LdsGap::Read) { self.line("xcl_x_meet();"); } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 4dd688c9de..7045241df9 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -802,7 +802,7 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT", "XCL_WAVE64_LDS_ORDER"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -1850,7 +1850,7 @@ mod shader_cache_tests { #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT", "XCL_WAVE64_LDS_ORDER"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index dbc87e46da..3374c29e96 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -112,7 +112,8 @@ it. A program that really uses the whole 32 KB of LDS therefore loses its top dw lanes of both halves write or atomically update the same word in one instruction, which half goes first is not the console's order. Geometry mode has no meetings: it assumes ES code reads no other lane's item before the `s_barrier` (ES lanes write their own items, - and the phases meet at a group barrier). + and the phases meet at a group barrier). `XCL_WAVE64_LDS_ORDER=0` leaves the meetings + out, to compare a title with and without them. ### Masks read lane by lane