diff --git a/HANDOFF.md b/HANDOFF.md index 3b648df..1fd251d 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1576,7 +1576,18 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 - NVIDIA forms 32-lane waves of non-consecutive `SV_GroupIndex` for 3-D groups (8×8×4): `xcl_x_thread` gives each hardware wave the next 32 console threads as it arrives. - Cost (`bench_split_wave64`, worst case: one mask per 8 instructions): 1.3× with one console wave per group, ~5× - with four (waiting waves keep issuing). Next: no exchange for masks only used lane by lane (`v_cndmask`). + with four (waiting waves keep issuing). +- Masks only read lane by lane (`v_cndmask` selectors, `v_add_co_ci` / `v_sub(rev)_co_ci` carry-ins) are no longer + exchanged: `x64_masks.rs`, a backward liveness pass over the SGPRs ("whole-live": some path reads the whole value + before it is overwritten; EXEC, indirect jumps, loop exits through the iteration budget and the kernel runner's + end count as whole reads; geometry mode unchanged). It follows the emitter, not only the operand tables: SDWA + compares into their SDST, `s_cmov*` / `s_addk` / `s_mulk` / `s_bitset*` and `s_movreld` are not overwrites, + `s_movrels` reads every register from its base, SDWA scalar sources and SMEM register offsets are reads (each was a + way for the halves to diverge: tests `gpu_split_wave64_masks_read_whole_after_partial_writes`, `x64_masks::tests`). + `bench_split_wave64` now times GPU work only (timestamps, `runner::dispatch_timed`; before: wall time with + pipeline creation and copies). RTX 3090, `XCL_X64_ALL_MASKS=1` vs default: mask-only loop 1.64–1.68× → 1.04–1.11× + (one console wave per group), 3.90–4.14× → 1.07–1.16× (four); with a readfirstlane too 1.99–2.02× → 1.74–1.81×, + 6.45–6.64× → 4.09–4.34×. Test `gpu_split_wave64_lane_local_masks` (fails if the local word lands in the wrong half). - Still open on NVIDIA: wave64 VS / PS with readlane of lanes 32..63 (`wave_hazards`; the driver picks 32-lane waves, lanes ≥ 32 do not exist – `WaveReadLaneAt` wraps to lane & 31 there). diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index eb5b880..59ae7fe 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -39,6 +39,11 @@ pub(super) struct Em { /// split wave64 (`x64`): words one exchange carries (1: masks and lane reads, up to 16: /// coherent scalar loads, 32: `ds_bpermute`) x64_words: usize, + /// split wave64: pc → SGPRs whose whole value may be read after that instruction + /// (`x64_masks`); a mask written to none of them stays in its half (no exchange) + pub x64_whole_live: BTreeMap, + /// pc of the instruction being emitted + cur_pc: u64, /// MIMG instruction address → its sampler's S# when the code builds it from constants pub static_ss: BTreeMap, /// the static samplers sampled with: (S#, comparison), in register order @@ -152,7 +157,7 @@ fn float_compare(op: &str, a: &str, b: &str, isnan: &str) -> Option { } /// Layout of the SDWA / DPP extension dword for this instruction's base encoding. -fn ext_encoding(d: &Decoded) -> Option<&'static Encoding> { +pub(super) fn ext_encoding(d: &Decoded) -> Option<&'static Encoding> { let base = match d.enc.name { "ENC_VOP1" => "VOP1", "ENC_VOP2" => "VOP2", @@ -444,6 +449,8 @@ impl Em { uses_lds: false, uses_scratch: false, x64_words: 1, + x64_whole_live: BTreeMap::new(), + cur_pc: 0, static_ss: BTreeMap::new(), static_used: Vec::new(), max_vgpr: 0, @@ -757,7 +764,17 @@ impl Em { fn write_mask(&mut self, dst: &Dst, cond: &str) { let a = self.act(); let m = self.t(); - let ballot = self.ballot_fn(); + let mut ballot = self.ballot_fn(); + // no exchange for a mask that is only ever read lane by lane (the half's own word is + // enough), that goes nowhere, or that is 0 in every lane anyway + let local = match *dst { + Dst::S(n) => n < 126 && self.x64_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::Null => true, + Dst::V(_) => false, + }; + if self.x64() && (local || cond == "false") { + ballot = "xcl_x_ballot_local"; + } self.line(&format!("uint2 {m} = {ballot}(and({a}, ({cond})));")); if self.opt.wave64 { self.write64(dst, &format!("{m}.x"), &format!("{m}.y")); @@ -780,6 +797,7 @@ impl Em { let name = d.inst.name.to_ascii_lowercase(); let text = rdna2::format(d); self.line(&format!("// {:04x}: {text}", d.pc)); + self.cur_pc = d.pc; // a far jump (`rdna2::resolve_far_jumps`) is an unconditional branch if let Some(t) = d.far_target { return Flow::Jump(t); @@ -4982,6 +5000,12 @@ uint xcl_x_rla_any(uint v, uint l) { uint m = WaveReadLaneAt(v, l & 31u); return (l >> 5) == xcl_half ? m : o; } +// a mask only ever read lane by lane (v_cndmask, carry-ins; `x64_masks`): each half's own +// word, the other half's 0 – no exchange +uint2 xcl_x_ballot_local(bool b) { + uint m = WaveActiveBallot(b).x; + return xcl_half != 0u ? uint2(0u, m) : uint2(m, 0u); +} // DPP16, DPP8, ds_swizzle, v_permlane(x)16: the ISA keeps the source in the reader's half uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } "#; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index c2bd69b..00efeec 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -55,6 +55,7 @@ pub mod dxc; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; +pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; pub mod runner; @@ -579,6 +580,40 @@ type MemoKey = (u64, u64, Option, usize, Option, Vec); /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// The loops the translator emits: ranges spanned by backward jumps (far jumps included), +/// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the +/// exits through `LOOP_GUARD`. +pub(super) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { + let mut loops: Vec<(u64, u64)> = Vec::new(); + for d in insts { + if let Some(t) = rdna2::branch_target(d) { + if t <= d.pc { + loops.push((t, d.pc + d.len as u64)); + } + } + } + loop { + let mut merged = false; + 'scan: for i in 0..loops.len() { + for j in 0..loops.len() { + let (a, b) = (loops[i], loops[j]); + if i != j && a.0 < b.0 && b.0 < a.1 && a.1 < b.1 { + loops[i] = (a.0, b.1); + loops.remove(j); + merged = true; + break 'scan; + } + } + } + if !merged { + break; + } + } + loops.sort(); + loops.dedup(); + loops +} + /// Target of an s_endpgm before the end of the program: "skip to the end". const END: u64 = u64::MAX; /// "Target" of a jump back to the head of the innermost loop: `continue`. @@ -1299,6 +1334,11 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { let mut em = emit::Em::new(opt.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 + // continues from the ES into the GS through s_setpc: left as it is) + if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { + em.x64_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); + } em.max_vgpr = insts .iter() .flat_map(|d| { @@ -1330,33 +1370,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // dispatcher loop over all blocks, but DXC sees an acyclic graph almost everywhere // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); - let mut loops: Vec<(u64, u64)> = Vec::new(); - for d in &insts { - if let Some(t) = rdna2::branch_target(d) { - if t <= d.pc { - loops.push((t, d.pc + d.len as u64)); - } - } - } - loop { - let mut merged = false; - 'scan: for i in 0..loops.len() { - for j in 0..loops.len() { - let (a, b) = (loops[i], loops[j]); - if i != j && a.0 < b.0 && b.0 < a.1 && a.1 < b.1 { - loops[i] = (a.0, b.1); - loops.remove(j); - merged = true; - break 'scan; - } - } - } - if !merged { - break; - } - } - loops.sort(); - loops.dedup(); + let loops = loop_ranges(&insts); let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, memo: Default::default() }; let mut flags = BTreeSet::new(); diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 1e40158..f8f8dec 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1237,7 +1237,24 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) +} + +/// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not +/// reset), each between two GPU timestamps: GPU milliseconds per dispatch – no pipeline, +/// buffer, upload, submission or CPU wait time in them. For benchmarks. +pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], reps: usize) -> Result, String> { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; + let pso: ID3D12PipelineState = unsafe { + gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&gpu.rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + } + .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true).map(|(_, t)| t) } /// Dispatch with an existing compute pipeline on `dev` (its own queue), e.g. one the D3D12.X @@ -1247,7 +1264,7 @@ pub fn dispatch_on(dev: &ID3D12Device, pso: &ID3D12PipelineState, rs: &ID3D12Roo unsafe { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; - dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem) + dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) } } @@ -1262,7 +1279,9 @@ fn dispatch_with( groups: [u32; 3], sgprs: &[u32], mem: &[u32], -) -> Result, String> { + reps: usize, + timed: bool, +) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); io.resize(KERNEL_SGPRS, 0); let mem_len = mem.len().max(64); @@ -1294,7 +1313,32 @@ fn dispatch_with( list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); - list.Dispatch(groups[0], groups[1], groups[2]); + // `reps` dispatches, each between two timestamps when `timed` + let stamps = 2 * reps as u32; + let queries = if timed { + let mut h: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: stamps, NodeMask: 0 }, &mut h).map_err(e)?; + let heap = h.ok_or("CreateQueryHeap")?; + let out = buffer(dev, stamps as u64 * 8, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; + Some((heap, out)) + } else { + None + }; + for k in 0..reps as u32 { + if k > 0 { + list.ResourceBarrier(&[uav_barrier(&mem_buf), uav_barrier(&io_buf)]); + } + if let Some((heap, _)) = &queries { + list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); + } + list.Dispatch(groups[0], groups[1], groups[2]); + if let Some((heap, _)) = &queries { + list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k + 1); + } + } + if let Some((heap, out)) = &queries { + list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, stamps, out, 0); + } list.ResourceBarrier(&[transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); list.CopyBufferRegion(&readback, 0, &mem_buf, 0, mem_bytes); list.Close().map_err(e)?; @@ -1312,6 +1356,15 @@ fn dispatch_with( readback.Map(0, None, Some(&mut q)).map_err(e)?; let out = std::slice::from_raw_parts(q as *const u32, mem_len).to_vec(); readback.Unmap(0, None); - Ok(out) + let mut ms = Vec::new(); + if let Some((_, stamps_buf)) = &queries { + let hz = queue.GetTimestampFrequency().map_err(e)? as f64; + let mut t = std::ptr::null_mut(); + stamps_buf.Map(0, None, Some(&mut t)).map_err(e)?; + let ticks = std::slice::from_raw_parts(t as *const u64, stamps as usize); + ms = ticks.chunks(2).map(|c| c[1].saturating_sub(c[0]) as f64 * 1000.0 / hz).collect(); + stamps_buf.Unmap(0, None); + } + Ok((out, ms)) } } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 39711cf..eacdabe 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4526,6 +4526,239 @@ fn gpu_split_wave64_cross_half_operations() { } } +/// Masks only read lane by lane (`x64_masks`): a v_cndmask selector and a 64-bit carry chain, +/// both with bits in the two halves, need no exchange in the split form – and give the same +/// lanes as a whole-wave mask. +#[test] +fn gpu_split_wave64_lane_local_masks() { + if !gpu_ready() { + return; + } + let code = prog(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(40)), // vcc = lanes 0..39 + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V + 2), ("VSRC1", 3)], None), + // s[20:21] = lanes 0..49, as a VOP3 selector + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", 255)], Some(50)), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", 20)], None), + // v[4:5] + v[6:7] as 64-bit numbers: the carry of the low words feeds the high words + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 106), ("SRC0", V + 4), ("SRC1", V + 6)], None), + ("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 5), ("VSRC1", 7)], None), + // the masks end dead (the kernel runner reads every SGPR back) + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128)], None), + ]); + if runner::split_wave64() { + let t = translate(&code, &runner::options(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 4, "every mask stays in its half"); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 0); + } + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = l; + r[2] = 100 + l; + r[3] = 200 + l; + // a carry out of the low word in every third lane + r[4] = if l.is_multiple_of(3) { 0xFFFF_FFF0 } else { l }; + r[5] = 1000 + l; + r[6] = 0x20; + r[7] = 7; + } + let r = runner::run_code(&code, &st, &[]).unwrap(); + for l in 0..64u32 { + let v = &r.vgpr[l as usize]; + assert_eq!(v[1], if l < 40 { 200 + l } else { 100 + l }, "lane {l}: v_cndmask on vcc"); + assert_eq!(v[8], if l < 50 { 200 + l } else { 100 + l }, "lane {l}: v_cndmask on s[20:21]"); + let a = ((1000 + l as u64) << 32) | if l % 3 == 0 { 0xFFFF_FFF0 } else { l as u64 }; + let sum = a + ((7u64 << 32) | 0x20); + assert_eq!((v[4], v[5]), (sum as u32, (sum >> 32) as u32), "lane {l}: 64-bit add with carry"); + } +} + +/// Masks that are read whole after a write `x64_masks` must not take for an overwrite (an +/// SDWA compare into its SDST, `s_bitset1`, `s_movreld`) or through a read the operand +/// tables do not show (`s_movrels`, an SMEM register offset, an SDWA scalar src1): each is +/// still exchanged, and both halves end with the same SGPRs (the runner checks) and the +/// whole-wave values. A mask that goes nowhere is not exchanged. +#[test] +fn gpu_split_wave64_masks_read_whole_after_partial_writes() { + if !gpu_ready() { + return; + } + type Inst = (&'static str, &'static str, &'static [(&'static str, u64)], Option); + // vcc / s[20:21] = lanes 0..39, or lane 2 only (low word 4) + let cmp_vcc: Inst = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(40)); + let cmp_s20: Inst = ("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 255), ("SRC1", V)], Some(40)); + let lane2_s20: Inst = ("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", 130)], None); + let s20_dead: Inst = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128)], None); + let cases: Vec<(&str, Vec)> = vec![ + ( + "SDWA compare into s[22:23]", + vec![ + cmp_vcc, + ("V_CMP_EQ_U32", "VOPC_VOP_SDWA_SDST_ENC", &[("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 0), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("SD", 1), ("SDST", 22)], None), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)], None), + ], + ), + ("s_bitset1_b64", vec![cmp_s20, ("S_BITSET1_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 191)], None), ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 20)], None)]), + ( + "s_movrels_b64 from VCC", + vec![ + cmp_vcc, + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 124), ("SSRC0", 134)], None), // m0 = 6 + ("S_MOVRELS_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 100)], None), // s[0:1] = s[106:107] + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)], None), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 0)], None), + ], + ), + ( + "s_movreld_b64 past the mask", + vec![ + cmp_s20, + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 124), ("SSRC0", 132)], None), // m0 = 4 + ("S_MOVRELD_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 2)], None), // s[24:25] = s[2:3] + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 20)], None), + ], + ), + ("SMEM register offset", vec![lane2_s20, ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 0), ("SBASE", 4), ("OFFSET", 0), ("SOFFSET", 20)], None), s20_dead]), + ( + "SDWA scalar src1", + vec![ + lane2_s20, + ("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[("VDST", 9), ("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 20), ("S1", 1), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)], None), + s20_dead, + ], + ), + ]; + let mem = [11u32, 22, 33, 44]; + for (what, list) in cases { + let code = prog(&list); + if runner::split_wave64() { + let t = translate(&code, &runner::options(Mode::Kernel)).unwrap(); + assert!(t.hlsl.contains("= xcl_x_ballot(and("), "{what}: the mask is exchanged"); + } + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + } + st.sgpr[2] = 0x1234; + let r = runner::run_code(&code, &st, &mem).unwrap_or_else(|e| panic!("{what}: {e}")); + match what { + "SDWA compare into s[22:23]" => { + assert_eq!(r.sgpr[0], 40, "{what}"); + assert_eq!((r.sgpr[22], r.sgpr[23]), (!0, !0), "{what}"); + } + "s_bitset1_b64" => assert_eq!(r.sgpr[0], 41, "{what}"), + "s_movrels_b64 from VCC" => assert_eq!(r.sgpr[0], 40, "{what}"), + "s_movreld_b64 past the mask" => { + assert_eq!(r.sgpr[0], 40, "{what}"); + assert_eq!(r.sgpr[24], 0x1234, "{what}"); + } + "SMEM register offset" => assert_eq!(r.sgpr[0], mem[1], "{what}"), + _ => { + for l in 0..64u32 { + assert_eq!(r.vgpr[l as usize][9], l + 4, "{what}: lane {l}"); + } + } + } + } + if runner::split_wave64() { + // v_cmp into NULL: nothing to exchange + let code = prog(&[("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 125), ("SRC0", V), ("SRC1", V + 1)], None)]); + let t = translate(&code, &runner::options(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 0); + assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 1); + } +} + +/// Four wave64s per group whose waves loop a different number of times (the counter-paired +/// form on 32-lane GPUs): each iteration a mask read lane by lane (`v_cndmask`) that only the +/// odd waves also read whole (`s_bcnt1`, on their own path), and a 64-bit carry chain (not +/// exchanged). The exchanged and the local masks interleave without the halves losing step. +#[test] +fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { + if !gpu_ready() { + return; + } + use super::{dxc, CsInterface}; + let p = prog(&[ + // v0 = thread index in the group, v1 = wave, v2 = lane (as gpu_split_wave64_waves_diverge) + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)], None), + ("V_LSHRREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 134), ("VSRC1", 0)], None), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], Some(63)), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 1)], None), + ("S_AND_B32", "ENC_SOP2", &[("SDST", 17), ("SSRC0", 10), ("SSRC1", 129)], None), // odd wave + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None), // n = 2 (w + 1) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 128)], None), // sum (odd waves) + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), // i + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)], None), // per-lane count + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 2)], Some(0x9E37_79B9)), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)], None), + // loop: k = 5 i + 3 + ("S_MUL_I32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 12), ("SSRC1", 133)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 13), ("SSRC0", 13), ("SSRC1", 131)], None), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 13), ("VSRC1", 2)], None), // vcc = lanes < k + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 129), ("VSRC1", 4)], None), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 5)], None), // count += lane < k + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 17), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 2)], None), // even waves: skip + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 14), ("SSRC0", 106)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 14)], None), + // v[8:9] += 0x9E3779B9 + lane, through s[20:21] + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 8), ("SDST", 20), ("SRC0", V + 8), ("SRC1", V + 6)], None), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 9), ("SDST", 20), ("SRC0", V + 9), ("SRC1", 128), ("SRC2", 20)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 12), ("SSRC1", 10)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF0)], None), // → loop + // out[group · 256 + thread] = (count, sum, v8, v9) + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 24), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", 11)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", V + 8)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 9)], None), + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 16), ("SSRC0", 4), ("SSRC1", 136)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 16), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 132), ("VSRC1", 30)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 0), ("VSRC1", 30)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 30), ("DATA", 24), ("SADDR", 0x7D)], None), + ]); + for dims in [[256u32, 1, 1], [8, 8, 4]] { + let threads = dims.iter().product::(); + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + if runner::split_wave64() { + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 1, "the v_cmp: read whole by the odd waves"); + assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 2, "the carries"); + } + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let base = 0x100usize; + let mut io = vec![0u32; 128]; + io[0] = base as u32; + io[1] = dims[0]; + io[2] = dims[0] * dims[1]; + let groups = 3usize; + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 256 * 16) / 4]).unwrap(); + for g in 0..groups { + for tid in 0..threads as usize { + let (w, l) = (tid / 64, (tid % 64) as u32); + let n = 2 * (w as u32 + 1); + let count = (0..n).filter(|i| 5 * i + 3 > l).count() as u32; + let sum = if w % 2 == 1 { (0..n).map(|i| (5 * i + 3).min(64)).sum() } else { 0 }; + let acc = n as u64 * (0x9E37_79B9u64 + l as u64); + let at = (base + (g * 256 + tid) * 16) / 4; + let what = format!("{dims:?}, group {g} thread {tid} (wave {w}, lane {l})"); + assert_eq!(out[at], count, "{what}: per-lane count"); + assert_eq!(out[at + 1], sum, "{what}: s_bcnt1 sum"); + assert_eq!((out[at + 2], out[at + 3]), (acc as u32, (acc >> 32) as u32), "{what}: 64-bit carry chain"); + } + } + } +} + /// A group of four wave64s whose waves take different paths: each loops 2 · (wave + 1) /// times through a ballot, s_bcnt1 and a readlane, then exchanges lanes across its halves /// with ds_bpermute. Split (32-lane GPUs) this is the counter-paired form – a group barrier @@ -4603,7 +4836,7 @@ fn gpu_split_wave64_waves_diverge() { /// --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 /// program (no exchanges) and as a wave64 program – natively on a GPU with 64-lane waves, -/// split on one with 32-lane waves only. Wall time of the dispatch, best of 5. +/// split on one with 32-lane waves only. GPU time of the dispatch (timestamps), median of 9. #[test] #[ignore] fn bench_split_wave64() { @@ -4648,9 +4881,13 @@ fn bench_split_wave64() { let p = body(readfirstlane); for threads in [64u32, 256] { let mut ms = Vec::new(); + let mut exchanges = 0; for wave64 in [false, true] { let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() })).unwrap(); + // the loop's exchanges: masks read whole (`x64_masks`: not the v_cndmask + // selector, unless `XCL_X64_ALL_MASKS`) and the readfirstlane + exchanges = t.hlsl.matches("= xcl_x_ballot(and(").count() + t.hlsl.matches("xcl_x_rla_uniform(").count().saturating_sub(1); assert!(t.complete(), "{:?}", t.unsupported_why); let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); let groups = (1u32 << 18) / threads; @@ -4658,19 +4895,16 @@ fn bench_split_wave64() { io[0] = 0; io[1] = iterations; let mem = vec![0u32; threads as usize]; - let best = (0..5) - .map(|_| { - let t0 = std::time::Instant::now(); - runner::dispatch(&dxil, [groups, 1, 1], &io, &mem).unwrap(); - t0.elapsed().as_secs_f64() * 1000.0 - }) - .fold(f64::MAX, f64::min); - ms.push(best); + // GPU time of each dispatch (timestamps: no pipeline creation, uploads or CPU + // wait in it), the median of 9 + let mut t = runner::dispatch_timed(&dxil, [groups, 1, 1], &io, &mem, 9).unwrap(); + t.sort_by(f64::total_cmp); + ms.push(t[t.len() / 2]); } let form = if runner::split_wave64() { if threads > 64 { "split, counter-paired" } else { "split, barrier" } } else { "native" }; println!( - "{} exchange(s) / iteration, {threads} threads per group, 2^18 threads x {iterations} iterations: wave32 {:.1} ms, wave64 ({form}) {:.1} ms = {:.2}x", - 1 + readfirstlane as u32, + "v_cmp + v_cndmask{}: {exchanges} exchange(s) / iteration, {threads} threads per group, 2^18 threads x {iterations} iterations: wave32 {:.1} ms, wave64 ({form}) {:.1} ms = {:.2}x", + if readfirstlane { " + v_readfirstlane" } else { "" }, ms[0], ms[1], ms[1] / ms[0] diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs new file mode 100644 index 0000000..431e57b --- /dev/null +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -0,0 +1,454 @@ +//! Split wave64 (docs/wave64-on-wave32.md): which masks need the exchange. +//! +//! In the split form every mask write (`v_cmp*`, carries) exchanges the two halves' ballots so +//! that both halves hold the whole 64-bit mask. A mask that is only ever read lane by lane – +//! `v_cndmask_b32`'s selector, the carry-in of `v_add_co_ci` / `v_sub(rev)_co_ci` – needs just +//! the reading lane's own bit, which its own half has. This is a backward liveness analysis +//! over the SGPRs: a register is *whole-live* after an instruction when some path may read +//! its whole value (any SALU / SMEM / VALU scalar operand, a branch on VCCZ, …) before it is +//! written again. A mask write whose destination is not whole-live needs no exchange. +//! +//! After a mask stays in its half the two halves hold different values in its registers, so a +//! whole read that is missed here – or a write taken for a full overwrite that is not one – +//! lets them diverge. The rules follow what the emitter does, not only the ISA tables: +//! - a write counts as an overwrite only when the emitter replaces the register whatever its +//! old value: not `s_cmov*` (conditional), `s_addk` / `s_mulk` / `s_bitset*` (read the old +//! value), `s_movreld` / `s_movrelsd` (write `s[dst + m0]`), nor SDWA compares that write +//! their SDST (SD = 1) instead of VCC; +//! - `s_movrels*` read `s[src + m0]`: every register from `src` up; +//! - SDWA scalar sources (S0 / S1 bits) and SMEM register offsets are reads. +//! +//! Conservative where it cannot see: an indirect jump makes every SGPR whole-live, EXEC is +//! always whole-live, and so is every SGPR at the end of a kernel-mode program (the runner +//! reads them back). Every emitted loop may also be left where its iteration budget +//! (`LOOP_GUARD`) is checked: what is live after a loop, or at the end, is live before each of +//! its instructions. + +use std::collections::BTreeMap; + +use super::emit::ext_encoding; +use crate::gpu::rdna2::{self, Decoded, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; + +/// SGPR set: bit n = s (106/107 VCC, 124 M0, 126/127 EXEC). +pub type Regs = u128; + +const VCC: Regs = 3 << 106; +const M0: Regs = 1 << 124; +const EXEC: Regs = 3 << 126; +const ALL: Regs = !0; + +fn range(first: u64, n: u64) -> Regs { + (first..(first + n).min(128)).fold(0, |m, r| m | 1u128 << r) +} + +/// SGPRs a scalar source code names (`n` dwords from it): s0–s105, VCC, M0, EXEC; src_vccz / +/// src_execz are derived from the whole VCC / EXEC; NULL, constants and literals name none. +fn scalar_code(v: u64, n: u64) -> Regs { + match v { + 251 => VCC, + 252 => EXEC, + 125 => 0, + v if v <= 127 => range(v, n), + _ => 0, + } +} + +/// Instructions whose mask operand is read lane by lane (the emitter's `lane_of`). +fn reads_mask_per_lane(name: &str) -> bool { + matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") +} + +/// Instructions that keep (part of) their destination's old value: the destination is read +/// and not overwritten. +fn keeps_destination(name: &str) -> bool { + name.starts_with("S_CMOV") || matches!(name, "S_ADDK_I32" | "S_MULK_I32" | "S_BITSET0_B32" | "S_BITSET1_B32" | "S_BITSET0_B64" | "S_BITSET1_B64") +} + +/// (read whole, overwritten) SGPRs of one instruction. Lane-by-lane mask reads are left out +/// of the first, writes that keep anything of the old value out of the second. +pub fn uses(d: &Decoded) -> (Regs, Regs) { + let name = d.inst.name; + if name.starts_with("S_MOVREL") { + // `smovrel`: s[src + m0] is read, s[dst + m0] written (s_movrelsd_2: both) – any + // register from the encoded one up to s123, VCC included; nothing for certain + // overwritten + let src = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0).min(124); + return (range(src, 124 - src) | M0 | EXEC, 0); + } + let (mut whole, mut written) = (0 as Regs, 0 as Regs); + let per_lane = reads_mask_per_lane(name); + let keeps = keeps_destination(name); + // SDWA: scalar sources and the compare's destination are in the extension dword + let mut sdwa_dst = None; + if d.variant == Variant::Sdwa { + let Some(e) = ext_encoding(d) else { return (ALL, 0) }; + let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + if fv("S0") == 1 { + whole |= scalar_code(fv("VSRC0"), 1); + } + if d.enc.field("VSRC1").is_some() && fv("S1") == 1 { + whole |= scalar_code(fv("VSRC1"), 1); + } + if d.enc.name == "ENC_VOPC" && !name.starts_with("V_CMPX") { + sdwa_dst = Some(if fv("SD") == 1 { scalar_code(fv("SDST"), 2) } else { VCC }); + } + } + for o in d.ienc.operands { + let n = (o.size as u64).div_ceil(32).max(1); + let regs = match (o.field, o.ty) { + (_, "OPR_VCC") => VCC, + (_, "OPR_EXEC" | "OPR_SDST_EXEC") => EXEC, + (_, "OPR_SDST_M0") => M0, + (None, _) | (Some("LITERAL"), _) => continue, + (Some(f), ty) => { + if o.implicit || !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| ty.contains(k)) { + continue; + } + // SDWA / DPP src0 is in the extension dword (above for SDWA; a VGPR for DPP) + if f == "SRC0" && d.variant != Variant::Plain { + continue; + } + scalar_code(rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f), n) + } + }; + if o.output { + if keeps { + whole |= regs; + } else { + written |= regs; + } + } else if !(per_lane && (o.ty == "OPR_VCC" || o.field == Some("SRC2"))) { + whole |= regs; + } + } + if let Some(dst) = sdwa_dst { + written = (written & !VCC) | dst; + } + (whole, written) +} + +/// For each instruction (index in `insts`): the SGPRs whose whole value may be read after it. +/// `end_reads_all`: the program's end reads every SGPR (kernel mode). +pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { + let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let at_end = if end_reads_all { ALL } else { EXEC }; + // successors; None = unknown (indirect): everything is live + let succ: Vec>> = insts + .iter() + .enumerate() + .map(|(i, d)| { + let next = insts.get(i + 1).map(|n| n.pc).and_then(|pc| pcs.get(&pc).copied()); + // a far jump (`rdna2::resolve_far_jumps`) is an unconditional branch + if let Some(t) = d.far_target { + return Some(vec![*pcs.get(&t)?]); + } + if d.inst.flags & F_INDIRECT != 0 || d.inst.name == "S_SETPC_B64" || d.inst.name == "S_SWAPPC_B64" { + return None; + } + let mut out = Vec::new(); + if let Some(t) = rdna2::branch_target(d) { + out.push(*pcs.get(&t)?); + if d.inst.flags & F_CONDITIONAL != 0 { + out.extend(next); + } + } else if d.inst.flags & F_TERMINATOR == 0 { + out.extend(next); + } + Some(out) + }) + .collect(); + // `LOOP_GUARD`: a loop may be left where its guard runs – at its top, before the head + // instruction, and in the `pc` dispatcher form before every block of it – to the code + // after it (structured) or the end of the program (dispatcher: no later block matches + // the `pc` it leaves with). Taken as: before any instruction of a loop, whatever is live + // after the loop or at the end may be read. + let loops = super::loop_ranges(insts); + let exits: Vec>> = insts + .iter() + .map(|d| loops.iter().filter(|&&(a, b)| a <= d.pc && d.pc < b).map(|&(_, b)| pcs.range(b..).next().map(|(_, &j)| j)).collect()) + .collect(); + let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(uses).collect(); + let mut live_in = vec![0 as Regs; insts.len()]; + let mut live_out = vec![0 as Regs; insts.len()]; + loop { + let mut changed = false; + for i in (0..insts.len()).rev() { + let out = match &succ[i] { + None => ALL, + Some(s) if s.is_empty() => at_end, + Some(s) => s.iter().fold(EXEC, |m, &j| m | live_in[j]), + }; + let left = exits[i].iter().fold(0, |m, e| m | at_end | e.map_or(0, |j| live_in[j])); + let (gen, kill) = gen_kill[i]; + let inn = gen | (out & !kill) | left | EXEC; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + if !changed { + return live_out; + } + } +} + +/// pc → SGPRs whole-live after that instruction, for the emitter. +pub fn by_pc(insts: &[Decoded], end_reads_all: bool) -> BTreeMap { + insts.iter().map(|d| d.pc).zip(whole_live_out(insts, end_reads_all)).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn program(bytes: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + out + } + + fn mask_needed(live: &[Regs], i: usize, pair: u64) -> bool { + live[i] & range(pair, 2) != 0 + } + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + const CMP_LT: I = ("V_CMP_LT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + const CNDMASK: I = ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 3), ("VSRC1", 4)]); + const MOV_S2_VCC: I = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 106)]); + + fn asm(lines: &[I]) -> Vec { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + program(&bytes) + } + + #[test] + fn a_selector_only_mask_needs_no_exchange() { + let p = asm(&[CMP, CNDMASK, ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 106)); + // the kernel runner reads VCC at the end: still exchanged there + assert!(mask_needed(&whole_live_out(&p, true), 0, 106)); + } + + #[test] + fn a_carry_chain_needs_no_exchange() { + let p = asm(&[ + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 0), ("SDST", 106), ("SRC0", V), ("SRC1", V + 2)]), + ("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V + 1), ("VSRC1", 3)]), + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106)); + assert!(!mask_needed(&live, 1, 106)); + } + + #[test] + fn scalar_reads_and_branches_keep_the_exchange() { + let readers: [I; 5] = [ + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + MOV_S2_VCC, + ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 106)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ]; + for reader in readers { + let p = asm(&[CMP, reader, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{}", reader.0); + } + } + + #[test] + fn a_whole_read_on_one_path_or_around_a_loop_keeps_the_exchange() { + // v_cmp; s_cbranch_scc0 → skip; v_cndmask; s_branch → end; skip: s_mov s[2:3], vcc; end + let p = asm(&[ + CMP, + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 2)]), + CNDMASK, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)]), + MOV_S2_VCC, + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + // loop: the mask written at the bottom is read whole at the top of the next iteration + let p = asm(&[MOV_S2_VCC, CMP, ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)]), ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 1, 106)); + } + + #[test] + fn overwritten_before_any_whole_read() { + let p = asm(&[CMP, CNDMASK, CMP_LT, MOV_S2_VCC, ENDPGM]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106)); + assert!(mask_needed(&live, 2, 106)); + } + + #[test] + fn exec_is_always_exchanged() { + let p = asm(&[("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), ENDPGM]); + assert!(whole_live_out(&p, false)[0] & EXEC == EXEC); + } + + const CMP_S20: I = ("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", V + 1)]); + const BCNT_S20: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 20)]); + const BCNT_VCC: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); + + // review findings: writes that are not full overwrites, reads the operand tables miss + + #[test] + fn an_sdwa_compare_into_its_sdst_leaves_vcc() { + let sdwa = |sd: u64| -> I { + let f: &'static [(&'static str, u64)] = if sd == 1 { + &[("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 0), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("SD", 1), ("SDST", 22)] + } else { + &[("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 0), ("SRC0_SEL", 6), ("SRC1_SEL", 6)] + }; + ("V_CMP_EQ_U32", "VOPC_VOP_SDWA_SDST_ENC", f) + }; + let p = asm(&[CMP, sdwa(1), BCNT_VCC, ENDPGM]); + assert_eq!(uses(&p[1]).1, range(22, 2), "SD = 1 writes s[22:23], not VCC"); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + // SD = 0: VCC is written, the first compare's mask is dead + let p = asm(&[CMP, sdwa(0), BCNT_VCC, ENDPGM]); + assert_eq!(uses(&p[1]).1, VCC); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106) && mask_needed(&live, 1, 106)); + } + + #[test] + fn read_modify_write_destinations_are_reads() { + let cases: [&[I]; 4] = [ + &[("S_BITSET1_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 191)])], + &[("S_BITSET0_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 129)]), ("S_BITSET0_B32", "ENC_SOP1", &[("SDST", 21), ("SSRC0", 129)])], + &[("S_ADDK_I32", "ENC_SOPK", &[("SDST", 20), ("SIMM16", 1)]), ("S_MULK_I32", "ENC_SOPK", &[("SDST", 21), ("SIMM16", 3)])], + &[("S_CMOVK_I32", "ENC_SOPK", &[("SDST", 20), ("SIMM16", 1)]), ("S_CMOV_B32", "ENC_SOP1", &[("SDST", 21), ("SSRC0", 129)])], + ]; + for rmw in cases { + let mut l = vec![CMP_S20]; + l.extend_from_slice(rmw); + l.extend([BCNT_S20, ENDPGM]); + assert!(mask_needed(&whole_live_out(&asm(&l), false), 0, 20), "{}", rmw[0].0); + } + } + + #[test] + fn scalar_relative_moves_reach_any_register_from_their_base() { + // s_movrels_b64 s[0:1], s[100 + m0 : 101 + m0] – VCC with m0 = 6 + let p = asm(&[CMP, ("S_MOVRELS_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 100)]), ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 0)]), ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + // s_movreld_b64 s[20 + m0 : 21 + m0]: s[20:21] itself only when m0 = 0 + let p = asm(&[CMP_S20, ("S_MOVRELD_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 0)]), BCNT_S20, ENDPGM]); + assert_eq!(uses(&p[1]).1, 0); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + } + + #[test] + fn smem_register_offsets_and_sdwa_scalar_sources_are_reads() { + let readers: [I; 3] = [ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 0), ("SBASE", 4), ("OFFSET", 0), ("SOFFSET", 20)]), + ("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[("VDST", 11), ("SRC0", 0xF9), ("VSRC0", 1), ("VSRC1", 20), ("S1", 1), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)]), + ("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[("VDST", 11), ("SRC0", 0xF9), ("VSRC0", 20), ("S0", 1), ("VSRC1", 2), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)]), + ]; + for r in readers { + let p = asm(&[CMP_S20, r, ENDPGM]); + assert!(uses(&p[1]).0 & range(20, 1) != 0, "{} {}", r.0, r.1); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20), "{} {}", r.0, r.1); + } + // a VGPR src1 is not + let p = asm(&[CMP_S20, ("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[("VDST", 11), ("SRC0", 0xF9), ("VSRC0", 1), ("VSRC1", 20), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)]), ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 20)); + } + + #[test] + fn a_selector_that_is_also_a_scalar_source_is_read_whole() { + // v_cndmask_b32 v2, vcc_lo, v3, vcc: the selector per lane, src0 the whole VCC_LO + let p = asm(&[CMP, ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 106), ("SRC1", V + 3), ("SRC2", 106)]), ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + let p = asm(&[CMP, ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", 106)]), ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 106)); + } + + #[test] + fn a_far_jump_is_a_branch_not_an_unknown_jump() { + // v_cmp vcc; s_getpc s[30:31]; s_add_u32 s30, s30, 20; s_addc_u32 s31, s31, 0; + // s_setpc s[30:31] → +28 (past the s_mov that reads VCC whole); +28: v_cndmask; end + let mut bytes = Vec::new(); + for (n, e, f, l) in [ + (CMP.0, CMP.1, CMP.2, None), + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 30)][..], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 30), ("SSRC0", 30), ("SSRC1", 255)][..], Some(20)), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 31), ("SSRC0", 31), ("SSRC1", 128)][..], None), + ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 30)][..], None), + (MOV_S2_VCC.0, MOV_S2_VCC.1, MOV_S2_VCC.2, None), + (CNDMASK.0, CNDMASK.1, CNDMASK.2, None), + (ENDPGM.0, ENDPGM.1, ENDPGM.2, None), + ] { + bytes.extend(rdna2::encode(n, e, f, l).unwrap()); + } + let mut p = program(&bytes); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "unresolved: an indirect jump"); + rdna2::resolve_far_jumps(&mut p); + assert_eq!(p[4].far_target, Some(p[6].pc)); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 106)); + } + + #[test] + fn a_loop_may_be_left_at_its_top() { + // loop: s_mov_b64 vcc, s[4:5]; v_cmp vcc; v_cndmask; s_branch loop – then s_bcnt1 vcc: + // only the emitter's iteration budget leaves the loop, at its top, with the v_cmp's VCC + let p = asm(&[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 4)]), + CMP, + CNDMASK, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + BCNT_VCC, + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 1, 106)); + } + + #[test] + fn a_loop_left_before_its_head_overwrites() { + // v_cmp vcc; v_cndmask; loop: s_mov_b64 vcc, s[4:5]; v_cndmask; s_branch loop – then + // s_bcnt1 vcc: a budget already spent leaves the loop before its s_mov, with the + // first v_cmp's VCC + let p = asm(&[CMP, CNDMASK, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 4)]), CNDMASK, ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFD)]), BCNT_VCC, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + } + + #[test] + fn a_dispatcher_loop_left_by_its_budget_ends_the_program() { + // loop: v_cmp vcc; v_cndmask; s_mov_b64 vcc, s[4:5]; s_branch loop – then s_mov_b64 + // vcc, 0: structured, the loop's exit overwrites VCC; in the `pc` dispatcher form the + // budget's break ends the program, whose end the kernel runner reads + let p = asm(&[ + CMP, + CNDMASK, + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 4)]), + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, true), 0, 106)); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 106)); + } + + #[test] + fn s_movrelsd_2_reads_from_its_base_and_overwrites_nothing() { + let mov = ("S_MOVRELSD_2_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 100)][..]); + let p = asm(&[CMP_S20, mov, BCNT_S20, ENDPGM]); + assert_eq!(uses(&p[1]).1, 0); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + // its source s[100 + (m0 & 0x3FF)] reaches VCC + let p = asm(&[CMP, mov, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)]), ENDPGM]); + assert!(uses(&p[1]).0 & VCC == VCC); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + } +} diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 9125dba..a447de3 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -36,7 +36,7 @@ whole-wave: | operation | exchange | |---|---| -| `ballot()` (every mask: `v_cmp*`, `v_cmpx*`, carries, EXEC at entry) | one word: each half gives its 32-bit ballot, both get the 64-bit mask | +| `ballot()` (every mask: `v_cmp*`, `v_cmpx*`, carries, EXEC at entry) | one word: each half gives its 32-bit ballot, both get the 64-bit mask – unless the mask is only read lane by lane (below) | | `v_readlane`, `v_readfirstlane` (lane index uniform) | one word: each half gives the value of lane `l & 31`, the half that owns `l` wins | | `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)`) | @@ -99,11 +99,46 @@ it. A program that really uses the whole 32 KB of LDS therefore loses its top dw 4. **`WaveReadLaneAt` with a per-lane index** – used inside a half as before. 5. **Forward progress** – only the multi-wave variant spins; see above. +### Masks read lane by lane + +A mask whose only readers take the reading lane's own bit – `v_cndmask_b32`'s selector, the +carry-in of `v_add_co_ci` / `v_sub(rev)_co_ci` – needs just that lane's half, so it is not +exchanged: `xcl_x_ballot_local` gives the half's own word and 0 for the other half +(`x64_masks.rs`). Which masks those are is a backward liveness analysis over the SGPRs: a +register is *whole-live* after an instruction when some path may read its whole value (any +SALU / SMEM operand, a VALU scalar operand, `s_cbranch_vcc*`, `src_vccz`, …) before it is +written again; a mask written to registers that are not whole-live stays in its half. + +The halves then hold different values in those registers, so the rules follow what the +emitter does, not only the ISA's operand tables: +- a write is an overwrite only when the emitter replaces the whole register whatever it held: + not `s_cmov*` / `s_cmovk` (conditional), `s_addk` / `s_mulk` / `s_bitset*` (they read the + old value), `s_movreld` / `s_movrelsd_2` (they write `s[dst + m0]`), nor an SDWA compare + with SD = 1 (it writes its SDST, VCC keeps its value); +- `s_movrels*` read `s[src + m0]`: every register from `src` up to s123, VCC included; +- SDWA scalar sources (the S0 / S1 bits), SMEM register offsets, `src_vccz` / `src_execz` and + M0 are reads; +- EXEC is always whole-live; an indirect jump (`s_setpc` / `s_swappc` other than a far jump, + which is a branch) makes every SGPR whole-live, and so does the end of a kernel-mode program + (the runner reads the SGPRs back – the halves still end with the same SGPRs); +- every emitted loop can be left where its iteration budget (`LOOP_GUARD`) is checked – at + its top, and in the `pc` dispatcher form before each of its blocks, to the code after it or + (dispatcher) the end of the program: what is live there is live before each instruction of + the loop. + +A mask with no destination (VOP3 compare into NULL) or one that is 0 in every lane (the +`false` mask of `v_div_scale`) is not exchanged either. Both halves make the same static +choice, so their exchange counts stay in step. Geometry mode (ES → GS through `s_setpc`) +has no liveness pass: its masks are exchanged as before, except those two kinds (no +destination, 0 in every lane), which are the same in both halves either way. +`XCL_X64_ALL_MASKS=1` exchanges every mask (for comparison). + ## Cost -A wave64 program pays one exchange per mask write (`v_cmp*`, carries) and per readlane / -readfirstlane / ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP -instruction. Wave32 programs, VS / PS and everything on GPUs with 64-lane waves are +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 +masks read lane by lane (selects, 64-bit carry chains). Wave32 programs, VS / PS and everything on GPUs with 64-lane waves are unchanged (the HLSL of every native translation the test suite makes is byte-identical). Measured on an RTX 5070 Ti (`bench_split_wave64`, an ignored test): a loop of 8 @@ -121,6 +156,29 @@ it in HLSL), taking issue slots from the waves it waits for. The next step would the exchange for masks only used lane by lane (`v_cmp` + `v_cndmask` selects; each half's own word is enough there), which needs a liveness pass over the mask registers. +That pass is now in (see "Masks read lane by lane"). The benchmark now counts the +exchanges a loop iteration makes and times each dispatch with GPU timestamps (median of 9 +dispatches in one command list; `runner::dispatch_timed`). Before, it took the wall time of +a whole `runner::dispatch` – pipeline creation, buffers, uploads, submission and the CPU's +wait included – which shrank every ratio towards 1 (the 5070 Ti figures above were taken +that way). On an RTX 3090, three runs with all masks exchanged (`XCL_X64_ALL_MASKS=1`) and +five with the default: + +| | mask only | mask + `v_readfirstlane` | +|---|---|---| +| exchanges per iteration (all masks / default) | 1 / 0 | 2 / 1 | +| one console wave per group (barrier) | 1.64–1.68× → 1.04–1.11× | 1.99–2.02× → 1.74–1.81× | +| four console waves per group (counters) | 3.90–4.14× → 1.07–1.16× | 6.45–6.64× → 4.09–4.34× | + +(wave32 baseline 11.4–14.1 ms.) The 4–16 % left with no exchange at all is the rest of +the split form (64-bit masks, the threads' start), not measured further. The benchmark's +loop mask is exactly the kind the pass keeps local – it shows the exchange gone and what +one costs, not how often real shaders gain. + +What is left is readlane / readfirstlane, `ds_bpermute`, coherent scalar loads and masks +read whole. Not measured on real compute shaders (none on that machine); Minecraft's 273 +wave64 programs, translated as compute, have 38 mask writes, all only read lane by lane. + ## Relation to earlier work * **PR #33** (ElHombreAlex, draft): first wave64 → wave32 "rendezvous" through groupshared