runtime(cpu): add ahead-of-time AVX1/SSE4.2 stub compiler for pre-Haswell hosts #2414

Open
github-bot wants to merge 7 commits from github-bot/gh-2414 into main AGit
Owner

@⁠robot00f on GitHub · 2026-11-26 23:57 UTC · original
robot00f:feat/rt-cpu-avx1-aot-patch → main · +4987 −0 · 10 files · 7 commits · open

Claimed in the coordination issue as: RT-CPU-AVX1-AOT-PATCH (#1608)

Depends on: #2190, #2191

What and why

While #2190 and #2191 enable pre-Haswell AVX1 + SSE4.2 hosts (Intel Sandy Bridge and Ivy Bridge) to execute BMI1, BMI2, MOVBE, F16C, FMA3 and AVX2 instructions via #UD (STATUS_ILLEGAL_INSTRUCTION), each #UD round-trip through KiUserExceptionDispatcher costs ~4,000–6,000 cycles, stalling hot decompression and SIMD loops.

Add runtime/src/isa_jit_patch.h and wire it into Loader::protect_sections (runtime/src/pe_loader.cpp) before executable sections are write-protected (LEONIDA_ISA_PATCH=0 disables it):

  • Same-length in-place AVX1 VEX rewrites (zero stub overhead): rewrites bit-identical 256-bit vpand/vpandn/vpor/vpxor (-> vandps/vandnps/vorps/vxorps), vextracti128/vinserti128/vperm2i128 (-> *f128), vbroadcasti128 m128 (-> vbroadcastf128), vpblendd (-> vblendps), vpbroadcastd m32 (-> vbroadcastss), and vpbroadcastq ymm, m64 (-> vbroadcastsd).
  • Out-of-line native x86-64 + AVX1 stubs (jmp rel32 within ±2 GiB):
    • >=5-byte BMI1, BMI2, and MOVBE sites compile to native GPR sequences preserving or computing exact architectural RFLAGS (including [rsp + disp] stack adjustments, [rip + disp32] relocation, rcx/rax/rdx register-aliasing handling, and 16-bit movbe).
    • >=5-byte AVX2 and FMA3 sites compile to native AVX1 (YMM + 2x128-bit XMM via vextractf128/vinsertf128, flag-preserving lea rsp, [rsp ± N] scratch spills, and upper-128 zeroing on scalar FMA3).
    • 4-byte 0xC5 AVX2 sites fuse forward with the immediately following instruction when a whole-module target scan (exports, relocations, .pdata unwind scopes, data/gap RVA tables, and direct branches) confirms the interior boundary is never targeted.
  • Any unpatched site (F16C, vpmaskmov*, pdep/pext, unfusable 4-byte sites) stays intact and falls back cleanly to #UD emulation (#2190, #2191). Zero changes to cpu_emulation.h.

Tested

  • Built and ran ctest -R "^(isa_jit_patch|bmi_emulation|avx2_emulation|pe_loader)$" live on an Intel Core i7-2600 (Sandy Bridge, AVX1 + SSE4.2, bmi1=0 bmi2=0 movbe=0 avx2=0 fma=0 f16c=0, Windows 10 19045):
    • isa_jit_patch_test: 45 instruction families × 8 randomized GPR/YMM/RFLAGS trials + 2 fused 4B+6B / 4B+8B RIP-relative pairs + synthetic PE32+ image test (in-place rewrites, BMI/AVX2/FMA3 stubs, unmarked 4B fusion, RVA-table fusion refusal, and LEONIDA_ISA_PATCH=0), all executing with 0 #UD traps and exact state parity.
  • python -I tests/test_ctest_registration.py, python -I tests/test_docs_env_vars.py, test_docs_links.py, test_docs_repo_paths.py, test_text_write_line_endings.py, and python -I scripts/check_no_game_data.py: all clean.

GPUs tested: n/a (CPU runtime; tested on Intel Core i7-2600, Sandy Bridge, AVX1 + SSE4.2, Windows 10 19045)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a — x86-64 CPU runtime only)
**@⁠robot00f** on GitHub · 2026-11-26 23:57 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2414) `robot00f:feat/rt-cpu-avx1-aot-patch` → `main` · +4987 −0 · 10 files · 7 commits · open Claimed in the coordination issue as: RT-CPU-AVX1-AOT-PATCH (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608) Depends on: #2190, #2191 ### What and why While #2190 and #2191 enable pre-Haswell `AVX1 + SSE4.2` hosts (Intel Sandy Bridge and Ivy Bridge) to execute `BMI1`, `BMI2`, `MOVBE`, `F16C`, `FMA3` and `AVX2` instructions via `#UD` (`STATUS_ILLEGAL_INSTRUCTION`), each `#UD` round-trip through `KiUserExceptionDispatcher` costs ~4,000–6,000 cycles, stalling hot decompression and SIMD loops. Add `runtime/src/isa_jit_patch.h` and wire it into `Loader::protect_sections` (`runtime/src/pe_loader.cpp`) before executable sections are write-protected (`LEONIDA_ISA_PATCH=0` disables it): - **Same-length in-place `AVX1` VEX rewrites (zero stub overhead):** rewrites bit-identical 256-bit `vpand`/`vpandn`/`vpor`/`vpxor` (`-> vandps`/`vandnps`/`vorps`/`vxorps`), `vextracti128`/`vinserti128`/`vperm2i128` (`-> *f128`), `vbroadcasti128 m128` (`-> vbroadcastf128`), `vpblendd` (`-> vblendps`), `vpbroadcastd m32` (`-> vbroadcastss`), and `vpbroadcastq ymm, m64` (`-> vbroadcastsd`). - **Out-of-line native `x86-64` + `AVX1` stubs (`jmp rel32` within `±2 GiB`):** - `>=5`-byte `BMI1`, `BMI2`, and `MOVBE` sites compile to native GPR sequences preserving or computing exact architectural `RFLAGS` (including `[rsp + disp]` stack adjustments, `[rip + disp32]` relocation, `rcx`/`rax`/`rdx` register-aliasing handling, and 16-bit `movbe`). - `>=5`-byte `AVX2` and `FMA3` sites compile to native `AVX1` (`YMM` + `2x128`-bit `XMM` via `vextractf128`/`vinsertf128`, flag-preserving `lea rsp, [rsp ± N]` scratch spills, and upper-128 zeroing on scalar `FMA3`). - `4`-byte `0xC5` `AVX2` sites fuse forward with the immediately following instruction when a whole-module target scan (exports, relocations, `.pdata` unwind scopes, data/gap RVA tables, and direct branches) confirms the interior boundary is never targeted. - Any unpatched site (`F16C`, `vpmaskmov*`, `pdep`/`pext`, unfusable 4-byte sites) stays intact and falls back cleanly to `#UD` emulation (#2190, #2191). Zero changes to `cpu_emulation.h`. ### Tested - Built and ran `ctest -R "^(isa_jit_patch|bmi_emulation|avx2_emulation|pe_loader)$"` live on an **Intel Core i7-2600** (Sandy Bridge, `AVX1 + SSE4.2`, `bmi1=0 bmi2=0 movbe=0 avx2=0 fma=0 f16c=0`, Windows 10 `19045`): - `isa_jit_patch_test`: 45 instruction families × 8 randomized GPR/YMM/`RFLAGS` trials + 2 fused `4B+6B` / `4B+8B` RIP-relative pairs + synthetic `PE32+` image test (in-place rewrites, BMI/AVX2/FMA3 stubs, unmarked 4B fusion, RVA-table fusion refusal, and `LEONIDA_ISA_PATCH=0`), all executing with `0` `#UD` traps and exact state parity. - `python -I tests/test_ctest_registration.py`, `python -I tests/test_docs_env_vars.py`, `test_docs_links.py`, `test_docs_repo_paths.py`, `test_text_write_line_endings.py`, and `python -I scripts/check_no_game_data.py`: all clean. GPUs tested: n/a (CPU runtime; tested on Intel Core i7-2600, Sandy Bridge, AVX1 + SSE4.2, Windows 10 19045) AI-assisted: yes ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [x] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a — x86-64 CPU runtime only)
Add runtime/src/bmi_emulation.h and wire it into gta6rt and Loader::protect_sections
so pre-Haswell AVX1 + SSE4.2 CPUs (Intel Sandy Bridge and Ivy Bridge) can execute
the game's integer Haswell/ABM instruction delta:

