Skip to content

Compute paired FMA lanes in double on CPUs without FMA3 - #426

Merged
patchzyy merged 5 commits into
mainfrom
fix/v2-paired-fma-without-fma3
Nov 25, 2026
Merged

patchzyy merged 5 commits into
mainfrom
fix/v2-paired-fma-without-fma3

Conversation

@patchzyy

@patchzyy patchzyy commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Refs #374. This doesn't close it: I couldn't run the game on a CPU without FMA3, so I haven't confirmed this removes the whole 3.5 fps.

What

On x86-64-v2 builds, every ps_madd/ps_msub/ps_nmadd/ps_nmsub lane goes through std::fma(float). That's a CRT fmaf call, and on a CPU without FMA3 the CRT does it in software. The reporter in #374 has an i5-2500 (no FMA3), so Setup gives them the v2 build.

PpcFusedMultiplyAddFloatViaDoubleInline gets the same result in double instead. A float product is exact in double, so only the add rounds before the conversion to float. That double rounding only differs from the fused rounding when the double sum lands exactly on a float halfway point. Those sums go back to std::fma, along with:

  • results at or below FLT_MIN (the subnormal halfway point is at a different bit)
  • infinite and NaN operands (in double, 0*Inf or an sNaN conversion raises FE_INVALID, which fmaf(0, Inf, qNaN) doesn't)
  • subnormal operands (under DAZ the CRT's software fmaf doesn't zero them the way the double conversion does)

CPUs with FMA3 but not the rest of v3 (e.g. Piledriver) still get v2, so __builtin_cpu_supports("fma") keeps them on the CRT call, which uses the hardware instruction there. On glibc, FMA4 with AVX (first-gen Bulldozer) also keeps the call, since glibc dispatches fmaf to FMA4.

On v3, ps_msub/ps_nmsub now emit vfmsub213ps directly. Clang lowers _mm_fmsub_ps to an FMA with a negated addend, and with a constant NaN subtractor it folds that into vfmadd (or folds the whole result), which flips the NaN's sign.

The v2 lane path also stops negating a NaN subtractor before the FMA. ps_msub/ps_nmsub on v3 (vfmsub), the NEON path and Gekko return that NaN with its sign intact, but v2 flipped it.

Numbers

Measured on this machine with the shipped llvm-mingw, -march=x86-64-v2 -fno-fast-math -ffp-contract=off. _set_FMA3_enable(0) forces the CRT software path:

per ps_madd, 4096 independent lanes CRT fmaf via double
CRT FMA3 path 3.7 ns 4.5 ns (not used: dispatch keeps the CRT call)
CRT software path (no-FMA3 CPU) 52 ns 4.5 ns

__THPInverseDCTY8's loop body has 24 paired madd-family ops (48 lanes) and runs once per row-pair, per 8x8 block. That's why the menus with video previews are where this shows up. Issue #56 already shows those screens dropping to 30-40 fps on an FMA3 CPU.

Tests

mkw_ppc_pair_fma_{v2,v3}_tests now compare both the dispatched helper and the double path directly against std::fma, bit for bit:

  • a constructed halfway double-rounding case, normal and subnormal

  • a 16x16x16 edge-value grid

  • 2M random triples, half of them raw bit patterns

  • ps_madds0/ps_madds1 lane selection, signed zeros, and quiet and signaling NaNs in the paired ops

  • ps_msub/ps_nmsub on operands loaded at run time: result bits, FE_INVALID (clear for a quiet NaN subtractor, set for a signaling one) and a*c - b operand order

  • FE_INVALID parity with std::fma for invalid and NaN inputs (operands come from volatiles and the result goes to one, so Clang can't move the call past the flag checks)

Each runs with FTZ/DAZ off and on, and in the Windows v2 build also against the CRT's software fmaf (that pass skips signaling-NaN subtractors, since that fmaf returns them unquieted without FE_INVALID). Removing any one of the fallbacks, or the NaN-subtractor fix, makes the test fail. The header also compiles for the glibc branch (-D__GLIBC__=2, with and without -mfma4). Full platform suite: 28/28 pass.

The real THP shard compiles against this header for v2 and v3. In the v2 IDCT the lanes inline to cvtsd2ss, with fmaf left only on the fallback edges.

Not covered: scalar fmadd/fmadds also use CRT double fma on v2, which costs about 50 ns in software against 2 ns. Fixing that needs double-double arithmetic, so it's left for a separate change.

Summary by CodeRabbit

  • Bug Fixes
    • Improved the consistency of PowerPC single-precision fused multiply-add results across supported processor configurations.
    • Corrected edge-case handling for subnormal values, rounding boundaries, and exceptional results, including when flush-to-zero modes are enabled.
    • Improved paired single-precision multiply-add and multiply-subtract behavior for signed zero and NaN values, while retaining existing non-IEEE flushing behavior.
    • Improved handling of fused operations in cases involving cancellation and halfway rounding.

x86-64-v2 builds lower every ps_madd/msub/nmadd/nmsub lane to std::fma(float),
a CRT call. On a CPU without FMA3 the CRT does that in software: about 52 ns per
ps_madd here against 4.5 ns for the same result computed in double. THP decoding
runs dozens of these per 8x8 block, so menus with video previews suffer most.

The double path is bit-identical to std::fma. It hands halfway sums, results at
or below FLT_MIN, non-finite results and subnormal operands back to std::fma.
CPUs that have FMA3 but still get the v2 build keep the CRT call, which reaches
the hardware instruction there.
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The change adds float FMA helpers and runtime dispatch, routes paired-single lane operations through the dispatch, and adjusts x86-64 FMA subtract handling. Tests compare scalar and paired results with std::fma across rounding cases, exceptional values, randomized inputs, and runtime modes.

Changes: Float FMA

Layer / File(s) Summary
FMA implementation and paired-lane dispatch
runtime/include/isa/ppc_isa_float.h
Adds a double-based float FMA helper and dispatch based on x86-64 runtime FMA support. Paired-single lane helpers use the dispatch and preserve NaN signs for subtract forms. The x86-64 FMA subtract path uses vfmsub213ps inline assembly.
FMA accuracy and runtime-mode tests
runtime/tests/ppc_pair_fma_tests.cpp
Adds paired and scalar result and exception checks. Tests cover halfway rounding, exceptional values, deterministic randomized inputs, FTZ/DAZ modes, and Windows x86-64 FMA3 dispatch settings.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant LaneHelper as Paired-single lane helper
  participant Wrapper as PpcFusedMultiplyAddFloatInline
  participant DoubleHelper as Double-based FMA helper
  participant Fma as std::fma
  LaneHelper->>Wrapper: Evaluate lane FMA
  alt Runtime FMA unavailable
    Wrapper->>DoubleHelper: Evaluate selected inputs
    opt Input or result requires fallback
      DoubleHelper->>Fma: Evaluate float FMA
    end
  else Runtime FMA available or dispatch not used
    Wrapper->>Fma: Evaluate float FMA
  end
Loading

Suggested reviewers: darthmdev, theofficialgman

Merge Risk: Minimal · up to 5d21e

This change speeds up paired multiply-add lanes on CPUs without FMA3 and keeps results bit-identical to the reference fused operation. The supplied tests cover the edge cases that could differ. No merge-blocking issue was identified; the one gap is that the game has not been run on such a CPU.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Compute paired FMA lanes in double on CPUs without FMA3" matches the main change. The PR adds a double-precision path for paired multiply-add lanes on x86-64 builds without FMA3, with fallb…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Compute paired FMA lanes in double on CPUs without FMA3" matches the main change. The PR adds a double-precision path for paired multiply-add lanes on x86-64 builds without FMA3, with fallback to std::fma for edge cases. The title is specific and does not use vague terms.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 529d40a6-1bab-40dc-b6b2-26493ce95418
Commits

Reviewing files that changed from the base of the PR and between f7a0ba3 and 5d21e5d.

Files selected for processing: 2

  • runtime/include/isa/ppc_isa_float.h
  • runtime/tests/ppc_pair_fma_tests.cpp
Files skipped from review as they are similar to previous changes: 2

  • runtime/include/isa/ppc_isa_float.h
  • runtime/tests/ppc_pair_fma_tests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Non-finite operands now go straight to std::fma. Evaluating 0*Inf or converting
an sNaN in double raised FE_INVALID where fmaf(0, Inf, qNaN) does not.

On glibc, a CPU with FMA4 and AVX keeps the fmaf call, because glibc already
dispatches it to the FMA4 instruction (first-gen Bulldozer).

A NaN subtractor is no longer negated before the lane fma. x86 vfmsub on the v3
path, the NEON path and Gekko return it with its sign intact; v2 flipped it.

The tests also cover ps_madds0/ps_madds1, signed zeros, quiet and signaling
NaNs, and FE_INVALID parity. That check reads its operands from volatiles and
stores the result to one, so Clang cannot move the call past the flag calls.
Clang lowers _mm_fmsub_ps to an fma with a negated addend. With a constant NaN
subtractor it folds the negation into the constant and emits vfmadd, or folds
the whole result, flipping the NaN sign that vfmsub keeps. The Linux and Intel
macOS host jobs failed mkw_ppc_pair_fma_v3_tests on exactly that.

The tests now also run ps_msub/ps_nmsub on operands loaded at run time. They
check the result bits and FE_INVALID (clear for a quiet NaN subtractor, set for
a signaling one) and the a*c - b operand order. The CRT software fmaf pass only
runs where std::fma is actually a CRT call, and it skips the signaling cases,
because that fmaf returns sNaNs unquieted and raises nothing.
Plain asm let the compiler merge two identical ps_msub calls across an MXCSR
write, so a result computed before DAZ came on was reused after it. It could
also drop an unused vfmsub along with its FE_INVALID. The asm is now volatile
with a memory clobber; the real THP IDCT functions keep the same instruction
count. A new test runs the same ps_msub on both sides of MkwApplyHostNiMode and
expects FLT_MIN then 0. It covers only the asm path: v2 lanes are ordinary
std::fma, which the compiler may move across MXCSR writes like every other FP
operation in translated code.

The Windows v2 test assumed the CRT starts with FMA3 enabled. On a CPU without
FMA3 it starts in software mode, and the default pass then expected hardware
sNaN handling. The test now reads _get_FMA3_enable() and only forces the
software pass when the CRT started with FMA3, restoring the initial state after.
@patchzyy
patchzyy merged commit 4721944 into main Nov 25, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant