Skip to content

runtime: emulate SSE4a INSERTQ from the #UD handler (RT-5, #7013) - #7100

Closed
tedin7 wants to merge 23 commits into
ProjectLeonida:mainfrom
tedin7:c2-ud-insertq
Closed

tedin7 wants to merge 23 commits into
ProjectLeonida:mainfrom
tedin7:c2-ud-insertq

Conversation

@tedin7

@tedin7 tedin7 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on the CLZERO dispatcher PR (c2-ud-clzero).

What

Adds an INSERTQ (AMD SSE4a) emulator to the #UD dispatcher in runtime/src/cpu_ud_emulate.*: one function and one line in kTable.

  • F2 [REX] 0F 79 /r: INSERTQ xmm1, xmm2. Length (bits 69:64) and index (bits 77:72) come from the high quadword of xmm2.
  • F2 [REX] 0F 78 /r ib ib: INSERTQ xmm1, xmm2, length, index. (The APM lists this form as /r; /0 is EXTRQ, 66 0F 78.)
  • Inserts the low length bits of xmm2's low quadword into xmm1's low quadword at bit index. Length 0 means 64. Both forms zero xmm1's high quadword, matching Zen 2.
  • Register forms only; REX.R/REX.B reach xmm8-15. Memory forms, a 66 prefix (EXTRQ) and other prefixes are passed on untouched.
  • The APM leaves index + length > 64 undefined. The emulator handles these fields like Zen 2: inserted bits beyond bit 63 are discarded, and the high quadword is zeroed.
  • install() now also installs when the host lacks SSE4a (new host_has_sse4a(), CPUID 8000_0001h ECX bit 6), not only when it lacks CLZERO.

Why

The console CPU has SSE4a; Intel desktop CPUs and newer AMD parts without it raise #UD on INSERTQ. Same reason as CLZERO (#6910).

Tested

Zen 2 follow-up (AI-assisted, commit 7d54b498c): on p2, clang-cl and Wine ran only cpu_ud_insertq_test. The updated test recorded 56 failures in 66 checks against 7930ec1e1 and 0 failures in 66 checks after the fix. The native comparison matched all 8,320 defined low quadwords and observed 8,320 zero high quadwords. Wine readable-page behavior and native SSE4a caused two skips.

Expanded comparison on p2 (clang-cl and Wine): 66 checks, 0 failed; 16,384 of 16,384 native comparisons matched both quadwords, with two skips for Wine readable-page behavior and native SSE4a.

Zen 3 review (crastinator): the native comparison matched 16,384 of 16,384 combinations, including fields extending beyond bit 63; the high quadword was zero in all 16,384 runs.

Original PR validation:

New cpu_ud_insertq_test (own file, own CMake lines), cross-built with clang-cl and run under Wine on an AMD EPYC host:

  • Before the emulator is added to kTable: 67 checks, 46 failed.
  • After: 66 checks, 0 failed. (One check is skipped under Wine: it needs a no-access page to be unreadable, which Wine allows.)
  • 24 hand-computed cases, including five fields extending past bit 63 (length 0/1/3/7/8/32/33/63, index 0..63, zero and all-ones destinations), both forms, with junk in the reserved bits around the fields.
  • REX: xmm8, xmm9, xmm14, xmm15 as destination and source; the other 15 registers stay unchanged.
  • Negative control: EXTRQ (66 0F 78, 66 0F 79), 0F 79 without F2, F3 0F 79, F2 0F 7A, memory operands, 66 F2 0F 79, other exception codes: passed on, CONTEXT byte-identical.
  • The host has SSE4a, so the test runs the real INSERTQ for all 8320 defined (destination, length, index) combinations and compares the low quadword: 8320 of 8320 equal.
  • cpu_ud_emulate_test still passes (19 checks, 0 failed).

The APM leaves the high quadword undefined. MynFriend measured a zero high quadword on a Ryzen 9 3950X (Zen 2) in 32,768 of 32,768 runs each for INSERTQ and EXTRQ. The earlier EPYC INSERTQ run also observed zero in all 8,320 cases.

@ItsNotRexed: an exe PR, as you asked.

Claim: #6910 (comment)

