diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index cf3ac8d40..c05824daa 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -282,9 +282,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); } - for &i in &blk.insts { - lw.inst(&cfg.insts[i])?; - } + lw.lower_block_insts(&cfg.insts, &blk.insts, |_| None)?; let next = match blk.term { Term::End => lw.c(END), Term::Jump(_) => taken, diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 01a48a1b4..5e5264621 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -581,3 +581,133 @@ fn gpu_direct_unaligned_multi_dword_format_store() { let got: Vec = r.mem.iter().flat_map(|v| v.to_le_bytes()).collect(); assert_eq!(&got[0xFC..0x118], &want[0xFC..0x118], "bytes 0xFC..0x118 after the store at 0x102"); } + +/// Consecutive independent `v_readfirstlane_b32` / `v_readlane_b32` in split-wave64 mode +/// share one cross-half `exchange_n` (one barrier pair in `Partner::Present`, one spin loop +/// in `Partner::Spin`) and validate. +#[test] +fn split_readlane_batch_merges_present_and_spin_exchanges() { + use crate::gpu::recomp::CsInterface; + const V: u64 = 256; + let code = prog(&[ + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 2)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 3)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 4), ("SRC1", 128 + 7)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 5), ("SRC1", 128 + 41)], None), + // Consume all 6 SGPRs so DCE keeps every exchange result live. + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 11)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 12)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 13)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 14)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 15)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 10)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 6), ("SADDR", 0x7F)], None), + ]); + let ko = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + + // 1-wave group (Partner::Present): 1 setup barrier + 2 exchange_n barriers = 3 (vs 1 + 12 = 13 unbatched). + let cs64 = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let dxil64 = super::kernel::translate_compute(&code, ko, &cs64).unwrap_or_else(|e| panic!("cs64: {e}")).dxil; + if crate::gpu::recomp::dxc::location().is_ok() { + let dis64 = super::validate::disassemble(&dxil64).expect("disasm cs64"); + let barriers = dis64.matches("call void @dx.op.barrier(").count(); + assert_eq!(barriers, 3, "expected 1 setup + 2 batched exchange barriers, got {barriers}"); + } + + // 2-wave group (Partner::Spin): 1 setup atomic + 2 spin-loop atomics = 3 (vs 1 + 12 = 13 unbatched). + let cs128 = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let dxil128 = super::kernel::translate_compute(&code, ko, &cs128).unwrap_or_else(|e| panic!("cs128: {e}")).dxil; + if crate::gpu::recomp::dxc::location().is_ok() { + let dis128 = super::validate::disassemble(&dxil128).expect("disasm cs128"); + let atomics = dis128.matches("atomicrmw add").count(); + assert_eq!(atomics, 3, "expected 1 setup + 2 batched spin-exchange atomics, got {atomics}"); + } +} + +/// SGPR read-after-write hazards (lane selector written by an earlier item, or EXEC written) +/// split the batch rather than merging across a dependency. +#[test] +fn split_readlane_batch_respects_sgpr_hazards() { + use crate::gpu::recomp::CsInterface; + const V: u64 = 256; + let ko = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let cs64 = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + + // Case 1: second v_readlane reads s10 written by first v_readlane -> 2 separate exchanges (1 + 4 = 5 barriers). + let dep = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 128 + 5)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", 10)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 11)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 6), ("SADDR", 0x7F)], None), + ]); + let dxil_dep = super::kernel::translate_compute(&dep, ko, &cs64).unwrap_or_else(|e| panic!("dep: {e}")).dxil; + + // Case 2: first v_readfirstlane writes EXEC_LO (126) -> second must not batch with it (1 + 4 = 5 barriers). + let exec_wr = prog(&[ + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 126), ("SRC0", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 11)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 6), ("SADDR", 0x7F)], None), + ]); + let dxil_exec = super::kernel::translate_compute(&exec_wr, ko, &cs64).unwrap_or_else(|e| panic!("exec_wr: {e}")).dxil; + + if crate::gpu::recomp::dxc::location().is_ok() { + let b_dep = super::validate::disassemble(&dxil_dep).expect("disasm dep").matches("call void @dx.op.barrier(").count(); + assert_eq!(b_dep, 5, "RAW lane-selector hazard must split into 2 exchanges (5 barriers), got {b_dep}"); + let b_exec = super::validate::disassemble(&dxil_exec).expect("disasm exec").matches("call void @dx.op.barrier(").count(); + assert_eq!(b_exec, 5, "EXEC write must split into 2 exchanges (5 barriers), got {b_exec}"); + } +} + +/// Batched split-wave64 `v_readfirstlane_b32` / `v_readlane_b32` (both lower-half and upper-half +/// lanes plus a dependent chain) produce exact RDNA2 results on the GPU. +#[test] +fn gpu_split_readlane_batch_executes_correctly() { + use crate::gpu::recomp::runner::{self, KernelState}; + const V: u64 = 256; + let code = prog(&[ + // Batch 1 (EXEC = all 64 lanes, first active = lane 0): + // s10 = v0[0], s11 = v1[0], s12 = v2[7], s13 = v3[41] + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128 + 7)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 3), ("SRC1", 128 + 41)], None), + // Dependent chain (must NOT merge): s14 = v4[35] (= 52), then s15 = v5[s14] (= v5[52]) + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 4), ("SRC1", 128 + 35)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 5), ("SRC1", 14)], None), + // Mask off lower half so first active lane is 37 (bit 5 of EXEC_HI = 0x20), + // then batch 2 reads v0[37] and v1[37] from the upper half. + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128 + 32)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 16), ("SRC0", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 17), ("SRC0", V + 1)], None), + ]); + let ko = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let dxil = translate(&code, ko).unwrap_or_else(|e| panic!("split translate: {e}")); + super::validate::validate(&dxil).unwrap_or_else(|e| panic!("validator: {e}")); + if runner::adapter().is_err() || runner::wave32_supported() != Ok(true) || crate::gpu::recomp::dxc::location().is_err() { + runner::skip_test("no GPU / DXC / wave32"); + return; + } + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = 0x1000 + l; + r[1] = 0x2000 + l * 3; + r[2] = 0x3000 + l * 5; + r[3] = 0x4000 + l * 7; + r[4] = if l == 35 { 52 } else { 1 }; + r[5] = 0x5000 + l * 11; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run"); + assert_eq!(r.sgpr[10], 0x1000, "s10 = v0[0]"); + assert_eq!(r.sgpr[11], 0x2000, "s11 = v1[0]"); + assert_eq!(r.sgpr[12], 0x3000 + 7 * 5, "s12 = v2[7]"); + assert_eq!(r.sgpr[13], 0x4000 + 41 * 7, "s13 = v3[41]"); + assert_eq!(r.sgpr[14], 52, "s14 = v4[35]"); + assert_eq!(r.sgpr[15], 0x5000 + 52 * 11, "s15 = v5[52]"); + assert_eq!(r.sgpr[16], 0x1000 + 37, "s16 = v0[37]"); + assert_eq!(r.sgpr[17], 0x2000 + 37 * 3, "s17 = v1[37]"); +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 8687e4807..4220dbb33 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -347,11 +347,7 @@ fn translate_on_this_thread( let l = lw.sub(left, one); lw.wr(VAR_BUDGET, l); } - for &i in &cfg.blocks[b].insts { - lw.reload = reloads.get(b, i); - lw.inst(&cfg.insts[i])?; - } - lw.reload = None; + lw.lower_block_insts(&cfg.insts, &cfg.blocks[b].insts, |i| reloads.get(b, i))?; match cfg.blocks[b].term { Term::Jump(t) if es_block && in_gs(t) => { // the ES's s_setpc_b64 into the GS: through the phase switch @@ -574,6 +570,15 @@ impl Lw { if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } + if split { + let batch_max = super::lower_valu::max_readlane_batch(insts, leaders); + if batch_max >= 2 { + // Keep LDS-carved exchange storage bounded (<= 256 dwords = 1 KiB); without + // LDS a dedicated groupshared array safely holds up to 16 words per half. + let cap = if uses_lds { (64 / lw.waves.max(1)).clamp(1, 8) } else { 16 }; + slot = slot.max(batch_max.min(cap)); + } + } lw.setup_storage(uses_lds, if split { slot } else { 1 }); if let (Some(t), true) = (group_threads, split) { lw.partner = match t { diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 04491ba07..35fa45b3c 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -483,6 +483,48 @@ impl Lw { self.sel(mine, m, o) } + /// Batched [`Lw::read_lane_uniform`] for independent consecutive `v_readfirstlane_b32` / + /// `v_readlane_b32` instructions: performs one cross-half [`Lw::exchange_n`] for the + /// whole run (one barrier pair in `Partner::Present`, one spin-exchange loop in + /// `Partner::Spin`). + pub fn read_lane_uniform_batch(&mut self, items: &[(Value, Value)]) -> Vec { + if items.is_empty() { + return Vec::new(); + } + if !self.split { + return items.iter().map(|&(v, l)| self.rla(v, l)).collect(); + } + let mut mine_vals = Vec::with_capacity(items.len()); + let mut last_l31: Option<(Value, Value)> = None; + for &(v, l) in items { + let l31 = match last_l31 { + Some((prev_l, prev_l31)) if prev_l == l => prev_l31, + _ => { + let l31 = self.andc(l, 31); + last_l31 = Some((l, l31)); + l31 + } + }; + mine_vals.push(self.s.wave_read_lane_at(v, l31)); + } + let others = self.exchange_n(&mine_vals); + let mut out = Vec::with_capacity(items.len()); + let mut last_mine: Option<(Value, Value)> = None; + for ((&(_, l), m), o) in items.iter().zip(mine_vals).zip(others) { + let mine = match last_mine { + Some((prev_l, prev_mine)) if prev_l == l => prev_mine, + _ => { + let lh = self.lshrc(l, 5); + let mine = self.cmp(Pred::Eq, lh, self.half); + last_mine = Some((l, mine)); + mine + } + }; + out.push(self.sel(mine, m, o)); + } + out + } + /// `v` of lane `l` within the reader's 32-lane half (DPP, swizzle, permlane). pub fn read_lane_half(&mut self, v: Value, l: Value) -> Value { if self.split { diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 5e373200d..9285807f9 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1356,4 +1356,179 @@ impl Lw { self.selc(le, 0, m) } } + + /// Lowers a basic block's instruction indices in order, batching consecutive independent + /// `v_readfirstlane_b32` / `v_readlane_b32` exchanges in split-wave64 mode into one + /// [`Lw::exchange_n`]. + pub fn lower_block_insts( + &mut self, + all: &[Decoded], + indices: &[usize], + mut reload: impl FnMut(usize) -> Option, + ) -> LResult<()> { + if !self.split || self.xslot < 2 || self.guard_override.is_some() { + for &i in indices { + self.reload = reload(i); + self.inst(&all[i])?; + } + self.reload = None; + return Ok(()); + } + let max_batch = self.xslot as usize; + let mut pos = 0usize; + while pos < indices.len() { + let mut written = 0u128; + let mut len = 0usize; + while pos + len < indices.len() && len < max_batch { + let d = &all[indices[pos + len]]; + let Some(dst) = readlane_batch_eligible(d, written) else { + break; + }; + if let Dst::S(n) = dst { + if n < 128 && n != 125 { + written |= 1u128 << n; + } + } + len += 1; + } + if len < 2 { + let i = indices[pos]; + self.reload = reload(i); + self.inst(&all[i])?; + pos += 1; + continue; + } + self.reload = None; + let z = self.c(0); + let wmask = if self.wave64 { 63 } else { 31 }; + let mut first_lane: Option = None; + let mut items: Vec<(Value, Value)> = Vec::with_capacity(len); + let mut dsts: Vec = Vec::with_capacity(len); + for k in 0..len { + let d = &all[indices[pos + k]]; + self.pc = d.pc; + self.dpp_enable = None; + let (outs, ins) = Self::ops(d); + let u = self.sources(d, &ins, false)?; + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let a = u.first().map(|s| s.w()).unwrap_or(z); + let lane = if d.inst.name == "V_READFIRSTLANE_B32" { + *first_lane.get_or_insert_with(|| { + let (el, eh) = self.exec_mask(); + self.first_lane(el, eh) + }) + } else { + let b = u.get(1).map(|s| s.w()).unwrap_or(z); + self.andc(b, wmask) + }; + items.push((a, lane)); + dsts.push(dst); + } + let vals = self.read_lane_uniform_batch(&items); + for (dst, v) in dsts.into_iter().zip(vals) { + self.write32(&dst, v); + } + pos += len; + } + self.reload = None; + Ok(()) + } +} + +/// Returns the destination of a `v_readfirstlane_b32` / `v_readlane_b32` if it can safely join +/// a split-wave64 exchange batch whose earlier items wrote `written_sgprs` (bit `r` = SGPR `r`). +fn readlane_batch_eligible(d: &Decoded, written_sgprs: u128) -> Option { + if d.variant != Variant::Plain { + return None; + } + if !matches!(d.inst.name, "V_READFIRSTLANE_B32" | "V_READLANE_B32") { + return None; + } + let (outs, ins) = Lw::ops(d); + let dst = outs.first().map(|o| Lw::dst_of(d, o)).unwrap_or(Dst::Null); + if matches!(dst, Dst::V(_) | Dst::S(126) | Dst::S(127)) { + return None; + } + if d.inst.name == "V_READFIRSTLANE_B32" && (written_sgprs & (3u128 << 126)) != 0 { + return None; + } + for o in ins { + match o.field { + Some("LITERAL") => {} + Some(f) => { + if o.ty.starts_with("OPR_VGPR") && d.enc.field_width(f) <= 8 { + continue; + } + let v = Lw::field(d, f); + match v { + 0..=124 | 126 | 127 => { + if (written_sgprs & (1u128 << v)) != 0 { + return None; + } + } + 251 => { + if (written_sgprs & (3u128 << 106)) != 0 { + return None; + } + } + 252 => { + if (written_sgprs & (3u128 << 126)) != 0 { + return None; + } + } + 125 | 128..=208 | 235..=248 | 253 | 255 | 256..=511 => {} + _ => return None, + } + } + None => match o.ty { + "OPR_VCC" => { + if (written_sgprs & (3u128 << 106)) != 0 { + return None; + } + } + "OPR_EXEC" | "OPR_SDST_EXEC" => { + if (written_sgprs & (3u128 << 126)) != 0 { + return None; + } + } + "OPR_SDST_M0" => { + if (written_sgprs & (1u128 << 124)) != 0 { + return None; + } + } + "OPR_SSRC_SPECIAL_SCC" => {} + _ => return None, + }, + } + } + Some(dst) +} + +/// Longest consecutive independent `v_readfirstlane_b32` / `v_readlane_b32` run within any +/// basic block (stopping at block `leaders`), used to size split-wave64 exchange slots. +pub(super) fn max_readlane_batch(insts: &[Decoded], leaders: &std::collections::BTreeSet) -> u32 { + let mut best = 0u32; + let mut i = 0usize; + while i < insts.len() { + let mut written = 0u128; + let mut len = 0u32; + while i + (len as usize) < insts.len() { + let d = &insts[i + len as usize]; + if len > 0 && leaders.contains(&d.pc) { + break; + } + let Some(dst) = readlane_batch_eligible(d, written) else { + break; + }; + if let Dst::S(n) = dst { + if n < 128 && n != 125 { + written |= 1u128 << n; + } + } + len += 1; + } + best = best.max(len); + i += (len as usize).max(1); + } + best }