x64_recomp: preserve carry flag across zero-count shifts (X64-RECOMP-SHIFT-ZERO-COUNT-CARRY) #2150

Manually merged
github merged 3 commits from gh-pr/2150/head into gh-pr/2150/base 2026-11-26 10:20:20 +00:00
Owner

@⁠abnalstlll-byte on GitHub · 2026-11-25 23:55 UTC · original
abnalstlll-byte:fix/x64-recomp-shift-zero-count-carry → main · +148 −11 · 3 files · 3 commits · merged 2026-11-26 00:39 UTC

Summary

Fixes carry flag inversion when an x86-64 shift or rotate instruction has a count of zero (X64-RECOMP-SHIFT-ZERO-COUNT-CARRY).

In x86-64, shifts and rotates (shl, shr, sar, rol, ror) leave all arithmetic flags untouched when the masked count is zero. In tools/x64_recomp.py:

  1. Immediate count 0 shifts were unconditionally classified with flags_w = FLAG_WRITERS[mnem], causing FunctionTranslator to treat them as flag producers in arm_path, while emitting no instructions (if cval == 0: return). Downstream condition checks (setc, jcc, adc, sbb) therefore used ADD_KIND condition cs against the preceding SUB_KIND instruction (which set ARM C == 0 on borrow), causing inverted carry flag evaluation.
  2. Variable count shifts (cl) skipped execution on cbz(T1, skip) when cl == 0, leaving ARM NZCV in the preceding SUB_KIND instruction's borrow polarity (C == 0 for borrow), while downstream consumers expected ADD_KIND polarity (C == 1 for borrow).

Solution

  1. Immediate Zero Shifts: In _classify(), check if ins.ops[1] is immediate and its masked count (mod 32 for <64-bit, mod 64 for 64-bit) is 0. If so, clear flags_w = "" and flags_r = "". The instruction is not recorded as a flag writer, allowing downstream readers to directly see the true reaching flag producer in arm_path.
  2. Preceding Writer Tracking: In _flag_analysis(), track shift_prev_c, recording the nearest carry writer preceding variable shifts within the basic block.
  3. ARM Carry Normalization on Zero Count: In _emit_shift(), on the cl == 0 path when need_c is true:
    • If the preceding carry producer was in SUB_KIND, invert ARM NZCV bit 29 (eor_i(GTMP, GTMP, 0x20000000)) before jumping to skip. This converts subtraction borrow polarity (C == 0 for borrow) to ADD_KIND polarity (C == 1 for borrow), perfectly satisfying downstream consumers.
    • If there was no preceding carry producer in the block, restore EF_CF from CTX_EFLAGS into NZCV bit 29.
    • If the preceding producer was already in ADD_KIND, ARM C already has the correct polarity.
  4. Materialization: Place _maybe_mkflags(ins) after the skip label so that basic blocks with materialized flags correctly capture the preserved flags when cl == 0.
  5. Testing: Added unit tests in tests/test_x64_recomp.py covering decode flags, reaching producer selection, arm64 translation words, and QEMU execution cases.

Verification

  • python -I tests/test_x64_recomp.py: 41 tests pass (0 failures, 0 errors).
  • python -m compileall -q make_game.py tools tests: Clean.
  • python -I scripts/check_no_game_data.py tools/x64_recomp.py tests/test_x64_recomp.py: Clean (0 violations).
  • python -I tests/test_text_write_line_endings.py: 3 tests pass.

AI-assisted (Claude Code)

