Skip to content

switchmerge: drop hole labels default reaches, merge range splits, read guarded tables past jumptablemax - #1872

Merged
mahaloz merged 33 commits into
Noelo-Lab:mainfrom
coleleavitt:fix/switchmerge-values
Nov 22, 2026
Merged

mahaloz merged 33 commits into
Noelo-Lab:mainfrom
coleleavitt:fix/switchmerge-values

Conversation

@coleleavitt

Copy link
Copy Markdown
Contributor

[AUTOMATED] Stacked on #1863 (review that first; this branch adds three commits on top of it).

A jump table's holes print as case labels of a goto arm when the switch's default: is not the code they reach but an == test or a range test that only gets there for those values. The reader sees labels that the source never had.

echo a10300b4080401511f1d0071a8000054a90400102a79a8b829010a8b20011fd61f800171000200541fc001710002005411000014200080521900001440008052170000148000805215000014a000805213000014e000805211000014000180520f000014200180520d000014400180520b0000140004001100001952200000b9027c001b220400b94200000b220800b940041c52200c00b9c0035fd600781f53c0035fd690ffffff98ffffffd0ffffffa0ffffffa8ffffffd0ffffffb0ffffffb8ffffff | xxd -r -p > f.bin
kuna decompile f.bin --raw-image --target AARCH64:LE:64:v8A:default --base 0x100000 0x100000 --addr
    case 0x43:
    case 0x46:
      goto label_100074;
    ...
    default:
      if (a0 != 0x60) { // branch-flip
        if (a0 != 0x70) goto label_100074;

With this change case 0x43: and case 0x46: are gone: for both values default: reaches label_100074 before printing anything.

  • switchmerge drops a hole label when, for each value the arm lists, a walk through default: that decides every test and switch on the selector with that value reaches the arm's target before any printed statement. Labels change, the code each value runs does not.
  • if (v > K) { switch (v) A } else { switch (v) B } prints as one switch when every label of A and B takes its own branch and the two defaults do the same thing. An if (v == c) S with no else at the start of default: prints as case c: S.
  • jumptablemax stays 1024, but a table whose guard (not the selector's width) bounds it to at most 65536 entries is read to that bound and refused only when it reaches more than jumptablemax distinct destinations. clang's tables for cmark-gfm's cmark_utf8proc_case_fold are about 1500 entries long and printed as jump-as-call. A 60000-entry table with four arms reads in 2.7 s; switches with 2000 to 65000 distinct arms are still refused in under 0.4 s.

Tests: new stage tests kuna-switchmerge-values.xml (holes, plus an 1100-entry guarded table) and kuna-switchmerge-split.xml (range split, == fold); each has an option switchmerge off run, and both fail without the change. 0/675 datatest assertions move. cmark_utf8proc_case_fold, CFG edit distance to the source: Perplexity's cmark-gfm 1744 -> 370, a clang -O2 build of swift-cmark 3455 -> 70 (231 -> 1401 case labels; the source has 1401).

Model: anthropic/claude-opus-5-5:high

coleleavitt and others added 22 commits November 21, 2026 21:09
…old to its last copy

The extent fold that names a function's jump tables walked each
instruction's p-code linearly. AArch64 csel/csinc lift to a conditional
branch over one copy, so the fold took the last copy as the register's
value: a dispatch whose index a csel picks from constants read as a load
from one address, and its table was never named. The byte-masked last
table of the function before it then had no table to end at and kept
230 phantom rows. A Swift enum-to-string switch on Perplexity iOS
(sub_1028ab1c8) printed its case bodies' mov/movk string-literal chains
as `v1 & 0xffff0000ffffffff | 0x676100000000` joins.

Both folds (decompiler and discovery Listing) now treat what an
instruction writes after a branch inside it as unknown.

This is part of option switchextent (default on). The stage test is
kuna-switchnextcsel-a64.
…itch

A sparse source switch compiles to several range-checked jump tables on one
selector: a failed range check goes to the next table and the holes go to the
default code. kuna printed each table as its own switch nested in the previous
one's default arm, and every hole as a case label of an arm that only jumps to
the code default runs.

New option switchmerge (P8, default on, C output only) plans each switch's
printed arms on the final structured tree: a default arm that starts with a
switch on the same selector takes that switch's arms, and an arm that only
jumps to the default code prints no labels. The goto census places break and
labels for the printed switch. 0/675 datatest assertions move; with the
option off the output is byte-identical to before.

cmark-gfm cmark_utf8proc_case_fold (arm64): 2161 -> 1837 case labels,
17 -> 12 switches; GED vs source 2726 -> 1744.

[AUTOMATED]
…he same place

A jump table's holes go to the source's default code. When the switch's
default arm is not that code but an == chain or a range test that leads on
to the next table, every hole printed as a `case N:` of a goto or break arm.

switchmerge now walks the default arm for each value such an arm lists,
deciding every test and switch on the selector with the value; if the walk
reaches the arm's target before any printed statement, the label is left
out. This is a print-plan change: no value runs different code.

jumptablemax now ships at 16384 (upstream 1024): clang emits range-checked
tables past 1024 entries for one sparse switch, and they printed as
jump-as-call. A 60000-entry table recovers in under a second; a 2-byte
selector with no range check (65536 entries) stays over the cap.

0/675 datatest assertions move. New stage test kuna-switchmerge-values.

cmark_utf8proc_case_fold, ged_measure GED vs source:
Perplexity cmark-gfm 1744 -> 379, clean O2ni build 3455 -> 70.

[AUTOMATED]
… tests into cases

`if (v > K) { switch (v) A } else { switch (v) B }` now prints as one switch
when the value walk sends every label of A and B to its own branch and both
defaults do the same thing. An `if (v == c) S` with no else at the head of
`default:` prints as `case c: S` before `default:`.

Both are print-plan changes: every value runs the same code. 0/675 datatest
assertions move. New stage test kuna-switchmerge-split.

Perplexity cmark-gfm cmark_utf8proc_case_fold, ged_measure: 379 -> 370;
DecBench GED 174 -> 167.

[AUTOMATED]
…(objcsdk)

A for-in loop sends countByEnumeratingWithState:objects:count: with the
address of a stack NSFastEnumerationState. The header reader spelled the
NSFastEnumerationState * parameter as a class pointer and could not spell
the (id [_Nonnull]) buffer or NSDictionary's generic (K []) form, so the
selector had no prototype, and the encoding decoder made every ^{...}
pointer a void *. The state printed as eight loose locals and the loop
read *(objc_object **)(v8 + v7 * 8) for state.itemsPtr[i].

The reader now lays out a pointer to a typedef'd struct with its member
names (^{NSFastEnumerationState="state"Q"itemsPtr"^@...}), spells an array
parameter as a pointer, a scalar pointer with its pointee and a generic
parameter as id; the decoder turns a named struct layout behind a pointer
into a pointer to that struct. The typelocked parameter then types the
stack object (gatherOpen), so the state is one local.

Perplexity 26.46: 3/3 for-in loops of a 390-function sample and 14/14 of
AppAuthCore print one NSFastEnumerationState and state.itemsPtr[i].
…ort's address

A Mach-O __got slot of a data import (a Swift witness table, type metadata or conformance descriptor, an Objective-C class object) holds the import's address. Code that passes that address on, to swift_getWitnessTable or as a message receiver, printed the slot as dat_<slot>. With importdata on, a read of the value the loader put in a slot machodataslots marks as data now renders &<import>; function-import slots and values the function stored are unchanged.

[AUTOMATED]
…eep 1024

The previous commit raised jumptablemax to 16384. A switch with thousands of
distinct arms then reached the structurer and ran past the 120 s budget
(a 4000-case switch with one call per case). Put the default back at 1024
and instead let a table pass the cap when a guard of the switch, not the
selector's width, bounds it to at most 65536 entries; after enumeration
the table is refused when it reaches more than jumptablemax distinct
addresses.

clang's cmark_utf8proc_case_fold tables (about 1500 entries, a few hundred
arms) now recover; a 60000-entry guarded table with four arms reads in
2.7 s; switches with 2000 to 65000 distinct arms stay jump-as-call in
under 0.4 s. 0/675 datatest assertions move.

[AUTOMATED]
A Swift switch over a multi-payload enum indexes its jump table with the
case swift_getEnumCaseMultiPayload returns, with no range check. When the
table is its function's last, or the extent scan dropped the next table,
switchextent had no bound and the dispatch stayed a computed call.

The swiftmetadata pass now records each local enum's case count (payload
cases plus empty cases, from the enum descriptor) by its metadata
accessor. The extent scan follows an accessor's result in a preserved
register into swift_getEnumCaseMultiPayload and the returned case into a
table, and the re-bound uses that count. The scan's register set also
drops its oldest value when full instead of refusing new ones, so a run
of constants early in a function no longer hides later tables.

