Apply the AMD CPU patches automatically on hosts that lack the instructions #1439
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!1439
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/1439/head"
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?
@wuboo on GitHub · 2026-10-12 06:54 UTC · original
wuboo:pr/amd-cpu-auto→main· +1148 −30 · 15 files · 5 commits · closed without mergingProblem
The guest is built for an AMD CPU and uses SSE4a (
EXTRQ/INSERTQ), and sometimesRDPID/CLWB.Since
77680ce9("Make AMD CPU patch optional") the instruction patcher is off unless--amd-cpuisgiven. On a host without those instructions every one of them then raises
SIGILLand is emulated inthe signal handler. macOS under Rosetta 2 reports an Intel CPU without SSE4a, so on a Mac the default
run takes about 9,400 signals per frame in the scene measured below, and every one is a trap plus a
handler round trip. Nobody gets the patcher unless they know to ask for it, and in the launcher the
checkbox is hidden on macOS.
What this does
all three nothing changes from today (patcher off). The decision and its reason are logged once
("AMD CPU compatibility: patching on (auto: host lacks SSE4a), kinds=sse4a").
--amd-cpu= on, new--no-amd-cpu= off,KYTY_AMD_CPU=auto|0|1from the environment(a command line flag wins over the variable; an unparsable value is auto).
KYTY_AMD_PATCH=all|none|sse4a,rsqrt,cpuext.In auto the default is
sse4aonly;--amd-cpu(on) still rewrites everything, as before.VRSQRTPS(rsqrt) is opt-in. On Rosetta the patch leaves about 1,080 call sites that stilltrap (+551
SIGILLper frame measured), it measures slower than the nativersqrtpsRosettatranslates, and its result is an exact reciprocal square root where AMD hardware returns the
hardware approximation, so it is not a drop-in replacement.
RDPID/CLWB(cpuext) are opt-in as well.is saved as
amd_cpu_mode. A storedamd_cpu_modewins. An olderamd_cpu_enabled = truemaps toon; an older
amd_cpu_enabled = falsemaps to auto, not off, because the old defaultfalsewaswritten for every configuration whether or not the user ever touched the checkbox, so it records no
choice. A missing key is auto. The checkbox is no longer hidden on macOS.
The decision logic, the parsing and the launcher mapping are header-only (
src/common/amdCpuMode.h)so they can be tested without Qt or a guest.
Measurements
On macOS (Apple silicon, Rosetta 2), the same build, the level scene of one game, patcher off vs auto:
SIGILLhandled per frameThe level renders the same as a reference capture in both modes (checked on 8 runs with auto).
These are numbers from a local stack that carries other work as well; the patcher code is the same.
Tests
amd_cpu_mode(CPU, no guest): auto against injected CPUID results (each of SSE4a, RDPID, CLWBmissing on its own), flag / variable precedence, parsing,
KYTY_AMD_PATCHparsing and the per-modedefaults, mapping of stored launcher settings. 14 mutants (built at configure time) (the header is copied with one
edit into the build tree, so the sources carry no test hooks), each must fail the test.
amd_trampoline_bitexact(macOS x86-64 only, likemacos_sse4a): about 3.7MEXTRQ/INSERTQinputs (immediate and register forms, REX registers, source == destination) against a bit-by-bit
model of the AMD APM, state preservation of the
EXTRQtrampoline (upper YMM, rax/rcx/rdx, CF, redzone),
VRSQRTPSagainst the signal emulator, the hostrsqrtpsand an exactlong double, and theselection of kinds. 19 mutants of the patcher and the emulator are rejected.
ctestunchanged againstmain(tests that need a Vulkan loader skip without one).Not tested / limits
there is small (
configuration.{h,cpp},configurationEditDialog.cpp,mainDialog.cpp, the.uitooltip and label) and the mapping logic is in the tested header, but the Qt code has only been
read, not compiled; the CI launcher builds on Windows, macOS and Linux will be its first compile.
auto rule applies: an Intel host without SSE4a now gets the patcher by default (before: off, traps
emulated by the signal / exception handler). AMD hosts with SSE4a, RDPID and CLWB are unaffected.
SetGameSettings(the launcher's key-value interface) no longer knows the keyamd_cpu_enabled;amd_cpu_modereplaces it. Stored settings of the old key are still read.amd_cpu_mode_testsis built on every platform but, like the other tests, only runs where ctest isasked to; the CI test lists are unchanged.
The patcher rewrites three groups: sse4a (EXTRQ/INSERTQ), rsqrt (VRSQRTPS) and cpuext (RDPID/CLWB). KYTY_AMD_PATCH selects them: all, none, or a comma list. An unset or unparsable value keeps the default of the mode: - auto (default) rewrites sse4a only; - --amd-cpu (on) rewrites everything, as before. VRSQRTPS and RDPID/CLWB are therefore opt-in in auto. On Rosetta the VRSQRTPS patch leaves about 1079 call sites that still trap (+551 SIGILL per frame) and measures slower than the native rsqrtps Rosetta translates; its result is an exact reciprocal square root where AMD hardware gives the approximation, so it is not a drop-in replacement. The patcher takes the kinds mask and the loader logs it with the patching decision ("AMD CPU compatibility: patching on (...), kinds=sse4a"). amd_trampoline_bitexact_tests runs the patched code on the CPU: ~3.7M EXTRQ and INSERTQ inputs (immediate and register forms, REX registers, source == destination) against a bit-by-bit model of the AMD APM, EXTRQ state preservation (upper YMM, rax/rcx/rdx, CF, red zone), VRSQRTPS against the signal emulator, the host rsqrtps and an exact long double, and the kind selection. 19 mutants of the patcher and the emulator are rejected, plus 5 mutants of the parsing and defaults in amd_cpu_mode_tests.@coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 13:58 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
fe4ef0bf-b487-40bf-a209-1f6309dfe0a5📥 Commits
Reviewing files that changed from the base of the PR and between
30c4cba442and97660188db.📒 Files selected for processing (4)
CMakeLists.txtsrc/common/amdCpuMode.hsrc/launcher/src/configuration.cpptests/AmdCpuModeTests.cpp🚧 Files skipped from review as they are similar to previous changes (4)
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
📝 Walkthrough
Walkthrough
The change adds automatic, forced-on, and forced-off AMD CPU modes, with patch-kind selection from configuration or environment variables. The launcher stores and displays the mode and passes the corresponding command-line option. Runtime loading evaluates host CPU features and passes the selected patch kinds to the guest instruction patcher. New tests cover mode resolution, patch selection, instruction behavior, trampoline state, and VRSQRTPS results.
Priority: ➖ Normal
Change: Bug fix
Merge Risk: ⚪ Minimal · up to
97660The reviewed mode and patch-selection paths show no actionable merge-blocking issue; normal build and test checks remain appropriate.
Pre-merge checks |
4 |
1
❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 24.24% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 66 functions across 13 files. (1 skipped: 1 unsupported.)
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
Comment
@coderabbitai helpto get the list of available commands.@coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 10:17 UTC
On
src/common/amdCpuMode.hline 78 (outdated):🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
Auto mode enables patching even when the selected patch kinds cannot rewrite anything.
DecideAmdCpuenables the patcher when the host lacks any of SSE4a, RDPID or CLWB. The default patch kinds for auto mode contain onlyAmdPatchSse4a. Consider a host that supports SSE4a but lacks RDPID or CLWB, such as an older AMD CPU without CLWB. On that host, auto mode turns the patcher on. InCollectAmdInstructions,!host_features.sse4ais false, so no site is collected.For every module, the loader still allocates the 8 MiB trampoline area and decodes every function. On Windows,
analyze_red_zone |= emulate_amdalso runs red-zone liveness analysis. The log also says "patching on" even though nothing can change.Base the auto decision on the resolved patch kinds. Enable patching only when at least one selected kind targets an instruction that the host does not support.
♻️ Proposed change
The
AmdPatchKindenum must be declared beforeDecideAmdCpu.runtimeLinker.cppmust passConfig::GetAmdPatchKinds().✅ Addressed in commits
eaa8ecato30c4cba@ -33,2 +33,3 @@KYTY_CFG_SET(renderdoc_enabled);KYTY_CFG_SET(amd_cpu_enabled);values.insert(QStringLiteral("amd_cpu_mode"),QString::fromLatin1(Common::AmdCpuModeName(amd_cpu_mode)));@coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 10:15 UTC
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 6718
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 12664
Accept
amd_cpu_enabledas a legacy import key.GameSettings()now exports onlyamd_cpu_mode, but older exports containamd_cpu_enabled.SetGameSettingsrejects that key beforeReadGameSettingsValuescan apply its existing legacy mapping. This causes the complete import to fail withUnknown game setting: amd_cpu_enabled.Accept the legacy key without adding it to the canonical comparison. If
amd_cpu_modeis absent, remove the default mode before reading the legacy value sotruemaps toonandfalsemaps toauto.🐛 Suggested fix
✅ Addressed in commits
eaa8ecato30c4cba@ -1667,3 +1691,3 @@EXIT_IF(tls_handler_size > UINT64_MAX - program->base_size_aligned);program->mapped_size = program->base_size_aligned + tls_handler_size;const bool emulate_amd = Config::AmdCpuEnabled();const bool emulate_amd = AmdCpuPatchEnabled();@coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · edited 2026-10-12 10:16 UTC
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 1586
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 20917
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 43844
Keep auto AMD patching disabled on Windows until unrelocated sites have a safe path.
Auto mode enables patching when the host lacks SSE4a, and auto mode selects the SSE4a patch group. On Windows, an unrelocatable EXTRQ or INSERTQ site with a live red zone reaches
TrapUnrelocatedInstructions, which callsEXIT. This can terminate program loading instead of preserving the previous trap-handler path.Suggested fix
✅ Addressed in commits
eaa8ecato30c4cba@coderabbitai[bot] on GitHub · 2026-10-12 07:01 UTC · original · reviewed
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
92e8d3c3-d938-4d3b-b3ba-11bc4ae4ec31📥 Commits
Reviewing files that changed from the base of the PR and between
dad900c61dandd8c2f32991.📒 Files selected for processing (15)
CMakeLists.txtsrc/common/amdCpuMode.hsrc/common/emulatorConfig.cppsrc/common/emulatorConfig.hsrc/launcher/forms/configuration_edit_dialog.uisrc/launcher/include/configuration.hsrc/launcher/src/configuration.cppsrc/launcher/src/configurationEditDialog.cppsrc/launcher/src/mainDialog.cppsrc/loader/guestInstructionPatcher.cppsrc/loader/guestInstructionPatcher.hsrc/loader/runtimeLinker.cppsrc/main.cpptests/AmdCpuModeTests.cpptests/amdTrampolineBitExactTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@wuboo on GitHub · 2026-10-12 10:09 UTC · original
On
src/common/amdCpuMode.hline 78 (outdated):Good catch, fixed in
eaa8eca5.DecideAmdCpunow takes the resolved patch kinds: auto turns the patcher on only when the host lacks an instruction that a selected kind rewrites (SSE4a forsse4a, RDPID/CLWB forcpuext). With the default auto kinds (sse4a) a host that has SSE4a but no CLWB no longer pays for the trampoline area and the decode.runtimeLinker.cpppassesConfig::GetAmdPatchKinds(). TheAmdPatchKindenum moved above the function. Covered byamd_cpu_mode(new cases for each kind set) with the mutantskinds_sse4a_ignoredandkinds_cpuext_ignored.@ -33,2 +33,3 @@KYTY_CFG_SET(renderdoc_enabled);KYTY_CFG_SET(amd_cpu_enabled);values.insert(QStringLiteral("amd_cpu_mode"),QString::fromLatin1(Common::AmdCpuModeName(amd_cpu_mode)));@wuboo on GitHub · 2026-10-12 10:09 UTC · original
Valid, fixed in
30c4cba4.SetGameSettingsacceptsamd_cpu_enabled, does not compare it with the canonical values, and when the import has noamd_cpu_modeit drops the default mode so that the existing legacy mapping applies (true -> on, false -> auto). Caveat: the launcher needs Qt, which I could not build locally, so this hunk is compile-checked by reading only; the mapping itself (AmdCpuModeFromStored) is already covered byamd_cpu_mode.@ -1667,3 +1691,3 @@EXIT_IF(tls_handler_size > UINT64_MAX - program->base_size_aligned);program->mapped_size = program->base_size_aligned + tls_handler_size;const bool emulate_amd = Config::AmdCpuEnabled();const bool emulate_amd = AmdCpuPatchEnabled();@wuboo on GitHub · 2026-10-12 10:09 UTC · original
Agreed that auto must not make this reachable on Windows. The
EXITitself was already there for an explicit--amd-cpu, but auto would have started to hit it on every Intel Windows host. Fixed ineaa8eca5in a slightly different way than suggested:DecideAmdCpuhas anauto_allowedargument,runtimeLinker.cpppassesfalseon Windows, so auto stays off there (reason is logged) while--amd-cpu/KYTY_AMD_CPU=1still patches. Tests:amd_cpu_modewith the mutantauto_allowed_ignored. The Windows branch itself is not compiled here (macOS only).@ -131,2 +153,4 @@const auto canonical = GameSettings();for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {if (it.key() == QStringLiteral("amd_cpu_enabled")) {continue; // not exported any more, so there is nothing to compare it with@coderabbitai[bot] on GitHub · 2026-10-12 10:13 UTC · original · edited 2026-10-12 14:01 UTC
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 7562
Validate the legacy value before skipping its comparison.
SetGameSettingsaccepts any string foramd_cpu_enabled, removes the default mode when the legacy key is present alone, and skips that key during canonical-value comparison. An invalid value such as"banana"can therefore be converted totrueand selectOninstead of being rejected. Accept only the legacy export’s boolean strings before applying the legacy value.✅ Addressed in commit
9766018@coderabbitai[bot] on GitHub · 2026-10-12 10:13 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
d6238a25-0abd-4c89-b592-6258acb92d91📥 Commits
Reviewing files that changed from the base of the PR and between
d8c2f32991and30c4cba442.📒 Files selected for processing (5)
CMakeLists.txtsrc/common/amdCpuMode.hsrc/launcher/src/configuration.cppsrc/loader/runtimeLinker.cpptests/AmdCpuModeTests.cpp🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@ -33,2 +33,3 @@KYTY_CFG_SET(renderdoc_enabled);KYTY_CFG_SET(amd_cpu_enabled);values.insert(QStringLiteral("amd_cpu_mode"),QString::fromLatin1(Common::AmdCpuModeName(amd_cpu_mode)));@coderabbitai[bot] on GitHub · 2026-10-12 10:15 UTC · original
@wubooThanks for the fix. The suppliedSetGameSettingscode addresses all three parts of the finding and preserves the legacy mapping.The
amd_cpu_modetests cover the mapping helper, not the Qt import path. Launcher compilation remains unverified until CI builds it.If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@ -1667,3 +1691,3 @@EXIT_IF(tls_handler_size > UINT64_MAX - program->base_size_aligned);program->mapped_size = program->base_size_aligned + tls_handler_size;const bool emulate_amd = Config::AmdCpuEnabled();const bool emulate_amd = AmdCpuPatchEnabled();@coderabbitai[bot] on GitHub · 2026-10-12 10:16 UTC · original
@wubooThanks for the clarification. The suppliedruntimeLinker.cpppassesauto_allowed=falseon Windows. This addresses the finding by keeping auto patching off while preserving explicit force-on behavior.The reported
auto_allowed_ignoredmutant covers the decision logic. Windows compilation remains unverified, as you stated.✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-10-12 10:18 UTC · original
On
src/common/amdCpuMode.hline 78 (outdated):@wuboo, thanks for the fix ineaa8eca5. Passing the resolved patch kinds toDecideAmdCpuaddresses this finding. The new kind-specific tests and mutants cover the reported regression.If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@ -131,2 +153,4 @@const auto canonical = GameSettings();for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {if (it.key() == QStringLiteral("amd_cpu_enabled")) {continue; // not exported any more, so there is nothing to compare it with@wuboo on GitHub · 2026-10-12 13:54 UTC · original
Good catch, fixed in
97660188. The legacyamd_cpu_enabledvalue is now parsed by a newCommon::ParseLegacyAmdCpuEnabled()inamdCpuMode.h, andConfiguration::SetGameSettingsrejects the import with "Invalid value for game setting: amd_cpu_enabled" unless the string is exactlytrueorfalse(the only two forms the old export wrote). So"banana", an empty string,"1"or"True"can no longer be read astrueand selectOn. Covered byamd_cpu_mode(new checks fortrue,false,banana, empty,1,True) plus two mutants that must fail:LEGACY_ANY_TRUE(any text is true) andLEGACY_FALSE_DROPPED("false" is not a bool); both exit 1. Note that I could not build the Qt launcher locally (no Qt installed), so theSetGameSettingscall site is covered by review only; the parsing logic is covered by the unit test.@ -131,2 +153,4 @@const auto canonical = GameSettings();for (auto it = settings.constBegin(); it != settings.constEnd(); ++it) {if (it.key() == QStringLiteral("amd_cpu_enabled")) {continue; // not exported any more, so there is nothing to compare it with@coderabbitai[bot] on GitHub · 2026-10-12 14:01 UTC · original
@wubooThanks for the fix. The suppliedSetGameSettingscode validates the legacy value before applying settings or skipping canonical comparison. This addresses the finding.The reported parser tests cover the invalid strings and both valid values. The Qt launcher call site remains untested locally, as you noted.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@Nawid3333 on GitHub · 2026-10-27 20:57 UTC · original
I measured the boot cost of the patcher, since boot time is the reason given in #1196 for keeping
--amd-cpuopt-in. ASTRO BOT (PPSA21564) on mainffc81377, Ryzen 5 7600X, red-zone protection off, 3 runs each. Time from start untileboot.binis relocated:--amd-cpuSo
--amd-cpucosts about 7 s per boot for this game.eboot.binhas 312,697 functions. On this CPU only VRSQRTPS gets rewritten (9,679 native, 1,079 trapped): it has SSE4a, so the EXTRQ sites #839 found in this game aren't collected here.With the auto mode in this PR, a host that has SSE4a, RDPID and CLWB doesn't patch and keeps the 0.9 s. A host without SSE4a would pay a patching pass at boot instead of trapping every EXTRQ (#839 measured 810,000 traps/s in this game). I measured
--amd-cpuwith all groups, not this PR'ssse4a-only default, and not on an Intel CPU.Pull request closed