**@⁠abnalstlll-byte** on GitHub · 2026-11-25 23:55 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2150) `abnalstlll-byte:fix/x64-recomp-shift-zero-count-carry` → `main` · +148 −11 · 3 files · 3 commits · merged 2026-11-26 00:39 UTC ## Summary Fixes carry flag inversion when an x86-64 shift or rotate instruction has a count of zero (`X64-RECOMP-SHIFT-ZERO-COUNT-CARRY`). In x86-64, shifts and rotates (`shl`, `shr`, `sar`, `rol`, `ror`) leave all arithmetic flags untouched when the masked count is zero. In `tools/x64_recomp.py`: 1. Immediate count 0 shifts were unconditionally classified with `flags_w = FLAG_WRITERS[mnem]`, causing `FunctionTranslator` to treat them as flag producers in `arm_path`, while emitting no instructions (`if cval == 0: return`). Downstream condition checks (`setc`, `jcc`, `adc`, `sbb`) therefore used ADD_KIND condition `cs` against the preceding SUB_KIND instruction (which set ARM `C == 0` on borrow), causing inverted carry flag evaluation. 2. Variable count shifts (`cl`) skipped execution on `cbz(T1, skip)` when `cl == 0`, leaving ARM NZCV in the preceding SUB_KIND instruction's borrow polarity (`C == 0` for borrow), while downstream consumers expected ADD_KIND polarity (`C == 1` for borrow). ## Solution 1. **Immediate Zero Shifts**: In `_classify()`, check if `ins.ops[1]` is immediate and its masked count (mod 32 for <64-bit, mod 64 for 64-bit) is 0. If so, clear `flags_w = ""` and `flags_r = ""`. The instruction is not recorded as a flag writer, allowing downstream readers to directly see the true reaching flag producer in `arm_path`. 2. **Preceding Writer Tracking**: In `_flag_analysis()`, track `shift_prev_c`, recording the nearest carry writer preceding variable shifts within the basic block. 3. **ARM Carry Normalization on Zero Count**: In `_emit_shift()`, on the `cl == 0` path when `need_c` is true: - If the preceding carry producer was in `SUB_KIND`, invert ARM NZCV bit 29 (`eor_i(GTMP, GTMP, 0x20000000)`) before jumping to `skip`. This converts subtraction borrow polarity (`C == 0` for borrow) to ADD_KIND polarity (`C == 1` for borrow), perfectly satisfying downstream consumers. - If there was no preceding carry producer in the block, restore `EF_CF` from `CTX_EFLAGS` into NZCV bit 29. - If the preceding producer was already in `ADD_KIND`, ARM `C` already has the correct polarity. 4. **Materialization**: Place `_maybe_mkflags(ins)` after the `skip` label so that basic blocks with materialized flags correctly capture the preserved flags when `cl == 0`. 5. **Testing**: Added unit tests in `tests/test_x64_recomp.py` covering decode flags, reaching producer selection, arm64 translation words, and QEMU execution cases. ## Verification - `python -I tests/test_x64_recomp.py`: 41 tests pass (0 failures, 0 errors). - `python -m compileall -q make_game.py tools tests`: Clean. - `python -I scripts/check_no_game_data.py tools/x64_recomp.py tests/test_x64_recomp.py`: Clean (0 violations). - `python -I tests/test_text_write_line_endings.py`: 3 tests pass. AI-assisted (Claude Code)
In x86-64, shifts and rotates (shl, shr, sar, rol, ror) leave all flags
untouched when the count is zero.

In tools/x64_recomp.py:
1. Immediate count 0 shifts were classified with flags_w = FLAG_WRITERS[mnem],
   causing FunctionTranslator to treat them as flag producers in arm_path,
   while emitting 0 instructions. Subsequent condition checks (e.g. setc/jcc)
   therefore checked ADD_KIND condition 'cs' against the preceding SUB_KIND
   instruction (which set C == 0 on borrow), inverting the carry flag.
2. Variable count shifts (cl) skipped execution on cbz(T1, skip) when cl == 0,
   leaving ARM NZCV in the preceding SUB_KIND instruction's polarity
   (C == 0 for borrow), while downstream consumers expected ADD_KIND polarity
   (C == 1 for borrow), inverting the carry flag.

Fix:
1. In _classify(), mark shifts and rotates with immediate count 0 (including
   masked mod 32/64 zero counts) with flags_w = '' and flags_r = '' so they
   are not treated as flag writers.
2. In _flag_analysis(), track the nearest reaching carry writer before variable
   shifts in the basic block (shift_prev_c).
