loader: native trampoline for VRSQRTPS under --amd-cpu #893

Manually merged
github merged 1 commit from gh-pr/893/head into gh-pr/893/base 2026-11-26 09:36:23 +00:00
Owner

@⁠ew-sudo on GitHub · 2026-09-28 20:40 UTC · original
ew-sudo:vrsqrtps-native → main · +519 −352 · 9 files · 1 commits · merged 2026-10-03 15:13 UTC

Description :

Problem

On Intel CPUs, Astro's Playroom (PPSA01325, v01.905, with the non-RT memory patch) crashes when loading Cooling Springs:

ASSERT: ...\engine\app\Module\Physics\PhysicsRigidBody.cpp:95
Assertion failed: !pos.IsNan()

It reproduced 2/2 at the same guest PC. With --amd-cpu (AMD-accurate VRSQRTPS emulation) the level loads and plays. So the NaN appears to come from the Intel/AMD difference in the VRSQRTPS approximation.

However, with --amd-cpu every VRSQRTPS goes through the illegal-instruction trap. I measured more than 1,000,000 traps per second in that level, which dropped it to about 7 FPS.

Change

When --amd-cpu is enabled, VRSQRTPS sites (VEX.128, register form, the same ones IsReciprocalSquareRoot already selects) are relocated into a native trampoline instead of being trapped. It uses the same relocation path as the red-zone patcher.

The trampoline computes exactly what ReciprocalSquareRoot() in x64InstructionEmulator.cpp computes:

  • 1/sqrt in double precision, rounded to float;
  • denormal inputs treated as zero (DAZ);
  • the guest MXCSR, including the sticky exception flags, is saved and restored;
  • RFLAGS is preserved (only LEA/MOV/SIMD instructions are used);
  • the upper YMM half of the destination is cleared, like the VEX.128 instruction.

Sites that cannot be relocated keep the existing trap path. KYTY_RSQRT_TRAP=1 forces the old trap path for A/B testing. At load time the log prints VRSQRTPS patching: found=…, native=…, trapped=….

Testing

  • Bit-exactness of the generated sequence was checked with a small standalone test harness (not included in this PR) against ReciprocalSquareRoot(): 36M random lanes including zeros, denormals, infinities, NaNs and negatives, several dst/src register combinations (including dst == src), 0 mismatches. It also checked that the upper YMM half is zeroed, the scratch register is preserved and MXCSR is unchanged.
  • Astro's Playroom, Cooling Springs, Core Ultra 7 155H + RTX 4070 Laptop, --redzone --amd-cpu:
    • trap path: about 7 FPS, >1M traps/s;
    • native trampoline: 14–20 FPS, trap count close to 0, no crash.

Note: the Playroom test build also included #839 (native EXTRQ trampolines); the log shows SSE4a EXTRQ native patching: found=96, patched=96 for this game. I have not tested this PR without #839. This PR itself does not depend on #839.

**@⁠ew-sudo** on GitHub · 2026-09-28 20:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/893) `ew-sudo:vrsqrtps-native` → `main` · +519 −352 · 9 files · 1 commits · merged 2026-10-03 15:13 UTC **Description :** ## Problem On Intel CPUs, Astro's Playroom (PPSA01325, v01.905, with the non-RT memory patch) crashes when loading Cooling Springs: ``` ASSERT: ...\engine\app\Module\Physics\PhysicsRigidBody.cpp:95 Assertion failed: !pos.IsNan() ``` It reproduced 2/2 at the same guest PC. With `--amd-cpu` (AMD-accurate VRSQRTPS emulation) the level loads and plays. So the NaN appears to come from the Intel/AMD difference in the VRSQRTPS approximation. However, with `--amd-cpu` every VRSQRTPS goes through the illegal-instruction trap. I measured more than 1,000,000 traps per second in that level, which dropped it to about 7 FPS. ## Change When `--amd-cpu` is enabled, VRSQRTPS sites (VEX.128, register form, the same ones `IsReciprocalSquareRoot` already selects) are relocated into a native trampoline instead of being trapped. It uses the same relocation path as the red-zone patcher. The trampoline computes exactly what `ReciprocalSquareRoot()` in `x64InstructionEmulator.cpp` computes: - 1/sqrt in double precision, rounded to float; - denormal inputs treated as zero (DAZ); - the guest MXCSR, including the sticky exception flags, is saved and restored; - RFLAGS is preserved (only LEA/MOV/SIMD instructions are used); - the upper YMM half of the destination is cleared, like the VEX.128 instruction. Sites that cannot be relocated keep the existing trap path. `KYTY_RSQRT_TRAP=1` forces the old trap path for A/B testing. At load time the log prints `VRSQRTPS patching: found=…, native=…, trapped=…`. ## Testing - Bit-exactness of the generated sequence was checked with a small standalone test harness (not included in this PR) against `ReciprocalSquareRoot()`: 36M random lanes including zeros, denormals, infinities, NaNs and negatives, several dst/src register combinations (including dst == src), 0 mismatches. It also checked that the upper YMM half is zeroed, the scratch register is preserved and MXCSR is unchanged. - Astro's Playroom, Cooling Springs, Core Ultra 7 155H + RTX 4070 Laptop, `--redzone --amd-cpu`: - trap path: about 7 FPS, >1M traps/s; - native trampoline: 14–20 FPS, trap count close to 0, no crash. > **Note:** the Playroom test build also included #839 (native EXTRQ trampolines); the log shows `SSE4a EXTRQ native patching: found=96, patched=96` for this game. I have not tested this PR without #839. This PR itself does not depend on #839.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:36:21 +00:00
github manually merged commit 01961b20f8 into gh-pr/893/base 2026-11-26 09:36:23 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 20:46 UTC · original · edited 2026-09-28 20:51 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The patch adds a native VEX sequence for VRSQRTPS that uses double-precision square root and division. It preserves RFLAGS and guest MXCSR, and saves and restores a temporary YMM register using stack storage. KYTY_RSQRT_TRAP selects the trap-emulation path when set. Patch reporting now separates native and trapped sites.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🔵 Low · up to bfe3e