[AUTOMATED]
…an in-instruction branch as unknown

Chapter 1 describes the discovery Listing's switchextent fold, which this
change also touches; say there that a csel/csinc result is unknown to it.
Rewrap the chapter 2 line the change left at 130 columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
…ount

Chapter 1's swiftmetadata section lists what the pass reads from a nominal
type descriptor; an enum's payload and empty case counts are now among them,
handed to the engine by the enum's metadata accessor for switchextent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
A data-import slot's value read by a mask, shift, multiply or division
printed `&OBJC_CLASS_$_NSObject >> 0x20` and `&Swift.Int.type_metadata | 1`,
which C rejects. Such a read, and a read narrower than the slot, keep
`dat_<slot>` as before; an addition still reads `&<import> + 8`. The check
returns early when the image marked no data-import slot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
…its printed code

The plan drops or moves an arm only when the arm printed before it cannot
run into it, and it judged that from the case's structured out-edges. Two
kinds of arm run into the next arm with no such edge: one whose trailing
jump goes to the arm after it in the switch's own order, which gotonext
prints as nothing, and one whose tail the cross-jump reverter duplicated
(the duplicated leaf carries no edges). Dropping the hole arm after either
sent the arm's values into a different case. falls_through now asks
whether the arm's printed code can run past its end: only a leaf whose
basic block has no successor and a BlockGoto whose jump prints cannot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
A struct decoded from an encoding padded every layout to a pointer and
placed a nested struct's members with no trailing padding. Now that a
pointer to a struct types the stack object a caller passes, a 12-byte
`{Tri2=iii}`, a 4-byte `{Pair16=ss}` or a 3-byte `{Three=ccc}` claimed
eight bytes too many and swallowed the neighbouring spill into a char array
(`*(objc_object **)&v2[0xc] = a0`), and `{Outer={Inner=ic}ci}` put `c` at 5,
not 8. The size is now padded to the widest member's alignment and a nested
struct is aligned and padded as a unit, so those stack objects read
`v2.x + v2.z`, `v2.a + v2.b` and `v2.c1 + v2.c3`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
…all-through test

