cpu_emulation: run a whole CLZERO zeroing loop in one emulated step (RT-CLZERO-LOOP) #421

Manually merged
github merged 2 commits from gh-pr/421/head into gh-pr/421/base 2026-11-26 08:59:17 +00:00
Owner

@⁠oscarlosu-lab on GitHub · 2026-11-24 04:56 UTC · original
oscarlosu-lab:pr/clzero-loop-fastpath → main · +174 −0 · 2 files · 2 commits · merged 2026-11-24 16:24 UTC

Claimed in the coordination issue as: RT-CLZERO-LOOP

Summary

Adds a fast-path in rt::cpu_emulation::handler (try_clzero_loop) for the Zen 2 cache-line zeroing loop pattern:
clzero; add rax, 0x40; cmp rax, reg64; jb -12 (12 bytes).

On CPUs without native CLZERO (e.g. Intel), executing one #UD exception + VirtualQuery + NtContinue per 64-byte line turns large zeroing loops into a heavy kernel-mode bottleneck. Recognizing the exact 12-byte loop lets the handler validate page writability once per 4 KiB page and zero the writable span in a single memset (capped at 64 MiB per trap so large spans make bounded progress without starving the handler), while preserving exact hardware fault semantics (Rax, Rip, write-fault EXCEPTION_RECORD) if an unwritable/guard page is encountered mid-loop, and updating EFlags (CF, PF, AF, ZF, SF, OF) to match cmp end, limit on loop exit.

Changes

  • runtime/src/cpu_emulation.h: add gpr_read, try_clzero_loop, and call it from handler (saving fault_rip before modifying Rip for the first-emulation log).
  • runtime/test/cpu_emulation_test.cpp: add live tests covering rdx limit, r8 (REX.R) limit, and non-64-byte-aligned limit (300 -> 320 round-up) while verifying surrounding guard bytes stay untouched. (Fault mid-loop and >64 MiB batching paths are covered by inspection, not live tests.)

Verification

  • Hardware/OS: Windows 11, Intel Core i5-12400F (no CLZERO), NVIDIA GeForce RTX 3060 (driver 621.35), MSVC x64.
  • cpu_emulation_test.exe: cpu_emulation: all checks passed (exit 0).
  • python -I scripts/check_no_game_data.py runtime/src/cpu_emulation.h runtime/test/cpu_emulation_test.cpp: PASS (exit 0).
  • Observed ~100x reduction in CLZERO exception overhead on Intel i5-12400F during runtime startup.

AI-assisted.

**@⁠oscarlosu-lab** on GitHub · 2026-11-24 04:56 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/421) `oscarlosu-lab:pr/clzero-loop-fastpath` → `main` · +174 −0 · 2 files · 2 commits · merged 2026-11-24 16:24 UTC Claimed in the coordination issue as: RT-CLZERO-LOOP ### Summary Adds a fast-path in `rt::cpu_emulation::handler` (`try_clzero_loop`) for the Zen 2 cache-line zeroing loop pattern: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes). On CPUs without native `CLZERO` (e.g. Intel), executing one `#UD` exception + `VirtualQuery` + `NtContinue` per 64-byte line turns large zeroing loops into a heavy kernel-mode bottleneck. Recognizing the exact 12-byte loop lets the handler validate page writability once per 4 KiB page and zero the writable span in a single `memset` (capped at 64 MiB per trap so large spans make bounded progress without starving the handler), while preserving exact hardware fault semantics (`Rax`, `Rip`, write-fault `EXCEPTION_RECORD`) if an unwritable/guard page is encountered mid-loop, and updating `EFlags` (`CF`, `PF`, `AF`, `ZF`, `SF`, `OF`) to match `cmp end, limit` on loop exit. ### Changes - `runtime/src/cpu_emulation.h`: add `gpr_read`, `try_clzero_loop`, and call it from `handler` (saving `fault_rip` before modifying `Rip` for the first-emulation log). - `runtime/test/cpu_emulation_test.cpp`: add live tests covering `rdx` limit, `r8` (`REX.R`) limit, and non-64-byte-aligned limit (`300 -> 320` round-up) while verifying surrounding guard bytes stay untouched. (Fault mid-loop and >64 MiB batching paths are covered by inspection, not live tests.) ### Verification - Hardware/OS: Windows 11, Intel Core i5-12400F (no `CLZERO`), NVIDIA GeForce RTX 3060 (driver 621.35), MSVC x64. - `cpu_emulation_test.exe`: `cpu_emulation: all checks passed` (exit 0). - `python -I scripts/check_no_game_data.py runtime/src/cpu_emulation.h runtime/test/cpu_emulation_test.cpp`: PASS (exit 0). - Observed ~100x reduction in `CLZERO` exception overhead on Intel i5-12400F during runtime startup. AI-assisted.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 08:59:15 +00:00
github manually merged commit 3b8c1555d8 into gh-pr/421/base 2026-11-26 08:59:17 +00:00
Author
Owner

