diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d28a2ffcb6..fb9d78e1a1 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -37,7 +37,7 @@ pub struct KernelOptions { /// Version of the direct translator's output, part of the on-disk translation cache's /// identity (`recomp::pso`): bump it on any change that alters the emitted containers /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 7; +pub const TRANSLATOR_VERSION: u32 = 8; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 3d4c760f41..81f8589bb9 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -868,7 +868,7 @@ impl Lw { let local = self.split && (self.s.m.const_u64(cond) == Some(0) || match *dst { - Dst::S(n) => n < 126 && self.whole_live.get(&self.pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::S(n) => n <= 126 && n % 2 == 0 && self.whole_live.get(&self.pc).is_some_and(|live| live & (3u128 << n) == 0), Dst::Null => true, Dst::V(_) => false, }); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 96966005b6..ecf8ea15f3 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 % 2 == 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 e1f73ef484..62938cdb84 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -6037,6 +6037,137 @@ fn gpu_split_wave64_masks_read_whole_after_partial_writes() { } } +/// Bit-parallel 64-bit mask chains (`s_and/or/xor/not/mov/andn2_b64`), branchless +/// `s_and_saveexec_b64` if/else predication, and half-local `v_cmpx_*` stay in their half +/// (zero exchanges), while cross-half consumers (`s_cbranch_scc0`, `s_cbranch_execz`, +/// `v_readfirstlane_b32`, `ds_bpermute_b32`) still force the exchange when only the upper half +/// has active bits (lanes 40..63). Verified on both the HLSL and direct DXIL paths. +#[test] +fn gpu_split_wave64_bit_parallel_and_exec_masks() { + if !gpu_ready() { + return; + } + use super::{dxc, CsInterface}; + // 1) Purely half-local chain in Compute mode (end_reads_all = false): + // bit-parallel masks + branchless saveexec if/else + restored outer EXEC + v_cmpx. + // Writes 4 dwords per lane (lanes 0..63) to flat memory. + let local_code = prog(&[ + // v0 = lane_id (tid.x, 0..63) + // vcc = (v0 < 40), s[20:21] = (v0 > 15) + ("V_CMP_LT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 0)], None), // dummy overwritten below + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(40)), // vcc = 0..39 + ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 255), ("SRC1", V)], Some(15)), // s[20:21] = 16..63 + // bit-parallel combinations across both halves: + ("S_AND_B64", "ENC_SOP2", &[("SDST", 22), ("SSRC0", 106), ("SSRC1", 20)], None), // 16..39 + ("S_NOT_B64", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 22)], None), // 0..15, 40..63 + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 26), ("SSRC0", 22), ("SSRC1", 20)], None), // 40..63 + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 28), ("SSRC0", 24)], None), // 0..15, 40..63 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)], None), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 22)], None), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 28)], None), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 26)], None), + // branchless if (v0 < 35) v6 = 10 else v6 = 20; restore EXEC; outer s_cbranch_execz + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)], None), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(35)), // vcc = 0..34 + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 16), ("SSRC0", 106)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 138)], None), // 10 + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 16), ("SSRC1", 126)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 148)], None), // 20 + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None), // outer EXEC read whole, inner stays local! + // pack (v3 | v4<<1 | v5<<2 | v6<<4) into v7, then predicate v7 += 100 via half-local v_cmpx + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 4), ("SRC1", 129), ("SRC2", V + 3)], None), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 130), ("SRC2", V + 7)], None), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 132), ("SRC2", V + 7)], None), + // store pre-cmpx value to mem[lane], then v_cmpx (v0 >= 21) adds 100 and overwrites mem[lane] + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 0x7D)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(20)), // active = 21..63 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 255), ("VSRC1", 7)], Some(100)), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 0x7D)], None), + ]); + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let opt = on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64: true, ..Default::default() }); + let t = translate(&local_code, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + if runner::split_wave64() { + assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 0, "all masks stay half-local:\n{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 5); + } + let hlsl_dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let ko = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let direct_dxil = crate::gpu::dxil::kernel::translate_compute(&local_code, ko, &cs).unwrap().dxil; + for (label, dxil) in [("hlsl", &hlsl_dxil), ("direct", &direct_dxil)] { + let out = runner::dispatch(dxil, [1, 1, 1], &vec![0u32; 128], &vec![0u32; 64]).unwrap(); + for l in 0..64u32 { + let b3 = u32::from((16..40).contains(&l)); + let b4 = u32::from(!(16..40).contains(&l)); + let b5 = u32::from(l >= 40); + let b6 = if l < 35 { 10 } else { 20 }; + let mut want = b3 | (b4 << 1) | (b5 << 2) | (b6 << 4); + if l > 20 { + want += 100; + } + assert_eq!(out[l as usize], want, "{label}: lane {l}"); + } + } + + // 2) Cross-half soundness: only upper-half lanes (45..63) match; every whole-wave consumer + // must force an exchange so lower-half lanes (0..31) see the same SCC / EXEC / lane value. + let sound_code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None), // s10 = 0 + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None), // s12 = 0 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 255)], Some(45 * 4)), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 255), ("VSRC1", 0)], Some(1000)), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)], None), + // s[20:21] = (v0 >= 45) -> lo = 0, hi != 0 + ("V_CMP_LE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 255), ("SRC1", V)], Some(45)), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 22), ("SSRC0", 20), ("SSRC1", 20)], None), // sets SCC = 1 + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)], None), // must NOT skip + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 129)], None), // s10 = 1 (taken if SCC == 1) + // v_cmpx -> only lanes 45..63 active; v_readfirstlane must return 45; s_cbranch_execz must NOT jump + ("V_CMPX_LE_U32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 0)], Some(45)), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V)], None), // s11 = 45 + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)], None), // must NOT skip + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 130)], None), // s12 = 2 + // restore all lanes, then set EXEC = {lane 0, lane 45} via v_cmp + s_or_b64 + s_mov_b64 exec: + // lane 0 (in half 0) reads lane 45 (in half 1) via ds_bpermute_b32; without the exchange + // half 0 would see exec_hi == 0 and return 0 instead of 1045. + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), // exec = all 1s + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 0)], None), // vcc = {0} + ("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 24), ("SRC0", 255), ("SRC1", V)], Some(45)), // s[24:25] = {45} + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 106), ("SSRC1", 24)], None), // exec = {0, 45} + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 1), ("DATA0", 2)], None), // lanes 0 & 45 get 1045 + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 10)], None), // s10 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 11)], None), // s11 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 12)], None), // s12 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 3), ("VSRC1", 4)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 7), ("VSRC1", 5)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 7), ("VSRC1", 6)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 0x7D)], None), + ]); + let ts = translate(&sound_code, &opt).unwrap(); + assert!(ts.complete(), "{:?}", ts.unsupported_why); + if runner::split_wave64() { + assert_eq!(ts.hlsl.matches("= xcl_x_ballot(and(").count(), 4, "every cross-half consumer exchanges:\n{}", ts.hlsl); + } + let hlsl_s = dxc::compile(&ts.hlsl, "main", "cs_6_6", &[]).unwrap(); + let direct_s = crate::gpu::dxil::kernel::translate_compute(&sound_code, ko, &cs).unwrap().dxil; + for (label, dxil) in [("hlsl", &hlsl_s), ("direct", &direct_s)] { + let out = runner::dispatch(dxil, [1, 1, 1], &vec![0u32; 128], &vec![0u32; 64]).unwrap(); + for l in 0..64u32 { + // s10=1, s11=45, s12=2; v6 = 1045 on lanes 0 and 45, 0 on all other lanes + let want = 1 + 45 + 2 + if l == 0 || l == 45 { 1045 } else { 0 }; + assert_eq!(out[l as usize], want, "{label}: soundness lane {l}"); + } + } +} + /// 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 diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index 431e57b949..7861fff88b 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -1,12 +1,19 @@ //! 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. +//! that both halves hold the whole 64-bit mask. A mask that stays *half-exact* – each half +//! holding its own 32 lanes' bits in its own word (even SGPR in half 0, odd SGPR in half 1) – +//! needs no exchange when it 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`, `EXEC`'s `act()` / in-half `lanebit_at`) or +//! combined through bit-parallel 64-bit SALU ops (`s_mov_b64`, `s_not_b64`, `s_wqm_b64`, +//! `s_cmov_b64`, `s_cselect_b64`, `s_{and,or,xor,andn2,orn2,nand,nor,xnor}_b64`, +//! `s_*_saveexec_b64`, `s_*_wrexec_b64`) whose destination and `SCC` are not observed whole. +//! This is a backward liveness analysis over the SGPRs, `EXEC`, and `SCC`: a register is +//! *whole-live* after an instruction when some path may read its whole value (any non-bit- +//! parallel SALU / SMEM / VALU scalar operand, a branch on VCCZ / EXECZ, `v_readfirstlane_b32`, +//! `ds_bpermute_b32`, or a live `SCC` derived from it) before it is written again. A mask write +//! into an even-aligned pair (including `EXEC`) 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 – @@ -16,13 +23,18 @@ //! 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. +//! - SDWA scalar sources (S0 / S1 bits) and SMEM register offsets are reads; +//! - `v_readfirstlane_b32` and `ds_(b)permute_b32` read `EXEC` across both halves, whereas +//! in-half lane reads (`act()`, DPP, `v_permlane(x)16`, `ds_swizzle`) only read their half's +//! word of `EXEC`; +//! - bit-parallel propagation requires even-aligned 64-bit pairs so low/high words never alias +//! across halves, and treats `src_vccz` / `src_execz` / `scc` sources as unconditional whole +//! 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. +//! Conservative where it cannot see: an indirect jump makes every SGPR (and `EXEC` / `SCC`) +//! whole-live, and so does 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; @@ -34,6 +46,9 @@ pub type Regs = u128; const VCC: Regs = 3 << 106; const M0: Regs = 1 << 124; +/// Internal-only liveness bit for SCC during backward dataflow (slot 125 is NULL, never an SGPR; +/// cleared before returning `Regs`). +const SCC: Regs = 1 << 125; const EXEC: Regs = 3 << 126; const ALL: Regs = !0; @@ -127,11 +142,180 @@ pub fn uses(d: &Decoded) -> (Regs, Regs) { (whole, written) } +/// Classify a 64-bit scalar source operand of a bit-parallel SALU instruction: +/// returns `Some((uncond_whole, bp_pair))`, or `None` for odd-aligned / unexpected register codes. +fn bp_src64(v: u64) -> Option<(Regs, Regs)> { + match v { + 0..=123 | 126 if v & 1 == 0 => Some((0, range(v, 2))), + // NULL, inline integer/float constants, 32-bit literal: uniform in both halves + 125 | 128..=208 | 240..=248 | 255 => Some((0, 0)), + // src_vccz / src_execz / scc: scalar 0/1 derived from the whole mask or SCC + 251 => Some((VCC, 0)), + 252 => Some((EXEC, 0)), + 253 => Some((SCC, 0)), + _ => None, + } +} + +/// Classify the 64-bit `SDST` of a bit-parallel SALU instruction: `0` for `NULL`, even pair for +/// valid 64-bit SGPRs / `EXEC`, `None` otherwise. +fn bp_dst64(v: u64) -> Option { + match v { + 125 => Some(0), + 0..=123 | 126 if v & 1 == 0 => Some(range(v, 2)), + _ => None, + } +} + +/// Backward transfer function for one instruction over SGPRs + `SCC` (bit 125) + `EXEC`. +enum Step { + Plain { + gen: Regs, + kill: Regs, + }, + BitParallel { + uncond_gen: Regs, + bp_srcs: Regs, + dst: Regs, + kill: Regs, + writes_scc: bool, + }, + SaveExec { + uncond_gen: Regs, + bp_s0: Regs, + dst: Regs, + wrexec: bool, + }, +} + +impl Step { + fn of(d: &Decoded) -> Self { + let name = d.inst.name; + if let Some(step) = Self::try_bit_parallel(d, name) { + return step; + } + let (mut gen, mut kill) = uses(d); + if matches!(name, "V_READFIRSTLANE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32") { + gen |= EXEC; + } + if d.variant == Variant::Sdwa { + if let Some(e) = ext_encoding(d) { + let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + if fv("S0") == 1 && fv("VSRC0") == 253 { + gen |= SCC; + } + if d.enc.field("VSRC1").is_some() && fv("S1") == 1 && fv("VSRC1") == 253 { + gen |= SCC; + } + } + } + let per_lane = reads_mask_per_lane(name); + for o in d.ienc.operands { + if o.ty == "OPR_SSRC_SPECIAL_SCC" { + if o.input { + gen |= SCC; + } + if o.output && !matches!(name, "S_QUADMASK_B32" | "S_QUADMASK_B64") { + kill |= SCC; + } + continue; + } + if o.output || 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; + } + let v = rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + if v == 253 { + gen |= SCC; + } else if per_lane && f == "SRC2" && v <= 127 && v != 125 && v & 1 == 1 { + // An odd-aligned mask selector breaks the even=lo / odd=hi half-exact invariant. + gen |= range(v, 2); + } + } + Self::Plain { gen, kill } + } + + fn try_bit_parallel(d: &Decoded, name: &str) -> Option { + let field = |f: &str| rdna2::field_value(d.enc, &d.words, f).map(|v| v * rdna2::register_scale(f)); + if matches!( + name, + "S_AND_SAVEEXEC_B64" + | "S_OR_SAVEEXEC_B64" + | "S_XOR_SAVEEXEC_B64" + | "S_ANDN2_SAVEEXEC_B64" + | "S_ORN2_SAVEEXEC_B64" + | "S_NAND_SAVEEXEC_B64" + | "S_NOR_SAVEEXEC_B64" + | "S_XNOR_SAVEEXEC_B64" + | "S_ANDN1_SAVEEXEC_B64" + | "S_ORN1_SAVEEXEC_B64" + | "S_ANDN1_WREXEC_B64" + | "S_ANDN2_WREXEC_B64" + ) { + let dst = bp_dst64(field("SDST")?)?; + let (uncond_gen, bp_s0) = bp_src64(field("SSRC0")?)?; + return Some(Self::SaveExec { uncond_gen, bp_s0, dst, wrexec: name.contains("WREXEC") }); + } + let (two_src, writes_scc, reads_scc, keeps_dst) = match name { + "S_MOV_B64" => (false, false, false, false), + "S_CMOV_B64" => (false, false, true, true), + "S_NOT_B64" | "S_WQM_B64" => (false, true, false, false), + "S_CSELECT_B64" => (true, false, true, false), + "S_AND_B64" | "S_OR_B64" | "S_XOR_B64" | "S_ANDN2_B64" | "S_ORN2_B64" | "S_NAND_B64" | "S_NOR_B64" | "S_XNOR_B64" => { + (true, true, false, false) + } + _ => return None, + }; + let dst = bp_dst64(field("SDST")?)?; + let (mut uncond_gen, mut bp_srcs) = bp_src64(field("SSRC0")?)?; + if two_src { + let (u1, b1) = bp_src64(field("SSRC1")?)?; + uncond_gen |= u1; + bp_srcs |= b1; + } + if reads_scc { + uncond_gen |= SCC; + } + if keeps_dst { + bp_srcs |= dst; + } + let kill = (if keeps_dst { 0 } else { dst }) | (if writes_scc { SCC } else { 0 }); + Some(Self::BitParallel { uncond_gen, bp_srcs, dst, kill, writes_scc }) + } + + fn apply(&self, out: Regs) -> Regs { + match *self { + Self::Plain { gen, kill } => gen | (out & !kill), + Self::BitParallel { uncond_gen, bp_srcs, dst, kill, writes_scc } => { + let need_whole = (out & dst) != 0 || (writes_scc && (out & SCC) != 0); + uncond_gen | (if need_whole { bp_srcs } else { 0 }) | (out & !kill) + } + Self::SaveExec { uncond_gen, bp_s0, dst, wrexec } => { + let kill = dst | EXEC | SCC; + let (need_new, need_old) = if wrexec { + let n = (out & (dst | EXEC | SCC)) != 0; + (n, n) + } else { + let n = (out & (EXEC | SCC)) != 0; + (n, n || (out & dst) != 0) + }; + uncond_gen | (if need_new { bp_s0 } else { 0 }) | (if need_old { EXEC } else { 0 }) | (out & !kill) + } + } + } +} + /// 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 }; + let at_end = if end_reads_all { ALL } else { 0 }; // successors; None = unknown (indirect): everything is live let succ: Vec>> = insts .iter() @@ -167,7 +351,7 @@ 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 steps: Vec = insts.iter().map(Step::of).collect(); let mut live_in = vec![0 as Regs; insts.len()]; let mut live_out = vec![0 as Regs; insts.len()]; loop { @@ -176,11 +360,10 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { 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]), + Some(s) => s.iter().fold(0, |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; + let inn = steps[i].apply(out) | left; if out != live_out[i] || inn != live_in[i] { live_out[i] = out; live_in[i] = inn; @@ -188,6 +371,9 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { } } if !changed { + for m in &mut live_out { + *m &= !SCC; + } return live_out; } } @@ -224,6 +410,7 @@ mod tests { 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)]); + const BCNT_S2: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)]); fn asm(lines: &[I]) -> Vec { let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); @@ -252,48 +439,154 @@ mod tests { #[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)]), + let readers: [&[I]; 6] = [ + &[("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)])], + &[("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)])], + &[MOV_S2_VCC, BCNT_S2], + &[("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); + let mut l = vec![CMP]; + l.extend_from_slice(reader); + l.push(ENDPGM); + assert!(mask_needed(&whole_live_out(&asm(&l), false), 0, 106), "{}", reader[0].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 + // v_cmp; s_cbranch_scc0 → skip; v_cndmask; s_branch → end; skip: s_mov s[2:3], vcc; s_bcnt1 s[2:3]; end let p = asm(&[ CMP, ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 2)]), CNDMASK, - ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)]), + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 2)]), MOV_S2_VCC, + BCNT_S2, 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, MOV_S2_VCC, BCNT_S2, 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); + fn exec_exchanged_only_when_read_whole() { + let cmpx: I = ("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + // per-lane VALU only: EXEC stays half-local + let p = asm(&[cmpx, ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 3), ("VSRC1", 4)]), ENDPGM]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 126)); + // kernel runner reads EXEC back: still exchanged + assert!(mask_needed(&whole_live_out(&p, true), 0, 126)); + // whole-wave EXEC readers force the exchange + let readers: [I; 5] = [ + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)]), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("DATA0", 1)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 252)]), // src_execz + ]; + for reader in readers { + let p = asm(&[cmpx, reader, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 126), "{}", reader.0); + } + } + + #[test] + fn bit_parallel_mask_chains_stay_local_until_read_whole_or_via_scc() { + let cmp_s4: I = ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 2), ("SRC1", V + 3)]); + let cnd_s2: I = ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 2)]); + // v_cmp vcc; v_cmp s[4:5]; s_and_b64 s[2:3], vcc, s[4:5]; s_not_b64 s[2:3], s[2:3]; v_cndmask(..., s[2:3]) + let p = asm(&[ + CMP, + cmp_s4, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 4)]), + ("S_NOT_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)]), + cnd_s2, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106)); + assert!(!mask_needed(&live, 1, 4)); + // reading SCC after s_and_b64 forces BOTH inputs whole + let p = asm(&[ + CMP, + cmp_s4, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 4)]), + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)]), + cnd_s2, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 106)); + assert!(mask_needed(&live, 1, 4)); + // overwriting SCC before s_cbranch_scc0 leaves the earlier s_and_b64's SCC dead + let p = asm(&[ + CMP, + cmp_s4, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 4)]), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)]), + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)]), + cnd_s2, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106)); + assert!(!mask_needed(&live, 1, 4)); + // reading even one 32-bit half of s[2:3] whole forces both inputs whole + let p = asm(&[ + CMP, + cmp_s4, + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 3)]), + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 106)); + assert!(mask_needed(&live, 1, 4)); + // s_mov_b64 reading src_vccz reads VCC whole even if s[2:3] is only read per lane + let p = asm(&[CMP, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 251)]), cnd_s2, ENDPGM]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + } + + #[test] + fn branchless_saveexec_keeps_condition_local_while_preserving_outer_exec() { + // v_cmp vcc; s_and_saveexec s[4:5], vcc; v_add; s_mov exec, s[4:5]; s_cbranch_execz + // Outer EXEC is read whole by s_cbranch_execz (so saved s[4:5] and old EXEC are whole-live), + // but new EXEC and SCC inside the predicated block are not, so v_cmp needs no exchange. + let p = asm(&[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 3), ("VSRC1", 4)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)]), + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106), "predicated block mask stays half-local"); + assert!(mask_needed(&live, 1, 4), "saved outer EXEC stays whole for the restore"); + assert!(!mask_needed(&live, 1, 126), "inner EXEC is only read by v_add's act()"); + // Adding s_cbranch_execz inside the block forces v_cmp to exchange too + let p = asm(&[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 3), ("VSRC1", 4)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]), + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); } const CMP_S20: I = ("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", V + 1)]); @@ -378,7 +671,7 @@ mod tests { #[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 + // s_setpc s[30:31] → +28 (past the s_bcnt1 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), @@ -386,7 +679,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), ] { @@ -399,6 +692,75 @@ mod tests { assert!(!mask_needed(&whole_live_out(&p, false), 0, 106)); } + #[test] + fn cselect_cmov_wqm_wrexec_and_scc_readers() { + let cmp_s4: I = ("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 2), ("SRC1", V + 3)]); + let cnd_s2: I = ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 2)]); + // s_cselect_b64: inputs stay half-local when dst is only read per lane, but SCC is read! + let p = asm(&[ + CMP, + cmp_s4, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 106), ("SSRC1", 4)]), // sets SCC + ("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 4)]), + cnd_s2, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(mask_needed(&live, 0, 106), "s_cselect_b64 reads SCC from s_and_b64"); + assert!(mask_needed(&live, 1, 4), "s_cselect_b64 reads SCC from s_and_b64"); + // When SCC comes from a plain scalar compare, s_cselect_b64 / s_cmov_b64 keep masks local + let p = asm(&[ + CMP, + cmp_s4, + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)]), + ("S_CSELECT_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 4)]), + ("S_CMOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 4)]), + ("S_WQM_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)]), + cnd_s2, + ENDPGM, + ]); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106)); + assert!(!mask_needed(&live, 1, 4)); + // Explicit src_scc (code 253) and s_addc_u32 both read SCC -> force s_and_b64 inputs whole + for scc_reader in [ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 253)][..]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128)][..]), + ] { + let p = asm(&[ + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 106)]), + scc_reader, + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{}", scc_reader.0); + } + // s_andn2_wrexec_b64 writes new_exec to BOTH dst and EXEC: whole-read of dst forces s0 whole + let p = asm(&[ + CMP, + ("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 106)]), + BCNT_S2, + ENDPGM, + ]); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); + // Without any whole read of dst/EXEC/SCC, wrexec keeps s0 local + let p = asm(&[ + CMP, + ("S_ANDN2_WREXEC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 106)]), + cnd_s2, + ENDPGM, + ]); + assert!(!mask_needed(&whole_live_out(&p, false), 0, 106)); + // Odd-aligned pair in s_mov_b64 falls back to whole-live + let p = asm(&[ + CMP, + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 106)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 3)]), + ENDPGM, + ]); + 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: