From 70540976ce32e6a8d3b1aa97773c9724a2574265 Mon Sep 17 00:00:00 2001 From: kais7654 Date: Wed, 25 Nov 2026 01:58:41 +0100 Subject: [PATCH] Shaders: v_mad_f32 and v_mac_f32 multiply apart from their add The lowering emits the product rounded (and flushed) before the add, which is what the ISA says, yet a driver folds the fmul into the fadd behind it as an FMA though nothing carries a fast-math flag: on the 2070-class card here the tail of the product escapes one rounding where two were due (2 of 2560 inputs on v_mad, 102 of 14440 on v_mac, WARP none, the model none). An FMad over a zero signed by the operands' signs rounds exactly like the plain product and hides the multiply behind a call the fusion pass sees no other side of; with it the arithmetic suite meets both backends word for word. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- crates/victory-shader/src/emit/lower.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index df1d2a2360..292db7c162 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2118,6 +2118,23 @@ impl<'a> Lower<'a> { ) } + /// A multiply kept apart from the add that follows it, rounding like the + /// plain product: a driver that folds a `fmul` feeding an `fadd`/`fsub` + /// into an FMA (one rounding where `v_mac_f32` and `v_mad_f32` round the + /// product first) does not see the `fmul` behind the FMad's call. The + /// third operand is a zero signed by the operands' own signs, which the + /// addition never steps out of and keeps a -0 product -0. + fn mul_apart(&mut self, a: V, b: V) -> V { + let c = self.cur; + let ia = self.as_int(a); + let ib = self.as_int(b); + let sign = self.s.m.bin(c, Bin::Xor, ia, ib); + let mask = self.s.m.i32(0x8000_0000); + let zeros = self.s.m.bin(c, Bin::And, sign, mask); + let zero = self.as_float(zeros); + self.fmad(a, b, zero) + } + /// `f` as an f16 in the low bits, rounded as the program's MODE says at /// this point: toward zero where it set that for 16-bit results (the /// title does around its 16-bit interpolation), else to nearest even; @@ -5592,7 +5609,7 @@ impl<'a> Lower<'a> { let r = match name { "v_fmac_f32" => self.fmad(a, bb, acc), "v_mac_f32" => { - let m = self.s.m.bin(c, Bin::Mul, a, bb); + let m = self.mul_apart(a, bb); self.s.m.bin(c, Bin::Add, m, acc) } _ => { @@ -5607,7 +5624,7 @@ impl<'a> Lower<'a> { let m = if name == "v_mad_legacy_f32" { self.legacy_mul(a, bb) } else { - self.s.m.bin(c, Bin::Mul, a, bb) + self.mul_apart(a, bb) }; let r = self.s.m.bin(c, Bin::Add, m, cc); float(self, r)