@⁠sodove on GitHub · 2026-11-24 05:57 UTC · original

Independent Windows check of head 361e8455a2 integrated locally with main 8f481cf16f. Windows 11 x64 build 26100, MSVC 19.44.35220, Ryzen 5 9600X. CPU-only, synthetic fixtures, AI-assisted.

The stock cpu_emulation test passed in Debug and Release. I then compared native CLZERO on this CPU with a synthetic illegal-instruction context passed to the handler.

  • For both a read-only page and a guard page after a writable prefix, the handler zeroed the same prefix and matched the native exception code, write address, RAX, RIP and page protection. The arithmetic flags at the fault still held their entry values. Native execution had already applied the CMP from the last successful iteration.
  • A span just over 64 MiB split into two batches and wrote exactly the rounded span. Final flags matched hardware. The first batch resumed at the loop with stale arithmetic flags, including a missing carry bit.

The expanded test produced those three flag failures in each configuration. A temporary local change applied CMP flags at the end of every completed batch and after a nonempty prefix before a fault. The same checks passed in both configurations with that change. A fault on the first line should keep the incoming flags because the loop has not reached its CMP yet.

**@⁠sodove** on GitHub · 2026-11-24 05:57 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/421#issuecomment-7123437347) Independent Windows check of head 361e8455a20aa6606fb542d86e39b552da2e60e6 integrated locally with main 8f481cf16f261c7f37458aeb45e8f4e19994146d. Windows 11 x64 build 26100, MSVC 19.44.35220, Ryzen 5 9600X. CPU-only, synthetic fixtures, AI-assisted. The stock cpu_emulation test passed in Debug and Release. I then compared native CLZERO on this CPU with a synthetic illegal-instruction context passed to the handler. - For both a read-only page and a guard page after a writable prefix, the handler zeroed the same prefix and matched the native exception code, write address, RAX, RIP and page protection. The arithmetic flags at the fault still held their entry values. Native execution had already applied the CMP from the last successful iteration. - A span just over 64 MiB split into two batches and wrote exactly the rounded span. Final flags matched hardware. The first batch resumed at the loop with stale arithmetic flags, including a missing carry bit. The expanded test produced those three flag failures in each configuration. A temporary local change applied CMP flags at the end of every completed batch and after a nonempty prefix before a fault. The same checks passed in both configurations with that change. A fault on the first line should keep the incoming flags because the loop has not reached its CMP yet.
Author
Owner

@⁠oscarlosu-lab on GitHub · 2026-11-24 06:26 UTC · original

