x64_recomp: bt/bts/btr/btc, bsf/bsr, tzcnt/lzcnt, and popcnt emitters (X64-RECOMP-BITOPS) #1205

Open
github-bot wants to merge 2 commits from github-bot/gh-1205 into main AGit
Owner

@⁠IlyassRS3 on GitHub · 2026-11-24 20:15 UTC · original
IlyassRS3:feat/x64-recomp-bitops → main · +481 −3 · 2 files · 2 commits · open

Claimed in the coordination issue as: X64-RECOMP-BITOPS (#14)

What and why

Implements the remaining decoded-but-unemitted bit-manipulation instructions in tools/x64_recomp.py (independent of #1174 and #1202, and conflict-free with all open x64_recomp PRs):

  • Asm.rbit / Asm.clz: adds 32-bit and 64-bit bit-reverse and count-leading-zeros encodings (verified against Apple Clang / LLVM 21).
  • bt / bts / btr / btc (_emit_bt):
    • Register forms wrap the bit index modulo operand width (16/32/64), update CF via _set_cf without clobbering N/Z/V, and preserve upper bits on 16-bit writes.
    • Memory immediate forms (0F BA /4../7) mask the immediate modulo operand width; memory register forms (0F A3/AB/B3/BB) sign-extend the bit index from operand width (sxth/sxtw/64-bit) to index bytes before or after the base address (base + (idx >>s 3), bit idx & 7).
    • Drops the spurious flags_r = "C" dependency on bts/btr/btc in _classify.
  • bsf / bsr: sets ZF = (src == 0) and leaves dst unmodified when src == 0 (matching x86-64 hardware); computes LSB/MSB index via rbit/clz for 16/32/64-bit operands.
  • tzcnt (F3 0F BC) / lzcnt (F3 0F BD): decodes F3-prefixed 0F BC/0F BD separately from bsf/bsr, returns operand width (16/32/64) when src == 0, and sets CF = (src == 0) and ZF = (result == 0).
  • popcnt (F3 0F B8): maps F3-prefixed popcnt_jmpe to popcnt (leaving unprefixed 0F B8 unhandled as sys), computes 16/32/64-bit Hamming weight with pure-GPR SWAR (no FP/SIMD dependency), and sets ZF = (src == 0) (N=C=V=0).
  • Pre-existing bug fix in Asm.li(rd, -1): when all four 16-bit chunks are 0xFFFF, nzc was empty and chunks[nzc[0]] raised IndexError; now emits movn rd, #0.
  • Tests (tests/test_x64_recomp_bitops.py): 9 tests covering decoding, LLVM 21–verified encodings, translation, and 5 end-to-end execution tests (BitopsExecTests).

Tested

  • Standalone on main: tests/test_x64_recomp_bitops.py (4 cross-platform passed, 5 exec cleanly skipped without QEMU), tests/test_x64_recomp.py, tests/test_recomp_census.py, tests/test_ci_registration.py, tests/test_text_write_line_endings.py, compileall, make_game.py --help, check_no_game_data.py: all passed.
  • Native arm64 hardware execution on Apple M5 / macOS 27.2.1 (Python 3.14, cleanly triple-merged with #1174 and #1202 in a scratch checkout): tests/test_x64_recomp_bitops.py 9/9 passed, tests/test_x64_recomp_sse.py 16/16 passed, tests/test_x64_recomp.py 46/46 passed (71/71 total).
  • Verified zero conflicts (git apply --check) against open x64_recomp PRs #847, #950, #1120, #1121, #1174, and #1202.

GPUs tested: n/a (CPU x86-64 -> arm64 recompiler; tested natively on Apple M5 arm64, macOS 27.2.1)

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.
**@⁠IlyassRS3** on GitHub · 2026-11-24 20:15 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1205) `IlyassRS3:feat/x64-recomp-bitops` → `main` · +481 −3 · 2 files · 2 commits · open Claimed in the coordination issue as: X64-RECOMP-BITOPS (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/14) ### What and why Implements the remaining decoded-but-unemitted bit-manipulation instructions in `tools/x64_recomp.py` (independent of `#1174` and `#1202`, and conflict-free with all open `x64_recomp` PRs): - **`Asm.rbit` / `Asm.clz`**: adds 32-bit and 64-bit bit-reverse and count-leading-zeros encodings (verified against Apple Clang / LLVM 21). - **`bt` / `bts` / `btr` / `btc`** (`_emit_bt`): - Register forms wrap the bit index modulo operand width (`16`/`32`/`64`), update `CF` via `_set_cf` without clobbering `N`/`Z`/`V`, and preserve upper bits on 16-bit writes. - Memory immediate forms (`0F BA /4../7`) mask the immediate modulo operand width; memory register forms (`0F A3`/`AB`/`B3`/`BB`) sign-extend the bit index from operand width (`sxth`/`sxtw`/64-bit) to index bytes before or after the base address (`base + (idx >>s 3)`, bit `idx & 7`). - Drops the spurious `flags_r = "C"` dependency on `bts`/`btr`/`btc` in `_classify`. - **`bsf` / `bsr`**: sets `ZF = (src == 0)` and leaves `dst` unmodified when `src == 0` (matching x86-64 hardware); computes LSB/MSB index via `rbit`/`clz` for 16/32/64-bit operands. - **`tzcnt` (`F3 0F BC`) / `lzcnt` (`F3 0F BD`)**: decodes `F3`-prefixed `0F BC`/`0F BD` separately from `bsf`/`bsr`, returns operand width (`16`/`32`/`64`) when `src == 0`, and sets `CF = (src == 0)` and `ZF = (result == 0)`. - **`popcnt` (`F3 0F B8`)**: maps `F3`-prefixed `popcnt_jmpe` to `popcnt` (leaving unprefixed `0F B8` unhandled as `sys`), computes 16/32/64-bit Hamming weight with pure-GPR SWAR (no FP/SIMD dependency), and sets `ZF = (src == 0)` (`N=C=V=0`). - **Pre-existing bug fix in `Asm.li(rd, -1)`**: when all four 16-bit chunks are `0xFFFF`, `nzc` was empty and `chunks[nzc[0]]` raised `IndexError`; now emits `movn rd, #0`. - **Tests (`tests/test_x64_recomp_bitops.py`)**: 9 tests covering decoding, LLVM 21–verified encodings, translation, and 5 end-to-end execution tests (`BitopsExecTests`). ### Tested - Standalone on `main`: `tests/test_x64_recomp_bitops.py` (4 cross-platform passed, 5 exec cleanly skipped without QEMU), `tests/test_x64_recomp.py`, `tests/test_recomp_census.py`, `tests/test_ci_registration.py`, `tests/test_text_write_line_endings.py`, `compileall`, `make_game.py --help`, `check_no_game_data.py`: all passed. - Native arm64 hardware execution on Apple M5 / macOS 27.2.1 (Python 3.14, cleanly triple-merged with `#1174` and `#1202` in a scratch checkout): `tests/test_x64_recomp_bitops.py` **9/9 passed**, `tests/test_x64_recomp_sse.py` **16/16 passed**, `tests/test_x64_recomp.py` **46/46 passed** (71/71 total). - Verified zero conflicts (`git apply --check`) against open `x64_recomp` PRs `#847`, `#950`, `#1120`, `#1121`, `#1174`, and `#1202`. GPUs tested: n/a (CPU x86-64 -> arm64 recompiler; tested natively on Apple M5 arm64, macOS 27.2.1) 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. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:42:52 +00:00
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-24 20:15 UTC · original · reviewed

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-24 20:15 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1205#pullrequestreview-6046644655) · **reviewed** Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
Author
Owner

@⁠kevincommits on GitHub · 2026-11-25 23:51 UTC · original

Independent run with QEMU. Apple M5 Pro, macOS 27.2.1 (26B131), Python 3.14.2, QEMU 11.1.3 from Homebrew. I merged main at 33bd07cf8 into the branch locally (960 commits behind, no conflicts). Head tested: a49107929.

Against a reference model the emitters match in 1,501 of 1,502 valid checks. The one that differs is popcnt leaving a stale carry.

  • python -I tests/test_x64_recomp_bitops.py: 9/9 under QEMU. This file calls x.run_result and gates on HAS_QEMU, so its exec tests really run. tests/test_x64_recomp.py 33/33, tests/test_recomp_census.py 11/11. Full standalone suite: 513 run, 509 pass; the 4 that fail are main's 4.

  • Beyond the file, I generated cases under QEMU and compared each against a small Python model:

    • bsf, bsr, tzcnt, lzcnt, popcnt at 16, 32 and 64 bits over 14 source values (0, single bits at each width boundary, all ones, mixed): the full 64-bit destination (so the untouched upper bits, and the unchanged destination when bsf/bsr see 0), ZF, and CF for tzcnt/lzcnt/popcnt.
    • bt, bts, btr, btc on a register at 16, 32 and 64 bits, register and imm8 index, indices 0 to 65 and 0x1234567f (so the modulo-width rule): value and CF.
    • The same four on [rbx+8], imm8 index and register index including 70, -1, -9 and -64 (so the signed bit offset that reaches outside the operand): the 16 surrounding bytes and CF.
  • popcnt after a borrowing cmp leaves CF=1; x86 clears it.

    41 b8 01 00 00 00 41 83 f8 02    mov r8d,1; cmp r8d,2     ; CF=1
    f3 0f b8 c8                      popcnt ecx, eax          ; x86: CF, OF, SF, AF, PF cleared, ZF = (src == 0)
    0f 92 c2                         setc dl                  ; want 0, got 1
    

    FLAG_WRITERS["popcnt"] is "Z", so the analysis still takes the cmp as the carry's producer and reads ARM C in subtract polarity, while the emitter's tst has already set C=0. After stc the same sequence gives 0, which is right only because the polarities happen to agree. Suggested fix: declare popcnt as writing C (and N and V, which tst also leaves at the x86 values) in FLAG_WRITERS. The table entry is on main; this pull request is what makes it reachable.

  • Six further mismatches were my model's mistake, not the code's: with a register index of 70 on [rbx+8] the bit lands in the byte after the 16 I compared. CF was right in those cases and the 16 bytes were correctly unchanged.

One thing I hit while writing the cases, for anyone probing this the same way: a setz placed between bt and setc, in a function where nothing has produced ZF yet, makes the setc read 0. stc; setz; setc does the same on main, and it goes away as soon as any earlier instruction sets ZF, so it is a read of a flag that is live into the function, not something this change does.

Not tested: popcnt_jmpe without f3, the OF/SF/PF results of the scans, and unaligned memory operands (those wait on #2143). No game files used. AI-assisted.

**@⁠kevincommits** on GitHub · 2026-11-25 23:51 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1205#issuecomment-7178134403) Independent run with QEMU. Apple M5 Pro, macOS 27.2.1 (26B131), Python 3.14.2, QEMU 11.1.3 from Homebrew. I merged `main` at `33bd07cf8` into the branch locally (960 commits behind, no conflicts). Head tested: `a49107929`. **Against a reference model the emitters match in 1,501 of 1,502 valid checks. The one that differs is `popcnt` leaving a stale carry.** - `python -I tests/test_x64_recomp_bitops.py`: 9/9 under QEMU. This file calls `x.run_result` and gates on `HAS_QEMU`, so its exec tests really run. `tests/test_x64_recomp.py` 33/33, `tests/test_recomp_census.py` 11/11. Full standalone suite: 513 run, 509 pass; the 4 that fail are `main`'s 4. - Beyond the file, I generated cases under QEMU and compared each against a small Python model: - `bsf`, `bsr`, `tzcnt`, `lzcnt`, `popcnt` at 16, 32 and 64 bits over 14 source values (0, single bits at each width boundary, all ones, mixed): the full 64-bit destination (so the untouched upper bits, and the unchanged destination when `bsf`/`bsr` see 0), ZF, and CF for `tzcnt`/`lzcnt`/`popcnt`. - `bt`, `bts`, `btr`, `btc` on a register at 16, 32 and 64 bits, register and `imm8` index, indices 0 to 65 and `0x1234567f` (so the modulo-width rule): value and CF. - The same four on `[rbx+8]`, `imm8` index and register index including 70, -1, -9 and -64 (so the signed bit offset that reaches outside the operand): the 16 surrounding bytes and CF. - **`popcnt` after a borrowing `cmp` leaves CF=1; x86 clears it.** ``` 41 b8 01 00 00 00 41 83 f8 02 mov r8d,1; cmp r8d,2 ; CF=1 f3 0f b8 c8 popcnt ecx, eax ; x86: CF, OF, SF, AF, PF cleared, ZF = (src == 0) 0f 92 c2 setc dl ; want 0, got 1 ``` `FLAG_WRITERS["popcnt"]` is `"Z"`, so the analysis still takes the `cmp` as the carry's producer and reads ARM C in subtract polarity, while the emitter's `tst` has already set C=0. After `stc` the same sequence gives 0, which is right only because the polarities happen to agree. Suggested fix: declare `popcnt` as writing C (and N and V, which `tst` also leaves at the x86 values) in `FLAG_WRITERS`. The table entry is on `main`; this pull request is what makes it reachable. - Six further mismatches were my model's mistake, not the code's: with a register index of 70 on `[rbx+8]` the bit lands in the byte after the 16 I compared. CF was right in those cases and the 16 bytes were correctly unchanged. One thing I hit while writing the cases, for anyone probing this the same way: a `setz` placed between `bt` and `setc`, in a function where nothing has produced ZF yet, makes the `setc` read 0. `stc; setz; setc` does the same on `main`, and it goes away as soon as any earlier instruction sets ZF, so it is a read of a flag that is live into the function, not something this change does. Not tested: `popcnt_jmpe` without `f3`, the OF/SF/PF results of the scans, and unaligned memory operands (those wait on #2143). No game files used. AI-assisted.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

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

Merge

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