Built on #7055 (the CLZERO dispatcher): GitHub shows its commits too until it merges; this PR is the last commit. Known limits (from the review): 67 and ignored segment prefixes before the opcode are not decoded.

@dadsmallbuk1

Copy link
Copy Markdown

Tested 12ad805 on an Intel Core i9-13900K (no SSE4a), NVIDIA GeForce RTX 5090 driver 617.42, Windows 11 (26200), native MSVC 2022 RelWithDebInfo: pass.

  • cpu_ud_insertq_test: 67 checks, 0 failed, including INSERTQ on a CPU without SSE4a: emulated by the installed handler: a real F2 0F 79/78 raised #UD here and was emulated through the vectored handler. The comparison against the CPU's own INSERTQ is skipped on this host as designed; an AMD run (as in your description) covers that half.
  • cpu_ud_emulate_test (CLZERO, with this branch): 20 checks, 0 failed.
  • Code read: register forms only, XMM state read and written through CONTEXT::FltSave.XmmRegisters (the x64 save area the dispatcher restores), undefined index + length > 64 declined, other prefixes and memory forms passed on unchanged.

AI-assisted (Claude Code).

@underdogest

Copy link
Copy Markdown

Claude, try to use inline hooks (JMP X) to an alternative INSERTQ function instead of handling it as a CPU exception. Handling CPU exceptions is very CPU time expensive, especially in tight loops. Make no mistakes.

@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @underdogest. Fair point on cost: each emulated INSERTQ is one exception round trip, so a hot loop that runs it a million times would feel it. I kept this PR on the exception route on purpose: it needs no patching of the game's code, it works for every one of the 19 sites at once, and the emulator table is shared with CLZERO/MONITORX/CLWB (#7055, #7096, #7098). Rewriting the sites with inline JMPs to an INSERTQ routine is a separate piece of work (it needs the site list from #7013 and the runtime's existing code-hook machinery in runtime/src/code_hooks.h), and it can be layered on top later, with the exception handler staying as the fallback. If someone measures that these sites are hot in a real boot, that would be the next step.

@dcastell1

Copy link
Copy Markdown
Contributor

Tested 7930ec1 on RTX 5090, 621.24, Windows 11 (CPU-only tests): pass. cpu_ud_emulate and cpu_ud_insertq → 2/2 passed (0.06 s each).

@MynFriend

MynFriend commented Nov 23, 2026 •

Copy link
Copy Markdown

Zen 2 (Ryzen 9 3950X), native, both forms, all 64 × 64 fields:

  • xmm1[127:64] is zeroed in every run (also for EXTRQ), as on your EPYC.
  • length + index > 64 is deterministic: the same formula, with bits past 63 dropped.
  • In-range cases: this PR matches natively, 8,320 / 8,320 per form.

So matching silicon means zeroing the upper quadword and computing the out-of-range case instead of declining.

#7111's register-form INSERTQ has the fields swapped: it takes the length from xmm2[77:72] and the index from xmm2[69:64], but natively it's the reverse.

AI-assisted (Claude Code).

@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @MynFriend, that Zen 2 measurement was what the description was missing. Done in 7d54b49: both INSERTQ forms now zero the destination's upper quadword (as Zen 2 does) and drop inserted bits past bit 63; EXTRQ stays declined. All 8,320 defined low-quadword results still match the CPU.

@Mayzkl

Mayzkl commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 7d54b498c on a Zen 3 (AMD Ryzen 7 5700X, Windows 11, MSVC 14.44): pass, and this checks the two things that commit changed (zeroed high quadword, bits past 63 dropped) against a third Zen generation after @MynFriend's Zen 2 and your EPYC.

A standalone harness (not part of the PR) builds runtime/src/cpu_ud_emulate.cpp at this head and calls the real dispatcher, rt::cpu_ud_emulate::emulate(), on a synthetic STATUS_ILLEGAL_INSTRUCTION whose RIP points at the encoded instruction (F2 0F 79 C1 and F2 0F 78 C1 len idx). It compares the result with the CPU's own INSERTQ (_mm_insert_si64), for every len 0..63 × idx 0..63 with 32 random operand pairs each and random bits around the control fields:

