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

Merged
abnalstlll-byte merged 3 commits from upstream-pr/2150 into main 2026-11-26 00:39:16 +00:00
abnalstlll-byte commented 2026-11-25 23:55:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by abnalstlll-byte on 2026-11-25T23:55:01Z.


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)

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5501275558 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2150). Originally posted by [abnalstlll-byte](https://github.com/abnalstlll-byte) on 2026-11-25T23:55:01Z. --- ## 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)
qhukz13 commented 2026-11-26 00:36:24 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by qhukz13 on 2026-11-26T00:36:24Z.


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).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7178930323 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2150#issuecomment-7178930323). Originally posted by [qhukz13](https://github.com/qhukz13) on 2026-11-26T00:36:24Z. --- 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).
aslan2142 commented 2026-11-26 00:39:18 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-11-26T00:39:18Z.


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).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7178979653 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2150#issuecomment-7178979653). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-11-26T00:39:18Z. --- 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).
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!2150
No description provided.