From ce0eeec142a08c0b341e215a825ddccbaa19d284 Mon Sep 17 00:00:00 2001 From: Zondybtw Date: Tue, 24 Nov 2026 19:37:32 +0800 Subject: [PATCH 1/3] Recompiler: propagate split-wave64 lane-local masks through 64-bit bitwise SALU ops --- crates/xcl/src/gpu/recomp/emit.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 75 +++++ crates/xcl/src/gpu/recomp/x64_masks.rs | 389 +++++++++++++++++++++++-- 3 files changed, 445 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8888caedad..9de945994d 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -826,7 +826,7 @@ impl Em { // 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::S(n) => n < 126 && n & 1 == 0 && self.x64_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), Dst::Null => true, Dst::V(_) => false, }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 56d71f0d1f..ba00cdc858 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5815,6 +5815,81 @@ fn gpu_split_wave64_lane_local_masks() { } } +/// Bitwise 64-bit SALU ops (`s_and_b64`, `s_or_b64`, `s_not_b64`, `s_andn2_b64`, `s_mov_b64`, +/// `s_cselect_b64`) over lane-local masks stay in each 32-lane half when neither their +/// destination nor `scc` is whole-live afterward; when `scc` IS read (e.g. only upper-half +/// lanes match and `s_cselect_b32` reads `scc`), the inputs stay exchanged so both halves +/// observe the same `scc`. +#[test] +fn gpu_split_wave64_bitwise_lane_masks() { + if !gpu_ready() { + return; + } + const V: u64 = 256; + // Part 1: 3 masks combined purely for v_cndmask_b32 -> zero ballot exchanges + let local_code = prog(&[ + // s[20:21] = (v0 >= 10), s[22:23] = (v0 < 50), vcc = ((v0 & 1) == 0) + ("V_CMP_GE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", 138)], None), + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 255)], Some(50)), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 129), ("VSRC1", 0)], None), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 9)], None), + // s[24:25] = s[20:21] & s[22:23] (10 <= l < 50) + ("S_AND_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 20), ("SSRC1", 22)], None), + // s[26:27] = s[24:25] & ~vcc (10 <= l < 50 && l odd) + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 24), ("SSRC1", 106)], None), + // s[28:29] = ~s[20:21] | s[26:27] (l < 10 || (10 <= l < 50 && l odd)) + ("S_NOT_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 20)], None), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 28), ("SSRC0", 28), ("SSRC1", 26)], None), + // vcc = s_mov_b64(s[28:29]), then s_cselect_b64 with uniform scc (s0 == 1) + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 28)], None), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 106), ("SSRC0", 106), ("SSRC1", 26)], None), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V + 2), ("VSRC1", 3)], None), + // Clear all mask SGPRs and overwrite SCC so kernel-mode readback sees uniform registers + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)], None), + ]); + if runner::split_wave64() { + let t = translate(&local_code, &runner::options(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 3, "all 3 compares stay local"); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 0, "no ballot exchange needed"); + } + let mut st = KernelState::default(); + st.sgpr[0] = 1; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[2] = 100 + l as u32; + r[3] = 200 + l as u32; + } + let r = runner::run_code(&local_code, &st, &[]).unwrap(); + for l in 0..64u32 { + let cond = l < 10 || ((10..50).contains(&l) && l % 2 == 1); + assert_eq!(r.vgpr[l as usize][1], if cond { 200 + l } else { 100 + l }, "lane {l}: bitwise local mask"); + } + + // Part 2: only upper-half lanes (40..49) match; s_and_b64's SCC is read by s_cselect_b32 -> + // both compares must stay exchanged so half 0 and half 1 agree on SCC == 1. + let scc_code = prog(&[ + ("V_CMP_GE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", 255)], Some(40)), + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 255)], Some(50)), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 20), ("SSRC1", 22)], None), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 255), ("SSRC1", 139)], Some(77)), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 128)], None), + ]); + if runner::split_wave64() { + let t = translate(&scc_code, &runner::options(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 2, "live SCC keeps both exchanges"); + } + let r = runner::run_code(&scc_code, &st, &[]).unwrap(); + assert_eq!(r.sgpr[1], 77, "both halves must see SCC == 1 from upper-half match"); +} + /// 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 diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index 431e57b949..747062aef9 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -2,10 +2,14 @@ //! //! 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 +//! `v_cndmask_b32`'s selector, the carry-in of `v_add_co_ci` / `v_sub(rev)_co_ci`, or even-aligned +//! 64-bit lane-wise SALU ops (`s_mov_b64`, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_not_b64`, +//! `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_wqm_b64`, +//! `s_cselect_b64`, `s_cmov_b64`) whose destination is not whole-live and whose `scc` (if written) +//! is dead – needs just the reading lane's own bit, which its own half has. This is a backward +//! liveness analysis over the SGPRs and `scc`: a register is *whole-live* after an instruction +//! when some path may read its whole value (any non-lane-wise SALU / SMEM / VALU scalar operand, +//! a branch on VCCZ, a lane-wise op whose destination or written `scc` is live, …) 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 @@ -58,12 +62,215 @@ 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") } +/// 64-bit SALU ops whose low and high dwords depend only on the corresponding dwords of their +/// inputs (no bit crosses the 32-lane half boundary): `(is_lane_wise, sets_scc)`. +/// When neither their destination nor (if `sets_scc`) `scc` is whole-live afterward, each half +/// can evaluate the op on its own 32-lane half word without exchanging the inputs. +fn lane_wise_salu64(name: &str) -> Option { + match name { + "S_MOV_B64" | "S_CMOV_B64" | "S_CSELECT_B64" => Some(false), + "S_NOT_B64" + | "S_WQM_B64" + | "S_AND_B64" + | "S_OR_B64" + | "S_XOR_B64" + | "S_ANDN2_B64" + | "S_ORN2_B64" + | "S_NAND_B64" + | "S_NOR_B64" + | "S_XNOR_B64" => Some(true), + _ => None, + } +} + +fn is_cmp_suffix(s: &str) -> bool { + matches!( + s, + "EQ_I32" | "LG_I32" | "GT_I32" | "GE_I32" | "LT_I32" | "LE_I32" | "EQ_U32" | "LG_U32" | "GT_U32" | "GE_U32" | "LT_U32" | "LE_U32" + ) +} + +/// Whether `emit.rs` unconditionally overwrites `scc` for `d` (conservative: false whenever unsure). +fn writes_scc(d: &Decoded) -> bool { + let n = d.inst.name; + match d.enc.name { + "ENC_SOPK" => n == "S_ADDK_I32" || n.strip_prefix("S_CMPK_").is_some_and(is_cmp_suffix), + "ENC_SOPC" => { + matches!(n, "S_CMP_EQ_U64" | "S_CMP_LG_U64" | "S_BITCMP0_B32" | "S_BITCMP1_B32" | "S_BITCMP0_B64" | "S_BITCMP1_B64") + || n.strip_prefix("S_CMP_").is_some_and(is_cmp_suffix) + } + "ENC_SOP1" | "ENC_SOP2" => { + if let Some(op) = n.strip_prefix("S_").and_then(|s| s.strip_suffix("_B32").or_else(|| s.strip_suffix("_B64"))) { + if let Some(kind) = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")) { + return matches!(kind, "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "NAND" | "NOR" | "XNOR" | "ANDN1" | "ORN1"); + } + } + matches!( + n, + "S_NOT_B32" + | "S_BCNT0_I32_B32" + | "S_BCNT1_I32_B32" + | "S_ABS_I32" + | "S_AND_B32" + | "S_OR_B32" + | "S_XOR_B32" + | "S_ANDN2_B32" + | "S_ORN2_B32" + | "S_NAND_B32" + | "S_NOR_B32" + | "S_XNOR_B32" + | "S_ADD_U32" + | "S_SUB_U32" + | "S_ADDC_U32" + | "S_SUBB_U32" + | "S_ADD_I32" + | "S_SUB_I32" + | "S_LSHL_B32" + | "S_LSHR_B32" + | "S_ASHR_I32" + | "S_LSHL1_ADD_U32" + | "S_LSHL2_ADD_U32" + | "S_LSHL3_ADD_U32" + | "S_LSHL4_ADD_U32" + | "S_BFE_U32" + | "S_BFE_I32" + | "S_MIN_U32" + | "S_MAX_U32" + | "S_MIN_I32" + | "S_MAX_I32" + | "S_WQM_B32" + | "S_ABSDIFF_I32" + | "S_NOT_B64" + | "S_WQM_B64" + | "S_BCNT1_I32_B64" + | "S_BCNT0_I32_B64" + | "S_LSHL_B64" + | "S_LSHR_B64" + | "S_ASHR_I64" + | "S_BFE_U64" + | "S_BFE_I64" + | "S_AND_B64" + | "S_OR_B64" + | "S_XOR_B64" + | "S_ANDN2_B64" + | "S_ORN2_B64" + | "S_NAND_B64" + | "S_NOR_B64" + | "S_XNOR_B64" + ) + } + _ => false, + } +} + +/// Whether `d` may read `scc` (either implicitly or via scalar source code 253). +fn reads_scc(d: &Decoded) -> bool { + let n = d.inst.name; + if matches!(n, "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" | "S_CSELECT_B32" | "S_CSELECT_B64" | "S_ADDC_U32" | "S_SUBB_U32") + || n.starts_with("S_CMOV") + { + return true; + } + if d.variant == Variant::Sdwa { + let Some(e) = ext_encoding(d) else { return true }; + let fv = |f: &str| rdna2::field_value(e, &d.words, f).unwrap_or(0); + if (fv("S0") == 1 && fv("VSRC0") == 253) || (d.enc.field("VSRC1").is_some() && fv("S1") == 1 && fv("VSRC1") == 253) { + return true; + } + } + for o in d.ienc.operands { + if o.output { + continue; + } + if o.ty == "OPR_SSRC_SPECIAL_SCC" { + return true; + } + if o.implicit { + continue; + } + let Some(f) = o.field else { continue }; + if f == "LITERAL" || (f == "SRC0" && d.variant != Variant::Plain) { + continue; + } + if !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| o.ty.contains(k)) { + continue; + } + if rdna2::register_scale(f) == 1 && rdna2::field_value(d.enc, &d.words, f) == Some(253) { + return true; + } + } + false +} + /// 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") } +struct InstFlow { + whole: Regs, + kill: Regs, + /// Even-aligned 64-bit lane-wise SALU op: `(dst, lane_srcs, sets_scc)`. + lane_op: Option<(Regs, Regs, bool)>, + reads_scc: bool, + writes_scc: bool, +} + +fn flow(d: &Decoded) -> InstFlow { + let (whole, kill) = uses(d); + let r_scc = reads_scc(d); + let w_scc = writes_scc(d); + let Some(sets_scc) = lane_wise_salu64(d.inst.name) else { + return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + }; + if d.variant != Variant::Plain { + return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + } + // Verify even SGPR pair alignment on dst and all register sources so low/high half words can + // never cross-alias; scalar special codes `vccz` (251) / `execz` (252) always read whole. + let keeps = keeps_destination(d.inst.name); + let (mut dst_regs, mut lane_srcs, mut force_whole) = (0 as Regs, 0 as Regs, 0 as Regs); + for o in d.ienc.operands { + let Some(f) = o.field else { continue }; + if o.implicit || f == "LITERAL" { + continue; + } + if !["SREG", "SSRC", "SDST", "OPR_SRC"].iter().any(|k| o.ty.contains(k)) { + continue; + } + let code = rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + let n = (o.size as u64).div_ceil(32).max(1); + if o.output { + if code == 125 { + continue; + } + if code > 126 || code & 1 != 0 || n != 2 { + return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + } + let r = range(code, 2); + dst_regs |= r; + if keeps { + lane_srcs |= r; + } + } else { + match code { + 251 => force_whole |= VCC, + 252 => force_whole |= EXEC, + 125 => {} + c if c <= 127 => { + if c > 126 || c & 1 != 0 || n != 2 { + return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + } + lane_srcs |= range(c, 2); + } + _ => {} + } + } + } + InstFlow { whole: force_whole, kill, lane_op: Some((dst_regs, lane_srcs, sets_scc)), reads_scc: r_scc, writes_scc: w_scc } +} + /// (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) { @@ -167,23 +374,39 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { .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 flows: Vec = insts.iter().map(flow).collect(); + let scc_at_end = end_reads_all; let mut live_in = vec![0 as Regs; insts.len()]; let mut live_out = vec![0 as Regs; insts.len()]; + let mut scc_in = vec![false; insts.len()]; + let mut scc_out = vec![false; 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 (out, sout) = match &succ[i] { + None => (ALL, true), + Some(s) if s.is_empty() => (at_end, scc_at_end), + Some(s) => s.iter().fold((EXEC, false), |(m, sc), &j| (m | live_in[j], sc || scc_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] { + let (left, sleft) = exits[i].iter().fold((0 as Regs, false), |(m, sc), e| { + (m | at_end | e.map_or(0, |j| live_in[j]), sc || scc_at_end || e.is_some_and(|j| scc_in[j])) + }); + let f = &flows[i]; + let mut gen = f.whole; + if let Some((dst, srcs, sets_scc)) = f.lane_op { + // Lane-wise 64-bit SALU op needs whole inputs iff its destination is whole-live + // afterward, or it writes `scc` and `scc` is live afterward. + if (out & dst) != 0 || (sets_scc && sout) { + gen |= srcs; + } + } + let inn = gen | (out & !f.kill) | left | EXEC; + let sinn = f.reads_scc || (sout && !f.writes_scc) || sleft; + if out != live_out[i] || inn != live_in[i] || sout != scc_out[i] || sinn != scc_in[i] { live_out[i] = out; live_in[i] = inn; + scc_out[i] = sout; + scc_in[i] = sinn; changed = true; } } @@ -252,9 +475,8 @@ mod tests { #[test] fn scalar_reads_and_branches_keep_the_exchange() { - let readers: [I; 5] = [ + let readers: [I; 4] = [ ("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)]), @@ -263,28 +485,31 @@ mod tests { let p = asm(&[CMP, reader, ENDPGM]); assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{}", reader.0); } + // s_mov_b64 keeps the exchange when its destination is read whole + let p = asm(&[CMP, MOV_S2_VCC, ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)]), ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); } #[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 + // v_cmp; s_cbranch_scc0 → skip; v_cndmask; s_branch → end; skip: s_bcnt1 vcc; end let p = asm(&[ CMP, ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 2)]), CNDMASK, ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)]), - MOV_S2_VCC, + BCNT_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]); + let p = asm(&[BCNT_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 p = asm(&[CMP, CNDMASK, CMP_LT, BCNT_VCC, ENDPGM]); let live = whole_live_out(&p, false); assert!(!mask_needed(&live, 0, 106)); assert!(mask_needed(&live, 2, 106)); @@ -386,7 +611,7 @@ mod tests { ("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), + (BCNT_VCC.0, BCNT_VCC.1, BCNT_VCC.2, None), (CNDMASK.0, CNDMASK.1, CNDMASK.2, None), (ENDPGM.0, ENDPGM.1, ENDPGM.2, None), ] { @@ -451,4 +676,128 @@ mod tests { assert!(uses(&p[1]).0 & VCC == VCC); assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); } + + #[test] + fn bitwise_mask_chain_for_selector_needs_no_exchange() { + let cmp_s22: I = ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 2), ("SRC1", V + 3)]); + let p = asm(&[ + CMP_S20, + cmp_s22, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 20), ("SSRC1", 22)]), + ("S_NOT_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 24)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 24), ("SSRC1", 20)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 26)]), + CNDMASK, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 20)); + assert!(!mask_needed(&live, 1, 22)); + // kernel mode reads all SGPRs and SCC at end: exchanges are kept + let live_k = whole_live_out(&p, true); + assert!(mask_needed(&live_k, 0, 20)); + assert!(mask_needed(&live_k, 1, 22)); + } + + #[test] + fn bitwise_mask_with_live_scc_keeps_exchange() { + let cmp_s22: I = ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 2), ("SRC1", V + 3)]); + let and_vcc: I = ("S_AND_B64", "ENC_SOP2", &[("SDST", 106), ("SSRC0", 20), ("SSRC1", 22)]); + let br_scc: I = ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)]); + // SCC from s_and_b64 is live at s_cbranch_scc0 -> inputs must be exchanged + let p = asm(&[CMP_S20, cmp_s22, and_vcc, CNDMASK, br_scc, ENDPGM]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 20)); + assert!(mask_needed(&live, 1, 22)); + // Overwriting SCC before the branch makes s_and_b64's SCC dead -> no exchange needed + let cmp_scc: I = ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)]); + let p = asm(&[CMP_S20, cmp_s22, and_vcc, CNDMASK, cmp_scc, br_scc, ENDPGM]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 20)); + assert!(!mask_needed(&live, 1, 22)); + } + + #[test] + fn bitwise_mask_feeding_whole_read_keeps_exchange() { + let cmp_s22: I = ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 2), ("SRC1", V + 3)]); + // Feeding s_and_saveexec_b64 (whole read of s[20:21]) + let p = asm(&[ + CMP_S20, + cmp_s22, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 20), ("SSRC1", 22)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 20)]), + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 20)); + assert!(mask_needed(&live, 1, 22)); + // Writing EXEC directly + let p = asm(&[CMP_S20, cmp_s22, ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 20), ("SSRC1", 22)]), ENDPGM]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 20)); + assert!(mask_needed(&live, 1, 22)); + } + + #[test] + fn cselect_and_cmov_b64_propagate_lane_masks_and_keep_scc_uniform() { + let cmp_s22: I = ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 2), ("SRC1", V + 3)]); + // Uniform SCC from s_cmp_eq_u32 -> s_cselect_b64 needs no exchange on its mask inputs + let p = asm(&[ + CMP_S20, + cmp_s22, + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)]), + ("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 106), ("SSRC0", 20), ("SSRC1", 22)]), + CNDMASK, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 20)); + assert!(!mask_needed(&live, 1, 22)); + // s_cmov_b64 reads SCC from s_and_b64 -> s_and_b64's inputs must be exchanged so SCC is uniform + let p = asm(&[ + CMP_S20, + cmp_s22, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 20), ("SSRC1", 22)]), + ("S_CMOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 20)]), + CNDMASK, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 20)); + assert!(mask_needed(&live, 1, 22)); + } + + #[test] + fn vccz_operand_and_odd_alignment_in_bitwise_ops_keep_exchange() { + // SRC_VCCZ (251) tests all 64 bits of VCC -> VCC must stay exchanged + let p = asm(&[ + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 22), ("SSRC1", 251)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 3), ("SRC1", V + 4), ("SRC2", 20)]), + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + // Odd-aligned pair s[21:22] crosses even/odd half boundary -> stay conservative + let p = asm(&[ + CMP_S20, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 21), ("SSRC1", 22)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 3), ("SRC1", V + 4), ("SRC2", 24)]), + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + } + + #[test] + fn loop_exit_reading_scc_keeps_exchange_inside_loop() { + // loop: v_cmp s[20:21]; s_and_b64 vcc, s[20:21], s[22:23]; v_cndmask; s_branch loop; s_cbranch_scc1 + let p = asm(&[ + CMP_S20, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 106), ("SSRC0", 20), ("SSRC1", 22)]), + CNDMASK, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)]), + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + } } From 524b25c1b7daaac3d131e5f9dce1661b8c35916d Mon Sep 17 00:00:00 2001 From: Miguel Machado Date: Tue, 24 Nov 2026 14:13:34 -0300 Subject: [PATCH 2/3] Recompiler: split-wave64 EXEC is exchanged only where it is read whole x64_masks kept EXEC whole-live everywhere, so every v_cmpx and every s_*_saveexec_b64 / s_*_wrexec_b64 exchanged the two halves' masks, and so did the compares feeding them. Every VALU reads EXEC lane by lane (the emitter's lanebit), and DPP, ds_swizzle and v_permlane(x)16 read it for a source lane in the reader's own half, so EXEC needs the whole value only where the program reads it whole: s_cbranch_exec(n)z, src_execz, a scalar operand, v_readfirstlane (first active lane) and ds_(b)permute (lanes of the other half). The last three are not in the operand tables and are now added in uses(). EXEC is now a mask like the others in the liveness: no longer live at every instruction or at the end of a compute program (the kernel runner still reads every SGPR at the end). An even-aligned saveexec / wrexec needs whole inputs only when the new EXEC or its scc is read whole, and whole EXEC alone when only the saved old EXEC is; odd pairs keep reading their operands whole. The emitter lets EXEC (s126) take the local ballot. Three tests from the bitwise-mask change relied on EXEC being always live; they now read EXEC whole after the write. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/gpu/recomp/emit.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 52 +++++++++ crates/xcl/src/gpu/recomp/x64_masks.rs | 147 +++++++++++++++++++++---- 3 files changed, 177 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 9de945994d..bb9e001038 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -826,7 +826,7 @@ impl Em { // 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 && n & 1 == 0 && self.x64_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::S(n) => n <= 126 && n & 1 == 0 && self.x64_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), Dst::Null => true, Dst::V(_) => false, }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index ba00cdc858..f21d5a6ed0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5890,6 +5890,58 @@ fn gpu_split_wave64_bitwise_lane_masks() { assert_eq!(r.sgpr[1], 77, "both halves must see SCC == 1 from upper-half match"); } +/// Split wave64 (`x64_masks`): EXEC written by `v_cmpx` or `s_and_saveexec_b64` and read only +/// lane by lane before it is restored stays in each half (no exchange); a `v_cmpx` whose EXEC +/// `v_readfirstlane` reads is still exchanged, and both halves see the first active lane. +#[test] +fn gpu_split_wave64_predicated_exec_masks() { + if !gpu_ready() { + return; + } + const V: u64 = 256; + let code = prog(&[ + // v_cmpx region: lanes 0..49 add 100 to v4, then EXEC is restored + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 6)], None), // v6 = 50 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 255), ("VSRC1", 4)], Some(100)), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)], None), + // s_and_saveexec_b64 region: lanes 20..63 add 50 to v5, then EXEC is restored + ("V_CMP_GE_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 148)], None), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 22)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 5)], Some(50)), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)], None), + // v_cmpx then v_readfirstlane: only lanes 41..63 active, both halves must read lane 41 + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)], None), + ("V_CMPX_GT_U32", "ENC_VOP3", &[("SRC0", V), ("SRC1", 255)], Some(40)), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)], None), + // the kernel runner reads every SGPR and SCC back: clear the local mask, overwrite SCC + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 128)], None), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 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(), 2, "both predicated regions stay local +{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 1, "the v_cmpx read by v_readfirstlane is exchanged"); + } + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = l; + r[4] = 1000 + l; + r[5] = 2000 + l; + r[6] = 50; + } + let r = runner::run_code(&code, &st, &[]).unwrap(); + assert_eq!(r.sgpr[2], 41, "v_readfirstlane after a v_cmpx that leaves only upper-half lanes"); + for l in 0..64u32 { + let v = &r.vgpr[l as usize]; + assert_eq!(v[4], 1000 + l + if l < 50 { 100 } else { 0 }, "lane {l}: v_cmpx region"); + assert_eq!(v[5], 2000 + l + if l >= 20 { 50 } else { 0 }, "lane {l}: s_and_saveexec region"); + } +} + /// 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 diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index 747062aef9..b189d676e8 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -6,11 +6,15 @@ //! 64-bit lane-wise SALU ops (`s_mov_b64`, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_not_b64`, //! `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_wqm_b64`, //! `s_cselect_b64`, `s_cmov_b64`) whose destination is not whole-live and whose `scc` (if written) -//! is dead – needs just the reading lane's own bit, which its own half has. This is a backward -//! liveness analysis over the SGPRs and `scc`: a register is *whole-live* after an instruction -//! when some path may read its whole value (any non-lane-wise SALU / SMEM / VALU scalar operand, -//! a branch on VCCZ, a lane-wise op whose destination or written `scc` is live, …) before it is -//! written again. A mask write whose destination is not whole-live needs no exchange. +//! is dead – needs just the reading lane's own bit, which its own half has. EXEC is a mask like +//! the others: every VALU reads it lane by lane, so a `v_cmpx*` or an even-aligned +//! `s_*_saveexec_b64` / `s_*_wrexec_b64` whose new EXEC (and `scc`) is not read whole needs no +//! exchange either. This is a backward liveness analysis over the SGPRs and `scc`: a register is +//! *whole-live* after an instruction when some path may read its whole value (any non-lane-wise +//! SALU / SMEM / VALU scalar operand, a branch on VCCZ / EXECZ, `v_readfirstlane` and +//! `ds_(b)permute` for EXEC, a lane-wise op whose destination or written `scc` is live, …) +//! 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 – @@ -22,9 +26,8 @@ //! - `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 +//! Conservative where it cannot see: an indirect jump makes every SGPR 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. @@ -213,19 +216,49 @@ struct InstFlow { kill: Regs, /// Even-aligned 64-bit lane-wise SALU op: `(dst, lane_srcs, sets_scc)`. lane_op: Option<(Regs, Regs, bool)>, + /// Even-aligned `s_*_saveexec_b64` / `s_*_wrexec_b64`: `(dst, lane_src, is_wrexec)`. + save_exec: Option<(Regs, Regs, bool)>, reads_scc: bool, writes_scc: bool, } +/// `s_*_saveexec_b64` / `s_*_wrexec_b64` with even-aligned register operands: +/// `((dst, lane_src, is_wrexec), read whole whatever is live)`. The new EXEC (and `scc`) is +/// `op(src, EXEC)` lane by lane; `dst` gets the old EXEC, or the new one for `wrexec`. +fn save_exec_b64(d: &Decoded) -> Option<((Regs, Regs, bool), Regs)> { + let name = d.inst.name; + let wrexec = name.contains("_WREXEC"); + if d.variant != Variant::Plain || !name.ends_with("_B64") || !(wrexec || name.contains("_SAVEEXEC")) { + return None; + } + let dst = match rdna2::field_value(d.enc, &d.words, "SDST")? { + 125 => 0, + v if v < 126 && v & 1 == 0 => range(v, 2), + _ => return None, + }; + let (src, whole) = match rdna2::field_value(d.enc, &d.words, "SSRC0")? { + 251 => (0, VCC), + 252 => (0, EXEC), + 125 => (0, 0), + v if v <= 126 && v & 1 == 0 => (range(v, 2), 0), + v if v <= 127 => return None, + _ => (0, 0), + }; + Some(((dst, src, wrexec), whole)) +} + fn flow(d: &Decoded) -> InstFlow { let (whole, kill) = uses(d); let r_scc = reads_scc(d); let w_scc = writes_scc(d); + if let Some((se, forced)) = save_exec_b64(d) { + return InstFlow { whole: forced, kill: se.0 | EXEC, lane_op: None, save_exec: Some(se), reads_scc: r_scc, writes_scc: w_scc }; + } let Some(sets_scc) = lane_wise_salu64(d.inst.name) else { - return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + return InstFlow { whole, kill, lane_op: None, save_exec: None, reads_scc: r_scc, writes_scc: w_scc }; }; if d.variant != Variant::Plain { - return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + return InstFlow { whole, kill, lane_op: None, save_exec: None, reads_scc: r_scc, writes_scc: w_scc }; } // Verify even SGPR pair alignment on dst and all register sources so low/high half words can // never cross-alias; scalar special codes `vccz` (251) / `execz` (252) always read whole. @@ -246,7 +279,7 @@ fn flow(d: &Decoded) -> InstFlow { continue; } if code > 126 || code & 1 != 0 || n != 2 { - return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + return InstFlow { whole, kill, lane_op: None, save_exec: None, reads_scc: r_scc, writes_scc: w_scc }; } let r = range(code, 2); dst_regs |= r; @@ -260,7 +293,7 @@ fn flow(d: &Decoded) -> InstFlow { 125 => {} c if c <= 127 => { if c > 126 || c & 1 != 0 || n != 2 { - return InstFlow { whole, kill, lane_op: None, reads_scc: r_scc, writes_scc: w_scc }; + return InstFlow { whole, kill, lane_op: None, save_exec: None, reads_scc: r_scc, writes_scc: w_scc }; } lane_srcs |= range(c, 2); } @@ -268,7 +301,7 @@ fn flow(d: &Decoded) -> InstFlow { } } } - InstFlow { whole: force_whole, kill, lane_op: Some((dst_regs, lane_srcs, sets_scc)), reads_scc: r_scc, writes_scc: w_scc } + InstFlow { whole: force_whole, kill, lane_op: Some((dst_regs, lane_srcs, sets_scc)), save_exec: None, reads_scc: r_scc, writes_scc: w_scc } } /// (read whole, overwritten) SGPRs of one instruction. Lane-by-lane mask reads are left out @@ -331,6 +364,10 @@ pub fn uses(d: &Decoded) -> (Regs, Regs) { if let Some(dst) = sdwa_dst { written = (written & !VCC) | dst; } + // EXEC reads the operand tables leave out: the first active lane, lanes of the other half + if matches!(name, "V_READFIRSTLANE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32") { + whole |= EXEC; + } (whole, written) } @@ -338,7 +375,7 @@ pub fn uses(d: &Decoded) -> (Regs, Regs) { /// `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 }; + let at_end = if end_reads_all { ALL } else { 0 }; // successors; None = unknown (indirect): everything is live let succ: Vec>> = insts .iter() @@ -386,7 +423,7 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { let (out, sout) = match &succ[i] { None => (ALL, true), Some(s) if s.is_empty() => (at_end, scc_at_end), - Some(s) => s.iter().fold((EXEC, false), |(m, sc), &j| (m | live_in[j], sc || scc_in[j])), + Some(s) => s.iter().fold((0, false), |(m, sc), &j| (m | live_in[j], sc || scc_in[j])), }; let (left, sleft) = exits[i].iter().fold((0 as Regs, false), |(m, sc), e| { (m | at_end | e.map_or(0, |j| live_in[j]), sc || scc_at_end || e.is_some_and(|j| scc_in[j])) @@ -400,7 +437,18 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { gen |= srcs; } } - let inn = gen | (out & !f.kill) | left | EXEC; + if let Some((dst, src, wrexec)) = f.save_exec { + // the new EXEC (or `scc`, derived from it) read whole needs both inputs whole; the + // saved old EXEC read whole needs EXEC whole (the new one for `wrexec`) + let (exec_w, dst_w) = ((out & EXEC) != 0 || sout, (out & dst) != 0); + if exec_w || dst_w { + gen |= EXEC; + } + if exec_w || (wrexec && dst_w) { + gen |= src; + } + } + let inn = gen | (out & !f.kill) | left; let sinn = f.reads_scc || (sout && !f.writes_scc) || sleft; if out != live_out[i] || inn != live_in[i] || sout != scc_out[i] || sinn != scc_in[i] { live_out[i] = out; @@ -475,8 +523,7 @@ mod tests { #[test] fn scalar_reads_and_branches_keep_the_exchange() { - let readers: [I; 4] = [ - ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + let readers: [I; 3] = [ ("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)]), @@ -485,6 +532,9 @@ mod tests { let p = asm(&[CMP, reader, ENDPGM]); assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{}", reader.0); } + // s_and_saveexec_b64 keeps the exchange when the new EXEC is read whole + let p = asm(&[CMP, ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), CBRANCH_EXECZ, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); // s_mov_b64 keeps the exchange when its destination is read whole let p = asm(&[CMP, MOV_S2_VCC, ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)]), ENDPGM]); assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); @@ -516,14 +566,64 @@ mod tests { } #[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); + fn exec_is_exchanged_only_when_read_whole() { + let cmpx: I = ("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + // v_cmpx; VALU; EXEC restored before s_cbranch_execz: the v_cmpx's EXEC is read lane by lane + let p = asm(&[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)]), + cmpx, + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 3), ("VSRC1", 4)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + CBRANCH_EXECZ, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 1, 126)); + assert!(mask_needed(&live, 0, 10), "the saved EXEC is restored and then read whole"); + // the kernel runner reads EXEC at the end + let p = asm(&[cmpx, ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 126)); + assert!(mask_needed(&whole_live_out(&p, true), 0, 126)); + for reader in [ + CBRANCH_EXECZ, + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V)]), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("DATA0", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 252)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 126)]), + ] { + let p = asm(&[cmpx, reader, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 126), "{}", reader.0); + } + } + + #[test] + fn saveexec_needs_whole_inputs_only_for_a_whole_read() { + let saveexec: I = ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 20)]); + let restore: I = ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]); + let valu: I = ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 3), ("VSRC1", 4)]); + let bcnt_s10: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 10)]); + // predicated region, EXEC restored before it is read whole + let p = asm(&[CMP_S20, saveexec, valu, restore, CBRANCH_EXECZ, ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 20)); + // the new EXEC read whole (branch), or its `scc` + let p = asm(&[CMP_S20, saveexec, CBRANCH_EXECZ, valu, restore, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + let p = asm(&[CMP_S20, saveexec, ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)]), restore, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + // the saved value read whole: the old EXEC for saveexec, the new one for wrexec + let p = asm(&[CMP_S20, saveexec, valu, bcnt_s10, ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 20)); + let p = asm(&[CMP_S20, ("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 20)]), valu, bcnt_s10, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); + // an odd-aligned source pair is read whole + let p = asm(&[CMP_S20, ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 21)]), valu, restore, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 20)); } 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)]); + const CBRANCH_EXECZ: I = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)]); // review findings: writes that are not full overwrites, reads the operand tables miss @@ -726,13 +826,14 @@ mod tests { cmp_s22, ("S_AND_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 20), ("SSRC1", 22)]), ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 20)]), + CBRANCH_EXECZ, ENDPGM, ]); let live = whole_live_out(&p, false); assert!(mask_needed(&live, 0, 20)); assert!(mask_needed(&live, 1, 22)); - // Writing EXEC directly - let p = asm(&[CMP_S20, cmp_s22, ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 20), ("SSRC1", 22)]), ENDPGM]); + // Writing EXEC directly, then reading it whole + let p = asm(&[CMP_S20, cmp_s22, ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 20), ("SSRC1", 22)]), CBRANCH_EXECZ, ENDPGM]); let live = whole_live_out(&p, false); assert!(mask_needed(&live, 0, 20)); assert!(mask_needed(&live, 1, 22)); From 6acbfb1f4d57e5d914161dde56faaf28da18f973 Mon Sep 17 00:00:00 2001 From: Miguel Machado Date: Tue, 24 Nov 2026 14:19:46 -0300 Subject: [PATCH 3/3] Recompiler: a split-wave64 bitwise mask tree exchanges once, at its end Compares combined by 64-bit bitwise ops into a mask that is read whole (s_bcnt1, saveexec, a live scc, ...) each exchanged the two halves' ballots, although the combination is lane-wise and only its result needs both halves. Within one basic block, x64_masks now follows such trees: when two or more compares or carries feed a tree of lane-wise s_*_b64 ops (not s_cmov / s_cselect) and nothing else reads them, the compares keep the local ballot and the tree's last op exchanges its result once with xcl_x_sync_mask (salu64, before scc is derived from it). A block ends after every branch, conditional or not, and where any jump lands: ending one only at branch targets would let a compare read whole on the taken side of a conditional branch be made local by a tree on the fall-through side. LOOP_GUARD runs only at block starts. gpu_split_wave64_bitwise_lane_masks expected the two compares under a live scc to exchange; they now stay local and the s_and_b64 exchanges. With no other half (a partial wave, xcl_xn == 0), xcl_x_sync_mask keeps the word the half computed for the absent one: its compare bits are 0, but an inverting tree op (s_nor_b64, s_not_b64, ...) sets them, and a fallback of 0 gave a wrong s_bcnt1 and scc. gpu_split_wave64_bitwise_mask_tree_in_a_partial_wave covers it (16 instead of 48 without the fallback). Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/gpu/recomp/emit.rs | 17 ++ crates/xcl/src/gpu/recomp/mod.rs | 4 +- crates/xcl/src/gpu/recomp/tests.rs | 98 ++++++++++- crates/xcl/src/gpu/recomp/x64_masks.rs | 218 ++++++++++++++++++++++++- 4 files changed, 328 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index bb9e001038..0b2f7b9e98 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -43,6 +43,9 @@ pub(super) struct Em { /// 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, + /// split wave64: pc of the 64-bit bitwise ops that exchange their result once, for the + /// compares they combine (`x64_masks`) + pub x64_sync: BTreeSet, /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, @@ -481,6 +484,7 @@ impl Em { uses_scratch: false, x64_words: 1, x64_whole_live: BTreeMap::new(), + x64_sync: BTreeSet::new(), upper: None, cur_pc: 0, static_ss: BTreeMap::new(), @@ -1456,6 +1460,10 @@ impl Em { } }; self.line(&format!("uint {t0} = {lo}; uint {t1} = {hi};")); + if self.x64() && self.x64_sync.contains(&self.cur_pc) { + let x = self.t(); + self.line(&format!("uint2 {x} = xcl_x_sync_mask({t0}, {t1}); {t0} = {x}.x; {t1} = {x}.y;")); + } if let Some(c) = scc { self.line(&format!("scc = (uint)({c});")); } @@ -5465,6 +5473,15 @@ uint2 xcl_x_ballot(bool b) { uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u; return xcl_half != 0u ? uint2(o, m) : uint2(m, o); } +// a mask each half holds only its own word of (`x64_masks`): both words, from both halves. +// With no other half, the word computed here for it is already right (its compare bits are 0, +// and a tree op such as s_nor_b64 may still set them). +uint2 xcl_x_sync_mask(uint lo, uint hi) { + uint m = select(xcl_half != 0u, hi, lo); + xcl_x_put(0u, m); + uint o = xcl_x_meet() ? xcl_x_get(0u) : select(xcl_half != 0u, lo, hi); + return xcl_half != 0u ? uint2(o, m) : uint2(m, o); +} // v_readlane / v_readfirstlane: the same lane index in both halves; the owner half's value uint xcl_x_rla_uniform(uint v, uint l) { uint m = WaveReadLaneAt(v, l & 31u); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 82876f01df..3d0a59b45c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1422,7 +1422,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // 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)); + let plan = x64_masks::analyze(&insts, matches!(opt.mode, Mode::Kernel)); + em.x64_whole_live = plan.whole_live; + em.x64_sync = plan.sync; } // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index f21d5a6ed0..c7dbf28221 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5818,7 +5818,7 @@ fn gpu_split_wave64_lane_local_masks() { /// Bitwise 64-bit SALU ops (`s_and_b64`, `s_or_b64`, `s_not_b64`, `s_andn2_b64`, `s_mov_b64`, /// `s_cselect_b64`) over lane-local masks stay in each 32-lane half when neither their /// destination nor `scc` is whole-live afterward; when `scc` IS read (e.g. only upper-half -/// lanes match and `s_cselect_b32` reads `scc`), the inputs stay exchanged so both halves +/// lanes match and `s_cselect_b32` reads `scc`), the result is exchanged so both halves /// observe the same `scc`. #[test] fn gpu_split_wave64_bitwise_lane_masks() { @@ -5872,7 +5872,7 @@ fn gpu_split_wave64_bitwise_lane_masks() { } // Part 2: only upper-half lanes (40..49) match; s_and_b64's SCC is read by s_cselect_b32 -> - // both compares must stay exchanged so half 0 and half 1 agree on SCC == 1. + // its result is exchanged (once, for both compares) so half 0 and half 1 agree on SCC == 1. let scc_code = prog(&[ ("V_CMP_GE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", 255)], Some(40)), ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 255)], Some(50)), @@ -5884,7 +5884,8 @@ fn gpu_split_wave64_bitwise_lane_masks() { ]); if runner::split_wave64() { let t = translate(&scc_code, &runner::options(Mode::Kernel)).unwrap(); - assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 2, "live SCC keeps both exchanges"); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 0, "the compares stay local"); + assert_eq!(t.hlsl.matches("= xcl_x_sync_mask(").count(), 1, "live SCC: s_and_b64 exchanges its result"); } let r = runner::run_code(&scc_code, &st, &[]).unwrap(); assert_eq!(r.sgpr[1], 77, "both halves must see SCC == 1 from upper-half match"); @@ -5942,6 +5943,97 @@ fn gpu_split_wave64_predicated_exec_masks() { } } +/// Split wave64 (`x64_masks`): two compares combined by `s_and_b64` and read whole +/// (`s_bcnt1`, and `scc` of a match in the upper half only) stay in their halves; the +/// `s_and_b64` exchanges its result once, and both halves see the whole-wave value. +#[test] +fn gpu_split_wave64_bitwise_mask_tree_exchanges_once() { + if !gpu_ready() { + return; + } + const V: u64 = 256; + let code = prog(&[ + // vcc = lanes 5..63, s[24:25] = lanes 0..41, s0 = bcnt1(s[24:25] & vcc) = 37 + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 7)], None), // v7 = 5 + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V), ("SRC1", 255)], Some(42)), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 24), ("SSRC1", 106)], None), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 24)], None), + // lanes 41..63 & lanes 0..49 = 41..49, all in the upper half: scc = 1 in both halves + ("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V), ("SRC1", 255)], Some(40)), + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 28), ("SRC0", V), ("SRC1", 255)], Some(50)), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 26), ("SSRC1", 28)], None), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 255), ("SSRC1", 139)], Some(77)), + // the kernel runner reads every SGPR and SCC back: clear the masks, overwrite SCC + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 128)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 128)], None), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 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, "the four compares stay local\n{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 0); + assert_eq!(t.hlsl.matches("= xcl_x_sync_mask(").count(), 2, "each s_and_b64 exchanges once"); + } + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[7] = 5; + } + let r = runner::run_code(&code, &st, &[]).unwrap(); + assert_eq!(r.sgpr[0], 37, "bcnt1 of lanes 5..41"); + assert_eq!(r.sgpr[1], 77, "scc of a match in the upper half only, in both halves"); +} + +/// Split wave64 (`x64_masks`): a wave64 group of 32 threads has no upper half to exchange +/// with. The absent lanes' compare bits are 0, so `s_nor_b64` of two compares sets the whole +/// upper word; the tree's exchange must keep the word the lower half computed, for +/// `s_bcnt1` and for `scc`. +#[test] +fn gpu_split_wave64_bitwise_mask_tree_in_a_partial_wave() { + if !gpu_ready() { + return; + } + use super::{dxc, CsInterface}; + let p = prog(&[ + // ~(lanes 0..7 | lanes 24..31) = lanes 8..23 and 32..63: s10 = 48 + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", 136)], None), + ("V_CMP_GE_U32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 152)], None), + ("S_NOR_B64", "ENC_SOP2", &[("SDST", 24), ("SSRC0", 20), ("SSRC1", 22)], None), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 24)], None), + // ~(lanes 0..15 | lanes 16..31) = lanes 32..63, none present: scc = 1, s11 = 77 + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V), ("SRC1", 144)], None), + ("V_CMP_GE_U32", "ENC_VOP3", &[("VDST", 28), ("SRC0", V), ("SRC1", 144)], None), + ("S_NOR_B64", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 26), ("SSRC1", 28)], None), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 255), ("SSRC1", 139)], Some(77)), + // each thread stores (s10, s11) at s0 + 8 · thread + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 10)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 11)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 131), ("VSRC1", 0)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 5), ("SADDR", 0x7D)], None), + ]); + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; + 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_local(and(").count(), 4, "the four compares stay local\n{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_sync_mask(").count(), 2, "each s_nor_b64 exchanges once"); + } + 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; + let out = runner::dispatch(&dxil, [1, 1, 1], &io, &vec![0u32; (base + 32 * 8) / 4]).unwrap(); + for tid in 0..32 { + let at = (base + tid * 8) / 4; + assert_eq!(out[at], 48, "thread {tid}: s_bcnt1 of an s_nor_b64 with no upper half"); + assert_eq!(out[at + 1], 77, "thread {tid}: scc of an s_nor_b64 set in the absent half only"); + } +} + /// 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 diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index b189d676e8..e41584eae1 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -16,6 +16,11 @@ //! before it is written again. A mask write whose destination is not whole-live needs no //! exchange. //! +//! A mask that is read whole can still skip the exchange where it is only combined first: when +//! two or more compares or carries feed, in one basic block and nowhere else, a tree of +//! lane-wise 64-bit bitwise ops whose result is read whole, the compares stay in their halves +//! and the tree's last op exchanges its result once (`xcl_x_sync_mask`). +//! //! 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: @@ -31,7 +36,7 @@ //! (`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 std::collections::{BTreeMap, BTreeSet}; use super::emit::ext_encoding; use crate::gpu::rdna2::{self, Decoded, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; @@ -371,9 +376,22 @@ pub fn uses(d: &Decoded) -> (Regs, Regs) { (whole, written) } +/// The liveness solution: per instruction, its successors (None: unknown), its flow, the SGPRs +/// whole-live after it and whether `scc` is live after it. +struct Solved { + succ: Vec>>, + flows: Vec, + live_out: Vec, + scc_out: Vec, +} + /// 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 { + solve(insts, end_reads_all).live_out +} + +fn solve(insts: &[Decoded], end_reads_all: bool) -> Solved { let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); let at_end = if end_reads_all { ALL } else { 0 }; // successors; None = unknown (indirect): everything is live @@ -459,14 +477,157 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { } } if !changed { - return live_out; + return Solved { succ, flows, live_out, scc_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() +/// What the emitter needs for split wave64. +pub struct Plan { + /// pc → SGPRs whole-live after that instruction (not the mask of a compare a tree exchanges) + pub whole_live: BTreeMap, + /// pc of the bitwise ops that exchange their result once (`xcl_x_sync_mask`) + pub sync: BTreeSet, +} + +/// Compares and carries: their mask is written with `write_mask`, which can leave it local. +fn mask_producer(name: &str) -> bool { + name.starts_with("V_CMP_") || matches!(name, "V_ADD_CO_U32" | "V_SUB_CO_U32" | "V_SUBREV_CO_U32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") +} + +fn bits(mut m: Regs) -> impl Iterator { + std::iter::from_fn(move || { + (m != 0).then(|| { + let r = m.trailing_zeros() as usize; + m &= m - 1; + r + }) + }) +} + +/// The mask trees open in one basic block. A tree is named by its last instruction (a compare +/// or a bitwise op) and is the register pair holding its value plus the compares it combines. +struct Trees { + owner: [Option; 128], + open: BTreeMap)>, +} + +impl Trees { + fn bind(&mut self, node: usize, pair: Regs, leaves: Vec) { + for r in bits(pair) { + self.owner[r] = Some(node); + } + self.open.insert(node, (pair, leaves)); + } + + fn take(&mut self, node: usize) -> Vec { + let Some((pair, leaves)) = self.open.remove(&node) else { return Vec::new() }; + for r in bits(pair) { + if self.owner[r] == Some(node) { + self.owner[r] = None; + } + } + leaves + } + + /// Ends the trees holding any of `regs`: read whole there (`whole`), or overwritten. + fn end(&mut self, regs: Regs, whole: bool, insts: &[Decoded], plan: &mut Plan, live_out: &mut [Regs]) { + for r in bits(regs) { + if let Some(node) = self.owner[r] { + let leaves = self.take(node); + if whole { + exchange_at(node, leaves, insts, plan, live_out); + } + } + } + } + + fn end_all(&mut self, insts: &[Decoded], plan: &mut Plan, live_out: &mut [Regs]) { + for (node, (_, leaves)) in std::mem::take(&mut self.open) { + exchange_at(node, leaves, insts, plan, live_out); + } + self.owner = [None; 128]; + } +} + +/// A tree read whole after `node`: with two or more compares, they stay in their halves and +/// `node` exchanges its result instead. +fn exchange_at(node: usize, leaves: Vec, insts: &[Decoded], plan: &mut Plan, live_out: &mut [Regs]) { + if leaves.len() < 2 { + return; + } + plan.sync.insert(insts[node].pc); + for l in leaves { + live_out[l] &= !uses(&insts[l]).1; + } +} + +/// Liveness, then the mask trees of each basic block. +pub fn analyze(insts: &[Decoded], end_reads_all: bool) -> Plan { + let Solved { succ, flows, mut live_out, scc_out } = solve(insts, end_reads_all); + let live = live_out.clone(); + let mut plan = Plan { whole_live: BTreeMap::new(), sync: BTreeSet::new() }; + // a block goes on only into an instruction it falls into and nothing else jumps to (every + // branch, conditional or not, ends one; `LOOP_GUARD` runs at block starts only) + let falls = |i: usize| succ[i].as_deref() == Some(&[i + 1][..]); + let mut joined = vec![false; insts.len()]; + for (i, s) in succ.iter().enumerate() { + if !falls(i) { + for &j in s.iter().flatten() { + joined[j] = true; + } + } + } + let mut trees = Trees { owner: [None; 128], open: BTreeMap::new() }; + for (i, d) in insts.iter().enumerate() { + if i > 0 && (!falls(i - 1) || joined[i]) { + trees.end_all(insts, &mut plan, &mut live_out); + } + let (read, written) = uses(d); + let name = d.inst.name; + // a compare whose mask is read whole starts a tree + if mask_producer(name) && written != 0 && written & EXEC == 0 && live[i] & written != 0 { + trees.end(read, true, insts, &mut plan, &mut live_out); + trees.end(written, false, insts, &mut plan, &mut live_out); + trees.bind(i, written, vec![i]); + continue; + } + let tree_op = flows[i].lane_op.filter(|_| !matches!(name, "S_CMOV_B64" | "S_CSELECT_B64")); + if let Some((dst, srcs, sets_scc)) = tree_op { + // sources that are whole trees whose value goes nowhere else after this op + let mut leaves = Vec::new(); + for r in bits(srcs).filter(|r| r % 2 == 0) { + let pair = range(r as u64, 2); + let Some(node) = trees.owner[r] else { continue }; + if trees.open[&node].0 == pair && live[i] & !dst & pair == 0 { + for l in trees.take(node) { + if !leaves.contains(&l) { + leaves.push(l); + } + } + } + } + trees.end(read | flows[i].whole, true, insts, &mut plan, &mut live_out); + trees.end(dst, false, insts, &mut plan, &mut live_out); + if dst == 0 || dst & EXEC != 0 || (sets_scc && scc_out[i]) { + exchange_at(i, leaves, insts, &mut plan, &mut live_out); + } else if !leaves.is_empty() && live[i] & dst != 0 { + trees.bind(i, dst, leaves); + } + continue; + } + trees.end(read, true, insts, &mut plan, &mut live_out); + // a write of one word of a tree's pair leaves the other read whole + for r in bits(written) { + if let Some(node) = trees.owner[r] { + let whole = trees.open[&node].0 & !written != 0; + trees.end(range(r as u64, 1), whole, insts, &mut plan, &mut live_out); + } + } + } + trees.end_all(insts, &mut plan, &mut live_out); + plan.whole_live = insts.iter().map(|d| d.pc).zip(live_out).collect(); + plan } #[cfg(test)] @@ -625,6 +786,53 @@ mod tests { const BCNT_VCC: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); const CBRANCH_EXECZ: I = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)]); + const AND_S20_VCC: I = ("S_AND_B64", "ENC_SOP2", &[("SDST", 20), ("SSRC0", 20), ("SSRC1", 106)]); + + fn exchanged(plan: &Plan, d: &Decoded, pair: u64) -> bool { + plan.whole_live[&d.pc] & range(pair, 2) != 0 + } + + #[test] + fn a_bitwise_tree_read_whole_exchanges_once_at_its_end() { + let p = asm(&[CMP, CMP_S20, AND_S20_VCC, BCNT_S20, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106) && mask_needed(&whole_live_out(&p, false), 1, 20)); + let plan = analyze(&p, false); + assert!(!exchanged(&plan, &p[0], 106) && !exchanged(&plan, &p[1], 20)); + assert_eq!(plan.sync.iter().copied().collect::>(), vec![p[2].pc]); + // through an s_mov_b64: the copy is the tree's end + let p = asm(&[CMP, CMP_S20, AND_S20_VCC, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 20)]), ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 30)]), ENDPGM]); + let plan = analyze(&p, false); + assert!(!exchanged(&plan, &p[0], 106) && !exchanged(&plan, &p[1], 20)); + assert_eq!(plan.sync.iter().copied().collect::>(), vec![p[3].pc]); + } + + #[test] + fn a_compare_read_whole_outside_the_tree_keeps_its_exchange() { + // VCC read whole after the tree + let p = asm(&[CMP, CMP_S20, AND_S20_VCC, BCNT_S20, BCNT_VCC, ENDPGM]); + let plan = analyze(&p, false); + assert!(exchanged(&plan, &p[0], 106) && exchanged(&plan, &p[1], 20) && plan.sync.is_empty()); + // VCC copied to a pair that is read whole + let p = asm(&[CMP, CMP_S20, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 106)]), AND_S20_VCC, BCNT_S20, ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 30)]), ENDPGM]); + let plan = analyze(&p, false); + assert!(exchanged(&plan, &p[0], 106) && plan.sync.is_empty()); + // VCC read whole on the taken side of a branch between the compares and the tree: + // v_cmp vcc; v_cmp s[20:21]; s_cbranch_scc0 → L; s_and s[20:21]; s_bcnt1 s[20:21]; + // s_branch → end; L: s_bcnt1 vcc; end + let p = asm(&[ + CMP, + CMP_S20, + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 3)]), + AND_S20_VCC, + BCNT_S20, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)]), + BCNT_VCC, + ENDPGM, + ]); + let plan = analyze(&p, false); + assert!(exchanged(&plan, &p[0], 106) && plan.sync.is_empty()); + } + // review findings: writes that are not full overwrites, reads the operand tables miss #[test]