feat(relinker): lower reciprocal approximations with measured Zen 2 tables #23747
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/23747"
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?
Imported from boykopovar/AnyPS5. Originally posted by adiologydev on 2026-11-19T15:36:47Z.
What
--to-intelreplaced (V)RCPPS, (V)RSQRTPS, (V)RCPSS and (V)RSQRTSS withDIVPS/SQRTPSstubs. Those stubs return correctly rounded results, not the AMD approximation, they set MXCSR status flags, and they raise #XM when an exception is unmasked. The 256-bit and memory forms kept the native instruction, so they gave the host's (Intel's) approximation.Now the stubs give the AMD result bit for bit:
codegen/src/x86/SharedStubData.cpp.tools/reciprocal-tables/measure.cppmakes them again on any x86-64 host (see Tested).ReciprocalLowering.cpp). It uses only integer operations: legacy SSE2/SSE4.1 encodings for legacy sites, and VEX.128 encodings for VEX sites, so AVX code pays no legacy-SSE penalty. VEX sites spill their scratch registers as full YMM registers. The 256-bit forms also usevextractf128/vinsertf128. It makes the table index, looks up each lane withpextrd/movzx/pinsrd, rebuilds the exponent, and selects the special cases with masks: zero/denormal, overflow, NaN, negative input and ±inf. RFLAGS and MXCSR do not change, and the stub cannot raise #XM, which is the same as the native instructions. Legacy SSE forms keep the destination's upper YMM bits. Memory operands are loaded without an alignment check, so a misalignedm128is read as in AMD's misaligned SSE mode; outside that mode, nativercpps/rsqrtpsraise #GP instead (checked on the Zen 2). VEX forms clear the upper bits.DecodeReciprocalnow decodes them). FS- and GS-prefixed memory forms stay native, because the guest TLS and GS handling owns them (the macOS writer rejects a trampoline over a guest GS or TLS access).StubRelocation::SharedDataand an optionalsharedDataAddressforApplyStubRelocations.LinuxElfPatcher,LinuxGuestModuleWriterandWindowsTrampolineBuilder(also used for macOS) write the tables and constants (24.8 KB) one time, before the first stub, and only when a stub refers to them.relinker.mdreciprocal entry. The PS5's own tables are not measured:Closes when: measured on a PS5.Tested
Debian Linux x86-64, AMD Ryzen 7 3700X (Zen 2), GCC 14.2, CMake 3.31, relinker-only build (
-DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON). I did not test on a title or on homebrew. PPSA21564 has not been run again.Tables, and how to make them again.
c++ -std=c++20 -O2 tools/reciprocal-tables/measure.cpp -o measure, then./measure --check core/relinker/codegen/src/x86/SharedStubData.cpp --verify.rcpss/rsqrtssat0x3F800000 | i << 11(RCP and RSQRT for odd exponents) and at0x40000000 | i << 11(RSQRT for even exponents), fori < 4096. It refuses a CPU whose entries do not have exponent 126 and 12 mantissa bits.--checkcompares the measured tables with the file.--verifytests the table model against the native instruction for all 2^32 inputs under MXCSR0x1F80,0x9FC0and0x7F80.AuthenticAMD family 0x17 model 0x71 stepping 0, AMD Ryzen 7 3700X. 12288 entries, 0 differ. 0 mismatches for every MXCSR value and both instructions.Exhaustive check against native instructions on that Zen 2. For each of the 2^32 inputs, it compares the output of the generated stub with native
rcpps/rsqrtps. The harness was a throwaway, not committed: it builds the stubs withMakeAmd64OnlyInstructionMatcher, places them withSharedStubData(), and runs them in OpenMP threads.Paired timing on the same machine (Zen 2 VM, pinned to one core, median of 5 runs, 20M calls each; the values include call/ret and loop overhead). It is the same benchmark built against
relinker_corefrommainand from this branch. Legacy sites run with clean upper YMM state, and VEX sites with dirty state, as in AVX code. Onmainthe VEX.256 forms were not lowered.mainstubThe
mainVEX.128 stub is slow because it ran legacy SSE while the upper YMM bits were dirty. On this host that costs about 60 ns per call: native legacyrcppstakes 63.7 ns after a VEX write and 1.4 ns aftervzeroupper. I did not usetools/trace_digest.pybecause I have no title to trace. These are microbenchmarks, not a speed claim.A table model against native
RCPSS/RSQRTSS, all 2^32 inputs: 0 mismatches under MXCSR0x1F80,0x9FC0and0x7F80. The packed and YMM lanes are equal to the scalar results.New
reciprocal_loweringtest, which runs on any x86-64 host, Intel CI included.vvvv,m32/m128/m256, and RSP-relative memory.End-to-end.
to_intel_linux_stubs(main executable) andguest_intel_trampolines_execution(guest module) run the real relinker with--to-intel. They check that the RCPPS/RSQRTPS site became a jump, and they call the converted code against Zen 2 values.windows_trampoline_builderchecks that the shared block starts.amdstub, that its relocation resolves, and that the block is absent when no stub uses it.VEX.L and VEX.W on scalar forms. The SDM encodes
VRCPSSandVRSQRTSSasVEX.LIG.F3.0F.WIG(rcpss, rsqrtss), andvvvvis thexmm2source. On the Zen 2,C5 E6 53 D5(L=1) andC4 E1 E6 53 D5(L=1, W=1) give the same results asC5 E2 53 D5. QEMU's Skylake model (Ubuntu 24.04qemu-user) raises SIGILL for them, so QEMU is stricter than the hardware here. The decoder accepts these forms, asmain'sVRSQRTSS ignores VEX.Ltest already expects.reciprocal_loweringruns them against the Zen 2 golden values.Misaligned
m128. On the Zen 2, native legacyrcpps/rsqrtpsraise #GP on a misalignedm128with the default MXCSR, and read it with MXCSR bit 17 (misaligned SSE mode,MXCSR_MASK 0x0002FFFF) set;movdqafaults in both modes. The stub now usesmovdqu.reciprocal_loweringruns[rax+4]and[rax+12]operands: the previous stub crashes on them (exit 139), and this one passes.Build procedure.
to_intel_linux_stubsandguest_intel_trampolines_executionrun$<TARGET_FILE:relinker>. Since6bf997882a, their test executables depend onrelinker, so building them also rebuilds it. Inubuntu:24.04/ GCC 13.3, withrelinkerbuilt atmainand then only the 5 review targets built at the PR head,d4c0520af3fails those 2 tests and6bf997882apasses all 6. The Python testguest_intel_trampolinesstill runs whicheverrelinkerexists, as all Python relinker tests do onmain; it has no reciprocal code.Host independence. Built in Docker
ubuntu:24.04with GCC 13.3.0, Ninja and Release, the 6 tests from the review pass.qemu-x86_64 -cpu Skylake-Client,reciprocal_lowering,windows_trampoline_builder,to_intel_linux_stubsandguest_intel_trampolines_executionpass. There, nativersqrtss(1.0)is0x3F800000, not the Zen 2 value0x3F7FF800.amd64_only_converter_testscrashes under QEMU onmainas well.main, with the message about the desktop Zen 2 results.Full relinker
ctest(rebased onmainatd8316aa43b): 1057 tests. The only failures are the 7shader_cache_runtime_sources*tests, which also fail onmainon this machine.Repository checks.
python3 tools/check_conventions.py --base origin/main: all checks passed.python3 tools/debt_fold.py --check: passed.python3 tools/pr_overlap.py --branch: no PR implements the same thing.APS5_RELINK_STUB_MAPprint next to theApplyStubRelocationscall inWindowsTrampolineBuilder.cpp. Several PRs edit the source lists incore/relinker/CMakeLists.txt.converterReciprocal().Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-19T15:40:46Z.
Review: CHANGES_REQUESTED
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against
c59121cfd9:tools/check_conventions.pypassed.amd64_only_converter_tests,guest_intel_trampolines_tests,reciprocal_lowering_tests,to_intel_linux_stubs_tests,windows_trampoline_builder_testsbuilt cleanly.reciprocal_lowering,amd64_only_converter,guest_intel_trampolines,windows_trampoline_builder,to_intel_linux_stubs,guest_intel_trampolines_execution):Requesting changes for the points above.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-19T16:57:50Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: prevent scalar VEX encodings from being decoded as packed operations when their mandatory
vvvv/width bits are invalid.What I ran
Reviewed head
c59121cfd93dc7eb3eff4e8fddb0018fe0417802. I read the prepared description, commit summary, manifest, diff, and targeted changed code and tests throughrepo_read.py. No build or test commands were run.Results
Negative control
Not run; no test was executed with an intentionally invalid VEX encoding.
Findings
Blocking
core/relinker/codegen/src/x86/ReciprocalOperands.cpp:68:vexScalaris inferred frompp == 2without checking thatL=0or that the scalar instruction'svvvvbits are valid. Thus an invalid VEX encoding ofRCPSS/RSQRTSScan be accepted and lowered as a real instruction. For example, a VEX scalar encoding withL=1is reserved, but the decoder passes it through because the packed-only validation is skipped wheneverpp == 2. Reject invalid scalar VEXLandvvvvfields before returning operands, and add decoder coverage for these malformed encodings.Non-blocking
None.
Not verified
No build or test suite was run, so the author-reported checks were not independently confirmed. The full changed-file set was not read; targeted reads covered
ReciprocalOperands.cpp,ReciprocalLowering.cpp,StubBodyBuilder.cpp,SharedStubData.cpptail, andReciprocalLoweringTests.cpp; other changed files and remaining diff sections were not inspected.files.jsonwas not available as a review document; the reader's file listing showed all changed files included.To get this to a good state
Reject reserved scalar VEX encodings and add regression tests for the invalid
Landvvvvcases. Then run the relevant decoder and reciprocal lowering tests on the new head.Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-19T21:25:04Z.
Review: CHANGES_REQUESTED
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against
99b3436032:tools/check_conventions.pypassed.amd64_only_converter_tests,guest_intel_trampolines_tests,reciprocal_lowering_tests,to_intel_linux_stubs_tests,windows_trampoline_builder_testsbuilt cleanly.reciprocal_lowering,amd64_only_converter,guest_intel_trampolines,windows_trampoline_builder,to_intel_linux_stubs,guest_intel_trampolines_execution):Requesting changes for the points above.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-19T21:29:34Z.
Review: DISMISSED
Reviewed — changes requested
Changes are required before merge: use an unaligned load for legacy packed memory operands, because the stub currently adds an alignment fault that the native instruction does not require.
What I ran
Reviewed head
99b3436032c76cee5374e1a58ab54fd68705a336using the prepared diff and repository reader. No commands or tests were run.Results
Findings
Blocking
core/relinker/codegen/src/x86/ReciprocalLowering.cpp:419loads a legacy packed memory operand withMOVDQA, which faults on a misaligned address.RCPPS/RSQRTPSmemory operands do not require 16-byte alignment, so these lowered instructions can fault where the original instruction succeeds. Use an unaligned load for this path and add a misaligned-memory case to the lowering tests.Non-blocking
None.
Not verified
Read the description, commits, manifest, prepared diff, and targeted code in
ReciprocalLowering.cpp,ReciprocalOperands.cpp,StubBodyBuilder.cpp,SharedStubData.cpp,LinuxElfPatcher.cpp, andWindowsTrampolineBuilder.cpp. The changed files were listed as included in the review bundle; the remaining changed source and test files were not read. No programmatic checks, builds, or tests were run. The author-reported test results were not independently verified.To get this to a good state
Replace the legacy packed
MOVDQAmemory load with an unaligned load and add coverage for misalignedm128input; rerun the reciprocal lowering and relevant end-to-end tests on the updated head.Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-20T11:04:19Z.
Review: CHANGES_REQUESTED
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against
d4c0520af3:tools/check_conventions.pypassed.amd64_only_converter_tests,guest_intel_trampolines_tests,reciprocal_lowering_tests,to_intel_linux_stubs_tests,windows_trampoline_builder_testsbuilt cleanly.reciprocal_lowering,amd64_only_converter,guest_intel_trampolines,windows_trampoline_builder,to_intel_linux_stubs,guest_intel_trampolines_execution):Requesting changes for the points above.
Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-20T11:27:00Z.
Review: APPROVED
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against
6bf997882a:tools/check_conventions.pypassed.amd64_only_converter_tests,guest_intel_trampolines_tests,reciprocal_lowering_tests,to_intel_linux_stubs_tests,windows_trampoline_builder_testsbuilt cleanly.reciprocal_lowering,amd64_only_converter,guest_intel_trampolines,windows_trampoline_builder,to_intel_linux_stubs,guest_intel_trampolines_execution):core/relinker/codegen/include/codegen/x86/Amd64OnlySubstitutionTypes.hpp,core/relinker/codegen/include/codegen/x86/ReciprocalOperands.hpp,core/relinker/codegen/include/codegen/x86/StubBodyBuilder.hpp,core/relinker/codegen/src/x86/ReciprocalLowering.cpp,core/relinker/codegen/src/x86/ReciprocalOperands.cpp,core/relinker/codegen/src/x86/StubBodyBuilder.cpp,core/relinker/elfpatcher/include/elfpatcher/linux/LinuxElfPatcher.hpp,core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp,core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp,core/relinker/elfpatcher/src/windows/WindowsTrampolineBuilder.cpp,core/relinker/codegen/src/x86/SharedStubData.cpp,tools/reciprocal-tables/measure.cppreverted tomain, the new tests do not build/link without the change; restoring it makes them build and pass.Looks Good To Me
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T11:35:47Z.
Review: COMMENTED
Reviewed — comments
The review is incomplete, so a formal merge decision is not justified.
What I ran
Inspected the prepared diff and selected source ranges at head
6bf997882aa8c9226b2e24355c1a82cdd14c7018; no build or tests were run.Results
Negative control
Not run; no tests were executed.
Findings
Blocking
None identified in the source ranges inspected.
Non-blocking
None.
Sources
Reviewed
review/description.md,review/commits.md,review/manifest.json, andreview/diff.patch, plus selected ranges ofReciprocalLowering.cpp,ReciprocalOperands.cpp,StubBodyBuilder.cpp,ReciprocalLoweringTests.cpp,LinuxElfPatcher.cpp,LinuxGuestModuleWriter.cpp, andWindowsTrampolineBuilder.cpp.Not verified
The review did not read every changed line or every changed file. In particular, the complete shared table data, remaining changed source and test files, and other changed files were not reviewed. No build, test, or runtime behavior was verified. The prepared bundle lists all changed files as included; no separate
files.jsonwas available in the reader listing.To get this to a good state
Nothing is required. Optional: complete the review of the remaining changed lines and run the relevant checks before making a formal merge decision.
Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T11:54:00Z.
Review: COMMENTED
Built this head with
ANYPS5_RELINKER_ONLY=ONand ranreciprocal_loweringandto_intel_linux_stubson Linux x86-64. Both passed. This run used the repository fixtures for the reciprocal approximation and the generated Linux stubs.AI-assisted: yes.
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.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.