From c272dbc8e40082fdb369196960df9483e24235cf Mon Sep 17 00:00:00 2001 From: upipibi Date: Mon, 23 Nov 2026 23:50:35 -0600 Subject: [PATCH 1/3] Recompiler: v_sin / v_cos reduce the argument in turns before scaling (#796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v_sin_* / v_cos_* take the argument in turns. XCL emitted sin(x * 6.2831853f), which rounds the phase away at radian scale before any reduction: on an RTX 3070 sin(100000.125) gave 0.6716 for 0.7071, and ±MaxFloat gave NaN because the product overflows. The RDNA 2 ISA's own examples (p.142, p.149) have sin(-MaxFloat) = 0, cos(-MaxFloat) = 1, cos(0.25) = 0 and V_SIN_F16(0x7bff) = 0. sin_turns / cos_turns reduce exactly with x - trunc(x) first, return exact zeros at whole and half turns (sin) and quarter turns (cos), keep sin(-0) = -0, and give ±inf the ISA's 0xFFC00000 and a NaN itself on the bits (DXC's relaxed float math otherwise turned sin(inf) into 0 on the 3070). The f16 forms use the same helpers on the exact f32 value. gpu_sin_cos_reduce_in_turns checks every functional example the ISA prints for the four instructions plus whole, half and quarter turns and large arguments; it fails on main with 21 mismatches. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 15 +++-- crates/xcl/src/gpu/recomp/tests.rs | 94 ++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7851791c94..09b5c7d854 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3489,8 +3489,8 @@ impl Em { "v_sqrt_f16" => fr(format!("sqrt({})", fh(0))), "v_log_f16" => fr(format!("log2({})", fh(0))), "v_exp_f16" => fr(format!("exp2({})", fh(0))), - "v_sin_f16" => fr(format!("sin({} * 6.2831853f)", fh(0))), - "v_cos_f16" => fr(format!("cos({} * 6.2831853f)", fh(0))), + "v_sin_f16" => fr(format!("sin_turns({})", fh(0))), + "v_cos_f16" => fr(format!("cos_turns({})", fh(0))), "v_fract_f16" => fr(format!("fract_f({})", fh(0))), "v_floor_f16" => fr(format!("floor({})", fh(0))), "v_ceil_f16" => fr(format!("ceil({})", fh(0))), @@ -3827,8 +3827,8 @@ impl Em { "v_sqrt_f32" => fr(format!("sqrt({})", fs(0))), "v_exp_f32" => fr(format!("exp2({})", fs(0))), "v_log_f32" => fr(format!("log2({})", fs(0))), - "v_sin_f32" => fr(format!("sin({} * 6.2831853f)", fs(0))), - "v_cos_f32" => fr(format!("cos({} * 6.2831853f)", fs(0))), + "v_sin_f32" => fr(format!("sin_turns({})", fs(0))), + "v_cos_f32" => fr(format!("cos_turns({})", fs(0))), "v_fract_f32" => fr(format!("fract_f({})", fs(0))), "v_trunc_f32" => fr(format!("trunc({})", fs(0))), "v_floor_f32" => fr(format!("floor({})", fs(0))), @@ -6273,6 +6273,13 @@ float mad_nf_f16(float a, float b, float c, uint rm) { precise float p = a * b; float med3f(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); } uint med3u(uint a, uint b, uint c) { return max(min(a, b), min(max(a, b), c)); } int med3i(int a, int b, int c) { return max(min(a, b), min(max(a, b), c)); } +// v_sin / v_cos take the argument in turns: reduced exactly (x - trunc(x)) before the scaling to +// radians, so a large argument keeps its phase (RDNA 2 ISA: sin(-MaxFloat) = 0, cos(-MaxFloat) = 1). +// Exact zeros at whole and half turns (sin) and quarter turns (cos); sin(-0) = -0. ±inf gives the +// ISA's 0xFFC00000 and a NaN itself, quiet, on the bits (DXC's relaxed float math loses inf - inf). +uint trig_nonfinite(float x) { uint u = asuint(x); return select((u & 0x7FFFFFFFu) == 0x7F800000u, 0xFFC00000u, u | 0x00400000u); } +float sin_turns(float x) { float r = x - trunc(x); float s = select(or(r == 0.0f, abs(r) == 0.5f), 0.0f, sin(r * 6.2831853f)); return asfloat(select((asuint(x) & 0x7FFFFFFFu) >= 0x7F800000u, trig_nonfinite(x), select(x == 0.0f, asuint(x), asuint(s)))); } +float cos_turns(float x) { float r = abs(x - trunc(x)); float c = select(or(r == 0.25f, r == 0.75f), 0.0f, cos(r * 6.2831853f)); return asfloat(select((asuint(x) & 0x7FFFFFFFu) >= 0x7F800000u, trig_nonfinite(x), asuint(c))); } // x - floor(x) below 1.0 (RDNA: a NaN stays NaN and ±inf gives NaN – min() would return the // clamp for both: HLSL min returns its non-NaN operand) float fract_f(float x) { float r = x - floor(x); return select(r >= 1.0f, asfloat(0x3F7FFFFFu), r); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8965a41caf..2979df0895 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1182,6 +1182,100 @@ fn gpu_valu_float_and_int() { } } +/// v_sin / v_cos take turns and reduce them exactly: every functional example the RDNA 2 ISA +/// prints for V_SIN_F32 / V_COS_F32 (p.142) and V_SIN_F16 / V_COS_F16 (p.149), exact zeros at +/// whole, half and quarter turns, and large arguments that keep their phase (2π·(x - trunc(x))). +#[test] +fn gpu_sin_cos_reduce_in_turns() { + if !gpu_ready() { + return; + } + #[derive(Clone, Copy, Debug)] + enum E { + Bits(u32), + Nan, + Near(f64), + } + use E::*; + let turn = |x: f64, f: fn(f64) -> f64| f(2.0 * std::f64::consts::PI * (x - x.trunc())); + let near = |x: f32| (Near(turn(x as f64, f64::sin)), Near(turn(x as f64, f64::cos))); + // (input, sin, cos) + let mut c32: Vec<(u32, E, E)> = vec![ + // the ISA's examples + (0xFF80_0000, Nan, Nan), + (0xFF7F_FFFF, Bits(0), Bits(0x3F80_0000)), + (0x8000_0000, Bits(0x8000_0000), Bits(0x3F80_0000)), + (0x3E80_0000, Bits(0x3F80_0000), Bits(0)), + (0x7F80_0000, Nan, Nan), + (0x7FC0_1234, Nan, Nan), // a NaN stays NaN + // +MaxFloat, and exact zeros at half and quarter turns + (0x7F7F_FFFF, Bits(0), Bits(0x3F80_0000)), + (f(0.5), Bits(0), Near(-1.0)), + (f(-0.75), Near(1.0), Bits(0)), + (f(12345.5), Bits(0), Near(-1.0)), + (f(7.25), Near(1.0), Bits(0)), + (f(8388607.5), Bits(0), Near(-1.0)), + ]; + for x in [0.1f32, -3.3, 255.125, 100000.125, 1000000.125, -2097151.875] { + let (s, c) = near(x); + c32.push((f(x), s, c)); + } + let f16v = |h: u32| -> f64 { + let (s, e, m) = (if h & 0x8000 != 0 { -1.0 } else { 1.0 }, (h >> 10) & 0x1F, (h & 0x3FF) as f64); + s * if e == 0 { m * 2f64.powi(-24) } else { (1.0 + m / 1024.0) * 2f64.powi(e as i32 - 15) } + }; + let c16: Vec<(u32, E, E)> = vec![ + (0xFC00, Nan, Nan), + (0xFBFF, Bits(0), Bits(0x3C00)), + (0x8000, Bits(0x8000), Bits(0x3C00)), + (0x3400, Bits(0x3C00), Bits(0)), + (0x7BFF, Bits(0), Bits(0x3C00)), + (0x7C00, Nan, Nan), + (0x7E01, Nan, Nan), + (0x5BF8, Bits(0), Bits(0x3C00)), // 255 turns + (0x3800, Bits(0), Near(-1.0)), // half a turn + (0x5BF9, Near(turn(255.125, f64::sin)), Near(turn(255.125, f64::cos))), + (0xD640, Near(turn(-100.0, f64::sin)), Near(turn(-100.0, f64::cos))), // -100 + ]; + let p = prog(&[ + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)], None), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 1)], None), + ("V_SIN_F16", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 6)], None), + ("V_COS_F16", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 6)], None), + ]); + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = c32[l % c32.len()].0; + r[6] = c16[l % c16.len()].0; + } + let r = runner::run_code(&p, &st, &[]).unwrap(); + let mut bad = Vec::new(); + let mut check = |name: &str, x: u32, got: u32, want: E, is_nan: bool, value: f64, tol: f64| { + let ok = match want { + Bits(b) => got == b, + Nan => is_nan, + Near(v) => (value - v).abs() <= tol, + }; + if !ok { + bad.push(format!("{name}({x:#X}) = {got:#X} ({value}), want {want:?}")); + } + }; + for l in 0..64 { + let v = &r.vgpr[l]; + let (x, s, c) = c32[l % c32.len()]; + for (name, got, want) in [("v_sin_f32", v[2], s), ("v_cos_f32", v[3], c)] { + check(name, x, got, want, f32::from_bits(got).is_nan(), f32::from_bits(got) as f64, 2f64.powi(-16)); + } + let (x, s, c) = c16[l % c16.len()]; + for (name, got, want) in [("v_sin_f16", v[4] & 0xFFFF, s), ("v_cos_f16", v[5] & 0xFFFF, c)] { + check(name, x, got, want, got & 0x7C00 == 0x7C00 && got & 0x3FF != 0, f16v(got), 2f64.powi(-10)); + } + } + bad.sort(); + bad.dedup(); + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// Output modifiers each instruction kind applies: omod on f64 (clamp stays in double /// precision) and on the f64 → f32 / f32 → f16 conversions, and the integer clamp (saturation) of the /// unsigned adds, the packed 16-bit adds and the integer dot products. From ade614c5cb960ed6b1bc3b3836886361da6d3b9a Mon Sep 17 00:00:00 2001 From: upipibi Date: Tue, 24 Nov 2026 04:16:33 -0600 Subject: [PATCH 2/3] =?UTF-8?q?Recompiler:=20v=5Fsin=20/=20v=5Fcos=20f16?= =?UTF-8?q?=20of=20=C2=B1Inf=20give=200xFE00;=20test=20against=20native=20?= =?UTF-8?q?RDNA2=20results?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit luckyteagirl measured the native instructions on an RX 6800M (gfx1031) in https://github.com/ivall/xcl/issues/796#issuecomment-7123464342. gpu_sin_cos_reduce_in_turns now uses those results as hardware rows: - f32: -0, 0.25 / -0.75, 0.5 / 8388607.5, ±MaxFloat, and ±Inf giving 0xFFC00000. Rows that used to check only "near ±1" now check exact bits. - f16: -0, 255, ±65504, and ±Inf giving 0xFE00. - 0.125 turns (f32 at 0.125, 255.125, 100000.125, 1000000.125, giving 0x3F3504F4 / 0x3F3504F3; f16 at 0.125, 255.125, giving 0x39A8): these values come from each GPU's own sine approximation, so they are compared within one ulp. On the RTX 3070, v_sin_f16 / v_cos_f16 of ±Inf gave 0x7FFF, because f32tof16 turns the f32 NaN into that value. They now take the infinity from the source bits and give 0xFE00. With clamp the NaN saturates as before. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 5 +++ crates/xcl/src/gpu/recomp/tests.rs | 50 ++++++++++++++++++------------ 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 09b5c7d854..6c6db2513f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3489,6 +3489,11 @@ impl Em { "v_sqrt_f16" => fr(format!("sqrt({})", fh(0))), "v_log_f16" => fr(format!("log2({})", fh(0))), "v_exp_f16" => fr(format!("exp2({})", fh(0))), + // ±Inf gives the f16 NaN 0xFE00 on RDNA2 (ivall/xcl#796); f32tof16 of the f32 NaN may not. + "v_sin_f16" | "v_cos_f16" if !m.clamp => { + let f = if name == "v_sin_f16" { "sin_turns" } else { "cos_turns" }; + format!("select(({} & 0x7FFFu) == 0x7C00u, 0xFE00u, {})", hb(0), fr(format!("{f}({})", fh(0)))) + } "v_sin_f16" => fr(format!("sin_turns({})", fh(0))), "v_cos_f16" => fr(format!("cos_turns({})", fh(0))), "v_fract_f16" => fr(format!("fract_f({})", fh(0))), diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 2979df0895..19665be13d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1185,6 +1185,9 @@ fn gpu_valu_float_and_int() { /// v_sin / v_cos take turns and reduce them exactly: every functional example the RDNA 2 ISA /// prints for V_SIN_F32 / V_COS_F32 (p.142) and V_SIN_F16 / V_COS_F16 (p.149), exact zeros at /// whole, half and quarter turns, and large arguments that keep their phase (2π·(x - trunc(x))). +/// Rows marked `hw` are native RDNA2 results (RX 6800M, gfx1031), measured by luckyteagirl in +/// https://github.com/ivall/xcl/issues/796#issuecomment-7123464342. Where the hardware value comes +/// from its own sine approximation (0.125 turns), `Ulps` allows one ulp, as the driver's sin() differs. #[test] fn gpu_sin_cos_reduce_in_turns() { if !gpu_ready() { @@ -1195,6 +1198,7 @@ fn gpu_sin_cos_reduce_in_turns() { Bits(u32), Nan, Near(f64), + Ulps(u32, u32), } use E::*; let turn = |x: f64, f: fn(f64) -> f64| f(2.0 * std::f64::consts::PI * (x - x.trunc())); @@ -1202,21 +1206,25 @@ fn gpu_sin_cos_reduce_in_turns() { // (input, sin, cos) let mut c32: Vec<(u32, E, E)> = vec![ // the ISA's examples - (0xFF80_0000, Nan, Nan), - (0xFF7F_FFFF, Bits(0), Bits(0x3F80_0000)), - (0x8000_0000, Bits(0x8000_0000), Bits(0x3F80_0000)), - (0x3E80_0000, Bits(0x3F80_0000), Bits(0)), - (0x7F80_0000, Nan, Nan), - (0x7FC0_1234, Nan, Nan), // a NaN stays NaN - // +MaxFloat, and exact zeros at half and quarter turns - (0x7F7F_FFFF, Bits(0), Bits(0x3F80_0000)), - (f(0.5), Bits(0), Near(-1.0)), - (f(-0.75), Near(1.0), Bits(0)), + (0xFF80_0000, Bits(0xFFC0_0000), Bits(0xFFC0_0000)), // hw + (0xFF7F_FFFF, Bits(0), Bits(0x3F80_0000)), // hw + (0x8000_0000, Bits(0x8000_0000), Bits(0x3F80_0000)), // hw + (0x3E80_0000, Bits(0x3F80_0000), Bits(0)), // hw + (0x7F80_0000, Bits(0xFFC0_0000), Bits(0xFFC0_0000)), // hw + (0x7FC0_1234, Nan, Nan), // a NaN stays NaN + (0x7F7F_FFFF, Bits(0), Bits(0x3F80_0000)), // hw, +MaxFloat + // exact zeros and ones at half and quarter turns + (f(0.5), Bits(0), Bits(0xBF80_0000)), // hw + (f(-0.75), Bits(0x3F80_0000), Bits(0)), // hw + (f(8388607.5), Bits(0), Bits(0xBF80_0000)), // hw (f(12345.5), Bits(0), Near(-1.0)), (f(7.25), Near(1.0), Bits(0)), - (f(8388607.5), Bits(0), Near(-1.0)), ]; - for x in [0.1f32, -3.3, 255.125, 100000.125, 1000000.125, -2097151.875] { + // hw: an eighth of a turn gives the same bits at every whole-turn offset + for x in [0.125f32, 255.125, 100000.125, 1000000.125] { + c32.push((f(x), Ulps(0x3F35_04F4, 1), Ulps(0x3F35_04F3, 1))); + } + for x in [0.1f32, -3.3, -2097151.875] { let (s, c) = near(x); c32.push((f(x), s, c)); } @@ -1225,16 +1233,17 @@ fn gpu_sin_cos_reduce_in_turns() { s * if e == 0 { m * 2f64.powi(-24) } else { (1.0 + m / 1024.0) * 2f64.powi(e as i32 - 15) } }; let c16: Vec<(u32, E, E)> = vec![ - (0xFC00, Nan, Nan), - (0xFBFF, Bits(0), Bits(0x3C00)), - (0x8000, Bits(0x8000), Bits(0x3C00)), + (0xFC00, Bits(0xFE00), Bits(0xFE00)), // hw + (0xFBFF, Bits(0), Bits(0x3C00)), // hw, -65504 + (0x8000, Bits(0x8000), Bits(0x3C00)), // hw (0x3400, Bits(0x3C00), Bits(0)), - (0x7BFF, Bits(0), Bits(0x3C00)), - (0x7C00, Nan, Nan), + (0x7BFF, Bits(0), Bits(0x3C00)), // hw, +65504 + (0x7C00, Bits(0xFE00), Bits(0xFE00)), // hw (0x7E01, Nan, Nan), - (0x5BF8, Bits(0), Bits(0x3C00)), // 255 turns - (0x3800, Bits(0), Near(-1.0)), // half a turn - (0x5BF9, Near(turn(255.125, f64::sin)), Near(turn(255.125, f64::cos))), + (0x5BF8, Bits(0), Bits(0x3C00)), // hw, 255 turns + (0x3800, Bits(0), Near(-1.0)), // half a turn + (0x3000, Ulps(0x39A8, 1), Ulps(0x39A8, 1)), // hw, 0.125 turns + (0x5BF9, Ulps(0x39A8, 1), Ulps(0x39A8, 1)), // hw, 255.125 turns (0xD640, Near(turn(-100.0, f64::sin)), Near(turn(-100.0, f64::cos))), // -100 ]; let p = prog(&[ @@ -1255,6 +1264,7 @@ fn gpu_sin_cos_reduce_in_turns() { Bits(b) => got == b, Nan => is_nan, Near(v) => (value - v).abs() <= tol, + Ulps(b, n) => (got as i64 - b as i64).abs() <= n as i64, }; if !ok { bad.push(format!("{name}({x:#X}) = {got:#X} ({value}), want {want:?}")); From f73e6ea8bd94f9e143dd33933152bf20e2f9608b Mon Sep 17 00:00:00 2001 From: upipibi Date: Wed, 25 Nov 2026 05:28:41 -0600 Subject: [PATCH 3/3] Direct DXIL: v_sin / v_cos reduce the argument in turns, as the HLSL path does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #818 moved the HLSL path's v_sin / v_cos (f32 and f16) to `sin_turns` / `cos_turns`: the argument reduced exactly (x - trunc(x)) before the scaling to radians, exact zeros at whole and half turns (sin, sin(±0) = x) and quarter turns (cos), and `trig_nonfinite` for ±inf (0xFFC00000) and NaN (itself, quiet); f16 ±inf gives 0xFE00 without clamp. The direct translator still took Sin / Cos of x · 2π, so `lower_dxil`'s `f32_programs_on_the_gpu`, which compares the two backends register for register, failed at v_sin_f32(-0.5): -0 from Sin(-3.1415927) on the direct path against the HLSL path's exact +0. `Lw::trig_turns` (prelude.rs) builds the HLSL helpers operation for operation; lower_valu.rs and lower_wide.rs lower the four instructions through it, the f16 path with the HLSL path's 0xFE00 select. No TRANSLATOR_VERSION bump: the direct translation cache keys on the hash of the gpu/dxil sources (XCL_DIRECT_DXIL_SOURCE_ID). A non-GPU test checks the container (validated when DXC's validator is present) for the Round_z, Sin / Cos and the selects. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/lower_valu.rs | 4 +--- crates/xcl/src/gpu/dxil/lower_wide.rs | 15 ++++++++---- crates/xcl/src/gpu/dxil/prelude.rs | 32 +++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/lower_dxil.rs | 22 +++++++++++++++++ 4 files changed, 66 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 5e373200d6..21e571e152 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -554,9 +554,7 @@ impl Lw { }), "v_sin_f32" | "v_cos_f32" => { let x = fs!(0); - let k = self.fc(6.283_185_3); - let x = self.fmul(x, k); - fr!(self.un(if name == "v_sin_f32" { op::SIN } else { op::COS }, x)) + fr!(self.trig_turns(x, name == "v_sin_f32")) } "v_fract_f32" => { let x = fs!(0); diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index 04eab931d0..d877485834 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -552,10 +552,17 @@ impl Lw { "v_exp_f16" => f1!(|s: &mut Self, x| s.un(op::EXP, x)), "v_sin_f16" | "v_cos_f16" => { let x = fh(self, 0); - let k = self.fc(6.283_185_3); - let x = self.fmul(x, k); - let e = self.un(if name == "v_sin_f16" { op::SIN } else { op::COS }, x); - fr(self, e) + let e = self.trig_turns(x, name == "v_sin_f16"); + let h = fr(self, e); + if m.clamp { + h + } else { + // ±Inf gives the f16 NaN 0xFE00, as the HLSL path selects it + let x = hb(self, 0); + let mag = self.andc(x, 0x7FFF); + let inf = self.cmpc(Pred::Eq, mag, 0x7C00); + self.selc(inf, 0xFE00, h) + } } "v_fract_f16" => f1!(|s: &mut Self, x| s.fract_f(x)), "v_floor_f16" => f1!(|s: &mut Self, x| s.un(op::ROUND_NI, x)), diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index ddc09c0f35..4775468bd5 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -78,6 +78,38 @@ impl Lw { let k = self.s.m.f32c(0x3F7F_FFFF); self.sel(ge, k, r) } + /// `sin_turns` / `cos_turns`: the argument in turns, reduced exactly (x - trunc(x)) before + /// the scaling to radians; exact zeros at whole and half turns (sin, with sin(±0) = x) and + /// quarter turns (cos, of |r|). `trig_nonfinite`: ±inf gives 0xFFC00000, a NaN itself, quiet. + pub fn trig_turns(&mut self, x: Value, sin: bool) -> Value { + let t = self.un(op::ROUND_Z, x); + let r = self.fsub(x, t); + let ar = self.fabs(r); + let (r, k0, k1) = if sin { (r, 0.0, 0.5) } else { (ar, 0.25, 0.75) }; + let k0 = self.fc(k0); + let k1 = self.fc(k1); + let e0 = self.fcmp(Pred::FOEq, r, k0); + let e1 = self.fcmp(Pred::FOEq, ar, k1); + let exact = self.lor(e0, e1); + let k = self.fc(6.283_185_3); + let rad = self.fmul(r, k); + let v = self.un(if sin { op::SIN } else { op::COS }, rad); + let z = self.fc(0.0); + let v = self.sel(exact, z, v); + let xb = self.bits(x); + let mut vb = self.bits(v); + if sin { + let x0 = self.fcmp(Pred::FOEq, x, z); + vb = self.sel(x0, xb, vb); + } + let mag = self.andc(xb, 0x7FFF_FFFF); + let inf = self.cmpc(Pred::Eq, mag, 0x7F80_0000); + let quiet = self.orc(xb, 0x0040_0000); + let nf = self.selc(inf, 0xFFC0_0000, quiet); + let nonfinite = self.cmpc(Pred::UGe, mag, 0x7F80_0000); + let res = self.sel(nonfinite, nf, vb); + self.f(res) + } /// HLSL `frexp` as DXC lowers it: (mantissa, exponent as float). fn frexp_dxc(&mut self, x: Value) -> (Value, Value) { let i = self.bits(x); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index a940dcb6fc..504ae8a29d 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -555,6 +555,28 @@ mod tests { } } + /// v_sin / v_cos (f32 and f16) reduce the argument in turns before Sin / Cos, as the HLSL + /// path's `sin_turns` / `cos_turns` (with `trig_nonfinite`, and 0xFE00 for an f16 ±inf): + /// a plain Sin of x · 2π gives sin(-0.5) = -0 there, against the HLSL path's +0. + #[test] + fn sin_and_cos_reduce_the_argument_in_turns() { + let lines: &[I] = &[ + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)]), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 6)]), + ("V_SIN_F16", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 7)]), + ("V_COS_F16", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 8)]), + ENDPGM, + ]; + let dxil = super::kernel(&decode(lines), false).unwrap_or_else(|e| panic!("{e}")).0; + if crate::gpu::dxil::validate::validator_supported() { + crate::gpu::dxil::validate::validate(&dxil).unwrap(); + } + let Ok(dis) = crate::gpu::dxil::validate::disassemble(&dxil) else { return }; + for (what, n) in [("; Round_z(", 4), ("; Sin(", 2), ("; Cos(", 2), ("i32 -4194304", 4), ("i32 65024", 2)] { + assert_eq!(dis.matches(what).count(), n, "{what}\n{dis}"); + } + } + /// The f16 and packed programs of `lower`'s tests, as `f32_programs_on_the_gpu`. #[test] fn f16_programs_on_the_gpu() {