- Decode and emulate VEX-encoded BMI1 (andn, bextr, blsi, blsmsk, blsr), BMI2
  (bzhi, mulx, pdep, pext, rorx, sarx, shlx, shrx), and legacy 16/32/64-bit MOVBE
  on STATUS_ILLEGAL_INSTRUCTION (#UD), using SEH-guarded non-inlined __movsb copies
  so valid pages take zero syscalls while xmem first-touch, write-watched shadow
  pages, read-only faults and unmapped faults behave like native accesses.
- Patch non-faulting legacy TZCNT (F3 0F BC) and LZCNT (F3 0F BD) before executable
  sections are protected by walking .pdata functions and 0xCC-delimited leaf
  routines: >=5-byte 32/64-bit register sites jump to branchless BSF/BSR + CMOV +
  BT stubs within 2 GiB, and 4-byte, 16-bit or memory sites become UD2 (0F 0B)
  backed by a side-table for the #UD handler (configurable via LEONIDA_LZCNT_PATCH).
- Add runtime/test/bmi_emulation_test.cpp covering decoding, synthetic CONTEXT
  application, immediate byte-trap rejection, stub/UD2 flag consumers, and live
  execution on hardware.

Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
Add runtime/src/avx2_emulation.h and wire it into gta6rt so pre-Haswell AVX1 +
SSE4.2 CPUs (Intel Sandy Bridge and Ivy Bridge) can execute the game's vector
Haswell instruction delta using the host's native 256-bit YMM0..YMM15 state:

- Read and write 256-bit YMM registers through CONTEXT::FltSave.XmmRegisters
  (bits [127:0]) and LocateXStateFeature(XSTATE_AVX) (bits [255:128]), zeroing
  YMM[dst][255:128] on every 128-bit VEX register write and zero-initializing
  untouched upper lanes when transitioning XSTATE_MASK_AVX from clean (0).
- Emulate F16C (vcvtph2ps, vcvtps2ph with RN/RD/RU/RZ and MXCSR rounding), all
  60 FMA3 forms (132/213/231 packed 128/256, scalar ss/sd preserving [127:32] /
  [127:64], and alternating fmaddsub/fmsubadd) via single-rounding std::fmaf /
  std::fma, and AVX2 (256-bit integer SIMD promotions, register/memory
  vbroadcastss/sd/i128 and vpbroadcastb/w/d/q, vinserti128, vextracti128,
  vperm2i128, vpermq, vpermpd, vpermd, vpermps, vpblendd/w/vb, vpsllv*/vpsrlv*/
  vpsravd, vpmovsx*/vpmovzx*, vpmovmskb, and per-lane fault-accurate
  vpmaskmovd/vpmaskmovq).
- Add runtime/test/avx2_emulation_test.cpp covering IEEE-754 F16C conversions,
  VEX decoding, XSTATE_AVX + VPMASKMOVD page-boundary semantics, and live
  256-bit YMM execution on hardware.

Depends on: #2190
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 00:35:43 +00:00
Author
Owner

@⁠akimfomin on GitHub · 2026-11-27 00:16 UTC · original

On native Windows / i5-13600KF I built and ran your exact synthetic test at 8cde0bef: 51 instruction families, two fused pairs and one synthetic PE image passed. LLVM-MinGW required -fms-extensions for SEH and emitted a missing explicit __cpuidex declaration warning. The host has AVX2/FMA/BMI; native pre-Haswell coverage remains open.

The useful next report is this same synthetic program on an AVX1-only host, with its printed capability line and exit code. If you have a volunteer or a receiving backport, PortBridge Test Lab can carry this one narrow task and return the credited result here. AI-assisted native test.

**@⁠akimfomin** on GitHub · 2026-11-27 00:16 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2414#issuecomment-7206328423) On native Windows / i5-13600KF I built and ran your [exact synthetic test at 8cde0bef](https://github.com/ubiquitarianism/leonida/blob/8cde0bef3922116bef153f2ab65ee6e8a8d01245/runtime/test/isa_jit_patch_test.cpp): 51 instruction families, two fused pairs and one synthetic PE image passed. LLVM-MinGW required -fms-extensions for SEH and emitted a missing explicit __cpuidex declaration warning. The host has AVX2/FMA/BMI; native pre-Haswell coverage remains open. The useful next report is this same synthetic program on an AVX1-only host, with its printed capability line and exit code. If you have a volunteer or a receiving backport, [PortBridge Test Lab](https://akimfomin.github.io/PortBridge/#/lab) can carry this one narrow task and return the credited result here. AI-assisted native test.
- Gate 4-byte 0xC5 cross-instruction fusion in isa_jit_patch::patch_image behind
  opt-in LEONIDA_ISA_FUSE_4B=1 (off by default) and document LEONIDA_ISA_FUSE_4B
  in runtime/README.md.
- When LEONIDA_ISA_FUSE_4B=1 is enabled and mark_block_targets resolves a
  RIP-relative target inside a non-executable data section, also scan
  consecutive signed 32-bit Clang/LLVM table-relative jump-table entries
  (	arget_rva = tbl_rva + entry) within [beg_rva, end_rva) so fusion never
  crosses a relative switch case boundary.
- Update isa_jit_patch_test to verify default non-fusion of 4-byte 0xC5 sites,
  opt-in fusion under LEONIDA_ISA_FUSE_4B=1, and fusion refusal across both
  image-base RVA tables and negative table-relative int32_t .rdata switch tables.
This pull request has changes conflicting with the target branch.
  • runtime/src/main.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2414/head:github-bot/gh-2414'
git switch 'github-bot/gh-2414'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2414'
git switch 'github-bot/gh-2414'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2414'
git switch 'github-bot/gh-2414'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2414'
git switch 'main'
git merge --squash 'github-bot/gh-2414'
git switch 'main'
git merge --ff-only 'github-bot/gh-2414'
git switch 'main'
git merge 'github-bot/gh-2414'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.