Skip to content

branchflip: flip negated-guard branches for linearity (angr-style if(x) vs if(x==0)) - #69

Merged
mahaloz merged 2 commits into
mainfrom
feat/branchflip
Jun 25, 2026
Merged

mahaloz merged 2 commits into
mainfrom
feat/branchflip

Conversation

@mahaloz

@mahaloz mahaloz commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

branchflip: flip negated-guard branches for linearity (angr-style if (x) vs if (x == 0))

Follow-up to PR #52 / the tee_O2 x2nrealloc case. angr's SAILR structurer
flips a branch guarded by a negative test (x == 0, !cond) so the
positive condition heads the if and the common path reads top-to-bottom;
kuna (inheriting Ghidra's structurer) keeps the source polarity and emits
if (x == 0). This adds the angr-style flip as an S8 structuring pass,
ActionBranchFlip, behind a new opt-in default-off option branchflip.

What it does

On a 3-component if/else (BlockIf) whose guard is the negated / equality-to-
zero form, it flips the condition to its positive complement and swaps the
if/else arms:

   if (x == 0) { A } else { B }   =>   if (x != 0) { B } else { A }

Mechanism: the cost oracle op_flip_in_place_test already classifies a flip as
0 (removes negation — ActionPreferComplement's job) or 1 (adds negation in
Ghidra's model — == / == 0 / constant compare). branchflip is the mirror of
prefer_complement: it takes the residual 1 class (the negated guards
prefer_complement leaves alone) and reuses the same proven dual-arena flip
machinery (split_flip_in_place_execute + op_flip_in_place_execute +
swap_blocks(sif,1,2)). Registered after the final prefer_complement. Each
flip is logged as a /* WARNING: branchflip: ... */ comment at the guard so the
rewrite is observable.

Scope (honest)

The motivating x2nrealloc guards (if (a0 == 0) break; if-goto, and a 2-armed
if (v3 == 0)) are not flippable in place — the if-goto has no else arm and
the 2-component if would need a synthesized else (region-structurer
territory; x2nrealloc's spurious loop is the separate noreturn_propagate
issue). branchflip is scoped to the polarity normalization it can do faithfully
(3-component if/else); it fires cleanly on e.g. tee_O2's usage,
close_stream, main. See docs/features/branchflip/analysis.md.

Default & gates

  • Default-off (the flip changes rendering, so not a 0/675 no-op → not
    default-on eligible; no DIV entry).
  • Wired: stages.toml settable+surface, KUNA_OPTION_NAMES,
    Architecture::branch_flip (field/ctor/reset/set_kuna_option) and the seam
    copy
    (build_arch_handle + seams.rs). No ElementId / no live_field (like
    stackguard).
  • make test 675/675 PARITY OK; make test-stages 166/166 PARITY OK
    (new tests/stages/branchflip-negated-guard.xml); make rust-test green;
    kuna catalog --check OK; docs/assertions.md regenerated.

Speed (tee_O2, decomp_dbg, median of 7, warm)

function off on
x2nrealloc (no flip) 0.167 s 0.167 s
usage (flips) 0.173 s 0.172 s

The pass is one BFS over the structured tree, only flipping on oracle result 1;
with the option off it is a single flag check (zero added work on the default
path).

🤖 Generated with Claude Code

https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac

mahaloz and others added 2 commits June 25, 2026 17:32
…x) vs if(x==0))

Follow-up to PR #52 / the tee_O2 x2nrealloc case. angr's SAILR structurer
flips a branch guarded by a negative test (x == 0, !cond) so the positive
condition heads the `if` and the common path reads top-to-bottom; kuna kept
Ghidra's polarity (if (x == 0)). A new S8 structuring pass, ActionBranchFlip
(option `branchflip`, opt-in default-off), adds the angr-style flip: on a
3-component if/else whose guard is the negated / equality-to-zero form, it
rewrites `if (x == 0) {A} else {B}` to the positive complement
`if (x != 0) {B} else {A}`.

