runtime(cpu): emulate F16C, FMA3 and AVX2 via XSTATE_AVX on AVX1 hosts #2191

Merged
leonida/mandy
robot00f merged 3 commits from feat/rt-cpu-fma-f16c-avx2 into main 2026-11-29 01:02:53 +00:00

Pull request successfully merged and closed

robot00f commented 2026-11-26 04:10:28 +00:00

Summary

Add runtime/src/avx2_emulation.h and wire it into gta6rt so pre-Haswell AVX1 + SSE4.2 hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's F16C, FMA3, and AVX2 vector instructions using the OS-saved 256-bit YMM0..YMM15 registers (docs/cpu_features.md, PR #2188):

  • Full 256-bit XSTATE_AVX register access:
    • Reads and writes XMM0..XMM15 ([127:0]) from CONTEXT::FltSave.XmmRegisters and YMM0..YMM15[255:128] via GetXStateFeaturesMask / LocateXStateFeature(c, XSTATE_AVX, &len) / SetXStateFeaturesMask.
    • Enforces the x86-64 VEX upper-128 zeroing rule (YMM[dst][255:128] = 0) on every 128-bit VEX register write, and zero-initializes the other 15 upper lanes before enabling XSTATE_MASK_AVX when transitioning out of a clean (vzeroupper) state.
    • Leaves native AVX1 instructions (including 256-bit vptest, vperm2f128, vpermilps, vmovups/vmovdqu, etc.) to execute directly on hardware.
  • Instruction coverage (#UD / STATUS_ILLEGAL_INSTRUCTION):
    • F16C: vcvtph2ps and vcvtps2ph (register and memory destinations, imm8 RN/RD/RU/RZ and MXCSR.RC rounding, subnormals, signed zero, Inf, and quiet NaN payloads).
    • FMA3: all 60 0F38 forms (132, 213, 231; single and double precision; 128-bit and 256-bit packed, scalar ss/sd preserving dst[127:32]/[127:64], and vfmaddsub*/vfmsubadd*) via single-rounding std::fmaf / std::fma.
    • AVX2: 256-bit integer SIMD promotions (2-byte C5 and 3-byte C4 VEX), vbroadcastss / vbroadcastsd (including ModRM.mod == 3 register-source forms), vbroadcasti128, vpbroadcastb/w/d/q, vinserti128, vextracti128, vperm2i128, vpermq, vpermpd, vpermd, vpermps, vpblendd (128/256), vpblendw, vpblendvb, vpsllvd/q, vpsrlvd/q, vpsravd, vpmovsx* / vpmovzx*, vpmovmskb, and vpmaskmovd / vpmaskmovq (reading/writing only enabled mask < 0 lanes so disabled lanes crossing into unmapped/PAGE_NOACCESS pages never fault).
  • Tests (runtime/test/avx2_emulation_test.cpp):
    • IEEE-754 half/float edge cases, 2-byte/3-byte VEX decoding + AVX1 non-interception, InitializeContext(..., CONTEXT_XSTATE) upper-lane and vpmaskmovd page-boundary tests, and live 256-bit YMM execution (vmovups/vmovdqu -> #UD FMA3 / F16C / AVX2 -> vmovups/vmovdqu -> vzeroupper) on hardware.

Validation

  • Built and executed ctest 3x (avx2_emulation, bmi_emulation, cpu_emulation, clzero_patch, run_tiny_game) on an Intel Core i7-2600 (Sandy Bridge, AVX1 + SSE4.2, AVX2=0 FMA=0 F16C=0), verifying live 256-bit YMM round-trips through Windows XSTATE_AVX on real pre-Haswell hardware.
  • python -I -m unittest discover -s tests -p "test_ctest_registration.py" and test_text_write_line_endings.py (OK).
  • python -I scripts/check_no_game_data.py (clean).

Depends on: #2190
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)

## Summary Add `runtime/src/avx2_emulation.h` and wire it into `gta6rt` so pre-Haswell `AVX1 + SSE4.2` hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's `F16C`, `FMA3`, and `AVX2` vector instructions using the OS-saved 256-bit `YMM0..YMM15` registers (`docs/cpu_features.md`, PR #2188): - **Full 256-bit `XSTATE_AVX` register access:** - Reads and writes `XMM0..XMM15` (`[127:0]`) from `CONTEXT::FltSave.XmmRegisters` and `YMM0..YMM15[255:128]` via `GetXStateFeaturesMask` / `LocateXStateFeature(c, XSTATE_AVX, &len)` / `SetXStateFeaturesMask`. - Enforces the x86-64 VEX upper-128 zeroing rule (`YMM[dst][255:128] = 0`) on every 128-bit VEX register write, and zero-initializes the other 15 upper lanes before enabling `XSTATE_MASK_AVX` when transitioning out of a clean (`vzeroupper`) state. - Leaves native `AVX1` instructions (including 256-bit `vptest`, `vperm2f128`, `vpermilps`, `vmovups`/`vmovdqu`, etc.) to execute directly on hardware. - **Instruction coverage (`#UD` / `STATUS_ILLEGAL_INSTRUCTION`):** - **F16C:** `vcvtph2ps` and `vcvtps2ph` (register and memory destinations, `imm8` `RN`/`RD`/`RU`/`RZ` and `MXCSR.RC` rounding, subnormals, signed zero, `Inf`, and quiet `NaN` payloads). - **FMA3:** all 60 `0F38` forms (`132`, `213`, `231`; single and double precision; 128-bit and 256-bit packed, scalar `ss`/`sd` preserving `dst[127:32]`/`[127:64]`, and `vfmaddsub*`/`vfmsubadd*`) via single-rounding `std::fmaf` / `std::fma`. - **AVX2:** 256-bit integer SIMD promotions (2-byte `C5` and 3-byte `C4` VEX), `vbroadcastss` / `vbroadcastsd` (including `ModRM.mod == 3` register-source forms), `vbroadcasti128`, `vpbroadcastb/w/d/q`, `vinserti128`, `vextracti128`, `vperm2i128`, `vpermq`, `vpermpd`, `vpermd`, `vpermps`, `vpblendd` (128/256), `vpblendw`, `vpblendvb`, `vpsllvd/q`, `vpsrlvd/q`, `vpsravd`, `vpmovsx*` / `vpmovzx*`, `vpmovmskb`, and `vpmaskmovd` / `vpmaskmovq` (reading/writing only enabled `mask < 0` lanes so disabled lanes crossing into unmapped/`PAGE_NOACCESS` pages never fault). - **Tests (`runtime/test/avx2_emulation_test.cpp`):** - IEEE-754 half/float edge cases, 2-byte/3-byte VEX decoding + `AVX1` non-interception, `InitializeContext(..., CONTEXT_XSTATE)` upper-lane and `vpmaskmovd` page-boundary tests, and live 256-bit `YMM` execution (`vmovups`/`vmovdqu` -> `#UD` `FMA3` / `F16C` / `AVX2` -> `vmovups`/`vmovdqu` -> `vzeroupper`) on hardware. ## Validation - Built and executed `ctest` 3x (`avx2_emulation`, `bmi_emulation`, `cpu_emulation`, `clzero_patch`, `run_tiny_game`) on an **Intel Core i7-2600** (Sandy Bridge, `AVX1 + SSE4.2`, `AVX2=0 FMA=0 F16C=0`), verifying live 256-bit `YMM` round-trips through Windows `XSTATE_AVX` on real pre-Haswell hardware. - `python -I -m unittest discover -s tests -p "test_ctest_registration.py"` and `test_text_write_line_endings.py` (OK). - `python -I scripts/check_no_game_data.py` (clean). Depends on: #2190 Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437 AI-assisted: yes (Antigravity, Gemini 4 Carbon)
ecox982745 commented 2026-11-26 04:17:00 +00:00

I found one F16C result mismatch at 9ec6b209af7853f6f1665a76a37c56b610d73a45. The VCVTPS2PH path reads the saved rounding mode but does not honor the saved MXCSR denormals-are-zero (DAZ) bit on its binary32 inputs. On a Windows Ryzen 7 7800X3D, with DAZ set and rounding toward negative infinity, native F16C converts input bits 0x80000001 to half 0x8000 (negative zero). The PR returns 0x8001. The same difference occurs with the largest negative binary32 subnormal, 0x807fffff.

I compared native _mm_cvtps_ph with decode + apply for the 128-bit register form, using 12 synthetic inputs, all four rounding modes, both immediate and MXCSR-selected rounding, and both FTZ settings. With all FP exceptions masked, the PR matched native on 192/192 lanes with DAZ clear and 176/192 with DAZ set. This compares result bits only.

A local edit to the conversion loop at line 762 matched native on 384/384. When c->FltSave.MxCsr & (1u << 6) is set and the input exponent bits are zero, write uint16_t((src.u32[k] >> 16) & 0x8000u) to preserve the sign of zero. Otherwise use the existing f32_to_f16. Keeping this check on the binary32 input preserves valid half-subnormal outputs even with FTZ set. The PR's existing avx2_emulation_test passed all 38 checks on both versions. The two-case regression I'd add is the smallest negative binary32 subnormal with round-down, DAZ clear (0x8001) and DAZ set (0x8000).

CPU-only, synthetic data. AI-assisted review (OpenAI Codex). Intel's specification covers DAZ for legacy VCVTPS2PH.

I found one F16C result mismatch at `9ec6b209af7853f6f1665a76a37c56b610d73a45`. The `VCVTPS2PH` path reads the saved rounding mode but does not honor the saved MXCSR denormals-are-zero (DAZ) bit on its binary32 inputs. On a Windows Ryzen 7 7800X3D, with DAZ set and rounding toward negative infinity, native F16C converts input bits `0x80000001` to half `0x8000` (negative zero). The PR returns `0x8001`. The same difference occurs with the largest negative binary32 subnormal, `0x807fffff`. I compared native `_mm_cvtps_ph` with `decode` + `apply` for the 128-bit register form, using 12 synthetic inputs, all four rounding modes, both immediate and MXCSR-selected rounding, and both FTZ settings. With all FP exceptions masked, the PR matched native on **192/192 lanes with DAZ clear** and **176/192 with DAZ set**. This compares result bits only. A local edit to the conversion loop at line 762 matched native on **384/384**. When `c->FltSave.MxCsr & (1u << 6)` is set and the input exponent bits are zero, write `uint16_t((src.u32[k] >> 16) & 0x8000u)` to preserve the sign of zero. Otherwise use the existing `f32_to_f16`. Keeping this check on the binary32 input preserves valid half-subnormal outputs even with FTZ set. The PR's existing `avx2_emulation_test` passed all 38 checks on both versions. The two-case regression I'd add is the smallest negative binary32 subnormal with round-down, DAZ clear (`0x8001`) and DAZ set (`0x8000`). CPU-only, synthetic data. AI-assisted review (OpenAI Codex). [Intel's specification covers DAZ for legacy VCVTPS2PH](https://cdrdv2-public.intel.com/678970/intel-avx512-fp16.pdf).
zmasi commented 2026-11-28 21:24:30 +00:00

Independent Verification Report — b6e51b7376 + origin/main (aa918e5d9f)

Environment: Windows 11 (26200), AMD Ryzen 9 5950X (Zen 3 hardware oracle), MSVC 19.44.35228 (x64, /std:c++20 /EHsc /W4 /permissive- /utf-8, Debug /Od /MDd & Release /O2 /MD).
Verdict: Core test suite & PE-loader integration PASS; 2 silicon-verified ISA edge-case mismatches noted below — clean merge with origin/main (41c27e5d8a7b) and combined Batch 9 set (a422ed80f598).

1. Build & Test Suite Verification

  • Red (origin/main): bmi_emulation.h / avx2_emulation.h absent (C1083).
  • Green (b6e51b7376 + origin/main):
    • bmi_emulation_test (Debug & Release): PASS (65/65 checks), 0 warnings under /W4 /permissive-.
    • avx2_emulation_test (Debug & Release): PASS (38/38 checks), 0 warnings under /W4 /permissive-.
    • cpu_emulation_test (Debug & Release): PASS, 0 warnings.
    • loader_test + gta6rt_tls_host.dll + main.cpp / pe_loader.cpp /W4 /permissive- compile: PASS (0 new warnings in touched files; .pdata/leaf LZCNT/TZCNT patcher integration verified).

2. Ryzen 9 5950X Hardware Differential Findings on b6e51b7376

  1. Scalar FMA3 rejects VEX.L = 1, whereas x86-64 FMA3 specifies VEX.LIG (runtime/src/avx2_emulation.h:363):
    • Intel SDM / AMD APM specify VEX.LIG (VEX.L ignored) for scalar FMA3 (VFMADD*SS/SD, VFMSUB*SS/SD, VFNMADD*SS/SD, VFNMSUB*SS/SD, odd opcodes 0x99..0xBF).
    • Executing C4 E2 75 A9 C2 (vfmadd213ss xmm0, xmm1, xmm2 with VEX.L = 1) on Ryzen 9 5950X executes normally without #UD (2.0f * 3.0f + 5.0f = 11.0f), whereas avx2_emulation::decode has if (scalar && d.vex_l != 0) return {};, leaving #UD unhandled.
    • Suggested fix: Remove if (scalar && d.vex_l != 0) return {}; at avx2_emulation.h:363 (apply_fma3 already branches on scalar = (lo & 1u) != 0 and zeroes YMM[dst][255:128] via write_xmm).
  2. VCVTPS2PH still ignores saved MXCSR.DAZ (bit 6 = 0x0040) at b6e51b7376 (runtime/src/avx2_emulation.h:817):
    • Re-verified on Ryzen 9 5950X at current head b6e51b7376: with MXCSR = 0x3FC0 (DAZ = 1, round-down), native _mm_cvtps_ph converts negative binary32 subnormals 0x80000001 and 0x807FFFFF to 0x8000 (-0.0h), whereas avx2_emulation::apply returns 0x8001 (matching the earlier report in #issuecomment-7182457972). Flushing input binary32 subnormals ((bits & 0x7F800000u) == 0) to signed zero when (c->FltSave.MxCsr & 0x0040u) != 0 aligns all 4 lanes ([0x8000, 0x8000, 0x0000, 0x0000]).
  3. Minor note (apply_fma3, avx2_emulation.h:572-670): On Windows 11 (26200), we confirmed via live #UD VEH probe that handler_live_mxcsr matches ctx->FltSave.MxCsr (0xBFC0) on VEH entry, capability-wise, though std::fmaf/std::fma in synthetic apply(dec, ctx) calls (and software fmaf on AVX1 hosts) uses the host CRT environment rather than consulting c->FltSave.MxCsr (RC/DAZ/FTZ).

AI-assisted.

### Independent Verification Report — `b6e51b7376` + `origin/main` (`aa918e5d9f`) **Environment:** Windows 11 (`26200`), AMD Ryzen 9 5950X (Zen 3 hardware oracle), MSVC `19.44.35228` (`x64`, `/std:c++20 /EHsc /W4 /permissive- /utf-8`, Debug `/Od /MDd` & Release `/O2 /MD`). **Verdict:** **Core test suite & PE-loader integration PASS; 2 silicon-verified ISA edge-case mismatches noted below** — clean merge with `origin/main` (`41c27e5d8a7b`) and combined Batch 9 set (`a422ed80f598`). #### 1. Build & Test Suite Verification - **Red (`origin/main`):** `bmi_emulation.h` / `avx2_emulation.h` absent (`C1083`). - **Green (`b6e51b7376` + `origin/main`):** - `bmi_emulation_test` (Debug & Release): **PASS (`65/65` checks)**, `0` warnings under `/W4 /permissive-`. - `avx2_emulation_test` (Debug & Release): **PASS (`38/38` checks)**, `0` warnings under `/W4 /permissive-`. - `cpu_emulation_test` (Debug & Release): **PASS**, `0` warnings. - `loader_test` + `gta6rt_tls_host.dll` + `main.cpp` / `pe_loader.cpp` `/W4 /permissive-` compile: **PASS** (`0` new warnings in touched files; `.pdata`/leaf `LZCNT`/`TZCNT` patcher integration verified). #### 2. Ryzen 9 5950X Hardware Differential Findings on `b6e51b7376` 1. **Scalar FMA3 rejects `VEX.L = 1`, whereas x86-64 FMA3 specifies `VEX.LIG` (`runtime/src/avx2_emulation.h:363`):** - Intel SDM / AMD APM specify `VEX.LIG` (`VEX.L` ignored) for scalar FMA3 (`VFMADD*SS/SD`, `VFMSUB*SS/SD`, `VFNMADD*SS/SD`, `VFNMSUB*SS/SD`, odd opcodes `0x99..0xBF`). - Executing `C4 E2 75 A9 C2` (`vfmadd213ss xmm0, xmm1, xmm2` with `VEX.L = 1`) on Ryzen 9 5950X executes normally without `#UD` (`2.0f * 3.0f + 5.0f = 11.0f`), whereas `avx2_emulation::decode` has `if (scalar && d.vex_l != 0) return {};`, leaving `#UD` unhandled. - **Suggested fix:** Remove `if (scalar && d.vex_l != 0) return {};` at `avx2_emulation.h:363` (`apply_fma3` already branches on `scalar = (lo & 1u) != 0` and zeroes `YMM[dst][255:128]` via `write_xmm`). 2. **`VCVTPS2PH` still ignores saved `MXCSR.DAZ` (`bit 6 = 0x0040`) at `b6e51b7376` (`runtime/src/avx2_emulation.h:817`):** - Re-verified on Ryzen 9 5950X at current head `b6e51b7376`: with `MXCSR = 0x3FC0` (`DAZ = 1`, round-down), native `_mm_cvtps_ph` converts negative binary32 subnormals `0x80000001` and `0x807FFFFF` to `0x8000` (`-0.0h`), whereas `avx2_emulation::apply` returns `0x8001` (matching the earlier report in `#issuecomment-7182457972`). Flushing input binary32 subnormals (`(bits & 0x7F800000u) == 0`) to signed zero when `(c->FltSave.MxCsr & 0x0040u) != 0` aligns all 4 lanes (`[0x8000, 0x8000, 0x0000, 0x0000]`). 3. **Minor note (`apply_fma3`, `avx2_emulation.h:572-670`):** On Windows 11 (`26200`), we confirmed via live `#UD` VEH probe that `handler_live_mxcsr` matches `ctx->FltSave.MxCsr` (`0xBFC0`) on VEH entry, capability-wise, though `std::fmaf`/`std::fma` in synthetic `apply(dec, ctx)` calls (and software `fmaf` on AVX1 hosts) uses the host CRT environment rather than consulting `c->FltSave.MxCsr` (`RC`/`DAZ`/`FTZ`). AI-assisted.
TheGeogeo commented 2026-11-28 22:16:34 +00:00

Duplicate check (diff reading only, no build): not a duplicate of #2190 but its next step: it contains #2190 (Depends on: #2190) and adds the F16C, FMA3 and AVX2 emulation. Both #2190 and #2191 are in #2414 (git merge-base --is-ancestor), which declares Depends on: #2190, #2191.

Suggest landing the stack as one: merging #2414 with a merge commit (not a squash) also lands #2190 and #2191, and GitHub then shows them as merged. With a squash merge of #2414, these two stay open and must be closed by hand.

AI-assisted (Claude Code).

Duplicate check (diff reading only, no build): not a duplicate of #2190 but its next step: it contains #2190 (`Depends on: #2190`) and adds the F16C, FMA3 and AVX2 emulation. Both #2190 and #2191 are in #2414 (`git merge-base --is-ancestor`), which declares `Depends on: #2190, #2191`. Suggest landing the stack as one: merging #2414 with a merge commit (not a squash) also lands #2190 and #2191, and GitHub then shows them as merged. With a squash merge of #2414, these two stay open and must be closed by hand. AI-assisted (Claude Code).
Sign in to join this conversation.
No description provided.