From ad836cb4ff3d7ca871d95c0af612ef7451131bcf Mon Sep 17 00:00:00 2001 From: murdoa Date: Tue, 6 Oct 2026 20:53:08 +0100 Subject: [PATCH] fix(fpu): round fused multiply-add only once --- .../lib/src/core/iterative_fp_arith.dart | 232 ++++++++++++++---- .../test/fpvector/fma_core_test.dart | 118 +++++++++ .../test/fpvector/fma_reference.dart | 96 ++++++++ .../fpvector/iterative_fp_arith_test.dart | 161 +++++++++++- 4 files changed, 552 insertions(+), 55 deletions(-) create mode 100644 packages/river_hdl/test/fpvector/fma_core_test.dart create mode 100644 packages/river_hdl/test/fpvector/fma_reference.dart diff --git a/packages/river_hdl/lib/src/core/iterative_fp_arith.dart b/packages/river_hdl/lib/src/core/iterative_fp_arith.dart index fd88efa..dd11120 100644 --- a/packages/river_hdl/lib/src/core/iterative_fp_arith.dart +++ b/packages/river_hdl/lib/src/core/iterative_fp_arith.dart @@ -36,18 +36,14 @@ import 'package:rohd/rohd.dart'; /// fnmsub (-(a*b)) + c [selFma, selNegA] /// fnmadd (-(a*b)) + (-c) [selFma, selNegA, selNegB] /// fcvt a, re-rounded at the other precision [selCvt] -/// A fused multiply-add runs TWO passes through the unit: pass 0 multiplies -/// a by b, pass 1 adds c to that product. Each pass rounds, so the answer is -/// the same one the golden model gives, which computes the product and the -/// sum as two separate roundings. +/// A fused multiply-add retains the complete product through alignment and +/// addition, including cancellation, and rounds only the final sum. /// /// PRECISION. A unit wider than binary32 also serves the binary32 family, and /// it does so without a converter on either side: [selSingle] tells it to read /// the operand fields at binary32 and to round the answer back to binary32. -/// The widening is exact, and the answer is rounded ONCE, so it is the -/// correctly rounded binary32 answer. That matches what the golden model gives, -/// because binary64 keeps 53 bits where the bound for innocuous double -/// rounding into binary32 is 2*24 + 2 = 50. +/// Widening is exact; guard and sticky information is retained until the +/// answer is rounded once at the destination precision. /// /// [selCvt] flips the destination precision against the source, which is what /// fcvt.s.d and fcvt.d.s ask for. Such a convert runs as an add of the operand @@ -110,7 +106,8 @@ class IterativeFpArith extends Module { // The working exponent is signed and reaches about -(2*bias + 2*m). final expW = e + 3; final bias = (1 << (e - 1)) - 1; - final cntW = (ww + 2).bitLength; + final fw = 2 * n + 4; // full product, carry and guard/round/sticky + final cntW = (fw + 2).bitLength; // The narrow format. Every internal value stays in the WIDE exponent // domain, so a narrow operand adds this offset on the way in and a narrow @@ -154,7 +151,12 @@ class IterativeFpArith extends Module { sNorm = 7, sDenorm = 8, sRound = 9, - sDone = 10; + sDone = 10, + sFmaNormC = 11, + sFmaSetup = 12, + sFmaAlign = 13, + sFmaAdd = 14, + sFmaNorm = 15; Logic st(int v) => Const(v, width: 4); const opAdd = 0, opMul = 1, opDiv = 2; @@ -175,7 +177,12 @@ class IterativeFpArith extends Module { final sgn = Logic(name: 'sgn'); final effSub = Logic(name: 'effSub'); final curOp = Logic(name: 'curOp', width: 2); - final phase = Logic(name: 'phase'); + final fmaProduct = Logic(name: 'fmaProduct', width: 2 * n); + final fmaExponent = Logic(name: 'fmaExponent', width: expW); + final fmaC = Logic(name: 'fmaC', width: n); + final fmaCExponent = Logic(name: 'fmaCExponent', width: expW); + final fmaLarge = Logic(name: 'fmaLarge', width: fw); + final fmaWork = Logic(name: 'fmaWork', width: fw); // The answer takes the narrow format. Latched, because the pack stage // reads it many cycles after the operands went in. final dstNarrow = Logic(name: 'dstNarrow'); @@ -185,30 +192,22 @@ class IterativeFpArith extends Module { // ---------------------------------------------------------------- decode - // Which operands this pass takes. A fused multiply-add gives pass 0 the - // raw a and b, and pass 1 the product it just made and c. The sign flips - // belong to the ADD pass, so pass 0 never applies them. - final ph0 = selFma & ~phase; - final ph1 = selFma & phase; - final negAeff = ~ph0 & ~selDiv & selNegA; - final negBeff = ~ph0 & ~selDiv & selNegB; - final rawA = mux(ph1, resReg, opA); - final rawB = mux(ph1, opC, opB); + // FMA sign controls apply to the product and addend, not the multiply's + // input operands. Keep the product unrounded until the three-operand sum. + final negAeff = ~selFma & ~selDiv & selNegA; + final negBeff = ~selFma & ~selDiv & selNegB; + final rawA = opA; + final rawB = opB; final cvt = dual ? selCvt : Const(0); - // The product a fused multiply-add makes on pass 0 is a WIDE value, so - // pass 1 reads its left operand at the wide format whatever the operation - // precision is, and pass 0 writes a wide product for it to read. - final narrowA = dual ? (selSingle & ~ph1) : Const(0); + final narrowA = dual ? selSingle : Const(0); final narrowB = dual ? selSingle : Const(0); - final narrowOut = dual - ? (~ph0 & mux(cvt, ~selSingle, selSingle)) - : Const(0); + final narrowOut = dual ? mux(cvt, ~selSingle, selSingle) : Const(0); final opNew = mux( selDiv, oc(opDiv), - mux(selMul | ph0, oc(opMul), oc(opAdd)), + mux(selMul | selFma, oc(opMul), oc(opAdd)), ); final newIsAdd = opNew.eq(oc(opAdd)); final newIsMul = opNew.eq(oc(opMul)); @@ -268,6 +267,7 @@ class IterativeFpArith extends Module { final ua = unpack(rawA, narrowA, negAeff); final ub = unpack(rawB, narrowB, negBeff); + final uc = unpack(opC, narrowB, selNegB); // A convert reads one operand only. It runs as an add of that operand and // a zero, so the right side is silenced here: same exponent, so nothing @@ -283,8 +283,8 @@ class IterativeFpArith extends Module { // An add wants the larger magnitude first, so the alignment only ever // shifts the right operand and the subtract never borrows. The compare is - // on the unpacked exponent and significand, because a fused multiply-add - // holds its two operands at DIFFERENT formats on the second pass. + // on the unpacked exponent and significand, including the conversion's + // synthetic zero addend. final aBigger = ua.exp.gt(bExp) | (ua.exp.eq(bExp) & ua.sig.gte(bSig)); final swapAB = newIsAdd & ~aBigger; @@ -305,8 +305,7 @@ class IterativeFpArith extends Module { // family costs one narrow mux and no wide one. An add with ONE zero // operand is not special: it runs the ordinary path with a zero addend, // which re-rounds the other operand at the destination format. That is - // what a convert needs and what a fused multiply-add needs when its third - // operand is zero and the product still has to round. + // what a convert needs. FMA handles its three-operand specials separately. final xorSign = signA ^ signB; final anyNaN = aNaN | bNaNs; final mulBad = (aInf & bZero) | (bInfs & aZero); @@ -352,6 +351,42 @@ class IterativeFpArith extends Module { ? mux(narrowOut, constNarrow(), constWide()) : constWide(); + // Three-operand FMA special cases must be resolved before rounding. A + // finite product that exceeds the output range is not an infinity here. + final fmaProductSign = ua.sign ^ ub.sign ^ selNegA; + final fmaProductInf = (ua.isInf | ub.isInf) & ~anyNaN & ~mulBad; + final fmaInvalidSum = fmaProductInf & uc.isInf & (fmaProductSign ^ uc.sign); + final fmaNaN = anyNaN | uc.isNaN | mulBad | fmaInvalidSum; + final fmaInf = ~fmaNaN & (fmaProductInf | uc.isInf); + final fmaZero = (ua.isZero | ub.isZero) & uc.isZero; + final fmaSign = + ~fmaNaN & + mux( + fmaProductInf, + fmaProductSign, + mux(uc.isInf, uc.sign, fmaProductSign & uc.sign), + ); + Logic fmaConstant(bool narrow) { + final eb = narrow ? eS : e; + final mb = narrow ? mS : m; + return [ + if (narrow && w > wS) Const(0, width: w - wS), + fmaSign, + mux( + fmaNaN | fmaInf, + Const((1 << eb) - 1, width: eb), + Const(0, width: eb), + ), + fmaNaN, + Const(0, width: mb - 1), + ].swizzle(); + } + + final fmaSpecialValue = dual + ? mux(narrowOut, fmaConstant(true), fmaConstant(false)) + : fmaConstant(false); + final initialSpecial = mux(selFma, fmaNaN | fmaInf | fmaZero, specHit); + // ------------------------------------------------------------- iteration // Sticky-preserving right shift: bit 0 keeps the OR of everything that has @@ -415,6 +450,34 @@ class IterativeFpArith extends Module { final loadIsMul = curOp.eq(oc(opMul)); + final fmaPWide = [Const(0), fmaProduct, Const(0, width: 3)].swizzle(); + final fmaCWide = [Const(0), fmaC, Const(0, width: n + 3)].swizzle(); + final productExpGreater = mux( + fmaExponent[expW - 1] ^ fmaCExponent[expW - 1], + ~fmaExponent[expW - 1], + fmaExponent.gt(fmaCExponent), + ); + final productBigger = + ~fmaC.or() | + (fmaProduct.or() & + (productExpGreater | + (fmaExponent.eq(fmaCExponent) & fmaPWide.gte(fmaCWide)))); + final fmaBigExponent = mux(productBigger, fmaExponent, fmaCExponent); + final fmaSmallExponent = mux(productBigger, fmaCExponent, fmaExponent); + final fmaSmall = mux(productBigger, fmaCWide, fmaPWide); + final fmaDistance = mux( + fmaSmall.or(), + fmaBigExponent - fmaSmallExponent, + Const(0, width: expW), + ); + final fmaCap = mux( + fmaDistance.gt(Const(fw, width: expW)), + Const(fw, width: expW), + fmaDistance, + ); + Logic fmaShift(Logic v) => + [Const(0), v.slice(fw - 1, 2), v[1] | v[0]].swizzle(); + // Normalise. A carry out of the significand shifts right once; a cancelling // subtract shifts left until the top bit appears. final normCarry = rw[ww - 1]; @@ -523,7 +586,12 @@ class IterativeFpArith extends Module { sgn < 0, effSub < 0, curOp < 0, - phase < 0, + fmaProduct < 0, + fmaExponent < 0, + fmaC < 0, + fmaCExponent < 0, + fmaLarge < 0, + fmaWork < 0, dstNarrow < 0, special < 0, specialHold < 0, @@ -543,9 +611,15 @@ class IterativeFpArith extends Module { expA < expAload, expB < expBload, dstNarrow < narrowOut, - special < specHit, - specialHold < specVal, - If(specHit, then: [state < sRound], orElse: [state < sNormA]), + fmaC < uc.sig, + fmaCExponent < uc.exp, + special < initialSpecial, + specialHold < mux(selFma, fmaSpecialValue, specVal), + If( + initialSpecial, + then: [state < sRound], + orElse: [state < sNormA], + ), ], ), ]), @@ -610,9 +684,79 @@ class IterativeFpArith extends Module { ]), CaseItem(st(sAddSub), [rw < addRes, state < sNorm]), CaseItem(st(sLoad), [ - rw < mux(loadIsMul, mulR, divR), - expR < mux(loadIsMul, mulExp, divExp), - state < sNorm, + If( + selFma, + then: [ + fmaProduct < + mux( + prodHi, + prod, + [prod.slice(2 * n - 2, 0), Const(0)].swizzle(), + ), + fmaExponent < mulExp, + state < sFmaNormC, + ], + orElse: [ + rw < mux(loadIsMul, mulR, divR), + expR < mux(loadIsMul, mulExp, divExp), + state < sNorm, + ], + ), + ]), + CaseItem(st(sFmaNormC), [ + If( + fmaC[n - 1] | ~fmaC.or(), + then: [state < sFmaSetup], + orElse: [ + fmaC < [fmaC.slice(n - 2, 0), Const(0)].swizzle(), + fmaCExponent < fmaCExponent - 1, + ], + ), + ]), + CaseItem(st(sFmaSetup), [ + fmaLarge < mux(productBigger, fmaPWide, fmaCWide), + fmaWork < fmaSmall, + expR < fmaBigExponent, + sgn < mux(productBigger, fmaProductSign, uc.sign), + effSub < (fmaProductSign ^ uc.sign), + cnt < fmaCap.getRange(0, cntW), + state < sFmaAlign, + ]), + CaseItem(st(sFmaAlign), [ + If( + cnt.eq(0), + then: [state < sFmaAdd], + orElse: [fmaWork < fmaShift(fmaWork), cnt < cnt - 1], + ), + ]), + CaseItem(st(sFmaAdd), [ + fmaWork < mux(effSub, fmaLarge - fmaWork, fmaLarge + fmaWork), + state < sFmaNorm, + ]), + CaseItem(st(sFmaNorm), [ + If( + fmaWork[fw - 1], + then: [fmaWork < fmaShift(fmaWork), expR < expR + 1], + orElse: [ + If( + fmaWork[fw - 2] | ~fmaWork.or(), + then: [ + // Jam only AFTER cancellation: no product bit may be lost + // before its position in the final significand is known. + rw < + [ + fmaWork.slice(fw - 1, n + 1), + fmaWork.slice(n, 0).or(), + ].swizzle(), + state < sNorm, + ], + orElse: [ + fmaWork < [fmaWork.slice(fw - 2, 0), Const(0)].swizzle(), + expR < expR - 1, + ], + ), + ], + ), ]), CaseItem(st(sNorm), [ If( @@ -660,16 +804,10 @@ class IterativeFpArith extends Module { ]), CaseItem(st(sRound), [ resReg < mux(special, specialHold, packed), - // A fused multiply-add takes a second pass: the product goes - // back in as the left operand and c comes in as the right one. - If( - selFma & ~phase, - then: [phase < 1, state < sIdle], - orElse: [state < sDone], - ), + state < sDone, ]), CaseItem(st(sDone), [ - If(~start, then: [state < sIdle, phase < 0]), + If(~start, then: [state < sIdle]), ]), ]), ], diff --git a/packages/river_hdl/test/fpvector/fma_core_test.dart b/packages/river_hdl/test/fpvector/fma_core_test.dart new file mode 100644 index 0000000..aa93bda --- /dev/null +++ b/packages/river_hdl/test/fpvector/fma_core_test.dart @@ -0,0 +1,118 @@ +import 'package:river/river.dart'; +import 'package:rohd/rohd.dart'; +import 'package:test/test.dart'; + +import '../core_harness.dart'; +import 'fma_reference.dart'; + +void main() { + tearDown(Simulator.reset); + for (final microcoded in [false, true]) { + group(microcoded ? 'microcoded' : 'static', () { + final config = RiverCoreConfig( + clock: const HarborClockConfig( + name: 'test', + rate: HarborFixedClockRate(10000), + ), + mxlen: RiscVMxlen.rv64, + extensions: [ + rv32i, + rv64i, + rvZicsr, + rvPriv, + rvF, + rvD, + rvFExtra, + rvDExtra, + ], + interrupts: [], + microcodeMode: microcoded ? MicrocodeMode.full : MicrocodeMode.none, + mmu: HarborMmuConfig( + mxlen: RiscVMxlen.rv64, + pagingModes: const [RiscVPagingMode.bare], + tlbLevels: const [], + pmp: HarborPmpConfig.none, + ), + type: RiverCoreType.general, + ); + for (final witness in [ + ( + 'cancellation', + 0x3ff0000000000001, + 0x3feffffffffffffe, + 0xbff0000000000000, + ), + ( + 'product overflow', + 0x7fefffffffffffff, + 0x4000000000000000, + 0xffefffffffffffff, + ), + ('product underflow', 1, 0x3fe0000000000000, 1), + ]) { + group(witness.$1, () { + for (final form in [ + ('fmadd.d', 0x43, false, false), + ('fmsub.d', 0x47, false, true), + ('fnmsub.d', 0x4b, true, false), + ('fnmadd.d', 0x4f, true, true), + ]) { + test(form.$1, () async { + final words = [ + 0x000022b7, // lui x5, 2: mstatus.FS <- Initial + 0x30029073, // csrrw x0, mstatus, x5 + 0x20000093, // addi x1, x0, 0x200 + 0x0000b087, // fld f1, 0(x1) + 0x0080b107, // fld f2, 8(x1) + 0x0100b187, // fld f3, 16(x1) + (3 << 27) | + (1 << 25) | + (2 << 20) | + (1 << 15) | + (4 << 7) | + form.$2, + (0x71 << 25) | (4 << 15) | (10 << 7) | 0x53, // fmv.x.d x10, f4 + 0x00100593, // addi x11, x0, 1: completion sentinel + 0x0000006f, + ]; + final image = StringBuffer('@0\n'); + void emit(int bits, int bytes) { + for (var i = 0; i < bytes; i++) { + image.write( + '${((bits >> (8 * i)) & 0xff).toRadixString(16).padLeft(2, '0')} ', + ); + } + image.writeln(); + } + + for (final word in words) { + emit(word, 4); + } + image.writeln('@200'); + for (final operand in [witness.$2, witness.$3, witness.$4]) { + emit(operand, 8); + } + await coreTest( + image.toString(), + { + Register.x10: fusedBits( + witness.$2, + witness.$3, + witness.$4, + exponentBits: 11, + fractionBits: 52, + negateProduct: form.$3, + negateAddend: form.$4, + ), + Register.x11: 1, + }, + config, + nextPc: (words.length - 1) * 4, + ); + }, timeout: const Timeout(Duration(minutes: 5))); + } + }); + } + }); + } +} diff --git a/packages/river_hdl/test/fpvector/fma_reference.dart b/packages/river_hdl/test/fpvector/fma_reference.dart new file mode 100644 index 0000000..78ccdb3 --- /dev/null +++ b/packages/river_hdl/test/fpvector/fma_reference.dart @@ -0,0 +1,96 @@ +/// Exact IEEE binary fused multiply-add, rounded once to nearest/even. +/// Integer significands and powers of two avoid the host's separately rounded +/// `a * b + c` expression. Inputs/outputs are packed IEEE bit patterns. +int fusedBits( + int aBits, + int bBits, + int cBits, { + required int exponentBits, + required int fractionBits, + bool negateProduct = false, + bool negateAddend = false, +}) { + final width = 1 + exponentBits + fractionBits; + final signMask = BigInt.one << (width - 1); + final fractionMask = (BigInt.one << fractionBits) - BigInt.one; + final maxExponent = (1 << exponentBits) - 1; + final bias = (1 << (exponentBits - 1)) - 1; + ({bool negative, bool nan, bool inf, BigInt significand, int exponent}) + unpack(int bits) { + final raw = BigInt.from(bits).toUnsigned(width); + final exp = ((raw >> fractionBits) & BigInt.from(maxExponent)).toInt(); + final fraction = raw & fractionMask; + return ( + negative: (raw & signMask) != BigInt.zero, + nan: exp == maxExponent && fraction != BigInt.zero, + inf: exp == maxExponent && fraction == BigInt.zero, + significand: exp == 0 + ? fraction + : (BigInt.one << fractionBits) | fraction, + exponent: (exp == 0 ? 1 : exp) - bias - fractionBits, + ); + } + + final a = unpack(aBits), b = unpack(bBits), c = unpack(cBits); + final productSign = a.negative ^ b.negative ^ negateProduct; + final cSign = c.negative ^ negateAddend; + final infinity = BigInt.from(maxExponent) << fractionBits; + final nan = infinity | (BigInt.one << (fractionBits - 1)); + int bits(BigInt value) => value.toSigned(64).toInt(); + final invalidProduct = + (a.inf && b.significand == BigInt.zero) || + (b.inf && a.significand == BigInt.zero); + if (a.nan || + b.nan || + c.nan || + invalidProduct || + ((a.inf || b.inf) && c.inf && productSign != cSign)) { + return bits(nan); + } + if (a.inf || b.inf) + return bits(infinity | (productSign ? signMask : BigInt.zero)); + if (c.inf) return bits(infinity | (cSign ? signMask : BigInt.zero)); + final product = a.significand * b.significand; + final productExponent = a.exponent + b.exponent; + final common = productExponent < c.exponent ? productExponent : c.exponent; + final p = product << (productExponent - common); + final q = c.significand << (c.exponent - common); + final sum = (productSign ? -p : p) + (cSign ? -q : q); + if (sum == BigInt.zero) { + return bits( + product == BigInt.zero && + c.significand == BigInt.zero && + productSign && + cSign + ? signMask + : BigInt.zero, + ); + } + final sign = sum.isNegative ? signMask : BigInt.zero; + final magnitude = sum.abs(); + final leadingExponent = magnitude.bitLength - 1 + common; + final minQuantum = 1 - bias - fractionBits; + final normalQuantum = leadingExponent - fractionBits; + final quantum = normalQuantum < minQuantum ? minQuantum : normalQuantum; + final shift = quantum - common; + BigInt rounded; + if (shift <= 0) { + rounded = magnitude << -shift; + } else { + rounded = magnitude >> shift; + final remainder = magnitude - (rounded << shift); + final half = BigInt.one << (shift - 1); + if (remainder > half || (remainder == half && rounded.isOdd)) + rounded += BigInt.one; + } + if (rounded == BigInt.zero) return bits(sign); + final exponent = rounded.bitLength - 1 + quantum; + if (exponent > maxExponent - 1 - bias) return bits(sign | infinity); + if (exponent < 1 - bias) return bits(sign | rounded); + final significand = rounded >> (rounded.bitLength - 1 - fractionBits); + return bits( + sign | + (BigInt.from(exponent + bias) << fractionBits) | + (significand & fractionMask), + ); +} diff --git a/packages/river_hdl/test/fpvector/iterative_fp_arith_test.dart b/packages/river_hdl/test/fpvector/iterative_fp_arith_test.dart index 3dd8295..dea5029 100644 --- a/packages/river_hdl/test/fpvector/iterative_fp_arith_test.dart +++ b/packages/river_hdl/test/fpvector/iterative_fp_arith_test.dart @@ -6,8 +6,10 @@ import 'package:rohd/rohd.dart'; import 'package:river_hdl/src/core/iterative_fp_arith.dart'; import 'package:test/test.dart'; -/// [IterativeFpArith] against Dart's own arithmetic, which is IEEE binary64 -/// and is the model the emulator uses. +import 'fma_reference.dart'; + +/// Non-fused operations use Dart's IEEE arithmetic as their reference. FMA +/// uses exact integer arithmetic so the oracle does not round the product. /// /// The execution unit reads this core for fadd, fsub, fmul, fdiv and the four /// fused multiply-add forms, at both precisions, because a single-precision @@ -122,6 +124,111 @@ void main() { List fnmsub(int a, int b, int c) => [a, b, c, 1, 1, 0, 0, 0]; List fnmadd(int a, int b, int c) => [a, b, c, 1, 1, 1, 0, 0]; + for (final shape in [(8, 23, false), (11, 52, false), (11, 52, true)]) { + final (e, m, narrow) = shape; + final single = narrow || e == 8; + final eb = single ? 8 : 11; + final mb = single ? 23 : 52; + final directed = single + ? >[ + [0x3f800001, 0x3f7ffffe, 0xbf800000, 0xa8800000], + [0x7f7fffff, 0x40000000, 0xff7fffff, 0x7f7fffff], + [1, 0x3f000000, 1, 2], + [0x80000000, 0x40000000, 0x80000000, 0x80000000], + [0x7f800000, 0, 0x3f800000, 0x7fc00000], + ] + : >[ + [ + 0x3ff0000000000001, + 0x3feffffffffffffe, + 0xbff0000000000000, + 0xb970000000000000, + ], + [ + 0x7fefffffffffffff, + 0x4000000000000000, + 0xffefffffffffffff, + 0x7fefffffffffffff, + ], + [1, 0x3fe0000000000000, 1, 2], + [ + 0x8000000000000000, + 0x4000000000000000, + 0x8000000000000000, + 0x8000000000000000, + ], + [0x7ff0000000000000, 0, 0x3ff0000000000000, 0x7ff8000000000000], + ]; + test('single-rounding FMA e=$e m=$m narrow=$narrow', () async { + for (final row in directed) { + expect( + fusedBits(row[0], row[1], row[2], exponentBits: eb, fractionBits: mb), + row[3], + reason: 'independent exact cancellation/range/special witness', + ); + } + final rnd = math.Random(0xf00d); + int randomBits() => single + ? rnd.nextInt(1 << 32) + : (rnd.nextInt(1 << 32) << 32) | rnd.nextInt(1 << 32); + final triples = >[ + for (final row in directed) row.sublist(0, 3), + for (var i = 0; i < 128; i++) + [randomBits(), randomBits(), randomBits()], + ]; + // Cancellation exposes low product bits that broad random exponents + // rarely exercise. The rounded host product is only the input addend, + // never the expected fused answer. + for (var i = 0; i < 64; i++) { + final a = single + ? 0x3f800000 | rnd.nextInt(1 << 23) + : 0x3ff0000000000000 | (randomBits() & 0x000fffffffffffff); + final b = single + ? 0x3f800000 | rnd.nextInt(1 << 23) + : 0x3ff0000000000000 | (randomBits() & 0x000fffffffffffff); + final c = single + ? f32Bits(-bitsF32(a) * bitsF32(b)) + : f64Bits(-bitsF64(a) * bitsF64(b)); + triples.add([a, b, c]); + } + final jobs = >[]; + final expected = []; + for (final row in triples) { + for (final negateProduct in [false, true]) { + for (final negateAddend in [false, true]) { + jobs.add([ + row[0], + row[1], + row[2], + 1, + negateProduct ? 1 : 0, + negateAddend ? 1 : 0, + 0, + 0, + 0, + narrow ? 1 : 0, + ]); + expected.add( + fusedBits( + row[0], + row[1], + row[2], + exponentBits: eb, + fractionBits: mb, + negateProduct: negateProduct, + negateAddend: negateAddend, + ), + ); + } + } + } + final got = await run(jobs, exponentWidth: e, mantissaWidth: m); + for (var i = 0; i < got.length; i++) { + expect(got[i], expected[i], reason: 'FMA job $i: ${jobs[i]}'); + } + }, timeout: const Timeout(Duration(minutes: 10))); + } + List spread(math.Random rnd, int count) { final vals = [ 1.0, @@ -225,13 +332,41 @@ void main() { final bb = f64Bits(b); final cb = f64Bits(c); jobs.add(fmadd(ab, bb, cb)); - want.add(f64Bits(a * b + c)); + want.add(fusedBits(ab, bb, cb, exponentBits: 11, fractionBits: 52)); jobs.add(fmsub(ab, bb, cb)); - want.add(f64Bits(a * b - c)); + want.add( + fusedBits( + ab, + bb, + cb, + exponentBits: 11, + fractionBits: 52, + negateAddend: true, + ), + ); jobs.add(fnmsub(ab, bb, cb)); - want.add(f64Bits(-(a * b) + c)); + want.add( + fusedBits( + ab, + bb, + cb, + exponentBits: 11, + fractionBits: 52, + negateProduct: true, + ), + ); jobs.add(fnmadd(ab, bb, cb)); - want.add(f64Bits(-(a * b) - c)); + want.add( + fusedBits( + ab, + bb, + cb, + exponentBits: 11, + fractionBits: 52, + negateProduct: true, + negateAddend: true, + ), + ); } final got = await run(jobs, exponentWidth: 11, mantissaWidth: 52); for (var i = 0; i < jobs.length; i++) { @@ -494,9 +629,19 @@ void main() { jobs.add(divS(ab, bb)); want.add(f32Bits(a / b)); jobs.add(fmaddS(ab, bb, cb)); - want.add(f32Bits(a * b + c)); + want.add(fusedBits(ab, bb, cb, exponentBits: 8, fractionBits: 23)); jobs.add(fnmaddS(ab, bb, cb)); - want.add(f32Bits(-(a * b) - c)); + want.add( + fusedBits( + ab, + bb, + cb, + exponentBits: 8, + fractionBits: 23, + negateProduct: true, + negateAddend: true, + ), + ); } final got = await run(jobs, exponentWidth: 11, mantissaWidth: 52); for (var i = 0; i < jobs.length; i++) {