Mechanism: polarity is decided in S8 (S9/printc faithfully renders the
boolean_flip flag + edge order). The cost oracle op_flip_in_place_test
classifies a flip as 0 (removes negation — ActionPreferComplement's job) or
1 (adds negation in Ghidra's model — ==/== 0/constant compare). branchflip is
the mirror of prefer_complement: it takes the residual `1` class and reuses the
same proven dual-arena machinery (split_flip_in_place_execute +
op_flip_in_place_execute + swap_blocks(sif,1,2)). Registered after the final
prefer_complement. Each flip is logged as a `branchflip:` warning comment at
the guard (new drain_pipeline_comments flushes pipeline-time warnings).

Scope: the x2nrealloc guards themselves (an if-goto break and a 2-armed if)
are not flippable in place — no else arm to swap into; those need the region
structurer + noreturn_propagate. branchflip is scoped to the 3-component
if/else it can flip faithfully (fires on e.g. tee_O2 usage/close_stream/main).

Default-off (the flip changes rendering, not a 0/675 no-op → not default-on
eligible; no DIV). Wired: stages.toml settable+surface, KUNA_OPTION_NAMES,
Architecture::branch_flip (field/ctor/reset/set_kuna_option) AND the seam copy
(build_arch_handle + seams.rs). No ElementId / no live_field (like stackguard).

Gates: make test 675/675 PARITY OK, make test-stages 166/166 PARITY OK,
make rust-test green, kuna catalog --check OK, docs/assertions.md regenerated.
Testcase tests/stages/branchflip-negated-guard.xml; writeup
docs/features/branchflip/analysis.md. Speed in the noise (off==on).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
Resolve union conflicts with main (which since this branch's base landed
gotoreduce, loopbreak_recovery/DIV-10, switchguardbound/#60, tailcalljump/#59,
macho-arm64e, and more). branchflip (S8 readability, opt-in/default-off,
ElementId-free) coexists with all of them:

- stages.toml: union [[settable]]/[[surface]] -> surface 93->94, settable
  47->48 (30 stage-model + 15 analysis + 3 loader); branchflip inserted
  after stackguard, before loopbreak_recovery; header counts updated.
- options.rs KUNA_OPTION_NAMES: union (branchflip + loopbreak_recovery).
- architecture.rs: union the set_kuna_option arm (branchflip on_off! +
  loopbreak_recovery); branch_flip field/ctor/reset/seam-copy all preserved.
- kuna_stages/tests.rs: surface_count 94, settable_count 48, live_value
  present-for-23 / suppressed-for-25 (branchflip is NOT field-backed),
  catalog-json trailing-commas 47.
- catalog_bytecompat.rs: fixture_has_all_48_settables; stage_catalog.json
  fixture regenerated from the binary (byte-for-byte test green).
- verify_w8_fw_universalaction.rs: nonblank 261 (252 C++ + branchflip +
  gotoreduce + 7 headers); list_action_decompile_oracle.txt re-numbered
  for the branchflip + gotoreduce leaves (byte-equal test green).
- xml.rs corpus count 139->140 (83 datatests + 57 stage tests).
- kuna-catalog.xml: source_decompiler=angr 13, structure-recovery 7,
  opt-in-tool 9.
- PROGRESS.md: union both session sets.

No DIV entry (opt-in/default-off; output byte-identical when off).
Regenerated docs/assertions.md + docs/baseline-stages.json (183/183).
Gates: kuna catalog --check OK; make test PARITY OK 675/675; make
test-stages PARITY OK 183/183. docs/baseline.json untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
@mahaloz
mahaloz merged commit 0701879 into main Jun 25, 2026
@mahaloz
mahaloz deleted the feat/branchflip branch July 29, 2026 08:01
mahaloz added a commit that referenced this pull request Nov 9, 2026
IfHelper.ifElseChainDenesting rewrites `if (a) { if (b) X; ...; Y } Z` as
`if (!a) { Z } else { ... }` once the body has *some* jump to the end of the
enclosing sequence (hasDirectEndEdge: a catch's return, a finally handler's
rethrow edge). Unlike reorderIf before the same swapBranches, it does not
check that no jump from inside the if reaches the statements it moves, so a
body that also falls through to Z keeps break edges that now enter the
then-branch from outside (ValidationHelper: "Break edge with closure with
invalid direct path", right after the swap, in both engines). Upstream:
introduced in 91ff9353 (#69), unchanged on develop/1.13.0.

Effects in Vineflower: Z a lone return -> CondenseExits copies it, output
correct but restructured; otherwise a `break` past Z (skipped statement,
missing return: wrong code); with an assert before the try, AssertProcessor
moves the stale edge onto the assert block, Z is emptied and dropped, and
VarDefinitionHelper fails with "Could not find destination nodes for stat id"
(Elasticsearch InternalEngine.closeNoLock).

Fix: skip the swap when an edge from inside the if reaches a statement after
it in the sequence (KunaFix::IfDenestFallthrough, option row, gate in
if_helper.rs; Java kept verbatim under compat).

Evidence:
(a) pass trace (vftrace) identical to Vineflower's on the case; both engines'
    ValidationHelper fail every changed method at the validate call after
    ifElseChainDenesting (IfHelper.java:104 in the release jar); with the fix
    no validation error.
(b) case pkg/TestIfDenestFallthrough (javac 17.0.20.1 -g): default output
    recompiles, `javap -c -p` identical to the original class; the compat
    text does not compile (missing return). closeNoLock recompiled with the
    benchmark's javac/classpath: bytecode exact (169 insns).
(c) jvmdec compat vs default, kuna_fix_diff.py: guava, spring-boot,
    spring-framework, ghidra, elasticsearch (input-full and classes.jar),
    okio, okhttp, kotlin-stdlib, kotlinx-coroutines: differences only in
    closeNoLock (fixed, + its import) and two methods Vineflower printed via
    the healed path: ghidra DataTypeManagerDB.resolveBuiltIn (bytes 0.56 ->
    exact) and spring AnnotationTypeFilter.hasAnnotation (0.92 -> exact),
    both now the source's shape; plus tracker notes.
(d) corpus gate 611/611, 0 regressions; cargo test -p kuna-jvm 485 passed,
    3 ignored; check_spec --strict OK; clippy 1.98.1 -D warnings clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKReqhJewXF589wZswF
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.

1 participant