3. In _emit_shift(), on the cl == 0 path when carry is needed:
   - If the preceding carry producer was in SUB_KIND, invert NZCV bit 29
     (C := !C) to convert subtraction borrow polarity into ADD_KIND carry
     polarity.
   - If there was no preceding carry producer in the block, restore CF from
     CTX_EFLAGS into NZCV bit 29.
4. Move _maybe_mkflags(ins) after the skip label so that materialized flag
   blocks preserve valid flags on both zero and non-zero count paths.
5. Add unit tests in tests/test_x64_recomp.py.

AI-assisted (Claude Code)
No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
x86 changes no flag for a shift or rotate whose masked count is 0. The
first version patched ARM's carry when cl is 0, taking CF from ctx when no
carry writer came before the shift in its block. But flag liveness treated
the shift as always writing, so a writer in an earlier block never stored
its word, and ctx held a stale CF: cmp r8d, 2 (r8d = 1); jmp; mov cl, 0;
shl eax, cl; setc read 0 instead of 1.

_flag_analysis now treats a shift by cl as a conditional writer: liveness
does not kill the flags it writes, the writer before it stores its word as
well, and a consumer behind it reads the ctx word. With cl = 0 the shift
is skipped whole, its flag store included, so ctx keeps the earlier word.
The ARM-carry patching and shift_prev_c go; the immediate-count-0 change
stays.

Tests: the analysis checks of the patching are replaced by checks of the
new rule, and three execution cases are added (a carry from an earlier
block with cl = 0 and cl = 1, and one a logic op cleared). The first one
fails on the previous head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:20:19 +00:00
github manually merged commit 4a1c850a7a into gh-pr/2150/base 2026-11-26 10:20:20 +00:00
Author
Owner

@⁠qhukz13 on GitHub · 2026-11-26 00:36 UTC · original

Code review at 5ce5769d4 (Linux; tests/test_x64_recomp.py here runs 12 of its 41 tests and skips the 29 that need qemu-system-aarch64, so the new end-to-end cases did not run on my side).

The immediate-zero case is right (no flag writer, so readers see the real producer), and so are the two variable-count paths you handle. One producer kind is still open on the cl == 0 path:

  • A logic op as the previous C writer. For and/or/xor/test, _arm_cond (tools/x64_recomp.py:1452-1457) does not read ARM C and V at all: x86 clears CF and OF there, so b/o are never taken and l/ge map to mi/pl. After a variable shift, though, the consumer's producer is the shift, an ADD_KIND mnemonic, so b maps to cs, o to vs and l to lt, all read from the ARM flags. When cl == 0 those are whatever the logic op left in C and V, which is not necessarily 0 (ARM's flag-setting logical ops leave V alone and C as the shifter left it). So test eax, eax; shl ebx, cl; jb/setc/adc/jl with cl == 0 can take the wrong branch. prev_c finds the logic op (it has C in flags_w), prev_c_in_sub is false and it is not None, so it goes to the plain cbz path.
  • A fix in the same place: when prev_c.mnem in LOGIC_KIND, clear C and V in NZCV on the zero-count path (CF = OF = 0 as x86 left them), next to the SUB_KIND inversion. A case like test_var_shift_sub_kind_producer_inversion with test before the shift would pin it.

AI-assisted (Claude Code).