The native path can produce misleading patch counts and fail an existing Windows test. Both issues are bounded, but should be corrected or explicitly accepted before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to bfe3e

Native execution is limited to selected instructions in loaded guest programs, and the trap fallback remains available. However, the new path relies on generated code preserving guest state, while its reported native-versus-trapped counts can misstate whether the fallback is in use.

Retained concerns

  • Low · reliability · inferred: Trap-only rollback can report a relocated, subsequently trapped site as native, obscuring which execution path is active.
Security review details

Security Blast Radius

  • inferred — A guest program can supply matching instructions and their register values. The native path can affect matching sites across that program’s executable segments in the host process, rather than an independently exposed service or tenant boundary.

Trust Boundaries and Controls

  • observed — Instruction decoding limits native selection, and unsuccessful relocation leaves a trap-patching route. The generated sequence saves guest-visible MXCSR and scratch-register state; complete behavioral parity with the trap handler is not established by the included source evidence.

Resilience and Maintainability Implications

  • inferred — The inaccurate native-versus-trapped count weakens observation of the trap-only rollback state, although it does not by itself show that the fallback stops functioning.

Hardening Proposals

  • proposed — Derive reporting from the execution mode of each relocated site, including trampoline trap patches, and retain reproducible native-versus-emulator checks for exceptional values and guest-state preservation.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: a native VRSQRTPS trampoline for the --amd-cpu path.
Description check ✅ Passed The description is directly related to the changeset. It explains the problem, implementation, configuration option, behavior, and testing results.
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.

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 help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 20:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/893#issuecomment-5878207419) · edited 2026-09-28 20:51 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/893?cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The patch adds a native VEX sequence for `VRSQRTPS` that uses double-precision square root and division. It preserves RFLAGS and guest MXCSR, and saves and restores a temporary YMM register using stack storage. `KYTY_RSQRT_TRAP` selects the trap-emulation path when set. Patch reporting now separates native and trapped sites. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"bfe3e0ddef6df2c17ba1789c9c6a04d076cbac3d" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `bfe3e` <!-- final_review_risk_coverage:{"sourceCommitId":"bfe3e0ddef6df2c17ba1789c9c6a04d076cbac3d","coveredCommitId":"bfe3e0ddef6df2c17ba1789c9c6a04d076cbac3d","kind":"reviewed"} --> The native path can produce misleading patch counts and fail an existing Windows test. Both issues are bounded, but should be corrected or explicitly accepted before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `bfe3e` Native execution is limited to selected instructions in loaded guest programs, and the trap fallback remains available. However, the new path relies on generated code preserving guest state, while its reported native-versus-trapped counts can misstate whether the fallback is in use. **Retained concerns** - **Low · reliability · inferred:** Trap-only rollback can report a relocated, subsequently trapped site as native, obscuring which execution path is active. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — A guest program can supply matching instructions and their register values. The native path can affect matching sites across that program’s executable segments in the host process, rather than an independently exposed service or tenant boundary. **Trust Boundaries and Controls** - _observed_ — Instruction decoding limits native selection, and unsuccessful relocation leaves a trap-patching route. The generated sequence saves guest-visible MXCSR and scratch-register state; complete behavioral parity with the trap handler is not established by the included source evidence. **Resilience and Maintainability Implications** - _inferred_ — The inaccurate native-versus-trapped count weakens observation of the trap-only rollback state, although it does not by itself show that the fallback stops functioning. **Hardening Proposals** - _proposed_ — Derive reporting from the execution mode of each relocated site, including trampoline trap patches, and retain reproducible native-versus-emulator checks for exceptional values and guest-state preservation. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 1 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: a native VRSQRTPS trampoline for the --amd-cpu path. | | Description check | ✅ Passed | The description is directly related to the changeset. It explains the problem, implementation, configuration option, behavior, and testing results. | | 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. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=893)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 20:46 UTC · original
On src/loader/redZonePatcher.cpp line 841 (outdated):

