Skip to content

PE loader: a title's CLZERO loops run as native code on a CPU without CLZERO - #2892

Merged
Prime1997 merged 1 commit into
xcl-dev:nvidia-devfrom
Prime1997:contrib/nv-clzero-native-loops
Nov 26, 2026
Merged

Prime1997 merged 1 commit into
xcl-dev:nvidia-devfrom
Prime1997:contrib/nv-clzero-native-loops

Conversation

@Prime1997

@Prime1997 Prime1997 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Requested by Prime · project thread

On a CPU without CLZERO (every Intel CPU), each run of a title's clzero; add rax, 0x40; cmp rax, <reg>; jb loop raises an illegal-instruction exception that eh::emulate_console_only answers: one exception for every run of the loop. A retail title's memset is such a loop. This patches those loops once, when the image is mapped, into a call of a native stand-in next to the image that zeroes the same whole lines and leaves rax, the flags and every other register as the loop does.

Part of #2688.

Why
On an Intel i5-10400, while a retail title's world loaded, one of its threads stood in the exception path (eh::cpp_exception_logger / is_writable) at every thread dump (XCL_THREAD_DUMP_AT, 300, 360 and 400 s, several runs), and XCL_GPU_TIMES measured 0.17 to 0.51 s of GPU work in world frames that took 17 to 43 s: the GPU stood idle while the CPU side crawled. With the loops patched (6 in that title) the same run's world frames took 1.05 to 1.81 s and it issued 102,739 dispatches where it had issued 12,000 to 24,000. In the 60 s regression run below the title shows 1393 frames against the base's 459.

What is in it

  • crates/xcl/src/eh.rs: cpu_has_clzero (CPUID 8000_0008h EBX bit 0), clzero_loop_thunk (the stand-in for one end register: zero [rax & !63 ..) in whole lines up to it with rep stosb, at least one line as the loop's first pass, rax and the flags as the loop's last add/cmp leave them, no other register changed), code_near (64 KiB a call rel32 reaches), patch_clzero_loops (finds the 12-byte loops with insn::decode, leaves an 0x67-prefixed CLZERO and a loop against rsp alone, writes call + a 7-byte nop). XCL_CLZERO_PATCH=0 keeps the emulation; a lone CLZERO is still emulated.
  • crates/xcl/src/loader.rs: step 9 of mapping an image, after the stack-cookie hook, on a CPU without CLZERO only.
  • Test eh::tests::a_patched_clzero_loop_zeroes_whole_lines_and_keeps_registers: patches a real loop in executable memory and runs it (lines zeroed, bytes around them kept, rax where the loop leaves it, rcx/rdi/rdx unchanged, end at or before the start zeroing one line).

Tested

  • NVIDIA GeForce RTX 3060 Ti 8 GB (driver 32.0.16.1714), Intel Core i5-10400, Windows 11 26200, rustc 1.100.0; debug tests, release smoke.
  • cargo test --locked --workspace --no-fail-fast -- --test-threads=4 with XCL_DXC_DIR set to DXC 1.9.2609.5: 1817 passed, 9 failed, 48 ignored. The 9 failures are the same tests that fail on nvidia-dev eae01502 itself (1816 passed, 9 failed, 48 ignored there, same command): async_compute_pso_registers_real_pso_and_not_standin, console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly, gpu::recomp::tests::gpu_compute_thread_limits_leave_the_lanes_past_them_out, hle::d3d12x::texture_upload::tests::gpu_parts_of_a_texture_go_up_and_the_rest_stays, hle::d3d12x::texture_upload::tests::pieces_hold_the_texels_of_their_levels, split_compute_prefers_the_offline_whole_pipeline, two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs.
  • SKIPPED on this adapter: 27 (no wave64: 20, per-lane f16 form refused: 3, no dxc.exe: 1, no heap windows (opt-in: XCL_HEAP_WINDOWS=1): 1, cannot disable the driver cache (Windows Developer Mode is required): The application requested an operation that depend: 1, no heap windows: 1).
  • GitHub's Build and test (Windows, no GPU) fails here on hle::d3d12x::sparse::tests::a_gpu_write_into_a_gpu_view_lands_in_its_cpu_view (the WARP device is removed, 0x887a0005). That test passes on the card above, on this branch and on eae01502, and fails the same way on the other open pull requests against nvidia-dev (kernelx: physical page homes in window 0 first, from the top, keeping 64 MB free (#2867) #2905, for one).