**@⁠qhukz13** on GitHub · 2026-11-26 00:36 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2150#issuecomment-7178930323) Code review at `5ce5769d4` (Linux; `tests/test_x64_recomp.py` here runs 12 of its 41 tests and skips the 29 that need `qemu-system-aarch64`, so the new end-to-end cases did not run on my side). The immediate-zero case is right (no flag writer, so readers see the real producer), and so are the two variable-count paths you handle. One producer kind is still open on the `cl == 0` path: - **A logic op as the previous C writer.** For `and`/`or`/`xor`/`test`, `_arm_cond` (`tools/x64_recomp.py:1452-1457`) does not read ARM C and V at all: x86 clears CF and OF there, so `b`/`o` are never taken and `l`/`ge` map to `mi`/`pl`. After a variable shift, though, the consumer's producer is the shift, an `ADD_KIND` mnemonic, so `b` maps to `cs`, `o` to `vs` and `l` to `lt`, all read from the ARM flags. When `cl == 0` those are whatever the logic op left in C and V, which is not necessarily 0 (ARM's flag-setting logical ops leave V alone and C as the shifter left it). So `test eax, eax; shl ebx, cl; jb/setc/adc/jl` with `cl == 0` can take the wrong branch. `prev_c` finds the logic op (it has `C` in `flags_w`), `prev_c_in_sub` is false and it is not `None`, so it goes to the plain `cbz` path. - A fix in the same place: when `prev_c.mnem in LOGIC_KIND`, clear C and V in NZCV on the zero-count path (CF = OF = 0 as x86 left them), next to the SUB_KIND inversion. A case like `test_var_shift_sub_kind_producer_inversion` with `test` before the shift would pin it. AI-assisted (Claude Code).
Author
Owner

@⁠aslan2142 on GitHub · 2026-11-26 00:39 UTC · original

Merged, thanks! x86 changes no flag for a shift or rotate whose masked count is 0, and the recompiler now follows that.

  • Immediate count 0 (yours): such a shift is no longer a flag writer, so a later setc/jc sees the real producer.
  • Count in cl, changed by us (4a1c850a7): patching ARM's carry at the shift left one case wrong. With the carry from an earlier block, cmp r8d, 2 (r8d = 1); jmp; mov cl, 0; shl eax, cl; setc read 0 instead of 1, because liveness treated the shift as always writing and the earlier writer never stored its word. _flag_analysis now treats a shift by cl as a writer that may leave the flags alone: the flags stay live across it, the writer before it stores its word too, and a consumer behind it reads the ctx word. With cl = 0 the shift is skipped whole. docs/mobile.md says so.
  • Tested: all 44 tests in test_x64_recomp.py, including qemu runs of the carry from an earlier block with cl = 0 and cl = 1 and of a carry a logic op cleared; the first fails on the previous head. The docs and line-ending tests pass.
  • Checked on main 61732aca1 + 4a1c850a7: the semantic suite passes (495 files, 6,333 tests, 0 files failed); test_x64_recomp pass; the 15 docs and writer tests pass; check_no_game_data.py is clean on the 3 changed files.

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

**@⁠aslan2142** on GitHub · 2026-11-26 00:39 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2150#issuecomment-7178979653) Merged, thanks! x86 changes no flag for a shift or rotate whose masked count is 0, and the recompiler now follows that. - **Immediate count 0** (yours): such a shift is no longer a flag writer, so a later `setc`/`jc` sees the real producer. - **Count in `cl`, changed by us** (`4a1c850a7`): patching ARM's carry at the shift left one case wrong. With the carry from an earlier block, `cmp r8d, 2` (r8d = 1); `jmp`; `mov cl, 0`; `shl eax, cl`; `setc` read 0 instead of 1, because liveness treated the shift as always writing and the earlier writer never stored its word. `_flag_analysis` now treats a shift by `cl` as a writer that may leave the flags alone: the flags stay live across it, the writer before it stores its word too, and a consumer behind it reads the ctx word. With `cl = 0` the shift is skipped whole. `docs/mobile.md` says so. - **Tested:** all 44 tests in `test_x64_recomp.py`, including qemu runs of the carry from an earlier block with `cl = 0` and `cl = 1` and of a carry a logic op cleared; the first fails on the previous head. The docs and line-ending tests pass. - **Checked on `main` `61732aca1` + `4a1c850a7`:** the semantic suite passes (495 files, 6,333 tests, 0 files failed); `test_x64_recomp` pass; the 15 docs and writer tests pass; `check_no_game_data.py` is clean on the 3 changed files. AI-assisted (Claude Code, Claude Opus 5.5).
This discussion has been locked. Commenting is limited to contributors.
No description provided.