@@ -796,6 +835,10 @@ void CollectReciprocalSquareRoots(const DecodedFunction& function,
 		if (protect_red_zone) {
 			rewrite_sites[address].protect_red_zone = true;
 		}
+		static const bool trap_only = std::getenv("KYTY_RSQRT_TRAP") != nullptr;
+		if (!trap_only) {
+			rewrite_sites[address].emulate_rsqrt = true;
+		}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '2850,3000p' tests/VirtualMemoryAllocationTests.cpp
sed -n '810,875p' src/loader/redZonePatcher.cpp

Repository: KytyPS5/KytyPS5

Length of output: 9563


Update the reciprocal-square-root test contract for native patching.

On Windows, CollectReciprocalSquareRoots enables native relocation by default. The test still requires the relocated instruction to increment g_rsqrt_traps. The native path does not invoke ReciprocalSquareRootHandler, so the test can fail unless KYTY_RSQRT_TRAP is set.

The test must either select trap mode explicitly or assert the native and trapped paths separately.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 20:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/893#discussion_r4126867912) On `src/loader/redZonePatcher.cpp` line 841 (outdated): ```diff @@ -796,6 +835,10 @@ void CollectReciprocalSquareRoots(const DecodedFunction& function, if (protect_red_zone) { rewrite_sites[address].protect_red_zone = true; } + static const bool trap_only = std::getenv("KYTY_RSQRT_TRAP") != nullptr; + if (!trap_only) { + rewrite_sites[address].emulate_rsqrt = true; + } ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '2850,3000p' tests/VirtualMemoryAllocationTests.cpp sed -n '810,875p' src/loader/redZonePatcher.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 9563 --- </details> **Update the reciprocal-square-root test contract for native patching.** On Windows, `CollectReciprocalSquareRoots` enables native relocation by default. The test still requires the relocated instruction to increment `g_rsqrt_traps`. The native path does not invoke `ReciprocalSquareRootHandler`, so the test can fail unless `KYTY_RSQRT_TRAP` is set. The test must either select trap mode explicitly or assert the native and trapped paths separately. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4aa004deb0861f4501d1f2a5 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 20:46 UTC · original
On src/loader/redZonePatcher.cpp line 863 (outdated):

@@ -812,11 +855,18 @@ uint64_t ApplyReciprocalSquareRootPatches(const PatchModule& module,
 	}
 
 	uint64_t patched = 0;
+	uint64_t native  = 0;
 	for (const auto& site: sites) {
 		if (!module.patched.contains(reinterpret_cast<u8*>(site.address))) {
 			patched += X64InstructionEmulator::PatchReciprocalSquareRoots(site.address, site.length);
+		} else {
+			++native;

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '820,930p' src/loader/redZonePatcher.cpp
rg -n 'module\.patched|CollectReciprocalSquareRoots|RelocateRedZoneInstructions' src/loader/redZonePatcher.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5166


Count native generation, not relocation.

When KYTY_RSQRT_TRAP is set, red-zone protection can relocate a VRSQRTPS site without calling GenerateReciprocalSquareRoot. The relocation still follows the trap path, but ApplyReciprocalSquareRootPatches counts every address in module.patched as native. Track whether the relocation emitted GenerateReciprocalSquareRoot before reporting native and trapped.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 20:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/893#discussion_r4126867926) On `src/loader/redZonePatcher.cpp` line 863 (outdated): ```diff @@ -812,11 +855,18 @@ uint64_t ApplyReciprocalSquareRootPatches(const PatchModule& module, } uint64_t patched = 0; + uint64_t native = 0; for (const auto& site: sites) { if (!module.patched.contains(reinterpret_cast<u8*>(site.address))) { patched += X64InstructionEmulator::PatchReciprocalSquareRoots(site.address, site.length); + } else { + ++native; ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '820,930p' src/loader/redZonePatcher.cpp rg -n 'module\.patched|CollectReciprocalSquareRoots|RelocateRedZoneInstructions' src/loader/redZonePatcher.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5166 --- </details> **Count native generation, not relocation.** When `KYTY_RSQRT_TRAP` is set, red-zone protection can relocate a `VRSQRTPS` site without calling `GenerateReciprocalSquareRoot`. The relocation still follows the trap path, but `ApplyReciprocalSquareRootPatches` counts every address in `module.patched` as native. Track whether the relocation emitted `GenerateReciprocalSquareRoot` before reporting `native` and `trapped`. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:bde67d8fde3f6ba50aede448 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 20:46 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 8fd96e13-1b32-49d0-bf23-9a51a4ca1838

📥 Commits

Reviewing files that changed from the base of the PR and between 4b0de1b672 and bfe3e0ddef6df2c17ba1789c9c6a04d076cbac3d.

📒 Files selected for processing (1)
  • src/loader/redZonePatcher.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 20:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/893#pullrequestreview-5344430181) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `8fd96e13-1b32-49d0-bf23-9a51a4ca1838` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 4b0de1b67265069110492e5e1005d5c7635043a9 and bfe3e0ddef6df2c17ba1789c9c6a04d076cbac3d. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/loader/redZonePatcher.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.