From 9e2c7a566574700755c2da4971bb2e882f56f506 Mon Sep 17 00:00:00 2001 From: Zondybtw Date: Tue, 24 Nov 2026 17:49:22 +0800 Subject: [PATCH] Recompiler: fold split-wave64 reduction tail v_readlane exchanges --- crates/xcl/src/gpu/recomp/emit.rs | 238 +++++++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 27 +--- crates/xcl/src/gpu/recomp/tests.rs | 134 ++++++++++++++++ 3 files changed, 375 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 216240bd2..028913af2 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -851,6 +851,244 @@ impl Em { // ---------------------------------------------------------------- one instruction + /// Emit one basic block's instructions in order; stops at the first non-fallthrough flow. + /// In split-wave64 mode, folds cross-half reduction tails (`v_readlane(v, L)` -> `v_op(v, s, v)` + /// -> `v_readlane(v, L^32)`, 32-bit and 64-bit `v_add_f64`) into a single `xcl_x_meet()`. + pub fn emit_insts(&mut self, block: &[Decoded], end: u64) -> Flow { + let mut flow = Flow::Next; + let mut i = 0; + while i < block.len() { + if self.x64() { + if let Some(consumed) = self.try_emit_x64_reduction_tail(&block[i..]) { + i += consumed; + continue; + } + } + let next = block.get(i + 1).map(|n| n.pc).unwrap_or(end); + flow = self.inst(&block[i], next); + if !matches!(flow, Flow::Next) { + break; + } + i += 1; + } + flow + } + + /// If `d` is a plain split-wave64 `v_readlane_b32` reading VGPR `v` at constant lane `0..63` + /// that will emit an exchange, returns `(dst, v, lane)`. + fn x64_const_readlane(&self, d: &Decoded) -> Option<(Dst, u64, u64)> { + if d.variant != Variant::Plain || d.inst.name != "V_READLANE_B32" { + return None; + } + if self.upper.as_ref().and_then(|u| u.reads.get(&d.pc)).is_some() { + return None; + } + let src0 = rdna2::field_value(d.enc, &d.words, "SRC0")?; + let v = src0.checked_sub(256)?; + let src1 = rdna2::field_value(d.enc, &d.words, "SRC1")?; + let lane = match src1 { + 128..=192 => src1 - 128, + 255 => d.literal? as u64, + _ => return None, + }; + let (outs, _) = Self::ops(d); + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + if !matches!(dst, Dst::S(_) | Dst::Null) { + return None; + } + Some((dst, v, lane & 63)) + } + + /// Check that `mid` is a plain, modifier-free binary VALU op writing VGPR `v` with inputs + /// `{S(s_in), V(v)}` in either order. Returns `Some(s_first)` (`true` if `ins[0]` is `S(s_in)`). + fn x64_match_binary_valu(mid: &Decoded, v: u64, s_in: u64) -> Option { + if mid.variant != Variant::Plain { + return None; + } + let m = Self::mods(mid); + if m.clamp || m.omod != 0 || m.opsel != 0 || m.abs.iter().any(|&x| x) || m.neg.iter().any(|&x| x) { + return None; + } + let (outs, ins) = Self::ops(mid); + if outs.len() != 1 || ins.len() != 2 { + return None; + } + if !matches!(Self::dst_of(mid, &outs[0]), Dst::V(dv) if dv == v) { + return None; + } + let decode_op = |o: &Operand| -> Option<(bool, u64)> { + let f = o.field?; + let raw = rdna2::field_value(mid.enc, &mid.words, f)? * rdna2::register_scale(f); + if f == "VSRC1" || o.ty.starts_with("OPR_VGPR") { + Some((false, raw)) + } else if raw >= 256 { + Some((false, raw - 256)) + } else if raw <= 124 || raw == 126 || raw == 127 { + Some((true, raw)) + } else { + None + } + }; + let (op0, op1) = (decode_op(&ins[0])?, decode_op(&ins[1])?); + if op0 == (true, s_in) && op1 == (false, v) { + Some(true) + } else if op0 == (false, v) && op1 == (true, s_in) { + Some(false) + } else { + None + } + } + + /// Scalar HLSL expression matching `emit.rs` for one lane of a supported 32-bit reduction op. + fn x64_reduction_expr32(&self, name: &str, lhs: &str, rhs: &str, old: &str) -> Option { + Some(match name { + "V_ADD_NC_U32" => format!("({lhs} + {rhs})"), + "V_ADD_F32" => format!("asuint(asfloat({lhs}) + asfloat({rhs}))"), + "V_MIN_F32" => format!("asuint(min(asfloat({lhs}), asfloat({rhs})))"), + "V_MAX_F32" => format!("asuint(max(asfloat({lhs}), asfloat({rhs})))"), + "V_MIN_U32" => format!("min({lhs}, {rhs})"), + "V_MAX_U32" => format!("max({lhs}, {rhs})"), + "V_MIN_I32" => format!("(uint)min((int){lhs}, (int){rhs})"), + "V_MAX_I32" => format!("(uint)max((int){lhs}, (int){rhs})"), + "V_AND_B32" => format!("({lhs} & {rhs})"), + "V_OR_B32" => format!("({lhs} | {rhs})"), + "V_XOR_B32" => format!("({lhs} ^ {rhs})"), + "V_ADD_F16" => { + let sum = to_f16_expr(self.dynamic_f16_rm, &format!("(f16tof32({lhs} & 0xFFFFu) + f16tof32({rhs} & 0xFFFFu))")); + format!("(({old} & 0xFFFF0000u) | {sum})") + } + _ => return None, + }) + } + + /// Fold split-wave64 cross-half `v_readlane_b32` reduction tails (and direct `(L, L^32)` pairs) + /// into a single `xcl_x_meet()` exchange. Both halves already receive both `v[L]` and `v[L^32]` + /// from the first exchange, so the trailing `v_readlane_b32` of the updated lane needs no + /// second exchange. + fn try_emit_x64_reduction_tail(&mut self, rest: &[Decoded]) -> Option { + let (dst1, v1, l1) = self.x64_const_readlane(&rest[0])?; + let l2 = l1 ^ 32; + let lane32 = l1 & 31; + + // 1. Direct pair: v_readlane(s1, v, L) ; v_readlane(s2, v, L^32) + if rest.len() >= 2 { + if let Some((dst2, v2, l_b)) = self.x64_const_readlane(&rest[1]) { + if v2 == v1 && l_b == l2 { + self.line(&format!("// {:04x}: {}", rest[0].pc, rdna2::format(&rest[0]))); + self.line(&format!("// {:04x}: {}", rest[1].pc, rdna2::format(&rest[1]))); + self.cur_pc = rest[1].pc; + let v = self.vreg(v1); + let t = self.t(); + self.line(&format!("uint {t}_m = WaveReadLaneAt({v}, {lane32}u);")); + self.line(&format!("xcl_x_put(0u, {t}_m);")); + self.line(&format!("uint {t}_o = xcl_x_meet() ? xcl_x_get(0u) : 0u;")); + self.line(&format!("uint {t}_r1 = xcl_half == {}u ? {t}_m : {t}_o;", l1 >> 5)); + self.line(&format!("uint {t}_r2 = xcl_half == {}u ? {t}_m : {t}_o;", l2 >> 5)); + self.write32(&dst1, &format!("{t}_r1")); + self.write32(&dst2, &format!("{t}_r2")); + return Some(2); + } + } + } + + // 2. 32-bit reduction tail: v_readlane(s1, v, L) ; v_op(v, s1, v) ; v_readlane(s2, v, L^32) + if rest.len() >= 3 { + if let (&Dst::S(s1), Some((dst2, v2, l_b))) = (&dst1, self.x64_const_readlane(&rest[2])) { + if s1 != 126 && s1 != 127 && v2 == v1 && l_b == l2 { + if let Some(s_first) = Self::x64_match_binary_valu(&rest[1], v1, s1) { + let t = self.t(); + let (r1, r2) = (format!("{t}_r1"), format!("{t}_r2")); + let (lhs, rhs) = if s_first { (r1.as_str(), r2.as_str()) } else { (r2.as_str(), r1.as_str()) }; + if let Some(expr) = self.x64_reduction_expr32(rest[1].inst.name, lhs, rhs, &r2) { + self.line(&format!("// {:04x}: {}", rest[0].pc, rdna2::format(&rest[0]))); + self.cur_pc = rest[0].pc; + let v = self.vreg(v1); + self.line(&format!("uint {t}_m = WaveReadLaneAt({v}, {lane32}u);")); + self.line(&format!("xcl_x_put(0u, {t}_m);")); + self.line(&format!("uint {t}_o = xcl_x_meet() ? xcl_x_get(0u) : 0u;")); + self.line(&format!("uint {r1} = xcl_half == {}u ? {t}_m : {t}_o;", l1 >> 5)); + self.line(&format!("uint {r2} = xcl_half == {}u ? {t}_m : {t}_o;", l2 >> 5)); + self.write32(&Dst::S(s1), &r1); + // Emit the VALU instruction normally so all 64 lanes of v stay exact + self.inst(&rest[1], rest[2].pc); + self.line(&format!("// {:04x}: {}", rest[2].pc, rdna2::format(&rest[2]))); + self.cur_pc = rest[2].pc; + let exec_w = self.sreg(if l2 < 32 { 126 } else { 127 }); + let mask = 1u32 << (l2 & 31); + self.line(&format!("uint {t}_out = (({exec_w} & {mask:#x}u) != 0u) ? ({expr}) : {r2};")); + self.write32(&dst2, &format!("{t}_out")); + return Some(3); + } + } + } + } + } + + // 3. 64-bit reduction tail: + // v_readlane(s, v, L) ; v_readlane(s+1, v+1, L) ; v_add_f64 v[v:v+1], s[s:s+1], v[v:v+1] ; + // v_readlane(o0, v, L^32) ; v_readlane(o1, v+1, L^32) + if rest.len() >= 5 && rest[2].inst.name == "V_ADD_F64" { + if let (&Dst::S(s_lo), Some((Dst::S(s_hi), v_hi, l_hi)), Some((out_lo, vo0, lo0)), Some((out_hi, vo1, lo1))) = ( + &dst1, + self.x64_const_readlane(&rest[1]), + self.x64_const_readlane(&rest[3]), + self.x64_const_readlane(&rest[4]), + ) { + if s_hi == s_lo + 1 + && s_lo != 126 + && s_lo != 127 + && s_hi != 126 + && s_hi != 127 + && v_hi == v1 + 1 + && l_hi == l1 + && vo0 == v1 + && vo1 == v1 + 1 + && lo0 == l2 + && lo1 == l2 + { + if let Some(s_first) = Self::x64_match_binary_valu(&rest[2], v1, s_lo) { + self.x64_words = self.x64_words.max(2); + self.line(&format!("// {:04x}: {}", rest[0].pc, rdna2::format(&rest[0]))); + self.line(&format!("// {:04x}: {}", rest[1].pc, rdna2::format(&rest[1]))); + self.cur_pc = rest[1].pc; + let (vl, vh) = (self.vreg(v1), self.vreg(v1 + 1)); + let t = self.t(); + self.line(&format!("uint {t}_ml = WaveReadLaneAt({vl}, {lane32}u);")); + self.line(&format!("uint {t}_mh = WaveReadLaneAt({vh}, {lane32}u);")); + self.line(&format!("xcl_x_put(0u, {t}_ml); xcl_x_put(1u, {t}_mh);")); + self.line(&format!("bool {t}_ok = xcl_x_meet();")); + self.line(&format!("uint {t}_ol = {t}_ok ? xcl_x_get(0u) : 0u;")); + self.line(&format!("uint {t}_oh = {t}_ok ? xcl_x_get(1u) : 0u;")); + let (h1, h2) = (l1 >> 5, l2 >> 5); + self.line(&format!("uint {t}_l1 = xcl_half == {h1}u ? {t}_ml : {t}_ol;")); + self.line(&format!("uint {t}_h1 = xcl_half == {h1}u ? {t}_mh : {t}_oh;")); + self.line(&format!("uint {t}_l2 = xcl_half == {h2}u ? {t}_ml : {t}_ol;")); + self.line(&format!("uint {t}_h2 = xcl_half == {h2}u ? {t}_mh : {t}_oh;")); + self.write32(&Dst::S(s_lo), &format!("{t}_l1")); + self.write32(&Dst::S(s_hi), &format!("{t}_h1")); + self.inst(&rest[2], rest[3].pc); + self.line(&format!("// {:04x}: {}", rest[3].pc, rdna2::format(&rest[3]))); + self.line(&format!("// {:04x}: {}", rest[4].pc, rdna2::format(&rest[4]))); + self.cur_pc = rest[4].pc; + let (d1, d2) = (format!("asdouble({t}_l1, {t}_h1)"), format!("asdouble({t}_l2, {t}_h2)")); + let sum = if s_first { format!("{d1} + {d2}") } else { format!("{d2} + {d1}") }; + self.line(&format!("double {t}_d = {sum}; uint {t}_sl, {t}_sh; asuint({t}_d, {t}_sl, {t}_sh);")); + let exec_w = self.sreg(if l2 < 32 { 126 } else { 127 }); + let mask = 1u32 << (l2 & 31); + self.line(&format!("bool {t}_act = ({exec_w} & {mask:#x}u) != 0u;")); + self.line(&format!("uint {t}_outl = {t}_act ? {t}_sl : {t}_l2;")); + self.line(&format!("uint {t}_outh = {t}_act ? {t}_sh : {t}_h2;")); + self.write32(&out_lo, &format!("{t}_outl")); + self.write32(&out_hi, &format!("{t}_outh")); + return Some(5); + } + } + } + } + + None + } + pub fn inst(&mut self, d: &Decoded, next: u64) -> Flow { let name = d.inst.name.to_ascii_lowercase(); let text = rdna2::format(d); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 7a6641bcf..3aa3ac06f 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -870,15 +870,7 @@ fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option, nest: usi /// The instructions of block [start, end) at `depth`; the flow of the last one. fn emit_block(c: &Ctx, em: &mut emit::Em, body: &mut String, start: u64, end: u64, depth: usize, blocks: &mut usize) -> emit::Flow { em.indent = depth; - let mut flow = emit::Flow::Next; - let block: Vec<&Decoded> = insts_in(c, start, end).iter().collect(); - for (k, d) in block.iter().enumerate() { - let next = block.get(k + 1).map(|n| n.pc).unwrap_or(end); - flow = em.inst(d, next); - if !matches!(flow, emit::Flow::Next) { - break; - } - } + let flow = em.emit_insts(insts_in(c, start, end), end); body.push_str(&em.take()); *blocks += 1; flow @@ -1067,15 +1059,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d let end = c.leaders.get(i + 1).copied().unwrap_or(u64::MAX); body.push_str(&format!("{pad}if (pc == {start}u) {{\n")); em.indent = depth + 1; - let mut flow = emit::Flow::Next; - let block: Vec<&Decoded> = insts_in(c, start, end).iter().collect(); - for (k, d) in block.iter().enumerate() { - let next = block.get(k + 1).map(|n| n.pc).unwrap_or(end); - flow = em.inst(d, next); - if !matches!(flow, emit::Flow::Next) { - break; - } - } + let flow = em.emit_insts(insts_in(c, start, end), end); body.push_str(&em.take()); let fallthrough = if end == u64::MAX || !c.starts.contains(&end) { "0xFFFFFFFFu".to_string() } else { format!("{end}u") }; let tail = match flow { @@ -1366,12 +1350,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { if branches == 0 { // straight line: stop at the first s_endpgm (the rest is unreachable) em.indent = 1; - for (i, d) in insts.iter().enumerate() { - let next = insts.get(i + 1).map(|n| n.pc).unwrap_or(u64::MAX); - if let emit::Flow::End = em.inst(d, next) { - break; - } - } + em.emit_insts(&insts, u64::MAX); body.push_str(&em.take()); blocks = 1; } else { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 4e032b68d..12ec10a94 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5790,6 +5790,140 @@ fn gpu_split_wave64_lane_local_masks() { } } +/// Split-wave64 reduction-tail folding rules: 32-bit reduction tails, 64-bit `v_add_f64` tails, +/// and direct `(L, L^32)` pairs fold into one `xcl_x_meet()`, while modifiers, mismatched lanes, +/// `EXEC` writes, jump targets, and native wave64 stay untouched. +#[test] +fn split_wave64_reduction_tail_rules() { + let split = Options { mode: Mode::Kernel, wave64: true, split_wave64: true, ..Default::default() }; + + // 32-bit reduction tail: v_readlane(s8, v2, 32) ; v_min_u32 v2, s8, v2 ; v_readlane(s12, v2, 0) + let tail32 = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 32)], None), + ("V_MIN_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 8), ("VSRC1", 2)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128)], None), + ]); + let t = translate(&tail32, &split).unwrap(); + assert_eq!(t.hlsl.matches("xcl_x_meet() ?").count(), 1 + 3, "1 folded meet + 3 in prelude:\n{}", t.hlsl); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 0); + + // Native wave64 is unchanged + let t_native = translate(&tail32, &Options { mode: Mode::Kernel, wave64: true, split_wave64: false, ..Default::default() }).unwrap(); + assert!(!t_native.hlsl.contains("xcl_x_meet")); + + // 64-bit v_add_f64 reduction tail: 4 readlanes -> 1 2-word meet + let tail64 = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 2), ("SRC1", 128 + 32)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 3), ("SRC1", 128 + 32)], None), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", 2), ("SRC1", V + 2)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 2), ("SRC1", 128)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 3), ("SRC1", 128)], None), + ]); + let t = translate(&tail64, &split).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_meet();").count(), 1, "64-bit tail shares 1 meet"); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 0); + assert!(t.hlsl.contains("#define XCL_X_SLOT 2u")); + + // Direct (L, L^32) pair: 2 readlanes -> 1 meet + let direct = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 5)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 128 + 37)], None), + ]); + let t = translate(&direct, &split).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 0); + + // Negative guards: CLAMP modifier, mismatched lanes, jump target in middle + let clamped = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 32)], None), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 8), ("SRC1", V + 2), ("CLAMP", 1)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128)], None), + ]); + assert_eq!(translate(&clamped, &split).unwrap().hlsl.matches("= xcl_x_rla_uniform(").count(), 2); + + let mismatched = prog(&[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 32)], None), + ("V_MIN_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 8), ("VSRC1", 2)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128 + 1)], None), + ]); + assert_eq!(translate(&mismatched, &split).unwrap().hlsl.matches("= xcl_x_rla_uniform(").count(), 2); + + let branched = prog(&[ + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 2)], None), // targets v_min_u32 (past 8-byte VOP3 readlane) + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 128 + 32)], None), + ("V_MIN_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 8), ("VSRC1", 2)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128)], None), + ]); + assert_eq!(translate(&branched, &split).unwrap().hlsl.matches("= xcl_x_rla_uniform(").count(), 2); +} + +/// GPU verification of folded split-wave64 reduction tails: 32-bit `v_min_u32` / `v_add_f32` / +/// `v_add_f16` (preserving high 16 bits), 64-bit `v_add_f64`, inactive lane 0 under `EXEC`, and +/// direct `(L, L^32)` pair. +#[test] +fn gpu_split_wave64_reduction_tails() { + if !gpu_ready() { + return; + } + let code = prog(&[ + // 1. v_min_u32 reduction tail: v0[32] & v0[0] -> s10 = v0[32], s11 = min(v0[32], v0[0]) + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 0), ("SRC1", 128 + 32)], None), + ("V_MIN_U32", "ENC_VOP2", &[("VDST", 0), ("SRC0", 10), ("VSRC1", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 0), ("SRC1", 128)], None), + // 2. v_add_f32 reduction tail (swapped operand order VOP3: v1, s12) + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", 128 + 32)], None), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V + 1), ("SRC1", 12)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 1), ("SRC1", 128)], None), + // 3. v_add_f16 reduction tail: high 16 bits of v2[0] must stay intact + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", 128 + 32)], None), + ("V_ADD_F16", "ENC_VOP2", &[("VDST", 2), ("SRC0", 14), ("VSRC1", 2)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 2), ("SRC1", 128)], None), + // 4. 64-bit v_add_f64 reduction tail on v[4:5] -> s[16:17] + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", 128 + 32)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 5), ("SRC1", 128 + 32)], None), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 4), ("SRC0", 16), ("SRC1", V + 4)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 4), ("SRC1", 128)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 5), ("SRC1", 128)], None), + // 5. Direct (lane 5, lane 37) pair on v6 -> s18, s19 + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 6), ("SRC1", 128 + 5)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 6), ("SRC1", 128 + 37)], None), + // 6. Lane 0 masked off in EXEC: v_add_nc_u32 must NOT alter lane 0, so s21 stays old v7[0] + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 7), ("SRC1", 128 + 32)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 20), ("VSRC1", 7)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 7), ("SRC1", 128)], None), + ]); + if runner::split_wave64() { + let t = translate(&code, &runner::options(Mode::Kernel)).unwrap(); + assert_eq!(t.hlsl.matches("= xcl_x_rla_uniform(").count(), 0, "all 6 patterns folded:\n{}", t.hlsl); + } + let mut st = KernelState::default(); + let d0 = 123456.75f64.to_bits(); + let d32 = 876543.125f64.to_bits(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = match l { 0 => 500, 32 => 123, _ => 999 }; + r[1] = match l { 0 => 1.5f32.to_bits(), 32 => 2.25f32.to_bits(), _ => 0 }; + // f16: 1.5 (0x3E00) + 2.5 (0x4100) = 4.0 (0x4400); high 16 bits = 0xCAFE on lane 0 + r[2] = match l { 0 => 0xCAFE_3E00, 32 => 0xBEEF_4100, _ => 0 }; + let db = match l { 0 => d0, 32 => d32, _ => 0 }; + r[4] = db as u32; + r[5] = (db >> 32) as u32; + r[6] = 0x6000 + l as u32; + r[7] = match l { 0 => 0x1111, 32 => 0x2222, _ => 0 }; + } + let r = runner::run_code(&code, &st, &[]).unwrap(); + assert_eq!(r.sgpr[10], 123, "v_min_u32 s_tmp = v0[32]"); + assert_eq!(r.sgpr[11], 123, "v_min_u32 s_out = min(500, 123)"); + assert_eq!(r.vgpr[0][0], 123, "v0[0] updated in VGPR too"); + assert_eq!(r.sgpr[13], 3.75f32.to_bits(), "v_add_f32 reduction"); + assert_eq!(r.sgpr[15], 0xCAFE_4400, "v_add_f16 reduction preserves high 16 bits"); + let got_d = (r.sgpr[16] as u64) | ((r.sgpr[17] as u64) << 32); + assert_eq!(got_d, (123456.75f64 + 876543.125f64).to_bits(), "v_add_f64 64-bit reduction"); + assert_eq!(r.sgpr[18], 0x6005, "direct pair lane 5"); + assert_eq!(r.sgpr[19], 0x6025, "direct pair lane 37"); + assert_eq!(r.sgpr[20], 0x2222, "inactive-lane-0 s_tmp still reads lane 32"); + assert_eq!(r.sgpr[21], 0x1111, "inactive-lane-0 s_out keeps unmodified old v7[0]"); +} + /// 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