Thanks @⁠sodove for the detailed Ryzen 5 9600X hardware verification! Pushed 3b8c1555d to address both edge cases:

  • Extracted apply_cmp_flags(c, lhs, rhs) (CF, PF, AF, ZF, SF, OF) and called it at the end of every batch (including partial >64 MiB batches where end < limit) and on faults after a non-empty writable prefix (cur > start, where the previous iteration's cmp cur, limit already ran).
  • Faults on the very first line (cur == start) continue to preserve the incoming EFlags.
  • Added three live try_clzero_loop unit tests in runtime/test/cpu_emulation_test.cpp (test_apply) covering first-line fault EFlags preservation, post-prefix 4096 B fault CMP flags (CF=1, ZF=0, SF=1), and two-batch >64 MiB flag transitions (CF=1 -> CF=0, ZF=1).
  • Re-verified cpu_emulation_test.exe (cpu_emulation: all checks passed) on Windows 11 / MSVC x64.

AI-assisted.

**@⁠oscarlosu-lab** on GitHub · 2026-11-24 06:26 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/421#issuecomment-7123932570) Thanks @⁠sodove for the detailed Ryzen 5 9600X hardware verification! Pushed `3b8c1555d` to address both edge cases: - Extracted `apply_cmp_flags(c, lhs, rhs)` (`CF`, `PF`, `AF`, `ZF`, `SF`, `OF`) and called it at the end of every batch (including partial `>64 MiB` batches where `end < limit`) and on faults after a non-empty writable prefix (`cur > start`, where the previous iteration's `cmp cur, limit` already ran). - Faults on the very first line (`cur == start`) continue to preserve the incoming `EFlags`. - Added three live `try_clzero_loop` unit tests in `runtime/test/cpu_emulation_test.cpp` (`test_apply`) covering first-line fault `EFlags` preservation, post-prefix `4096 B` fault `CMP` flags (`CF=1, ZF=0, SF=1`), and two-batch `>64 MiB` flag transitions (`CF=1 -> CF=0, ZF=1`). - Re-verified `cpu_emulation_test.exe` (`cpu_emulation: all checks passed`) on Windows 11 / MSVC x64. AI-assisted.
Author
Owner

@⁠sodove on GitHub · 2026-11-24 06:35 UTC · original

Confirmed the fix at 3b8c1555d8 integrated with main at 8f481cf16f. The stock cpu_emulation test passed in Debug and Release on Windows 11 build 26100 with MSVC 19.44.35220 and a Ryzen 5 9600X.

The independent comparison against native CLZERO went from 2/5 on the previous head to 5/5 on this head in both configurations. All six arithmetic flags now agree for the first-line fault, read-only and guard faults after a writable prefix, resume at the 64 MiB boundary, and completion with an unaligned limit. The fault state and exact zeroed spans also matched the native runs.

Synthetic CPU fixtures only. AI-assisted verification.

**@⁠sodove** on GitHub · 2026-11-24 06:35 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/421#issuecomment-7124089457) Confirmed the fix at 3b8c1555d8d375762e907927417bbaca96accbbf integrated with main at 8f481cf16f261c7f37458aeb45e8f4e19994146d. The stock cpu_emulation test passed in Debug and Release on Windows 11 build 26100 with MSVC 19.44.35220 and a Ryzen 5 9600X. The independent comparison against native CLZERO went from 2/5 on the previous head to 5/5 on this head in both configurations. All six arithmetic flags now agree for the first-line fault, read-only and guard faults after a writable prefix, resume at the 64 MiB boundary, and completion with an unaligned limit. The fault state and exact zeroed spans also matched the native runs. Synthetic CPU fixtures only. AI-assisted verification.
Author
Owner

@⁠QemmHD on GitHub · 2026-11-24 16:24 UTC · original

Merging.

Why merged: The CLZERO zeroing loop is emulated as one step instead of one #UD per 64-byte line, which is a large cut in exception traffic on that path. sodove's flag findings were fixed in this head, and he re-confirmed 5/5 against native CLZERO.

Why it's good: cpu_emulation passes both plain and under validation.

Tested on Windows 11 / RTX 4070 SUPER (NVIDIA 621.24), VS 2022 + Ninja RelWithDebInfo, Vulkan SDK 1.4.363.0. Alone on main, its tests passed both plain and with LEONIDA_VK_VALIDATION=1. Cumulative: #388, #418, #421, #434, #470, #484, #485, #486 and #488 merged onto main 1504c1af6 (a225e593e). There the repo-consistency set gives 566 passed / 5 skipped / 0 failed, compileall is clean, and full ctest is 306/308. The 2 failures are the same pre-existing ones as main (d3d12_execute_indirect_validation, d3d12_depth_resolve), with the same skip set. git merge-tree against current main 98a977b4b: no conflicts. Security read of the three-dot diff: no binaries, game data, downloads, network calls or CI changes.

AI-assisted (Claude Code, Claude Opus 5.5).

**@⁠QemmHD** on GitHub · 2026-11-24 16:24 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/421#issuecomment-7137626563) Merging. **Why merged:** The CLZERO zeroing loop is emulated as one step instead of one #UD per 64-byte line, which is a large cut in exception traffic on that path. sodove's flag findings were fixed in this head, and he re-confirmed 5/5 against native CLZERO. **Why it's good:** cpu_emulation passes both plain and under validation. Tested on Windows 11 / RTX 4070 SUPER (NVIDIA 621.24), VS 2022 + Ninja RelWithDebInfo, Vulkan SDK 1.4.363.0. Alone on main, its tests passed both plain and with LEONIDA_VK_VALIDATION=1. Cumulative: #388, #418, #421, #434, #470, #484, #485, #486 and #488 merged onto main 1504c1af6 (a225e593e). There the repo-consistency set gives 566 passed / 5 skipped / 0 failed, compileall is clean, and full ctest is 306/308. The 2 failures are the same pre-existing ones as main (d3d12_execute_indirect_validation, d3d12_depth_resolve), with the same skip set. git merge-tree against current main 98a977b4b: no conflicts. Security read of the three-dot diff: no binaries, game data, downloads, network calls or CI changes. AI-assisted (Claude Code, Claude Opus 5.5).
Author
Owner

@⁠Dezmonius on GitHub · 2026-11-24 18:56 UTC · original

Independent Intel check of the merged #421 diff (head 3b8c1555d) applied to DadaCap's boot-prototype at 9173e790. Windows 10 22H2, Core i7-7700K, RTX 5070 / NVIDIA 610.88, MSVC 19.51, Vulkan backend. The stock cpu_emulation CTest passed.

Runtime Runs Successful PresentX per run Final stop
Prototype baseline 2 0, 0 Title watchdog at +0x2215c35
Same prototype + #421 2 2, 2 0xc0000005 at +0xb5a5f8, read of 0x68

The baseline thread snapshot caught the worker in single-instruction CLZERO emulation while the main thread was waiting. The patch consistently got past that watchdog and into Vulkan presentation. Captured frames were black and the menu was not reached.

No game files, traces, disassembly, or captures attached. AI-assisted (Codex).

**@⁠Dezmonius** on GitHub · 2026-11-24 18:56 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/421#issuecomment-7141372741) Independent Intel check of the merged #421 diff (head `3b8c1555d`) applied to DadaCap's `boot-prototype` at `9173e790`. Windows 10 22H2, Core i7-7700K, RTX 5070 / NVIDIA 610.88, MSVC 19.51, Vulkan backend. The stock `cpu_emulation` CTest passed. | Runtime | Runs | Successful `PresentX` per run | Final stop | | --- | ---: | ---: | --- | | Prototype baseline | 2 | 0, 0 | Title watchdog at `+0x2215c35` | | Same prototype + #421 | 2 | 2, 2 | `0xc0000005` at `+0xb5a5f8`, read of `0x68` | The baseline thread snapshot caught the worker in single-instruction CLZERO emulation while the main thread was waiting. The patch consistently got past that watchdog and into Vulkan presentation. Captured frames were black and the menu was not reached. No game files, traces, disassembly, or captures attached. AI-assisted (Codex).
This discussion has been locked. Commenting is limited to contributors.
No description provided.