shader: emit legacy MADs without the optnone helpers on macOS (GTA V) #1521
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1521
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1521"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@AN0DIN on GitHub · 2026-10-15 07:18 UTC · original
AN0DIN:pr/shader/fused-mad-macos→main· +73 −0 · 3 files · 4 commits · openProblem
GTA V (PPSA04263 01.010.002) on an Apple M5 is GPU-bound at 19-23 fps at 1080p. A legacy MAD (
EmitFPMad32) isemitted as a multiply and an add decorated
NoContraction, so that the two roundings stay separate. SPIRV-Crosskeeps them apart in MSL with two calls to
[[clang::optnone]]helpers (spvFMul,spvFAdd; seeKhronosGroup/SPIRV-Cross#1999 and KhronosGroup/SPIRV-Cross#2156). The GTA V shaders I inspected hold 85 to 370 of
them per fragment shader, and on average about 90 per compute shader and 151 per vertex shader.
The helpers are there because the Metal compiler contracts a plain
a * b + cinto an FMA, even in safe math mode.#1304 by @carbonimax found the same cost and fused legacy MADs on Apple; it was closed without a review comment.
The first version of this PR fused them in pixel and compute shaders, which changed the last bit.
Change
#if defined(__APPLE__)), a legacy MAD is emitted asfma(a, b, -0.0) + cin every stage.fma(a, b, -0.0)is the product rounded once (-0.0keeps the sign of a zero product), then the add roundsagain. The Metal compiler does not contract this form, so the results stay those of the separate roundings,
without the helper calls.
shader_cfggains a test of the SPIR-V emitted for a MAD in compute, pixel, vertex and depth-exporting pixelshaders. The compute MAD tests keep their upstream expectations; on macOS only their
required_spirvchanges.Related open PRs: #1619 and #1622 also change
EmitFPMad32. The macOS path returns before the denormal flushes that#1619 adds, and #1622 changes the
NoContractiondecorations that the new test counts on other platforms. Whicheveris merged second needs a small adjustment; I can do it here.
Known limitation: this relies on the Metal compiler not turning
fma(a, b, -0.0)back into a plain multiply that itcould then contract. That holds for the compiler of macOS 26; the CI cannot check it.
Testing
macOS (Apple M5, 32 GB, macOS 26, x86_64 build under Rosetta 2, MoltenVK 1.4.2), this branch merged with current
main(02b17af3): build OK; ctest 14/14 (the macOS CI selection). Inshader_cfg(not in that selection) the newtest passes, fails when the macOS code path alone is compiled out ("compute shader MAD used the wrong rounding"),
and passes again with both
__APPLE__blocks (code and test) compiled out, as on other platforms.The program then stops at
TestGpuProducedWritableDescriptor, asmaindoes on this machine, with the same output;with that check skipped locally, every other check passes.
shader_recompiler_compute_testsbuilds but cannot runhere (MoltenVK has no 64-bit buffer/shared atomics). Among the upstream tests, only
VectorMadF32RoundsProductchecks the SPIR-V form of a MAD (its
required_spirv, changed on macOS); the others that use MADs check values.Outside the game, in Metal on the M5 (fast and safe math modes): over 2^20 random bit patterns plus signed zeros,
denormals, infinities, NaN and overflow,
fma(a, b, -0.0) + cgives the results of theoptnonehelpers, exceptfor the sign of a zero result when a negative denormal addend is flushed (116 to 140 of about 1.06 million
cases; the GPU flushes denormals in both forms). The inputs of
VectorMadF32RoundsProductandVectorMadF32FlushesDenormsgive the upstream expected values.In game: fixed script camera, 1080p, separate launches in the order A B B A, on my GTA V branch (upstream, the
patches the game needs on macOS, and other performance changes), so absolute fps depend on it.
So this version keeps the speed of the fused one in town. The results are those of the separate roundings (apart from
the zero sign case above), so I did not compare images again.
Windows / Linux: not tested locally; the change is under
#if defined(__APPLE__). On those platforms the newtest expects the separate roundings in all four cases.
AI assistance
An AI coding assistant (Claude Code) helped me find the cost in the generated MSL, test the Metal compiler outside
the game, write the change and the tests, run the measurements and draft this description. I reviewed the change
and this text.
@coderabbitai[bot] on GitHub · 2026-10-15 07:25 UTC · original · edited 2026-11-02 10:56 UTC
Findings
1fee7d46-2317-433d-ad42-45c9a39b4934Reviewing files that changed from the base of the PR and between
622448616canda9780f0d2d.src/graphics/shader/recompiler/backend/spirv/spirvEmitterAlu.cpptests/ShaderRecompilerComputeTests.cpptests/shaderCfgTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
Walkthrough
On Apple platforms,
EmitFPMad32computes the product withFma(a, b, -0.0)and adds the third operand throughEmitFPAdd32. Other platforms retain the separately rounded multiply and add path withNoContractiondecorations. Tests check platform-specific SPIR-V instruction expectations and instruction-count deltas across shader stages.Suggested reviewers:
nmzik,techx3Change: Bug fix
Merge Risk:
Moderate · up to
a9780Verify that a multiplied addend retains separate rounding on macOS before merging; otherwise affected shaders may produce different results.
Pre-merge checks:
5
Full details: Docstring Coverage
Explanation
No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 1 files. (2 skipped: 2 too large.)
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
@coderabbitai[bot] on GitHub · 2026-10-15 07:25 UTC · original · reviewed
🧹 Nitpick comments: 1
ℹ️ Review info
⚙️ Run configuration
65902959-453d-40dd-a98f-c5947d143d45📥 Commits
Reviewing files that changed from the base of the PR and between
9e41d8320aand15d889771e.📒 Files selected for processing: 2
src/graphics/shader/recompiler/backend/spirv/spirvEmitterAlu.cpptests/shaderCfgTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.
@coderabbitai[bot] on GitHub · 2026-10-15 07:25 UTC · original · edited 2026-10-17 07:38 UTC
On
src/graphics/shader/recompiler/backend/spirv/spirvEmitterAlu.cppline 118 (outdated):🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 25252
Guard pixel metadata access by shader stage.
ShaderStageInputInfois a union, so a non-nullinput_info.computealso makesinput_info.pixelnon-null. The current code readsps_depth_export_enablebefore checking the stage. For compute shaders, this treatsShaderComputeInputInfoasShaderPixelInputInfoand can read outside the compute object.Suggested fix
📝 Committable suggestion
✅ Addressed in commit
2e0630e@carbonimax on GitHub · 2026-10-15 15:21 UTC · original
Thanks for picking this up and for the measurements.
For context: #1304 was mine and was closed without review on 10/10. I'm fine with this PR replacing it.
Keeping separate rounding for vertex stages and depth-exporting pixel shaders makes sense to me. #1304 fused every stage; your split is the safer default, and your numbers show the cost sits in the pixel and compute shaders anyway.
LGTM from my side.
@xacrimon on GitHub · 2026-10-15 18:51 UTC · original
Apple has specific nonstandard pragmas to emit non fused math without these helpers FYI. that should bring the cost down while keeping precision. Might be worth just emitting those for metal targets instead.
@carbonimax on GitHub · 2026-10-15 22:23 UTC · original
Thanks, good pointer. I looked at what that would take with the SPIRV-Cross that MoltenVK bundles:
use_fast_math_pragmas(MSL 3.2+). It emits#pragma metal fp math_mode(...)and#pragma metal fp contract(...), but for the whole file:contract(off)as soon as one instruction lacks AllowContract.[[clang::optnone]]spvFMul/spvFAddhelpers are still emitted forNoContractionoperations whether or not the pragmas are on (has_legacy_nocontract), so enabling the option alone does not remove them.So the pragma route would mean a SPIRV-Cross change (plain
*/+when the file is compiled undercontract(off)) plus a MoltenVK switch, and the file-wide pragma would also stop contraction for the other multiply-adds in the shader. It keeps the separate rounding, which this PR gives up for pixel and compute shaders, so it could be worth measuring against theFmasplit here, but I'd see it as a follow-up in SPIRV-Cross/MoltenVK rather than a change to this PR.@Nmzik on GitHub · 2026-10-17 03:14 UTC · original
Latest Nvidia hardware 5000 series (5080) also has big perf hit with MAD
@AN0DIN on GitHub · 2026-10-17 08:05 UTC · original
Thanks for the reviews. Pushed
2e0630eand6224486:pixel member of
input_info. It is now read only for pixel shaders. The value was never used for the otherstages, so the emitted code does not change.
shader_cfgnow checks for GLSL.std.450Fmaitself, not just any extended instruction.on macOS. On macOS,
VectorMadF32RoundsProductnow expects the FMA result, and inVectorMadF32FlushesDenormsthe 2^-127 intermediate product of sample 3 is no longer flushed. So besides the last bit, a fused MAD also
keeps a denormal intermediate product. Other platforms are unchanged. I could not run these tests: the Vulkan
harness needs 64-bit buffer/shared atomics, which MoltenVK does not expose.
@Nmzik on the 5080: how much did the separate MAD rounding cost there? I kept this macOS-only on purpose. The cost
I measured comes from SPIRV-Cross, which turns each NoContraction multiply and add into calls to
[[clang::optnone]]helpers in MSL. Fusing on other platforms would also change the rounding these two testscheck for every title, so I'd leave that to a separate change measured on that hardware.
@xacrimon: thanks. As carbonimax found, SPIRV-Cross still emits the
optnonehelpers for NoContraction even withthe pragmas on, so that route needs a change there first. I'd keep it as a possible follow-up.
Tested on macOS (Apple M5, Rosetta 2, MoltenVK 1.4.2): build OK, ctest 14/14 (the macOS CI selection),
shader_cfgpasses,shader_recompiler_compute_testsbuilds. Not retested in game (same emitted code).Windows/Linux not tested locally.
@AN0DIN on GitHub · 2026-11-02 10:48 UTC · original
I reworked this PR in a new commit on top (
a9780f0, no rebase; it still merges cleanly withmain): it no longerfuses anything. On macOS, every legacy MAD, in every stage, is now emitted as
fma(a, b, -0.0) + c, so the resultsstay those of the separate roundings.
Why it works: the Metal compiler contracts a plain
a * b + cinto an FMA even in safe math mode, which is why theNoContraction pair needs the
[[clang::optnone]]helpers. It does not contractfma(a, b, -0.0) + c.fma(a, b, -0.0)is the product rounded once (-0.0keeps the sign of a zero product), and the add rounds again.Checked outside the game, in Metal on an Apple M5 (macOS 26 Metal compiler, fast and safe math modes):
spvFMul/spvFAddhelpers, except for the sign of a zero result when a negative denormal addend is flushed(116 to 140 of about 1.06 million cases; the GPU flushes denormals in both forms, so neither gives the IEEE
result there);
VectorMadF32RoundsProductandVectorMadF32FlushesDenorms: the upstream expected values, wherethe fused version gave
0xa8800000and0x00c00000. So the macOS-specific expectations are gone again. Onlyrequired_spirvdiffers on macOS (noOpFMuland noNoContractionthere). I still cannot run that harness onmacOS, because MoltenVK does not expose 64-bit buffer/shared atomics.
In game: GTA V on the same M5, 1080p, script camera at 11 places (about 25 s each), separate launches in the order
A B B A, all on my GTA V branch (so absolute fps depend on it):
So this version is as fast as the fused one in town, and faster than the previous version of this PR because the
vertex shaders (about 151 MADs each on average in GTA V) no longer call the helpers. I did not compare images: the
results are those of the separate roundings, apart from the zero sign case above.
shader_cfgnow expects, on macOS, oneFmaand oneFAddand noNoContractionper MAD in the four cases(compute, pixel, vertex, depth-exporting pixel). Elsewhere it expects the separate roundings, as before.
Known limitation: this relies on the Metal compiler not turning
fma(a, b, -0.0)back into a plain multiply thatit could then contract. That holds for the compiler of macOS 26 on this machine; the CI cannot check it.
When squashing, please keep only the message of
a9780f0: the three earlier commits describe the fused version.#1619 and #1622 also change
EmitFPMad32(the macOS path returns before #1619's denormal flushes; #1622 changesthe
NoContractiondecorations the new test counts elsewhere). Whichever is merged second needs a small adjustment;I can do it here.
Tested on macOS (Apple M5, x86_64 build under Rosetta 2, MoltenVK 1.4.2), this branch merged with current
main(
02b17af3): build OK; ctest 14/14 (the macOS CI selection); the newshader_cfgtest passes, fails when the macOScode path alone is compiled out, and passes again with both
__APPLE__blocks (code and test) compiled out. On thismachine
shader_cfgthen stops atTestGpuProducedWritableDescriptor, asmaindoes, and every other check passeswith that one skipped locally.
shader_recompiler_compute_testsbuilds.Windows/Linux: not tested locally; the change is under
#if defined(__APPLE__).@ -111,0 +117,4 @@// except for the sign of a zero result when the GPU flushes a negative denormal addend.const auto rounded_product =EmitGlsl<GLSLstd450Fma, IR::Type::F32>(state, a, b, ConstantF32(state, 0x80000000u));return EmitFPAdd32(state, rounded_product, c);@coderabbitai[bot] on GitHub · 2026-11-02 10:56 UTC · original
Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 23691
Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 12518
Web query:
SPIR-V NoContraction decoration floating-point contraction absent decoration specificationResult:
Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 12504
Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 3167
Preserve the rounded addend in the Apple MAD path.
EmitFPAdd32emits an undecoratedOpFAdd, so a precedingFPMul32used asccan be contracted with this add. That can replaceround(x * y) + round(a * b)withround(x * y + a * b). For example,x = y = 1.000244140625,a = -1, andb = 1.00048828125produce0with separate rounding but2^-24when thex * yproducer contracts with the add.Check the generated Metal code and this chained case under the supported compiler settings. Preserve the addend’s rounding without reintroducing the costly helper path.
@coderabbitai[bot] on GitHub · 2026-11-02 10:56 UTC · original · reviewed
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.