perf(loader): binary-patch immediate SSE4a extrq/insertq to native stubs (D3D12-LOADER-PATCH-SSE4A) #3375
Code
Clone this repository
Checkout
From your project repository, check out a new branch and test the changes.
git fetch -u origin "github-pr/3375:github-pr/3375" git switch "github-pr/3375"
Open
leonida/mandy
Bilalatss wants to merge 1 commit from
github-pr/3375 into main
pull from: github-pr/3375
merge into: leonida:main
leonida:main
leonida:github-pr/3295
leonida:beta
leonida:docs/changelog-3483-3500
leonida:github-pr/3294
leonida:github-pr/2975
leonida:github-pr/2815
leonida:feat/gate-driver-start
leonida:feat/skip-pipelines-release
leonida:perf/lazy-compare
leonida:perf/mwaitx-wait
leonida:test/prio-ceiling-main
leonida:fix/ab-cpu-stdout
leonida:fix/gate-old-crashes
leonida:diag/ab-cpu
leonida:test/main-0312
leonida:github-pr/3291
leonida:diag/indirect-clamp-census
leonida:feat/barrier-enhanced
leonida:perf/texture-frame-ceiling
leonida:perf/dstorage-threads
leonida:fix/console-queue-dma-tables
leonida:fix/port-descriptors-record-parts
leonida:fix/frame-waits-fence
leonida:fix/console-sampler-words
leonida:fix/graphics-userdata-spill
leonida:fix/xg-reserved-layout-rotation
leonida:fix/barrier-console-flags
leonida:fix/switches-wait-test-child
leonida:test/list-value-waits
leonida:test/lot-gxdk-0412
leonida:fix/bvh-compacted-size
leonida:docs/i18n-quickstarts
leonida:feat/native-pipeline-slots
leonida:fix/clippy-leonida-gpu
leonida:fix/list-value-producers
leonida:fix/descriptor-page-straddle
leonida:fix/xmem-low-window
leonida:fix/ffx-jitter-never-zero
leonida:fix/run-stdout-closed
leonida:github-pr/2892
leonida:github-pr/2896
leonida:feat/warm-save-every
leonida:github-pr/2980
leonida:github-pr/2994
leonida:github-pr/3005
leonida:github-pr/3010
leonida:github-pr/3136
leonida:github-pr/3303
leonida:github-pr/3220
leonida:github-pr/3143
leonida:github-pr/3330
leonida:github-pr/3226
leonida:github-pr/3187
leonida:carry/3395
leonida:github-pr/2946
leonida:github-pr/2947
leonida:github-pr/2945
leonida:github-pr/2983
leonida:github-pr/3001
leonida:github-pr/3372
leonida:github-pr/3128
leonida:github-pr/3296
leonida:github-pr/2588
leonida:github-pr/3119
leonida:github-pr/3378
leonida:fix/crash-diagnostics
leonida:feat/dlss-mip-bias
leonida:fix/retired-out-of-order
leonida:fix/dxr-postbuild-barrier
leonida:fix/amd-relay-default
leonida:fix/removed-report-wait
leonida:feat/heap-twin
leonida:feat/vram-margin
leonida:github-pr/2472
leonida:github-pr/3123
leonida:github-pr/3088
leonida:assets/annonce-v1
leonida:github-pr/2794
leonida:github-pr/3300
leonida:github-pr/3304
leonida:github-pr/3308
leonida:github-pr/3367
leonida:github-pr/3369
leonida:fix/launcher-dlss-diagnostics
leonida:github-pr/3269
leonida:github-pr/2957
leonida:github-pr/3205
leonida:fix/crash-zero-guard
leonida:github-pr/3185
leonida:github-pr/3099
leonida:github-pr/3104
leonida:github-pr/3348
leonida:github-pr/3379
leonida:github-pr/3377
leonida:perf/darner-title-priority-ceiling
leonida:github-pr/3376
leonida:gh-readonly-queue/main/pr-3311-b5c45b663dbc5a9c3532bb3f307e5f81b32faefa
leonida:gh-readonly-queue/main/pr-3088-af22e7847ff5808f72d1a1881c24be2fafd20b54
leonida:gh-readonly-queue/main/pr-3123-7f3fa026a94c6646e89244f28e1ce22290361867
leonida:github-pr/3373
leonida:github-pr/3368
leonida:github-pr/3198
leonida:gh-readonly-queue/main/pr-3354-637baa0b77ba47222e7280b17c1a59c6a1781d57
leonida:gh-readonly-queue/main/pr-3365-d7a0e0196a43834813014b4bd3aa5502a8263b14
leonida:gh-readonly-queue/main/pr-3361-5dfe8bbd05ed12fb2f2e1718d9af77a7c5f46fd8
leonida:gh-readonly-queue/main/pr-3366-8da9148204e9d12c585efa9ac2b7cc1ab08c7682
leonida:github-pr/3346
leonida:github-pr/2958
leonida:github-pr/3151
leonida:github-pr/3307
leonida:github-pr/3278
leonida:github-pr/3374
leonida:fix/runtime-test-conservative-fixtures
leonida:github-pr/3366
leonida:ci/shard-semantic-linux
leonida:github-pr/3354
leonida:docs/fg-limit-fps-switch
leonida:github-pr/3365
leonida:fix/read-file-hard-link
leonida:github-pr/3364
leonida:fix/book-slot-heap-never-read
leonida:github-pr/3361
leonida:github-pr/3263
leonida:github-pr/3360
leonida:github-pr/3353
leonida:github-pr/3331
leonida:fix/alias-later-queued-submissions
leonida:github-pr/3352
leonida:github-pr/3228
leonida:github-pr/3349
leonida:claude/gallant-sagan-aamatr
leonida:github-pr/3200
leonida:github-pr/3132
leonida:github-pr/3323
leonida:github-pr/3332
leonida:github-pr/3340
leonida:github-pr/3311
leonida:github-pr/3334
leonida:github-pr/3297
leonida:github-pr/3256
leonida:github-pr/2567
leonida:github-pr/2851
leonida:d3d12/agility-sdk-621
leonida:github-pr/3164
leonida:github-pr/3114
leonida:github-pr/3050
leonida:github-pr/3113
leonida:github-pr/3326
leonida:github-pr/3144
leonida:github-pr/2642
leonida:github-pr/3072
leonida:github-pr/2789
leonida:github-pr/2643
leonida:github-pr/3009
leonida:github-pr/3035
leonida:github-pr/3031
leonida:github-pr/2686
leonida:github-pr/2834
leonida:github-pr/3321
leonida:github-pr/3325
leonida:github-pr/3290
leonida:github-pr/3324
leonida:github-pr/3130
leonida:claude/fervent-curie-m19lnr
leonida:github-pr/3309
leonida:github-pr/3305
leonida:github-pr/3306
leonida:github-pr/3302
leonida:github-pr/3301
leonida:github-pr/3345
leonida:github-pr/3211
leonida:github-pr/3027
leonida:github-pr/3286
leonida:github-pr/3235
leonida:github-pr/3265
leonida:github-pr/3275
leonida:codex/skip-no-hit-ray-passes
leonida:github-pr/2823
leonida:github-pr/2911
leonida:github-pr/3262
leonida:github-pr/3125
leonida:github-pr/3206
leonida:github-pr/3250
leonida:github-pr/3238
leonida:github-pr/3188
leonida:github-pr/2952
leonida:github-pr/3217
leonida:github-pr/3168
leonida:t3/preserve-fsr-sdk-restart-path
leonida:t3/propagate-host-failure-hresult
leonida:github-pr/3209
leonida:t3/launcher-custom-parameters
leonida:github-pr/3207
leonida:github-pr/3183
leonida:github-pr/3160
leonida:github-pr/3201
leonida:ci/less-to-run
leonida:github-pr/2930
leonida:github-pr/2797
leonida:github-pr/2999
leonida:perf/native-compute-shader-forms
leonida:github-pr/3191
leonida:github-pr/3011
leonida:github-pr/3019
leonida:github-pr/2996
leonida:gh-readonly-queue/main/pr-2789-45dc41f95c1cd0dcc29c2c50582e0e9af8a77259
leonida:claude/blissful-franklin-ukp7ag
leonida:github-pr/3141
leonida:github-pr/3156
leonida:github-pr/3150
leonida:github-pr/3153
leonida:github-pr/3163
leonida:github-pr/3142
leonida:github-pr/3139
leonida:github-pr/2841
leonida:github-pr/3069
leonida:github-pr/3098
leonida:github-pr/3107
leonida:github-pr/3071
leonida:github-pr/2774
leonida:github-pr/2889
leonida:github-pr/3075
leonida:github-pr/2661
leonida:github-pr/3064
leonida:github-pr/3054
leonida:github-pr/3049
leonida:github-pr/2855
leonida:github-pr/2943
leonida:github-pr/3016
leonida:github-pr/2887
leonida:github-pr/3006
leonida:github-pr/3003
leonida:github-pr/2993
leonida:notes/card-time-and-plant-flicker
leonida:github-pr/2989
leonida:feat/vulkan-rs
leonida:github-pr/2985
leonida:github-pr/2951
leonida:github-pr/2982
leonida:github-pr/752
leonida:github-pr/792
leonida:github-pr/2877
leonida:github-pr/2654
leonida:github-pr/2893
leonida:github-pr/2948
leonida:github-pr/2944
leonida:github-pr/2919
leonida:github-pr/2915
leonida:archive/ci/less-to-run/20261202T1121Z
leonida:github-pr/2800
leonida:github-pr/2822
leonida:github-pr/2833
leonida:github-pr/2840
leonida:github-pr/2831
leonida:github-pr/2832
leonida:github-pr/2801
leonida:github-pr/2890
leonida:github-pr/2891
leonida:github-pr/2664
leonida:github-pr/2807
leonida:rt-call-trace
leonida:github-pr/2755
leonida:perf/ahead-split
leonida:github-pr/2587
leonida:github-pr/2698
leonida:github-pr/2609
leonida:github-pr/3219
leonida:docs/readme-runtime-proposal
leonida:github-pr/2017
leonida:github-pr/1741
leonida:github-pr/1667
leonida:codex/coord-claim-check-20261124-7e48
No reviewers
Assignees
Clear assignees
No assignees
Labels
Clear labels
bug
Something isn't working
dependencies
Pull requests that update a dependency file
documentation
Improvements or additions to documentation
enhancement
New feature or request
missing claim
Needs a claim in #14
needs rebase
Conflicts with the base branch: rebase it on main
needs-triage
Needs maintainer evaluation before the next triage state
question
Further information is requested
ready-for-agent
Fully specified and ready for an AFK agent
submodules
Pull requests that update submodules code
No labels
bug
dependencies
documentation
enhancement
missing claim
needs rebase
needs-triage
question
ready-for-agent
submodules
Projects
Clear projects
No items
No project
Milestone
Clear milestone
No items
No milestone
Dependencies
No dependencies set
Notifications
2 participants
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".
No due date set.
Reference
leonida/mandy!3375
Loading…
Reference in a new issue
No description provided.
Delete branch "github-pr/3375"
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?
This branch is out-of-date with the base branch
Reviewers 0 approvals
Details
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Claimed in the coordination issue as: D3D12-LOADER-PATCH-SSE4A (https://github.com/ProjectLeonida/mandy/issues/3312#issuecomment-7386960124)
What and why
leonida-loader::console_insnalready binary-patches wait instructions (monitorx/mwaitx) andclzeroloops after their first#UDtrap, but still emulated immediate-form SSE4aextrq(66 0F 78) andinsertq(F2 0F 78) on every execution. On CPUs lacking AMD SSE4a (such as Intel), hot immediateextrq/insertqsites incur a Windows kernel/VEH exception round-trip on every hit and contend on the VEH lock withwatch's page-guard handler.This change:
SSE4A_STUBS(Vec<(usize, usize)>) andalloc_sse4a_stub(withFlushInstructionCacheand bidirectionaljmp rel32reach checks), leavingpatch_clzeroandSTUBSuntouched so there is zero overlap withD3D12-CLZERO-STUB-REGIONS.sse4a_stub,patch_slice, andpatch_sse4ato atomically patch 5..=16 byte immediateextrq/insertqinstructions inside a single 16-byte aligned block viacmpxchg16btojmp rel32+ trailing NOPs, using flag-free SSE2 / SSE4.1-gated fast paths and a flag-preserving general bit-field path matchingdecode::extrq/decode::insertq(including upper-64-bit zeroing andxmm0..xmm15).[u8; 16]stack buffer inemulate(avoiding&[u8]aliasing againstcmpxchg16b) and guards concurrent#UDfaults at the same site (compiler_fence(SeqCst)+patched_jump_to_sse4a_stub+PatchOutcome::AlreadyPatched) so racing threads resume cleanly atripinstead of crashing or misdecoding torn bytes across an 8-byte boundary.LEONIDA_PATCH_SSE4A=0opt-out (matchingLEONIDA_PATCH_CLZERO=0andLEONIDA_PATCH_WAITS=0) and regeneratesd3d12/docs/switches.mdwithtools/d3d12_switches.py.Tested
python -I scripts/check_no_game_data.py— passed (exit 0).python -I tests/test_d3d12_switches.py— 21/21 passed.python -I scripts/red_green.py perf/loader-patch-sse4a --base origin/main --no-fetch— verdict:red then green(exit 0):leonida_loader::console_insn::tests::sse4a_stubs_match_emulation_and_preserve_flags(red -> green; live-executes 21 cases acrossxmm0..xmm15,len=8/16/32/64,len=0withidx>0,fidx+flen==64, bit-63 crossing,dst==src,len/idx >= 64, EFLAGS and source XMM preservation, concurrent re-entry at a patched site, plus straddling-16B and 4-byte register-form unpatched edges)pass on both: 94(0 failures).cargo clippy -p leonida-loader --all-targets --no-deps --locked -- -D warnings— passed (0 warnings).cargo clippy -p leonida-loader --features diagnostics --all-targets --no-deps --locked -- -D warnings— passed (0 warnings).cargo build --workspace --all-targets --locked— passed.cargo build -p leonida --features diagnostics,mimalloc --locked— passed.cargo test -p leonida-loader --locked -- --test-threads=1— 95/95 passed (92 unit + 2load_probe+ 1title_dlls).cargo test -p leonida-loader --features diagnostics --locked -- --test-threads=1— 98/98 passed (95 unit + 2load_probe+ 1title_dlls).cargo test -p leonida-gpu --features diagnostics --test replay --locked— 1/1 passed (a_frame_is_recorded_and_replayed).GPUs tested: Profile M (desktop, 16 GB VRAM), NVIDIA GeForce RTX 5070 Ti, driver 621.47 (32.0.16.2147), Windows 11 Pro (10.0.26200) (for
replay;leonida-loadertests are CPU-only)AI-assisted: yes (authored with Gemini 4 Neon; audited by an independent read-only reviewer subagent using Gemini 4 Neon)
Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).docs/design.md, with how it was confirmed. (n/a — loader-only change)Ran natively on Windows 11, head
88c4db792merged into currentmain(0f0f268de, clean merge).The stubs are bit-exact. They matched
decode::extrq/decode::insertqin every case I ran, about 1.03 million, and on this machine they also matched the real instructions. Flags,raxand the other XMM registers came through unchanged, and the upper 64 bits were zeroed. Racing faults at one site always ended correctly. The one thing I found is small: every thread that loses the race still builds its own stub, and that stub is never used.The tests ran on a CPU with SSE4a, so the
#UDpath never fires there on its own. I droveemulatewith synthetic contexts, as the PR's test does, and ran the stubs and the original instructions natively from a harness.Your checks (measured)
cargo clippy -p leonida-loader --all-targets -- -D warnings--features diagnosticsrustfmt --checkonconsole_insn.rsmaineither (31 hunks). The merge has 52, so the PR adds about 21, all long lines in its new codecargo test -p leonida-loader --lib --locked, 4 threadsmain: 91 passed. Merge: 92 passed, the extra one beingsse4a_stubs_match_emulation_and_preserve_flags. With--features diagnostics: 95 passedLEONIDA_PATCH_SSE4A=0: 50/50Bit-exactness (throwaway harness, not in the PR). The harness loads all 16 XMM registers with random 128-bit values, sets random CF/PF/AF/ZF/SF/OF/DF with
popfqand a sentinel inrax, then runs three things on the same input: (a) the PR'ssse4a_stuboutput, reached byjmp rel32+ NOPs, (b) the original instruction run natively, and (c)decode::*. After each run it stores all 16 registers, the flags andrax. The seed is fixed.raxchangedlen0..63 ×idx0..63,extrq xmm3andinsertq xmm5, xmm9, 3 values eachdst×src0..15 forinsertq, everydstforextrq, 13 fields covering each path (16/32/8-bit aligned, 64@0,len=0,len=0withidx>0,idx+len=64,idx+len>64, 1@63)& 63matters), random values and flagslen=0is 64 in all three.idx+len=64is exact.idx+len>64is undefined per AMD. The stub gives what the emulator gives:extrqis a plain right shift byidx, andinsertqis the mask truncated at bit 63. The hardware here gave the same low qword in every case.pinsrb/pinsrdfast paths. The general-path fallback that those fields would take without SSE4.1 wasn't exercised. Other fields cover the general path.Concurrency (measured, throwaway tests)
emulateon the same unpatched site at once, behind a barrier. 50 sites, alternatinginsertq(general path) andextrqE9. In each round, 1 thread emulated and advancedripwith the right value, and the other 7 returnedCONTINUE_EXECUTIONwithripunchanged. 0 wrong. The patched site run natively afterwards gave the right resultemulate, 50 sitesraxstayed intact across the switch from instruction tojmpLEONIDA_PATCH_SSE4A=0, same 8-thread race, 10 sitesrip. No stub bytes usedLosing racers leak their stub. In the 8-thread race, the stub slab's used bytes grew by 13,824 for 50 sites. One stub per site would be about 2.4 KB: 64 B for the
insertqgeneral path and 32 B for thisextrq, after rounding to 16. So about 5–6 of the 8 racing threads each built a stub that nothing jumps to. From reading the code:patch_sse4acheckspatched_jump_to_sse4a_stub, then callsalloc_sse4a_stub, thenpatch_slice, and no lock covers the three. Each thread that faults before the winner'scmpxchg16blands builds and keeps a stub. The cost is bounded at one stub per racing thread per site, and it's only paid once per site, so it's cosmetic. HoldingPATCHING(or a per-site check underSSE4A_STUBS) across allocate-and-patch would close it. Alternatively, a losing thread could roll backusedif its stub is still the slab's last one.Read, not run
(at & 15) + insn_len > 16→Skipped). The PR's test covers this at offset 14. The 16-byte block never crosses a page, so a site near a page end is either patched within one page or skipped.near()probes 64 KBVirtualAllocs at 1 MB steps out to ±1.75 GB, so it never reserves a large range. If none is free, orjumpoverflows either way, the site isSkippedand emulated. One small leak: whennear()succeeds butbuildreturnsNone, the new 64 KB slab stays in the list unused. It gets reused for the next site in reach.PAGE_EXECUTE_READWRITEonly for thecmpxchg16b, then put back, and followed byFlushInstructionCache(unchanged frompatch). Stub slabs stay RWX for the life of the process, like the existingclzeroSTUBS.alloc_sse4a_stubflushes the stub before returning the jump.SSE4A_STUBSandPATCHINGare never held together.emulate, a re-read of*ripaftercompiler_fenceand beforedecode, relies on x86 not reordering loads with other loads, plus the single 16-byte atomic store. That reasoning holds. Thedecode→None→patched_jump_to_sse4a_stubfallback also covers it.rsp. A stack walk of a thread caught inside one would be wrong, the same as for theclzerostub. Nothing in the stub can fault except stack growth, which the kernel handles without unwinding.Conflicts. No other open PR touches
console_insn.rs. 45 open PRs touchswitches.md. Against this merge, 10 of them conflict (#3299, #3248, #3225, #3197, #3185, #3171, #3140, #3128, #3126, #3119), and all 10 already conflict withmain. This PR adds no conflicts.Not checked: the title, so no measured speedup, and no real
#UDon a CPU without SSE4a. That means the vectored-handler path end to end, including aCONTEXTcaptured by Windows rather than built by hand. The no-SSE4.1 fallback for 8/32-bit fields.--release. Slab exhaustion past 64 KB, where a second slab is used.GPUs tested: n/a (CPU-only tests).
AI-assisted: yes (Claude Code).
Independent local verification of this change (I changed no code).
e751a393, merge base61a0ea78. The new test is absent on the base:git grep -F sse4a_stubs_match_emulation_and_preserve_flags 61a0ea78 -- d3d12/crates/leonida-loader/src/console_insn.rs-> exit 1.cargo test -p leonida-loader --locked --lib console_insn::tests::sse4a_stubs_match_emulation_and_preserve_flags -- --exact-> 1 passed / 91 filtered, with a privateCARGO_TARGET_DIR.git diff --check 61a0ea78 e751a393-> clean.python -I scripts/check_no_game_data.py d3d12/crates/leonida-loader/src/console_insn.rs d3d12/docs/switches.md-> clean.GPUs tested: none (CPU-only emulation/stub comparison on synthetic instruction bytes; no device-gated test). Driver: n/a. No game data, assets or extracted shaders were used or attached.
AI-assisted: yes, Hy4 flash (verification only). No approval implied; this is a local test report.