Regression run
A commit of main (b49be183, the last one before the shader preparation screen of #2555, which prepares every record before the title and so does not fit a 60 s run):

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 3060 Ti
title: 419239bf
seconds: 60
exit: 0x0
frames shown: 363 (PresentX 363)
presents per 2 s (last 3): 16 17 16
device removals: 0
crashes: 0
peak commit: 15320 MB

The base of this PR, nvidia-dev eae01502:

xcl-smoke v1
commit: eae015021c639866ab061cdff2e9daf8ba9daac5
gpu: NVIDIA GeForce RTX 3060 Ti
title: 419239bf
seconds: 60
exit: 0x0
frames shown: 459 (PresentX 459)
presents per 2 s (last 3): 16 17 17
device removals: 0
crashes: 0
peak commit: 15366 MB

This PR's head:

xcl-smoke v1
commit: f9362ed33aa600622cec7bcdf7ab0752da9295e4
gpu: NVIDIA GeForce RTX 3060 Ti
title: 419239bf
seconds: 60
exit: 0x0
frames shown: 1393 (PresentX 1393)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15346 MB

Not tested

  • An AMD CPU: the patch is not applied there, so that path is unchanged; not run.
  • A title whose CLZERO loop has no free address range within 1 GiB (the loops then stay emulated and a line is logged).

AI use
Claude Code (Claude Fable 5.2 and Claude Opus 5.5) wrote the code, ran the suite and the regression runs on the hardware above, and wrote this description; Prime asked for it and owns the account. We coordinate the 8 GB work on the XCL Discord too: https://discord.gg/gK3y7WRRY

🤖 Generated with Claude Code

… CLZERO

CLZERO is AMD's; on an Intel CPU each clzero raises an illegal-instruction
exception that XCL answers by emulating the loop it starts
(insn::ConsoleOnly::ClzeroLoop): one exception for every run of the loop. A
retail title's memset is such a loop. While its world loaded on an Intel CPU
one of its threads was in that exception at every thread dump (300, 360 and
400 s of several runs), and XCL_GPU_TIMES measured 0.17 to 0.51 s of GPU
work in world frames that took 17 to 43 s: the card stood idle while the
CPU side crawled.

When an image is mapped on a CPU without CLZERO, each such loop (12 bytes)
becomes a call of a stand-in next to the image that zeroes the same whole
lines with rep stosb and leaves rax, the flags and every other register as
the loop does. XCL_CLZERO_PATCH=0 keeps the emulation. A lone clzero is
still emulated.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Prime1997 Prime1997 self-assigned this Nov 26, 2026
@Prime1997
Prime1997 marked this pull request as ready for review November 26, 2026 22:48
@saintwolf

Copy link
Copy Markdown

Tested and reviewed commit f9362ed3 (merged cleanly onto nvidia-dev eae01502 alongside #2893–#2897, zero conflicts).

Tested

  • Hardware: NVIDIA GeForce RTX 4070 SUPER (12 GiB, driver 32.0.16.2140), AMD Ryzen 7 7800X3D, Windows 11 build 26300, rustc 1.100.0, debug test build
  • cargo test -p xcl --lib eh::tests::a_patched_clzero_loop -- --test-threads=1: 1 passed, 0 failed, 0 ignored, 0 skipped (a_patched_clzero_loop_zeroes_whole_lines_and_keeps_registers passed)

Review notes

  • Patching logic, register preservation across end_reg (0..15, excluding rsp), and 64-byte line advance look sound.
  • Minor compiler warning on rustc 1.100.0: crates/xcl/src/eh.rs:201 emits warning: unnecessary unsafe block.
  • Minor note: thunk arena pages remain PAGE_EXECUTE_READWRITE rather than flipping to PAGE_EXECUTE_READ after emission, and code_near only searches upward within +1 GiB of the module.

Not tested

  • Runtime CLZERO patching on a non-CLZERO CPU (Ryzen 7 7800X3D has native CLZERO, so only the unit test exercised patch_clzero_loops)
  • Full workspace test suite or retail-title smoke run on this PR

AI use

  • Antigravity (exact model name not provided to the agent): reviewed the diff, ran the build/test command, and drafted this report (checked before posting).

@Prime1997
Prime1997 merged commit 7e63fc6 into xcl-dev:nvidia-dev Nov 26, 2026
2 of 4 checks passed
rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
@pickles976

Copy link
Copy Markdown

Focused Intel/Wine verification of exact head f9362ed33aa600622cec7bcdf7ab0752da9295e4: 3 passed, 0 failed, 0 ignored, 0.04 s test time; checkout production and tests unchanged. Fresh Compiling xcl .../xcl-pr2892/crates/xcl recorded (41.41 s build).

Tested: Intel Core i7-13620H, 16 GiB system RAM, Linux 6.17 / Wine 11.0 / Rust 1.98.1, Windows MSVC target. This is CPU execution, not a GPU fixture; the laptop has an RTX 4060 but no rendering claim is made. Existing external 9 GiB/512 MiB scope and RAM/GPU/disk safety guards retained.

XCL_SOURCE_DIR="$PWD/xcl-pr2892" /usr/bin/bash .compat-tools/cargo-xcl-wine.sh \
  test --locked --target x86_64-pc-windows-msvc -p xcl --lib clzero \
  -- --nocapture --test-threads=1

XCL_CLZERO_PATCH unset. Touched crates/xcl/build.rs and crates/xcl/src/lib.rs before the build to defeat the shared-target cross-worktree cache ambiguity.

Passing owner fixtures:

  • a_patched_clzero_loop_zeroes_whole_lines_and_keeps_registers: patches and actually executes the native replacement on Intel. Checks unaligned-start whole-line zeroing with untouched neighboring lines, final RAX, RCX/RDI/RDX values and the observed carry flag; also the end-before-start one-line case. Log: 1 CLZERO loops run as native code on this CPU.
  • clzero_loop_aligns_updates_flags_and_falls_back_when_end_le_start: existing emulator alignment/flags/one-line fallback contract.
  • clzero_with_an_address_size_prefix_zeroes_at_eax: address-size prefix targets the low-address alias rather than the corresponding high 64-bit address.

Evidence: .compat-runtime/logs/verify-pr2892-clzero-20261126T235036Z/ (console, command/environment, clean provenance and resource samples), guarded command exit 0 in 42.13 s.

Not tested: full suite, every possible end register, retail loader patch-site discovery, opt-out integration, matched-main title regression, loading time/FPS, or gameplay. No title was launched. This clears the selected native-loop/emulator correctness checks here; it does not establish that this fixes our separate Game-Init stalled-fence watchdog, nor certify the complete nvidia-dev integration. The useful next comparison is a controlled title main/head run after the independent Wine synchronization/safety blockers are cleared, not an unchanged crashing launch.

AI-assisted verification/report: omp, OpenAI GPT-6 Astra; results above are from executed local commands.

JR-Wiederkehr pushed a commit to JR-Wiederkehr/xcl that referenced this pull request Nov 27, 2026
…st and version

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
voiceovarian1-max added a commit to voiceovarian1-max/xcl that referenced this pull request Nov 27, 2026
… their first trap

On a CPU without them these instructions trap at every run, and exception
handling is slow under Wine: a retail title's wait loop trapped on MONITORX/
MWAITX ~6,000 times a second (a core's worth of handling), and its CLZERO
loops ran thousands of times a second.
- MONITORX / MWAITX: rewritten in place at the first trap to a NOP of the same
  length (`0F 01 FA/FB` -> `0F 1F FA/FB`, one byte, one atomic store); the
  title's loop polls its memory itself. `XCL_MWAITX_PATCH=0`: emulated as before.
- A CLZERO loop (`clzero; add rax,0x40; cmp rax,r; jb`, after the 10-byte NOP
  pad compilers put before loops) is rewritten once to jump to a 58-byte stub
  near the image that zeroes the same lines with plain stores. `XCL_CLZERO_PATCH=0`:
  emulated as before.
- A thread that trapped before another thread's rewrite runs the new code.
nvidia-dev already rewrites CLZERO loops at image load (xcl-dev#2892,
`patch_clzero_loops`); this rewrite acts at a loop's first trap, for the loops
that still trap. Which loops still reach it on this branch is not measured.
Upstream issue xcl-dev#2497 (ours) describes the CLZERO case. Tests included.

Platform: all

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@throny

throny commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

#2892 (CLZERO loops as native code on a CPU without CLZERO) turns the open world black on an Intel CPU. Found by bisecting nvidia-dev on an i9-12900K + RTX 4080 16 GB (driver 621.40, 2 GiB shader heap profile), same save, same switches for every step (XCL_COHERENT_HEAPS=sparse XCL_TEXTURE_LEVEL_PAGES=1 XCL_CS_PSO_WAIT_MS=200 XCL_TWO_PASS_MB=3072, each build + #684 and #2951 so the launches are quick), a frame dump every 15 frames, judged on the dumps later than 200 s after the first game frame:

commit world dumps with a picture / black / overlay text only
af2cecc4 27 / 0 / 0
eae01502 19 / 7 / 0
71b9f7b2 (merge of #2896) 19 / 13 / 0
7e63fc6d (merge of #2892) 2 / 10 / 7
eff3bcab (merge of #2893) 2 / 9 / 7
3f39671d (head) 0 / 19 / 7

The two "pictures" in the black rows are the last loading-screen frames. From #2892 on, every dump in the world is 100 % black, or black with only the title's overlay text, for as long as the run lasts (15 minutes in three runs). The present rate is the same on both sides (about 2 per second here), there is no crash and no device removal, so nothing else points at it: the title just renders a black scene. On an AMD CPU the patch does nothing, which fits that most testers do not see this.

My guess from the commit message only (I have not debugged it): the stand-in does not zero exactly what the loop would have (a different length, alignment or end pointer in some loop shape), so the title's memset leaves or clears something the lighting depends on.

A run of the head with XCL_CLZERO_PATCH=0 is in progress to confirm from the other side; result follows here. If someone on Intel sees a lit world on nvidia-dev at or after 7e63fc6d, that would contradict this, so please say so.

Numbers are from the logs of these runs. AI use: Claude Code (Claude Fable 5.2) ran the bisect and wrote this.

voiceovarian1-max added a commit to voiceovarian1-max/xcl that referenced this pull request Nov 27, 2026
…time rewrite

nvidia-dev rewrites a title image's CLZERO loops when it is loaded (xcl-dev#2892,
`patch_clzero_loops`); our commit 719be72 also rewrote them at their first
trap. Checked against the retail title's executable: the five loops our runs
rewrote (end registers r10, r10, r9, r8, rdx) all have the 12-byte form the
load-time scan rewrites, as do all 6 loops in its code. So our trap-time
CLZERO rewrite and its stub are taken out; the MONITORX / MWAITX rewrite at
the first trap stays (nvidia-dev emulates those at every pass).

Platform: all

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Anon64

Anon64 commented Nov 27, 2026

Copy link
Copy Markdown

On @throny's guess that the stand-in zeroes something other than the loop: a code check, not a run. It rules that out for the retail title, so the cause is more likely a side effect of the patch.

  • The title's loops: it has 6 CLZERO loops, all of one shape: clzero; add rax, 0x40; cmp rax, <r10 | r9 | r8 | rdx>; jb (the 4C/48 39 C? form, so rax - end). Five run back to back, each starting at the previous one's end register (mov rax, r10; add r10, <size> between them), and the last is followed by sfence.
  • The stand-in, read for that shape (clzero_loop_thunk on nvidia-dev): it zeroes ceil((end - rax) / 64) whole lines from rax & !63, at least one, the same lines the loop does. It leaves rax at start + n * 64 and the flags of the last cmp rax, end, and it restores rcx and rdi. The REX bits of mov rcx, <end> and of the final cmp are right for r8–r10.
  • No branch into a loop: a scan of the title's executable sections for jmp / jcc / call with a target inside the 12 patched bytes (offsets 1–11) found none, so no path lands in the call offset or the nop padding.

Two leads I have not tested:

  1. code_near's arena: it VirtualAllocs 64 KiB in the first free place above each patched image. If the title or XCL later wants that range at a fixed address (the console's layout above the image), that allocation would now fail or move.
  2. Timing: each loop used to be one exception through emulate_console_only (thread dumps caught a thread there at every look during the world load). Now the memsets are instant, which can expose an ordering race somewhere else that the slow path hid.

XCL_CLZERO_PATCH=0 on the head, @throny's run, separates the patch from everything else. If it is the patch, keeping the patch but placing the arena differently would test lead 1.

Tested: none at runtime. Reading nvidia-dev eh.rs plus a local scan of the title's code on an i9-14900KF (no CLZERO), nothing from the title posted.

AI use: Claude Code (Claude Opus 5.5) read the code, ran the scan and wrote this comment.

@throny

throny commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Follow-up, and it is less clean than I hoped. XCL_CLZERO_PATCH=0 on the head does not give back the behaviour of the commit before this PR on this machine:

build CLZERO reaches the world world picture
71b9f7b2 (before #2892) emulated about 200 s after the first frame visible (19 of 32 dumps), 2.4 presents/s
7e63fc6d and the head patched (default) about 200 s black
head 3f39671d, XCL_CLZERO_PATCH=0 (3 runs, two builds) emulated not within 480 s; in a 900 s run after about 450 s then 2-3 presents a minute; the one world dump was black

So the bisect result stands (the merge of this PR is the first black commit), and @Anon64's reading that the stand-in zeroes the right lines may well be right, but the switch is not a clean way back: with it off, loading on the head is more than twice as slow as it was before the PR, although both should be the same emulation. Something else in this PR or after it depends on the patch being on, or the emulation path changed. I have not looked into which. If it helps, I can run 7e63fc6d itself with the switch off, or any instrumented build you give me, on this Intel + RTX 4080 machine.

AI use: Claude Code (Claude Fable 5.2) ran the tests and wrote this.

@Anon64

Anon64 commented Nov 27, 2026

Copy link
Copy Markdown

@throny, on why XCL_CLZERO_PATCH=0 on the head is not the old behaviour: #2892 itself can't be the cause. git diff 71b9f7b2 7e63fc6d is additions only (+145 in eh.rs, +4 in loader.rs, 0 lines removed). The emulated CLZERO path in emulate_console_only is unchanged. The only new call is the loader.rs step that calls patch_clzero_loops, and that returns before doing anything when XCL_CLZERO_PATCH=0. So at 7e63fc6d with the switch off, the code that runs is 71b9f7b2's.

That means the slower loading you saw comes from the merges after it. On nvidia-dev's first-parent history between 7e63fc6d and 3f39671d that is #2893 (eff3bcab), #2894, 8c3f1d10 (16 MB fill a submit), e0821b12, ecc0bb57, 7bf05109, 6f8ccb4a and 3f39671d (fills within 256 MB). Your table already hints at that: the head with the patch on also went black, and 2 of the 3 rows after 7e63fc6d are later merges.

The run that separates the two is the one you offered: 7e63fc6d with XCL_CLZERO_PATCH=0. If it loads in about 200 s with a lit world, as 71b9f7b2 does, then the patch causes the black world, and the slow loading on the head is a separate regression in the later merges. If it is black, or as slow as the head, something outside the code is different between the runs (caches, driver state). Nothing in the diff would explain it.

Tested: none at runtime. From git diff and git log --first-parent on nvidia-dev.

AI use: Claude Code (Claude Opus 5.5) read the diffs and wrote this comment.

@throny

throny commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Correction: my bisect above is wrong, and #2892 is not shown to blacken anything. I am sorry for the noise.

What I got wrong: I judged "visible" from frame dumps taken later than 200 s after the first game frame, assuming the title is in the world by then. That holds only for builds with this PR. Without it (the commits before, and XCL_CLZERO_PATCH=0), loading on this Intel CPU takes about 7 minutes, so the "visible" dumps of af2cecc4, eae01502 and 71b9f7b2 were loading screens: the draw counter in those logs is at 5,000-11,000 when the dumps were taken, against 40,000+ at world entry. A 15-minute run of 71b9f7b2 today confirmed it: still loading at 7 minutes, then about one frame a minute and a title crash at 485 s.

What the data does show:

  • With PE loader: a title's CLZERO loops run as native code on a CPU without CLZERO #2892 the title reaches the world in about 3 minutes on this CPU instead of 7+, as the PR says. That part is a clear win.
  • The world is black in every build that gets there on this machine (RTX 4080, 621.40), and I have no run of any build, old or new, with a non-black frame dump taken in the world. The one dump taken in the world with the patch off (XCL_CLZERO_PATCH=0, 900 s run) was black too. So the black world is not a regression I can pin on a commit; it may always have been there here.

@Anon64's reading of the stand-in stands, and I withdraw the guess about it. I have corrected the pointers on #505, #2572 and #3011.

AI use: Claude Code (Claude Fable 5.2) made the mistake and wrote this correction.

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.

5 participants