fold_guards let a second `case` follow a guard's then-branch when that
branch "ended in a jump", which counted any BlockGoto (also one the goto
census prints as nothing) and read a leaf's structured out-edges (none on a
tail the cross-jump reverter duplicated). It now uses runs_past_end, the
test falls_through uses. The value walk of default_reaches stops at a back
edge: past one it can reach a switch whose printed labels no longer match
its table. New assertion SWITCHVALUES #6 (function p, clang -O2 AArch64):
the arm before a table's holes runs into them, so they keep their labels;
before, they were dropped and 0x90 ran the next arm's code. Also drop a
repeated clause from the jumptablemax summary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
… not on the fold's 16-value cap

pick indexed its table with `ldrb w11, [x9, x8]`. SLEIGH lifts that index
through an INT_LEFT by 0, which the fold never folds, so a constant index
never made pick's load address constant there. What hid pick's table was
the fold's 16-value cap: the csel/csinc chain's copies filled it, and the
dispatch's last values were refused. With the join, fewer values are
tracked, so the test passed for that reason, and Noelo-Lab#1877's change to drop
the oldest value passes it too, without this change.

pick now adds the index to the table's address (`add x9, x9, x8;
ldrb w11, [x9]`), so a constant index really makes the load one from a
constant address. The stage test now fails on main and with Noelo-Lab#1877 alone,
and passes with the join. Fixture rebuilt with LLVM 21.1.8, README row,
stage bytes and comment updated; assertions unchanged. The chapter 2
sentence now names that shape.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
The decoder reads a bitfield code `b<n>` as a 4-byte uint, so a layout
such as `^{Packed=b8b4b20[8S]}` gave each bitfield its own word: 36 bytes
for a 20-byte struct, with the array at the wrong offset. The encoding does
not say how the bits pack, so such a struct is not laid out; the pointer
stays `void *`, as before this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
mahaloz and others added 2 commits November 22, 2026 10:52
…nested

An inner switch that is followed by more code in the default arm merges
only when no arm leaves it, since its unlisted values must reach that code.
The check covered fall-through exits and breaks inside arms but not a bare
`case k: break;` arm (a goto case to the switch's exit), which in the merged
switch would leave the outer switch and skip the code. Such a switch now
stays nested. 0 of 8,588 corpus functions change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
@mahaloz

mahaloz commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

[AUTOMATED] Pushed on top of this branch: merges of #1863's updated head (which brings current main), and 663eaed.

  • The hole drops could produce a wrong switch: a hole arm was dropped although the arm before it ran into it. That arm either ended in a jump that gotonext prints as nothing, or had a tail the cross-jump reverter duplicated. Example (clang -O2 AArch64, now function p in kuna-switchmerge-values.xml): case 0x90: v1 = ...; fell into case 0xa1: v1 = 0x2a3; break;.
  • The default_reaches walk now stops at a back edge. Past one it can re-enter a switch whose printed labels no longer match its table.
  • The jumptablemax summary repeated a clause. Fixed, with options.md and phase_catalog.json regenerated.

I checked semantics by recompiling decompiled switches (gcc/clang -O2/-O3; x86-64, AArch64, ARM) and running them against their source. This PR changes 1088 of 7560 functions; 0 now disagree with their source. Later commits:

  • 909986c: a table that only its guard lets past jumptablemax is also refused when it admits more than 4 values per distinct table slot it reads. That covers gcc's if (x <= 0x28ff) goto tbl[x >> 8], which printed 2560 labels for 41 slots and now keeps main's jump-as-call. The new stage test kuna-jumptableslots pins this.
  • 1d32781: the planner reads each arm's labels in one pass over the table, instead of one table scan per label. Output is unchanged, and a 60000-entry switch drops from 3.6 s to 1.0 s.
  • 94c008e: the stage test and the docs.

With the cap, 1055 of the 7560 fuzz functions change, 0 disagree with their source, and on decbench the cap changes nothing.

mahaloz and others added 4 commits November 22, 2026 11:28
…er value

A table that its guard bounds past jumptablemax was refused only when it
reached more than jumptablemax distinct targets. When gcc guards the
original value and indexes the table with a value derived from it
(`if (x <= 0x28ff) goto tbl[x >> 8]`), the guard admits 0x2900 values over
41 slots, and each value printed as its own case label (2560 of them).
Such a table is now also refused when it admits more than four values per
distinct slot it reads (the table entries its emulated values load, or its
distinct targets when it loads none), so it keeps the computed call it
printed before the guard bound. Tables of at most jumptablemax entries are
unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
…table

The switchmerge planner read every label of an arm through
get_index_by_block, which scans the table from its start for each label,
so a pass over a switch's labels cost entries x labels. It reads label sets
several times per switch, which added 1-2.5 s to a 60000-entry switch.
switch_case_labels now collects an arm's table indices in one scan
(JumpTable::kuna_indices_by_block) and gives the same values, sizes and
signedness as switch_case_label for each index; the planner's label sets
use it. Output is unchanged; the planner's share on a 60000-entry switch
drops from about 1.5 s to under 0.1 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
New stage test kuna-jumptableslots: gcc 11 -O2 x86-64 `switch (x >> 8)`
that gcc guards as `x <= 0x28ff` and dispatches through a 41-entry table.
It stays a computed call; before the slot bound it printed a switch on x
with 2560 case labels. The jumptablemax summary and spec chapter 02 state
the bound; options.md and phase_catalog.json are regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKNhsvezm24JAGcKtoV
@mahaloz
mahaloz merged commit c847970 into Noelo-Lab:main Nov 22, 2026
coleleavitt added a commit to coleleavitt/kuna that referenced this pull request Nov 22, 2026
Conflicts: p8_structure/mod.rs (kept both module lines) and the derived
counts (settables 242, tiers 50/129/63, corpus 866, KUNA-CATALOG Noelo-Lab#15 bound
250 = 242 rows + 8 queries); `scripts.repipe.counters --check` reports no
drift and phase_catalog.json recaptures byte-identical.

switchguardmerge and switchtrim stay default-on. Upstream's switchmerge
tests (Noelo-Lab#1872) ran their "switchmerge off" control and expected the pre-fix
text there; this branch's switchguardmerge independently folds the same
guards, so the control runs now print the source-like form too:
- SWITCHSPLIT: the unmerged m prints `case 0x60: return 0x117;` instead of
  `default: if (x == 0x60) return 0x117;` (the test's own comment calls
  the case form the fix).
- SWITCHVALUES: the unmerged f prints `default: goto` instead of
  `case 0x43: case 0x46: goto`, and also folds the 0x60/0x70 guard that
  switchmerge alone leaves as `default: if (x != 0x60) {...}` (also in the
  merged f with switchguardmerge off).
#4/#5 and #1/#3 are updated to these counts (renamed, so the stage baseline
swaps those four keys; 5015/5015 pass). With switchguardmerge off all 12
upstream assertions hold as written. switchtrim does not change either test
or any cmark function. cmark-gfm (Perplexity): switchguardmerge keeps
0x1c87/0x1c88 as cases in _cmark_utf8proc_case_fold (source is one switch);
off, they move to a default: if-chain. O2ni libcmark: no other change.

[AUTOMATED]
@coleleavitt
coleleavitt deleted the fix/switchmerge-values branch November 22, 2026 20:14
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.

2 participants