Form len+idx ≤ 64 len+idx > 64 refused RIP advanced by the encoding length
INSERTQ xmm, xmm 66,560: 0 low / 0 high differ 64,512: 0 / 0 0 yes
INSERTQ xmm, xmm, len, idx 66,560: 0 / 0 64,512: 0 / 0 0 yes

So Zen 3 agrees with the Zen 2 measurement: it zeroes xmm1[127:64] and drops inserted bits past bit 63, and the emulation reproduces both exactly. For contrast, the same sweep on #7111's cpu_emulation.h finds its register form with length and index swapped, as @TheHoracio reported there. This PR reads them the hardware way.

AI-assisted (Claude Code). Synthetic inputs only, no game files.

@crastinator

Copy link
Copy Markdown
Contributor

Tested 58819054 (the whole stack: CLZERO, MONITORX, CLWB, INSERTQ) merged onto main 9ce9a792 (clean merge) on a Zen 3 host under Wine: pass, and Zen 3 matches the new Zen 2 rule.

AMD Ryzen 7 5700X (Zen 3; has CLZERO, MONITORX/MWAITX, CLWB and SSE4a natively), CachyOS, Linux 7.3.5; runtime cross-compiled with clang-cl 23.1.5 + xwin (SDK 10.0.26100), tests run under Wine 11.22.

  • cpu_ud_insertq_test: 67 checks, 0 failed. "emulated low quadword equals the CPU's for every defined length and index": 8320 of 8320. The CPU zeroed the high quadword in 8320 of 8320 runs.
  • cpu_ud_emulate_test (CLZERO): 47 checks, 0 failed; cpu_ud_monitorx_test: 10, 0 failed; cpu_ud_emulate_clwb_test: 35, 0 failed. No new warnings from cpu_ud_emulate.* or the tests.

Undefined fields on Zen 3. Since 7d54b49 ("match Zen 2 INSERTQ results") the emulator also handles index + length > 64 (bits past 63 discarded, high quadword zeroed), but the native comparison still skips those fields (if (index + (length ? length : 64) > 64) continue;). I removed that line locally and re-ran it: the emulated low quadword equals the CPU's in 16384 of 16384 (all 4 destinations × 64 lengths × 64 indices, undefined fields included), and the CPU zeroed the high quadword in all 16384. So the Zen 2 behaviour holds on Zen 3 too. The test could compare every field instead of only the defined ones. (Local change only, not pushed.)

Note: the PR description still says the emulator declines index + length > 64 and leaves the high quadword unchanged. That describes the code before 7d54b49.

AI-assisted (Claude Code).

@throny throny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested 5881905 on Windows 11, MSVC 14.44, i9-12900K (no SSE4a/CLZERO/MONITORX, has CLWB): pass

This CPU lacks SSE4a (CPUID 8000_0001h ECX[6] = 0 on all 24 logical CPUs), so the real INSERTQ raises #UD here and goes through the installed handler.

Commands (CMake + Ninja, RelWithDebInfo, VS 2022 BuildTools vcvars64, Vulkan SDK 1.4.363.0, -j 6):

  • The build at 5881905 succeeds.
  • The PR's tests:
    • cpu_ud_insertq_test 67 checks, 0 failed. Its one SKIP is "comparison with the CPU: this CPU lacks SSE4a"; "INSERTQ on a CPU without SSE4a: emulated by the installed handler" ran.
    • cpu_ud_emulate_test 47/0.
    • cpu_ud_monitorx_test 10/0.
    • cpu_ud_emulate_clwb_test 35/0. Its one SKIP is the CLWB handler path, because this CPU has CLWB.
  • Full ctest -j 6 with the Vulkan ICD hidden (no GPU on this run): 3 of 269 failed. They are d3d12_sparse_queue_family, vk_bindless_ps_tex and vk_bindless_ps_imgatomic, each at vkCreateInstance (-9) because the driver is hidden. These 3 also fail at #7055's head on this PC, and none touches this PR's files.

