From aaaa7ada37e5cfd4114d172e4b39bf007afb8cc7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:11:45 +0100 Subject: [PATCH] GPU recomp: fix PS interp ints, wave ops EXEC zeroing, ALU edge cases, and BVH det underflow - v_interp_mov_f32 / v_interp_p2_f32: use asuint(xi.a{slot}[{chan}]) directly instead of casting through float, preserving uint/int PS inputs - ds_swizzle_b32 / ds_bpermute_b32: zero results when the source lane is inactive in EXEC (native wave32/64 and split_wave64) - v_ldexp_f32: replace HLSL ldexp() with bit-exact ldexp_f() handling |n| >= 127, +-0, +-inf, NaN, and subnormals - f64 32-bit literal (code 255): place literal in high 32 bits for f64 ops while keeping low 32 bits for integer/bitmask ops - v_cvt_pknorm_i16_f32 & fmt_encode: map NaN to 0 for SNORM conversions, clamp <= 0 to 0 and preserve NaN for 11/10-bit unsigned float formats - s_bfe_i64 / s_bfe_i32 / v_bfe_i32: arithmetic-shift before sign extension so o + w > width and w >= 64 preserve the sign bit - v_cmp_class_f16: apply abs/neg bitwise on the 16-bit half so sNaN is not quieted by an f32 round-trip - bvh::triangle_hit & HLSL bvh_intersect: replace det * det comparison with sign-based barycentric test to avoid underflow/overflow --- crates/xcl/src/gpu/bvh.rs | 25 ++- crates/xcl/src/gpu/recomp/emit.rs | 107 +++++++---- crates/xcl/src/gpu/recomp/tests.rs | 284 +++++++++++++++++++++++++++++ 3 files changed, 381 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 6a7f8a4..8aa4371 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -252,7 +252,11 @@ pub fn triangle_hit(v: &Triangle, o: [f32; 3], d: [f32; 3]) -> Option<[f32; 4]> let sv = sub(o, v[0]); let q = cross(sv, e1); let (i, j, t) = (dot(sv, p), dot(d, q), dot(e2, q)); - let hit = det != 0.0 && i * det >= 0.0 && j * det >= 0.0 && (i + j) * det <= det * det; + let hit = if det > 0.0 { + i >= 0.0 && j >= 0.0 && i + j <= det + } else { + det < 0.0 && i <= 0.0 && j <= 0.0 && i + j >= det + }; hit.then_some([t, det, i, j]) } @@ -605,4 +609,23 @@ pub(crate) mod tests { let got = intersect_node(&data, BOX32, 100.0, o, d, inv, true); assert_eq!(got, [c0, INVALID, INVALID, INVALID]); } + + #[test] + fn triangle_hit_small_and_large_det_avoids_underflow_and_overflow() { + let d = [0.0, 0.0, 1.0]; + // Tiny triangles where det * det underflows to subnormal (1e-40) or 0.0 (1e-48) + for s in [1e-10f32, 1e-12f32] { + let tri = [[0.0, 0.0, 0.0], [s, 0.0, 0.0], [0.0, s, 0.0]]; + assert!(triangle_hit(&tri, [2.0 * s, 2.0 * s, -1.0], d).is_none(), "s={s}: outside ray must miss"); + assert!(triangle_hit(&tri, [0.2 * s, 0.2 * s, -1.0], d).is_some(), "s={s}: inside ray must hit"); + // Opposite winding (det > 0) + let rev = [[0.0, 0.0, 0.0], [0.0, s, 0.0], [s, 0.0, 0.0]]; + assert!(triangle_hit(&rev, [2.0 * s, 2.0 * s, -1.0], d).is_none(), "s={s} rev: outside ray must miss"); + assert!(triangle_hit(&rev, [0.2 * s, 0.2 * s, -1.0], d).is_some(), "s={s} rev: inside ray must hit"); + } + // Huge triangle where det * det overflows to +inf + let big = [[0.0, 0.0, 0.0], [1e10, 0.0, 0.0], [0.0, 1e10, 0.0]]; + assert!(triangle_hit(&big, [2e10, 2e10, -1.0], d).is_none()); + assert!(triangle_hit(&big, [2e9, 2e9, -1.0], d).is_some()); + } } diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 59ae7fe..3c5b5c3 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -624,7 +624,9 @@ impl Em { } /// 64-bit value (lo, hi) of a scalar source code. - fn code64(&mut self, code: u64, lit: Option) -> Option<(String, String)> { + /// In RDNA2 ISA, a 32-bit literal (`code == 255`) goes in the high 32 bits for f64 + /// operands (`{0, lit}`) and in the low 32 bits for integer/bitmask operands (`{lit, 0}`). + fn code64(&mut self, code: u64, lit: Option, f64: bool) -> Option<(String, String)> { Some(match code { 0..=123 | 126 => (self.sreg(code), self.sreg(code + 1)), 125 => ("0u".into(), "0u".into()), @@ -636,7 +638,7 @@ impl Em { (hex(b as u32), hex((b >> 32) as u32)) } 253 => ("scc".into(), "0u".into()), - 255 => (hex(lit?), "0u".into()), + 255 => if f64 { ("0u".into(), hex(lit?)) } else { (hex(lit?), "0u".into()) }, 256..=510 => (self.vreg(code - 256), self.vreg(code - 255)), _ => return None, }) @@ -673,14 +675,14 @@ impl Em { } } - fn read64(&mut self, d: &Decoded, o: &Operand) -> Option<(String, String)> { + fn read64(&mut self, d: &Decoded, o: &Operand, f64: bool) -> Option<(String, String)> { match o.field { Some(f) => { let v = Self::field(d, f); if o.ty.starts_with("OPR_VGPR") && d.enc.field_width(f) <= 8 { return Some((self.vreg(v), self.vreg(v + 1))); } - self.code64(v, d.literal) + self.code64(v, d.literal, f64) } None => match o.ty { "OPR_VCC" => Some((self.sreg(106), self.sreg(107))), @@ -1037,7 +1039,7 @@ impl Em { } if d.enc.name == "ENC_SOPC" { if matches!(name, "s_bitcmp0_b64" | "s_bitcmp1_b64") { - let (a0, a1) = self.read64(d, ins[0]).ok_or("op")?; + let (a0, a1) = self.read64(d, ins[0], false).ok_or("op")?; let b = self.read(d, ins[1], false).ok_or("op")?; let bit = format!("((select(({b} & 32u) == 0u, {a0}, {a1}) >> ({b} & 31u)) & 1u)"); if name == "s_bitcmp0_b64" { @@ -1049,7 +1051,7 @@ impl Em { } let a64 = name.ends_with("_u64"); if a64 { - let (a, b) = (self.read64(d, ins[0]).ok_or("op")?, self.read64(d, ins[1]).ok_or("op")?); + let (a, b) = (self.read64(d, ins[0], false).ok_or("op")?, self.read64(d, ins[1], false).ok_or("op")?); let op = match name { "s_cmp_eq_u64" => "==", "s_cmp_lg_u64" => "!=", @@ -1076,7 +1078,7 @@ impl Em { // SOP1 / SOP2 let saveexec = name.contains("saveexec") || name.contains("wrexec"); if saveexec { - let s0 = self.read64(d, ins[0]).ok_or("op")?; + let s0 = self.read64(d, ins[0], false).ok_or("op")?; let (el, eh) = (self.sreg(126), self.sreg(127)); let op = |a: &str, e: &str| -> Option { Some(match base.split('_').nth(1)? { @@ -1286,7 +1288,7 @@ impl Em { fn salu64(&mut self, d: &Decoded, name: &str, dst: &Dst, ins: &[&Operand]) -> Result<(), &'static str> { let a = match ins.first() { - Some(o) => Some(self.read64(d, o).ok_or("op")?), + Some(o) => Some(self.read64(d, o, false).ok_or("op")?), None => None, }; let b = match ins.get(1) { @@ -1296,7 +1298,7 @@ impl Em { let v = self.read(d, o, false).ok_or("op")?; Some((v, "0u".into())) } else { - Some(self.read64(d, o).ok_or("op")?) + Some(self.read64(d, o, false).ok_or("op")?) } } None => None, @@ -1377,15 +1379,16 @@ impl Em { let w = self.t(); let o = self.t(); let x = self.t(); - self.line(&format!("uint {w} = ({bl} >> 16) & 0x7Fu; uint {o} = {bl} & 63u; uint64_t {x} = {v} >> {o};")); let r = self.t(); if name == "s_bfe_u64" { + self.line(&format!("uint {w} = ({bl} >> 16) & 0x7Fu; uint {o} = {bl} & 63u; uint64_t {x} = {v} >> {o};")); self.line(&format!( "uint64_t {r} = ({w} == 0u) ? 0ull : (({w} >= 64u) ? {x} : ({x} & (0xFFFFFFFFFFFFFFFFull >> (64u - {w}))));" )); } else { + self.line(&format!("uint {w} = ({bl} >> 16) & 0x7Fu; uint {o} = {bl} & 63u; int64_t {x} = ((int64_t){v}) >> {o};")); self.line(&format!( - "uint64_t {r} = ({w} == 0u) ? 0ull : (({w} >= 64u) ? (uint64_t)(int64_t){x} : (uint64_t)(((int64_t)({x} << (64u - {w}))) >> (64u - {w})));" + "uint64_t {r} = ({w} == 0u) ? 0ull : (({w} >= 64u) ? (uint64_t){x} : (uint64_t)(((int64_t)({x} << ((64u - {w}) & 63u))) >> ((64u - {w}) & 63u)));" )); } (format!("(uint){r}"), format!("(uint)({r} >> 32)"), Some(nz.clone())) @@ -1821,14 +1824,14 @@ impl Em { } "v_interp_p2_f32" => { let v = self.vreg(vdst); - self.line(&format!("if ({act}) {v} = asuint((float){src});")); + self.line(&format!("if ({act}) {v} = asuint({src});")); } "v_interp_mov_f32" => { if ij != 2 { return Err("v_interp_mov p10/p20"); } let v = self.vreg(vdst); - self.line(&format!("if ({act}) {v} = asuint((float){src});")); + self.line(&format!("if ({act}) {v} = asuint({src});")); } "v_interp_p2_f16" => { let v = self.vreg(vdst); @@ -2374,7 +2377,7 @@ impl Em { } match o.ty { "OPR_SREG" | "OPR_VCC" if o.size == 64 => { - let (l, h) = self.read64(d, o).ok_or("op")?; + let (l, h) = self.read64(d, o, false).ok_or("op")?; u.push(format!("{l}|{h}")); } _ if o.size == 64 => return Err("operand 64-bit"), @@ -2790,10 +2793,11 @@ impl Em { if d.variant != Variant::Plain { return Err("64-bit SDWA/DPP"); } + let src_f64 = name.ends_with("_f64"); let mut lo_hi: Vec<(String, String)> = Vec::new(); for o in &ins { if o.size == 64 { - lo_hi.push(self.read64(d, o).ok_or("op")?); + lo_hi.push(self.read64(d, o, src_f64).ok_or("op")?); } else { let v = self.read(d, o, false).ok_or("op")?; lo_hi.push((v, "0u".into())); @@ -3073,7 +3077,7 @@ impl Em { "v_rndne_f32" => fr(format!("round({})", fs(0))), "v_frexp_mant_f32" => fr(format!("frexp_mant({})", fs(0))), "v_frexp_exp_i32_f32" => format!("(uint)frexp_exp({})", fs(0)), - "v_ldexp_f32" => fr(format!("ldexp({}, (float)(int){b})", fs(0))), + "v_ldexp_f32" => fr(format!("ldexp_f({}, (int){b})", fs(0))), "v_add_f32" => fr(format!("{} + {}", fs(0), fs(1))), "v_sub_f32" => fr(format!("{} - {}", fs(0), fs(1))), "v_subrev_f32" => fr(format!("{} - {}", fs(1), fs(0))), @@ -3160,11 +3164,7 @@ impl Em { ), "v_cvt_pk_u16_u32" => format!("min({a}, 0xFFFFu) | (min({b}, 0xFFFFu) << 16)"), "v_cvt_pk_i16_i32" => format!("((uint)clamp((int){a}, -32768, 32767) & 0xFFFFu) | (((uint)clamp((int){b}, -32768, 32767) & 0xFFFFu) << 16)"), - "v_cvt_pknorm_i16_f32" => format!( - "((uint)(int)round(clamp({}, -1.0f, 1.0f) * 32767.0f) & 0xFFFFu) | (((uint)(int)round(clamp({}, -1.0f, 1.0f) * 32767.0f) & 0xFFFFu) << 16)", - fs(0), - fs(1) - ), + "v_cvt_pknorm_i16_f32" => format!("(cvt_norm_i16_f32({}) | (cvt_norm_i16_f32({}) << 16))", fs(0), fs(1)), "v_cvt_pknorm_u16_f32" => format!("(uint)round(saturate({}) * 65535.0f) | ((uint)round(saturate({}) * 65535.0f) << 16)", fs(0), fs(1)), // packed f16 sources: op_sel[0]/[1] pick each source's half; result fills all 32 bits "v_cvt_pknorm_i16_f16" | "v_cvt_pknorm_u16_f16" => { @@ -3303,15 +3303,14 @@ impl Em { "f16" => { // compare in f32: exact for every f16 value (class keeps the f16 view) if op == "class" { - let (h, c) = (half(0, &ua), ub.clone()); - let mut v = format!("f16tof32({h})"); + let (mut h, c) = (half(0, &ua), ub.clone()); if m.abs[0] { - v = format!("abs({v})"); + h = format!("({h} & 0x7FFFu)"); } if m.neg[0] { - v = format!("(-{v})"); + h = format!("({h} ^ 0x8000u)"); } - let cond = format!("((({c}) >> fclass16(f32tof16({v}))) & 1u) != 0u"); + let cond = format!("((({c}) >> fclass16({h})) & 1u) != 0u"); return self.vopc_write(d, cmpx, outs, &cond); } ua = format!("asuint(f16tof32({}))", half(0, &ua)); @@ -3644,8 +3643,12 @@ impl Em { if let Some(decl) = decl { self.line(&decl); } + let (el, eh) = (self.sreg(126), self.sreg(127)); + let eh = if self.opt.wave64 { eh } else { "0u".into() }; + self.line(&format!("uint {t}_l = {src};")); let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({a}, {src});")); + self.line(&format!("uint {t} = {rla}({a}, {t}_l);")); + self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); let dst = Dst::V(f("VDST")); self.write32(&dst, &t); return Ok(()); @@ -3653,13 +3656,17 @@ impl Em { "ds_bpermute_b32" => { let (a, v) = (self.vreg(f("ADDR")), self.vreg(f("DATA0"))); let m = if self.opt.wave64 { 63 } else { 31 }; + let (el, eh) = (self.sreg(126), self.sreg(127)); + let eh = if self.opt.wave64 { eh } else { "0u".into() }; + self.line(&format!("uint {t}_l = (({a} + {off16}u) >> 2) & {m}u;")); let rla = if self.x64() { self.x64_words = 32; "xcl_x_rla_any" } else { "rla" }; - self.line(&format!("uint {t} = {rla}({v}, (({a} + {off16}u) >> 2) & {m}u);")); + self.line(&format!("uint {t} = {rla}({v}, {t}_l);")); + self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); let dst = Dst::V(f("VDST")); self.write32(&dst, &t); return Ok(()); @@ -4867,8 +4874,8 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i float det = dot(e1, p); float3 sv = o - v0, q = cross(sv, e1); float i = dot(sv, p), j = dot(d, q), t = dot(e2, q); - // inside when i, j, 1 - i - j >= 0 relative to det (either winding) - bool hit = det != 0.0f && i * det >= 0.0f && j * det >= 0.0f && (i + j) * det <= det * det; + // inside when i, j, 1 - i - j >= 0 relative to det (either winding); avoid det * det underflow/overflow + bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); // barycentrics back to the original vertex order: triangle id @60, per triangle I / J source float bc[4] = { det - i - j, i, j, 0.0f }; uint tid = mem.Load(at + 60u) >> (8u * type); @@ -4888,12 +4895,15 @@ uint fmt_encode(uint x, uint info, uint c) { float maxu = w >= 32u ? 4294967295.0f : (float)((1u << w) - 1u); float maxs = w >= 32u ? 2147483647.0f : (float)((1u << (w - 1u)) - 1u); if (ty == 0u) return (uint)round(saturate(f) * maxu); - if (ty == 1u) return (uint)(int)round(clamp(f, -1.0f, 1.0f) * maxs); + if (ty == 1u) return (uint)(int)round((isnan(f) ? 0.0f : clamp(f, -1.0f, 1.0f)) * maxs); if (ty == 2u) return (uint)f; if (ty == 3u) return (uint)(int)f; if (ty == 4u || ty == 5u || w == 32u) return x; + if (w == 16u) return f32tof16(f); + if (isnan(f)) return w == 11u ? 0x7E0u : 0x3F0u; + if (f <= 0.0f) return 0u; uint h = f32tof16(f); - return w == 16u ? h : (w == 11u ? ((h >> 4) & 0x7FFu) : ((h >> 5) & 0x3FFu)); + return w == 11u ? ((h >> 4) & 0x7FFu) : ((h >> 5) & 0x3FFu); } uint4 fmt_pack(uint4 v, uint info) { uint4 r = uint4(0u, 0u, 0u, 0u); uint n = info & 7u; uint off = 0u; @@ -5140,9 +5150,9 @@ uint cvt_u32(float f) { return select(or(isnan(f), f <= 0.0f), 0u, select(f >= 4 int cvt_i32(float f) { return select(isnan(f), 0, select(f <= -2147483648.0f, (int)0x80000000u, select(f >= 2147483648.0f, 0x7FFFFFFF, (int)f))); } int i24(uint v) { return ((int)(v << 8)) >> 8; } uint bfe_u(uint v, uint o, uint w) { o &= 31u; w &= 31u; return select(w == 0u, 0u, (v >> o) & (0xFFFFFFFFu >> ((32u - w) & 31u))); } -int bfe_i(uint v, uint o, uint w) { o &= 31u; w &= 31u; uint s = (32u - w) & 31u; return select(w == 0u, 0, ((int)((v >> o) << s)) >> s); } +int bfe_i(uint v, uint o, uint w) { o &= 31u; w &= 31u; uint s = (32u - w) & 31u; return select(w == 0u, 0, ((int)(((uint)(((int)v) >> o)) << s)) >> s); } uint sbfe_u(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; return select(w == 0u, 0u, select(w >= 32u, v >> o, (v >> o) & (0xFFFFFFFFu >> ((32u - w) & 31u)))); } -int sbfe_i(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; uint s = (32u - w) & 31u; return select(w == 0u, 0, select(w >= 32u, ((int)v) >> o, ((int)((v >> o) << s)) >> s)); } +int sbfe_i(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; uint s = (32u - w) & 31u; return select(w == 0u, 0, select(w >= 32u, ((int)v) >> o, ((int)(((uint)(((int)v) >> o)) << s)) >> s)); } uint ffbh_i(uint v) { uint x = select((int)v < 0, ~v, v); return select(x == 0u, 0xFFFFFFFFu, 31u - firstbithigh(x)); } uint alignbit(uint s0, uint s1, uint s) { s &= 31u; return select(s == 0u, s1, (s1 >> s) | (s0 << ((32u - s) & 31u))); } uint perm_b32(uint s0, uint s1, uint sel) { @@ -5180,8 +5190,37 @@ uint cvt_norm_i16_f16(uint h) { uint r = cvt_norm_f16(h, 32767u); return ((h & 0x8000u) != 0u ? (uint)(-(int)r) : r) & 0xFFFFu; } +uint cvt_norm_i16_f32(float f) { + return (uint)(int)round((isnan(f) ? 0.0f : clamp(f, -1.0f, 1.0f)) * 32767.0f) & 0xFFFFu; +} float frexp_mant(float x) { float e; return (isinf(x) || isnan(x)) ? x : frexp(x, e); } int frexp_exp(float x) { float e; frexp(x, e); return (isinf(x) || isnan(x)) ? 0 : (int)e; } +// Exact f32 x * 2^n on the IEEE-754 bits: handles |n| >= 127, ±0, ±inf, NaN, and subnormals +// without exp2() overflow/underflow or FTZ flushing. +float ldexp_f(float x, int n) { + uint u = asuint(x); + uint sign = u & 0x80000000u; + uint exp = (u >> 23) & 0xFFu; + uint mant = u & 0x7FFFFFu; + if (exp == 0xFFu || (exp == 0u && mant == 0u)) return x; + int e = (int)exp; + if (exp == 0u) { + uint top = firstbithigh(mant); + mant = (mant << (23u - top)) & 0x7FFFFFu; + e = (int)top - 22; + } + int eo = e + clamp(n, -500, 500); + if (eo >= 255) return asfloat(sign | 0x7F800000u); + if (eo >= 1) return asfloat(sign | ((uint)eo << 23) | mant); + uint sh = (uint)(1 - eo); + if (sh > 24u) return asfloat(sign); + uint sig = 0x00800000u | mant; + uint q = sig >> sh; + uint half_bit = 1u << (sh - 1u); + uint rem = sig & ((1u << sh) - 1u); + bool inc = rem > half_bit || (rem == half_bit && (q & 1u) != 0u); + return asfloat(sign | (q + (uint)inc)); +} // f64 frexp pair: input = mant * 2^exp with |mant| in [0.5, 1); denormals are normalized. // 0/±inf/NaN: mant = input, exp = 0 (per the ISA and the amdgcn frexp intrinsics). // Bit-exact by construction – HLSL frexp() only takes float and would narrow the input. diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index eacdabe..0897f25 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5595,3 +5595,287 @@ fn gpu_mad_nf_f16_rounds_intermediate_in_binary16() { assert_eq!(r.vgpr[1][0], 0x0000, "mad_nf_f16 RTZ clamp: 65504*(1+2^-10)->65504, -65504 -> 0"); assert_eq!(r.vgpr[2][0], 0x0000, "mad_nf_f16 cancellation: (1+2^-10)^2-(1+2^-9) -> 0 (not 2^-20)"); } + +#[test] +fn ps_interp_preserves_integer_and_float_inputs() { + use super::PsInterface; + let ps_code = prog(&[ + ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 2), ("ATTR", 1), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", 1)], None), + ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 7), ("VSRC", 2), ("ATTR", 2), ("ATTRCHAN", 0)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), + ]); + let psi = PsInterface { + inputs: vec![ + el("SV_Position", 0, 1, 3, 0, 0xF), + el("TEXCOORD", 0, 0, 3, 1, 0xF), // float4 + el("TEXCOORD", 1, 0, 1, 2, 0xF), // uint4 + el("TEXCOORD", 2, 0, 2, 3, 0xF), // int4 + ], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: None, + }; + let pt = translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); + assert!(!pt.hlsl.contains("asuint((float)xi.a"), "integer PS inputs must not be cast through float:\n{}", pt.hlsl); + assert!(pt.hlsl.contains("asuint(xi.a0[0])"), "{}", pt.hlsl); + assert!(pt.hlsl.contains("asuint(xi.a1[0])"), "{}", pt.hlsl); + assert!(pt.hlsl.contains("asuint(xi.a1[1])"), "{}", pt.hlsl); + assert!(pt.hlsl.contains("asuint(xi.a2[0])"), "{}", pt.hlsl); + if super::dxc::location().is_ok() { + super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + } +} + +#[test] +fn gpu_ds_swizzle_and_bpermute_zero_inactive_lanes() { + let run_case = |wave64: bool, split_wave64: bool| { + let mut insns: Vec<(&str, &str, &[(&str, u64)], Option)> = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 255)], Some(0x5555_5555)), + ]; + if wave64 { + insns.push(("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 255)], Some(0x5555_5555))); + } + insns.extend_from_slice(&[ + // swizzle XOR 1: even lanes read inactive odd neighbor -> must be 0 + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 1 << 2)], None), + // bpermute targeting odd neighbor -> must be 0 + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 1), ("DATA0", 0)], None), + // bpermute targeting cross-half odd lane (lane ^ 33) -> must be 0 + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 12), ("ADDR", 2), ("DATA0", 0)], None), + // swizzle XOR 2: even lanes read active even lane -> must return its value + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 13), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 2 << 2)], None), + ]); + let code = prog(&insns); + let t = translate(&code, &Options { wave64, split_wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let mut st = KernelState::default(); + let lanes = if wave64 { 64 } else { 32 }; + for (l, r) in st.vgpr.iter_mut().take(lanes).enumerate() { + r[0] = if l & 1 == 1 { 0xDEAD } else { 0x1000 + l as u32 }; + r[1] = 4 * (l ^ 1) as u32; + r[2] = 4 * ((l ^ 33) & (lanes - 1)) as u32; + for dst in 10..=13 { + r[dst] = 0xCAFE_BABE; + } + } + let r = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..lanes { + let v = &r.vgpr[l]; + if l & 1 == 0 { + assert_eq!(v[10], 0, "wave{lanes} split={split_wave64} lane {l}: ds_swizzle inactive src"); + assert_eq!(v[11], 0, "wave{lanes} split={split_wave64} lane {l}: ds_bpermute inactive src"); + assert_eq!(v[12], 0, "wave{lanes} split={split_wave64} lane {l}: ds_bpermute cross-half inactive src"); + assert_eq!(v[13], 0x1000 + (l ^ 2) as u32, "wave{lanes} split={split_wave64} lane {l}: ds_swizzle active src"); + } else { + for dst in 10..=13 { + assert_eq!(v[dst], 0xCAFE_BABE, "wave{lanes} split={split_wave64} lane {l}: inactive dst v{dst}"); + } + } + } + }; + for wave64 in gpu_waves() { + run_case(wave64, false); + } + if gpu_ready() { + run_case(true, true); + } +} + +#[test] +fn gpu_ldexp_f32() { + for wave64 in gpu_waves() { + let p = prog(&[("V_LDEXP_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1)], None)]); + const CASES: [(u32, i32, u32); 15] = [ + (1e30f32.to_bits(), -150, 1e30f32.to_bits() - (150 << 23)), + (0.5f32.to_bits(), 128, 0x7F00_0000), // 2^127 + (2.0f32.to_bits(), -127, 0x0080_0000), // 2^-126 (min normal) + (0.0f32.to_bits(), 200, 0x0000_0000), // +0 stays +0 + (0x8000_0000, 200, 0x8000_0000), // -0 stays -0 + (f32::INFINITY.to_bits(), -200, 0x7F80_0000), // +inf stays +inf + (f32::NEG_INFINITY.to_bits(), -200, 0xFF80_0000),// -inf stays -inf + (0x7FC0_1234, 10, 0x7FC0_1234), // NaN stays NaN + (1.0f32.to_bits(), -149, 0x0000_0001), // min subnormal + (1.0f32.to_bits(), -150, 0x0000_0000), // tie to even -> 0 + (1.5f32.to_bits(), -149, 0x0000_0002), // tie to even -> 2 + (0x0000_0001, 149, 1.0f32.to_bits()), // subnormal input -> 1.0 + (0x0000_0001, 276, 0x7F00_0000), // subnormal input -> 2^127 + (1.0f32.to_bits(), i32::MAX, 0x7F80_0000), // overflow to +inf + ((-1.0f32).to_bits(), i32::MIN, 0x8000_0000), // underflow to -0 + ]; + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let (x, n, _) = CASES[l % CASES.len()]; + (r[0], r[1]) = (x, n as u32); + } + let (r, lanes) = run_wave(&p, &st, wave64); + for (l, v) in r.vgpr.iter().take(lanes).enumerate() { + let (x, n, want) = CASES[l % CASES.len()]; + let got = v[4]; + let both_nan = f32::from_bits(got).is_nan() && f32::from_bits(want).is_nan(); + assert!( + got == want || both_nan, + "wave{lanes} lane {l} v_ldexp_f32({x:#010x}, {n}) = {got:#010x}, want {want:#010x}" + ); + } + } +} + +#[test] +fn gpu_f64_literal_high_word() { + for wave64 in gpu_waves() { + let p = prog(&[ + // 1.0 + literal(1.5 = 0x3FF8_0000_0000_0000) == 2.5 + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 255)], Some(0x3FF8_0000)), + // compare result against literal(2.5 = 0x4004_0000_0000_0000) + ("V_CMP_EQ_F64", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 4), ("SRC1", 255)], Some(0x4004_0000)), + // verify integer 64-bit literal still goes in low 32 bits + ("V_CMP_EQ_U64", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 6), ("SRC1", 255)], Some(0x1234_5678)), + ]); + let mut st = KernelState::default(); + let one = 1.0f64.to_bits(); + for r in st.vgpr.iter_mut() { + (r[0], r[1]) = (one as u32, (one >> 32) as u32); + (r[6], r[7]) = (0x1234_5678, 0); + } + let (r, lanes) = run_wave(&p, &st, wave64); + for (l, v) in r.vgpr.iter().take(lanes).enumerate() { + assert_eq!(pair(v, 4), 2.5f64, "wave{lanes} lane {l} v_add_f64 literal"); + } + let expected_hi = if wave64 { u32::MAX } else { 0 }; + assert_eq!((r.sgpr[0], r.sgpr[1]), (u32::MAX, expected_hi), "wave{lanes} v_cmp_eq_f64 literal"); + assert_eq!((r.sgpr[2], r.sgpr[3]), (u32::MAX, expected_hi), "wave{lanes} v_cmp_eq_u64 literal"); + } +} + +#[test] +fn gpu_pknorm_i16_f32_nan_and_fmt_encode_snorm_ufloat() { + if !gpu_ready() { + return; + } + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let vs = |base: u32, fmt: u32| [base, 0, 0x100, ident | fmt << 12]; + // Formats: 43 = 11_11_10_FLOAT (X:10b, Y:11b, Z:11b), 36 = 10_11_11_FLOAT (X:11b, Y:11b, Z:10b), 24 = 16_16_SNORM + let p = prog(&[ + ("V_CVT_PKNORM_I16_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 0), ("SRC1", V + 0)], None), // (NaN, NaN) + ("V_CVT_PKNORM_I16_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 0), ("SRC1", V + 1)], None), // (NaN, 1.0) + ("V_CVT_PKNORM_I16_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", V + 0)], None), // (-1.0, NaN) + ("BUFFER_STORE_FORMAT_XYZ", "ENC_MUBUF", &[("VDATA", 20), ("SRSRC", 4), ("SOFFSET", 128)], None), // 11_11_10_FLOAT (-1, -inf, 1) + ("BUFFER_STORE_FORMAT_XYZ", "ENC_MUBUF", &[("VDATA", 24), ("SRSRC", 5), ("SOFFSET", 128)], None), // 11_11_10_FLOAT (NaN, +inf, -0.5) + ("BUFFER_STORE_FORMAT_XYZ", "ENC_MUBUF", &[("VDATA", 20), ("SRSRC", 6), ("SOFFSET", 128)], None), // 10_11_11_FLOAT (-1, -inf, 1) + ("BUFFER_STORE_FORMAT_XY", "ENC_MUBUF", &[("VDATA", 28), ("SRSRC", 7), ("SOFFSET", 128)], None), // 16_16_SNORM (NaN, -1.0) + ]); + let mut st = KernelState::default(); + st.sgpr[16..20].copy_from_slice(&vs(0x200, 43)); + st.sgpr[20..24].copy_from_slice(&vs(0x204, 43)); + st.sgpr[24..28].copy_from_slice(&vs(0x208, 36)); + st.sgpr[28..32].copy_from_slice(&vs(0x20C, 24)); + for r in st.vgpr.iter_mut() { + r[0] = f32::NAN.to_bits(); + r[1] = 1.0f32.to_bits(); + r[2] = (-1.0f32).to_bits(); + // (-1.0, -Inf, 1.0) + r[20] = (-1.0f32).to_bits(); + r[21] = f32::NEG_INFINITY.to_bits(); + r[22] = 1.0f32.to_bits(); + // (NaN, +Inf, -0.5) + r[24] = f32::NAN.to_bits(); + r[25] = f32::INFINITY.to_bits(); + r[26] = (-0.5f32).to_bits(); + // (NaN, -1.0) + r[28] = f32::NAN.to_bits(); + r[29] = (-1.0f32).to_bits(); + } + let mem = vec![0u32; 0x100]; + let r = runner::run_code(&p, &st, &mem).unwrap(); + assert_eq!(r.vgpr[0][10], 0x0000_0000, "v_cvt_pknorm_i16_f32(NaN, NaN)"); + assert_eq!(r.vgpr[0][11], 0x7FFF_0000, "v_cvt_pknorm_i16_f32(NaN, 1.0)"); + assert_eq!(r.vgpr[0][12], 0x0000_8001, "v_cvt_pknorm_i16_f32(-1.0, NaN)"); + // 11_11_10_FLOAT (-1, -inf, 1): X(10b)=0, Y(11b)=0, Z(11b)=0x3C0 -> 0x3C0 << 21 = 0x7800_0000 + assert_eq!(r.mem[0x200 / 4], 0x3C0 << 21, "11_11_10_FLOAT (-1, -inf, 1)"); + // 11_11_10_FLOAT (NaN, +inf, -0.5): X(10b)=0x3F0 (NaN), Y(11b)=0x7C0 (+inf), Z(11b)=0 + assert_eq!(r.mem[0x204 / 4], 0x3F0 | (0x7C0 << 10), "11_11_10_FLOAT (NaN, +inf, -0.5)"); + // 10_11_11_FLOAT (-1, -inf, 1): X(11b)=0, Y(11b)=0, Z(10b)=0x1E0 -> 0x1E0 << 22 = 0x7800_0000 + assert_eq!(r.mem[0x208 / 4], 0x1E0 << 22, "10_11_11_FLOAT (-1, -inf, 1)"); + // 16_16_SNORM (NaN, -1.0): lo=0, hi=-32767 (0x8001) + assert_eq!(r.mem[0x20C / 4], 0x8001_0000, "16_16_SNORM (NaN, -1.0)"); +} + +#[test] +fn gpu_signed_bfe_arithmetic_shift() { + for wave64 in gpu_waves() { + let p = prog(&[ + // s_bfe_i64(-1, offset=8, width=64) -> -1 + ("S_BFE_I64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 4), ("SSRC1", 6)], None), + // s_bfe_i64(0x8000_0000_0000_0000, offset=32, width=40) -> 0xFFFF_FFFF_8000_0000 + ("S_BFE_I64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 8), ("SSRC1", 10)], None), + // s_bfe_i32(0x8000_0000, offset=16, width=20) -> 0xFFFF_8000 + ("S_BFE_I32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 11), ("SSRC1", 13)], None), + // v_bfe_i32(0x8000_0000, offset=16, width=20) -> 0xFFFF_8000 + ("V_BFE_I32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 0), ("SRC1", 144), ("SRC2", 148)], None), + // v_bfe_i32(0x0000_8000, offset=0, width=16) -> 0xFFFF_8000 (o + w < 32) + ("V_BFE_I32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 1), ("SRC1", 128), ("SRC2", 144)], None), + // v_bfe_i32(0xFFFF_FFFF, offset=4, width=0) -> 0 + ("V_BFE_I32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 132), ("SRC2", 128)], None), + ]); + let mut st = KernelState::default(); + (st.sgpr[4], st.sgpr[5]) = (u32::MAX, u32::MAX); + st.sgpr[6] = (64 << 16) | 8; + (st.sgpr[8], st.sgpr[9]) = (0, 0x8000_0000); + st.sgpr[10] = (40 << 16) | 32; + st.sgpr[11] = 0x8000_0000; + st.sgpr[13] = (20 << 16) | 16; + for r in st.vgpr.iter_mut() { + r[0] = 0x8000_0000; + r[1] = 0x0000_8000; + r[2] = u32::MAX; + } + let (r, lanes) = run_wave(&p, &st, wave64); + assert_eq!((r.sgpr[0], r.sgpr[1]), (u32::MAX, u32::MAX), "wave{lanes} s_bfe_i64(-1, 8, 64)"); + assert_eq!((r.sgpr[2], r.sgpr[3]), (0x8000_0000, u32::MAX), "wave{lanes} s_bfe_i64(i64::MIN, 32, 40)"); + assert_eq!(r.sgpr[12], 0xFFFF_8000, "wave{lanes} s_bfe_i32(i32::MIN, 16, 20)"); + for (l, v) in r.vgpr.iter().take(lanes).enumerate() { + assert_eq!(v[4], 0xFFFF_8000, "wave{lanes} lane {l} v_bfe_i32(i32::MIN, 16, 20)"); + assert_eq!(v[5], 0xFFFF_8000, "wave{lanes} lane {l} v_bfe_i32(0x8000, 0, 16)"); + assert_eq!(v[6], 0, "wave{lanes} lane {l} v_bfe_i32(width=0)"); + } + } +} + +#[test] +fn gpu_cmp_class_f16_preserves_snan() { + for wave64 in gpu_waves() { + let p = prog(&[ + // 0x7C01 (sNaN) tested against mask 1 << 0 (sNaN) -> true + ("V_CMP_CLASS_F16", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 0), ("SRC1", 129)], None), + // 0x7C01 (sNaN) tested against mask 1 << 1 (qNaN) -> false + ("V_CMP_CLASS_F16", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 0), ("SRC1", 130)], None), + // 0x7E01 (qNaN) tested against mask 1 << 0 (sNaN) -> false + ("V_CMP_CLASS_F16", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 129)], None), + // 0x7E01 (qNaN) tested against mask 1 << 1 (qNaN) -> true + ("V_CMP_CLASS_F16", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 1), ("SRC1", 130)], None), + // 0xBC00 (-1.0) with ABS tested against mask 1 << 8 (+normal) -> true + ("V_CMP_CLASS_F16", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 2), ("SRC1", 255), ("ABS", 1)], Some(1 << 8)), + // 0xBC00 (-1.0) with NEG tested against mask 1 << 8 (+normal) -> true + ("V_CMP_CLASS_F16", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 255), ("NEG", 1)], Some(1 << 8)), + ]); + let mut st = KernelState::default(); + for r in st.vgpr.iter_mut() { + r[0] = 0x7C01; // f16 sNaN + r[1] = 0x7E01; // f16 qNaN + r[2] = 0xBC00; // f16 -1.0 + } + let (r, lanes) = run_wave(&p, &st, wave64); + let all = (u32::MAX, if wave64 { u32::MAX } else { 0 }); + assert_eq!((r.sgpr[0], r.sgpr[1]), all, "wave{lanes} f16 sNaN matches sNaN bit"); + assert_eq!((r.sgpr[2], r.sgpr[3]), (0, 0), "wave{lanes} f16 sNaN does not match qNaN bit"); + assert_eq!((r.sgpr[4], r.sgpr[5]), (0, 0), "wave{lanes} f16 qNaN does not match sNaN bit"); + assert_eq!((r.sgpr[6], r.sgpr[7]), all, "wave{lanes} f16 qNaN matches qNaN bit"); + assert_eq!((r.sgpr[8], r.sgpr[9]), all, "wave{lanes} f16 abs(-1.0) matches +normal"); + assert_eq!((r.sgpr[10], r.sgpr[11]), all, "wave{lanes} f16 neg(-1.0) matches +normal"); + } +}