Repository navigation
[AUTOMATED] s8: iteboolean - re-roll short-circuit 0/1 select diamonds into a boolean assignment (DIV-51) - #241
Merged
Merged
Conversation
…s into a boolean assignment (DIV-51) gcc at -O0 materializes a source `x = a && b;` as a jump-based select whose constant-0 arm is the shared target of every short-circuit exit. kuna printed that as an explicit two-arm constant diamond where the source and Hex-Rays have one statement; on bash time_command two of them are the entire residual structural gap vs IDA (GED 26 -> 6 with them re-rolled). Upstream fidelity: the P3 RuleConditionalMove bail that leaves this alone is a FAITHFUL port of upstream Ghidra (ruleaction.cc:9424-9439, `if (inblock->sizeIn() != 1) return 0;` on each MULTIEQUAL input block), so this ships as an option, not as a bug fix. The bail is also right at the IR level -- the constant arm's extra predecessor is a different CBRANCH whose boolean does not dominate the join, and reconstructing the whole chain would hoist a guarded load above its guard -- so the re-roll is done at P8, after structuring, where the chain is already one BlockCondition that C's own &&/|| renders with short-circuit semantics. ActionIteBoolean (p8_structure/kuna_iteboolean.rs, ELEM 4119) marks a 3-component gotoless BlockIf whose condition is that BlockCondition and whose two arms are each a single COPY of the constants 1/0 to the same integral storage; PrintC::emit_block_if_bool emits `v = ( cond );` (arms 0/1 -> `v = !( cond );`). Print-only: an addl-flag on the condition's terminal CBRANCH, no p-code cloned or mutated, so `option iteboolean off` is byte-identical. Requiring the BlockCondition is what makes the rewrite value-safe and not just shape-safe: &&/|| and the negating ! always yield exactly 0/1 in C, while a bare leaf condition renders truthy under DIV-37 (`if (x & 0x100)` prints `(x & 0x100)`, worth 0x100) and would store the wrong number. That bare-leaf shape is also the one P3 already folds. Measured: GED on O0-bash-bash-time_command 55 (recorded) / 26 (today's build) -> 6; 675/675 PARITY OK with the flip and no re-pin; 14 -O0 decbench binaries / 10,494 functions -> 126 functions change (1.2%), 160 diamonds collapse (81 positive, 79 negated), and a mechanical audit of all 160 confirms every emitted expression is boolean-valued at its top level; interleaved medians of 5 show no speed cost. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
mahaloz
added a commit
that referenced
this pull request
Aug 2, 2026
mahaloz
added a commit
that referenced
this pull request
Aug 2, 2026
…IV-52) (#242) * [AUTOMATED] fix(p9): (NOVEL) one local declaration per ScopeLocal Symbol (DIV-51) `PrintC::emitLocalVarDecls` walks HighVariables; upstream `emitScopeVarDecls` walks the ScopeLocal *Symbol* table (printc.cc:2667/2696), which is what makes one symbol one declaration. When two live ranges of one mapped stack slot did not merge, the shared-storage naming gave both the same name and P5 recovered different types for them, so the function opened with the same identifier declared twice at two widths: void applyLedFixedLayers(void) // betaflight_STM32F405, O2-noinline { ... unsigned int v12; // stack - 0x24 uint4 v12; // stack - 0x24 That is not compilable C, and a reader cannot tell which `v12` any body occurrence means. Ghidra emits one `undefined4 local_24;`, IDA one `int v23;`. The only collapse that existed, `option dedupvardecls` (DIV-7, default on), keys on the fully rendered LINE, so two spellings of one slot both survive by construction -- its own module doc recorded that residual as intentional. The composite (array/struct/union) collapse sitting beside it was already Symbol-keyed; the scalar case was the documented gap ("primitive types are shared by every scalar local of that type", so the type-Rc key does not identify a symbol). Upstream-fidelity verdict: an UNPORTED rule, not a mis-ported or deliberately simplified one. The scalar collapse is now Symbol-keyed too, inside that same option: highs whose declaration representative resolves to the same containing ScopeLocal Symbol -- base-byte containment, the query C++ `Funcdata::linkSymbol` itself uses (funcdata_varnode.cc:1190) -- AND that render the same identifier emit one declaration. Requiring the identifier to match is what makes the collapse incapable of removing the last declaration of a referenced name, i.e. the mirror-image failure #131 fixed. It is load-bearing: on the campaign function nine highs of symbol 5v13 are named `v12` (all whole 4-byte covers, so naming them alike is correct) while its partial covers carry their own names `v14`/`v15`/`v16`, and those must all keep their declarations. The duplicate NAME is therefore not a naming defect -- naming per symbol is right, and the declaration layer is where the rule was missing. Type arbitration when the collapsing highs disagree: the Symbol's own type, which is what C++ `emitVarDecl` declares (`sym->getType()`, printc.cc:1719) -- unless it is narrower than the widest storage the group covers, in which case the widest member wins. kuna's ScopeLocal ranges are sometimes narrower than the accesses that reach them (upstream `restructure` would have grown the symbol), and declaring a 2-byte object for a slot the body writes 4 bytes into and passes by address would be a new defect rather than a faithful one. A group that already agrees keeps its recovered type, which is sharper than the usually-`undefined<N>` symbol type. Strict bug fix inside an existing default-on option, so no new flag; recorded as DIV-51. `option dedupvardecls off` still restores the per-high rendering. Measured before/after on 14 decbench binaries / 11,874 functions (x86-64 and ARM Cortex-M, -O0 and -O2), the first measurement of this bug's real scope: functions emitting a duplicate local declaration 18 -> 0. The blast radius is exactly those 18 -- no other function changes a byte, 21 declaration lines disappear (35,412 -> 35,391), no function loses a declared name and none gains one. Every survivor is at least as wide as every access it absorbed (`undefined3`/`unsigned short`/`char` shadows of a 4-byte slot become one `unsigned int`). The collapse only runs where two declarations already share an identifier, so the symbol lookups are skipped on nearly every function; interleaved medians of `decompile-all --mode reliable`: betaflight STM32F405 (6,387 functions) 69,782 -> 69,754 ms (-0.04%), bzip2 9,926 -> 9,863 ms (-0.63%), gzip 3,162 -> 3,211 ms (+1.55%, 9 pairs). `verify_declared_vars` now asserts both failure modes on the `declmerge` fixture: no name undeclared (#131) and no name declared twice. `tests/stages/ghdec-symbol-keyed-local-decls.xml` is the end-to-end witness over a real binary -> decompile(addr) path (4 of 6 assertions pass pre-fix, 6/6 post-fix); it uses the smallest function in the same firmware showing the same defect, with `option dedupvardecls off` as pass 2 pinning the bug form. This function was already tied-best on the benchmark (kuna GED 25 == ghidra 25), so the fix moves zero benchmark points; its value is that the output stops being invalid C. Gates: make test PARITY OK (675/675, baseline untouched), make test-stages PARITY OK (352/352, re-recorded -- delta is purely the 6 new keys), make rust-test green, make check-spec OK, kuna catalog --check OK. inspiration = "decbench:O2-noinline-betaflight-betaflight_STM32F405-applyLedFixedLayers; NOVEL pool" Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo * [AUTOMATED] renumber DIV-51 -> DIV-52 (DIV-51 taken by #241 iteboolean) --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes the whole residual structural gap vs Hex-Rays on the mined decbench case
O0-bash-bash-time_command: a short-circuit boolean assignment (x = a && b;)staying an explicit
0/1diamond.The gap
Source (
execute_cmd.i,time_command):kuna before (
--mode reliable, whatautopicks for this 1.5 MB binary):kuna after (this PR, default):
Two diamonds = 6 CFG blocks / 8 edges of a 28-node function. Full panes:
docs/features/iteboolean/kuna-time_command-{off,on}.c.Upstream-fidelity verdict: faithful port ⇒ this is a feature, behind an option
P3
RuleConditionalMoveis the rule that foldsMULTIEQUAL(0,1)intozext(cond)/BOOL_AND/BOOL_OR. It fires on the simple one-test shape andbails when a MULTIEQUAL input block has more than one predecessor. That bail is
verbatim upstream,
Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.ccRuleConditionalMove::applyOp(lines 9424-9439, upstreamf9e13846b20c223334d37cfe75bf36fbe9e4dce7):kuna's
p3_dataflow/ruleaction_7.rs:1894-1914reproduces this character forcharacter. So it is a judgment call beyond upstream, not a mis-port: option,
not silent bug fix.
And the literal P3 relaxation is not implementable. gcc compiles the idiom to
The constant arm B2's extra predecessor is a different CBRANCH. B1's boolean is
not even defined on the B0 path, so folding the select to
zext(B1.cond)would bean SSA violation as well as wrong; and reconstructing the whole chain condition at
P3 would have to hoist
p[1]above itsp != 0guard. Upstream's bail is right atthe IR level — the short-circuit must stay in the CFG, and only C's own
&&/||can express it.
Where the decision belongs (P8, print-only)
By the end of structuring the chain P3 could not see is already one
BlockCondition— kuna prints it today as theif's condition, complete withC's short-circuit semantics and any comma-expression side effects. That is where
the re-roll is expressible and safe.
ActionIteBoolean(p8_structure/kuna_iteboolean.rs, ELEM 4119) marks a3-component gotoless
BlockIfwhoseBlockCondition(a tree of clean, unlabelledCBRANCH-terminated leaves, depth ≤ 16), and whoseCOPYofthe constants
1and0(either order) to the same integral storage,and
PrintC::emit_block_if_boolemitsdest = ( cond );(arms0/1->dest = !( cond );). The condition goes through the sameONLY_BRANCHrendererthat produced the
if (...)header, so parenthesization, evaluation order,short-circuiting and comma side effects are preserved verbatim. Print-only: an
addl-flag (
kuna_iteboolean, 0x4000) on the condition's terminalCBRANCH; nop-code is cloned or mutated, so
option iteboolean offis byte-identical.The safety argument (this is the part that could have produced wrong code)
Requiring the
BlockConditionis what makes the rewrite value-safe, not justshape-safe.
&&/||and the negating!always yield exactly0/1in C — thetwo constants the arms wrote. A bare leaf condition gives no such guarantee:
under
truthycond(DIV-37) anif (x & 0x100)renders as(x & 0x100), sov = (x & 0x100)would store 0x100 instead of 1. That bare-leaf shape is alsoexactly the one P3 already folds, so excluding it costs essentially nothing
(1 function / 1 diamond across the 14-binary corpus below). The matcher also
declines pointer/float/aggregate destinations (they would lose the constant's own
rendering/cast), labelled arms, computed arms, and any second statement in an arm.
Mechanical audit of every rewrite across the corpus: 160/160 emitted
expressions are boolean-valued at their top level (81 positive
v = ( a && b );,79 negated
v = !( ... );), 0 exceptions.Source-level spot checks (kuna output vs the project's own
.i):print_line_taileol_size = (lim > beg && lim[-1] == eolbyte);v1 = !((a1 <= a0) || (*(char *)(a1 - 1) != dat_33183));grepskip_nuls = skip_empty_lines && !eol;dat_33830 = ((dat_33831) && (!v2));yesnoyes = (c == 'y' || c == 'Y');v1 = !((v2 != 0x79) && (v2 != 0x59));Each is the exact De Morgan dual of the source.
num += out_line && num < INTMAX_MAX;likewise becomes
v6 = ((dat_33852) && (v19 != 0x7fffffffffffffff)); v19 += v6;—the
&&value is 0/1, so the+=is right.Ablation
One stage test needed a per-test
option iteboolean off:ghangr-earlyreturn,whose witness is a 0/1 diamond, so the re-roll would collapse it before the
return phi earlyreturn is about ever forms. No baseline was re-pinned.
Measurements
GED, the mined case (
scripts.decbench.rescore --case O0-bash-bash-time_command):28 nodes / 43 edges vs the source's 28/44 — exactly the hand-rerolled pane the
triage note predicted.
Corpus breadth —
kuna decompile-all, option off vs on, 14-O0decbenchbinaries:
finddiffipe2fsckminigzipinit/ shadowsu/ croniecrondSpeed —
decompile-all --mode reliable, interleaved median of 5 (off/onalternating; the machine was shared, so both arms absorb the same contention):
diffNo measurable cost — the pass is one linear walk of the structured tree with a
cheap match and no p-code mutation. Budget is +5%.
Gates
make testmake test-stagesmake rust-testmake check-spec--strict)kuna catalog --checkcatalog OKWhat's in the PR
p8_structure/kuna_iteboolean.rs(new),p9_emit/printc.rs(
ite_boolean_match+emit_block_if_bool, checked before theiteregionternary so the more specific form wins),
substrate/op.rs(addl-flag 0x4000),schedule entry after
iteregion.iteboolean(phases.tomlsettable +p0_knowledge/options.rs+Architecture/ArchSeamwiring) and the hard-coded catalog counts(82 -> 83 settables, transform tier 37 -> 38,
catalog_bytecompat+ itsphase_catalog.jsonfixture,kuna-catalog.xmlstructure-recovery 20 -> 21,the
list_actionschedule oracle + leaf count 269 -> 270).tests/stages/ghdec-iteboolean.xml(two-pass over a real gcc-O0binary -> decompile(f)path: 2 of 4 assertions fail with the option off, 4/4with it on), corpus file count 182 -> 183,
docs/baseline-stages.jsonre-recorded.
docs/spec/08-structuring.md(newitebooleansection, incl. theupstream-fidelity argument) and
docs/spec/09-emission.md; DIV-51 indocs/history.md; regenerateddocs/options.md; feature bundledocs/features/iteboolean/.Provenance:
inspiration = "decbench:O0-bash-bash-time_command",source_decompiler = "ida",change_kind = "structure-recovery",tier = "transform".🤖 Generated with Claude Code
https://claude.ai/code/session_011RXVU58TKJxb518oViChwo