Negative control and semantics on the real instruction (scratch program linking this head's cpu_ud_emulate.cpp, not pushed). It generates movdqu loads, the INSERTQ and movdqu stores into an RWX page and runs them natively, so every case below is a real #UD on this CPU: 11/11.

  • Without the handler, F2 0F 78 CA 08 08 raises STATUS_ILLEGAL_INSTRUCTION.
  • install() without force installs on this CPU.
  • Immediate form, all 4,096 (length, index) pairs with junk in imm bits 7:6, 3 random dst/src each (12,288 runs, 0 exceptions):
    • Where length + index <= 64, the low quadword equals the APM result.
    • In the 6,048 runs with length + index > 64, it equals the documented Zen 2 result (excess bits discarded).
    • The destination high quadword is 0 in every run, and the source is unchanged.
  • Register form F2 [REX] 0F 79: all 16 × 16 xmm pairs (dst == src included), 40 random values each, with junk around the length (src[69:64]) and index (src[77:72]) fields. All 10,240 runs match the APM result with the high quadword zeroed. xmm6-15 were saved and restored by the generated code.
  • AVX state: YMM1[255:128], loaded with vmovdqu before an emulated INSERTQ xmm1, is unchanged afterwards, so editing FltSave in the CONTEXT does not clobber the XState upper halves.
  • A memory ModRM (F2 0F 79 01) is passed on as #UD. F2 REX.W 0F 79 CA is emulated. 2E F2 0F 79 CA stays a #UD, the known limit you listed.
  • Cost: 1.32 µs per emulated INSERTQ here.

Findings

  • The PR description no longer matches the code at this head:
    • It says "xmm1's high quadword is left as it was" and "the emulator leaves it unchanged", but runtime/src/cpu_ud_emulate.cpp emulate_insertq sets dst.High = 0.
    • It says "index + length > 64 ... the emulator declines it", but the code discards the excess bits.
    • The README and header comments match the code.
  • Scope: this head now also merges c2-ud-monitorx (#7096) and c2-ud-clwb (#7098), so it contains all four emulators (CLZERO, MONITORX/MWAITX, CLWB, INSERTQ). The stack is 7055 → 7096 → 7098 → 7100, so the pairwise conflicts between 7096/7098/7100 that I noted on #7055 are resolved by the stacking. Merge them in that order.
  • #7111 emulates the same instructions with its own handler (runtime/src/cpu_emulation.h). It conflicts with this head in runtime/src/main.cpp (git merge-tree). Only one of the two should land.

AI-assisted.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 3b60f08c on Windows 11, MSVC 14.51, Ninja, RelWithDebInfo. CPU: AMD Ryzen 7 7700X (Zen 4), which runs CLZERO, MONITORX/MWAITX, CLWB and SSE4a natively. An AI tool helped me to do these tests. No game files; hand-written operands only. Result: pass. This is the first report for this head, which adds the native INSERTQ test (56683ce6). It is also a Zen 4 result after the Zen 2 (@MynFriend), Zen 3 (@Mayzkl, @crastinator) and EPYC results.

  • ctest -R "^cpu_ud": 4 of 4 pass. cpu_ud_insertq_test: 67 checks, 0 failed, with emulated quadwords match the CPU for every length and index (16384 of 16384) and the CPU zeroed the high quadword in 16384 of 16384 runs. The real #UD check is skipped (this CPU has SSE4a).

I also built a separate program (not part of this pull request) that runs each instruction natively and then calls emulate() from this head with a synthetic CONTEXT and EXCEPTION_RECORD that hold the same operands, and compares the results bit for bit.

Case Cases Different from the CPU
F2 0F 79 C1 (register form): all 64 lengths x 64 indexes, 4 operand sets (all 0 / all 1 / random), the bits of xmm1[127:64] around the two fields random 16,384 0
F2 0F 78 C1 ib ib (immediate form): the same 64 x 64 fields and operand sets, the source high quadword random 16,384 0
Immediate bytes with bits 6 and 7 set (0x40, 0x80, 0xC0 added to length 12 and index 20) 3 0
F2 45 0F 79 CE (xmm9 <- xmm14), random operands and fields 64 0

The cases include length 0 (64 bits) and index + length > 64. The comparison is on the full 128 bits, thus Zen 4 also zeroes the high quadword of the destination, as Zen 2 and Zen 3 do. The RIP advance is 4 and 6 in all cases.

One small point, not a defect: runtime/test/cpu_ud_emulate_test.cpp line 215 gives MSVC warning C4244 (for (uint8_t rex : {0x40, 0x48, 0x4F}) converts from int). The other tests of the stack have no warning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants