Skip to content

fix: collapse ternary with the same constant in both branches#2908

Open
obus-globus wants to merge 1 commit into
skylot:masterfrom
obus-globus:fix/ternary-same-const
Open

fix: collapse ternary with the same constant in both branches#2908
obus-globus wants to merge 1 commit into
skylot:masterfrom
obus-globus:fix/ternary-same-const

Conversation

@obus-globus

Copy link
Copy Markdown
Contributor

NOTE: This is what one may call "AI slop". Feel free to close this PR if it's not up to your quality standards or even if you just aren't interested in reviewing it. I use these changes downstream on an APK and thought I might as well make a PR offering to upstream them, as your CONTRIBUTING.md doesn't say anything discouraging this.

Description

if (c) return x; else return x; (and the assignment form) decompiled to a redundant c ? x : x, a ternary with the same constant in both branches, e.g. return apiException != null ? null : null;. It shows on every input path (dex and java/class alike): TernaryMod forms the ternary without noticing the two results are equal, and nothing removes it.

SimplifyVisitor.simplifyTernary (which already normalizes a ternary's condition) now also collapses c ? x : x to x when both value args are the same constant (InsnArg.isSameConst, covering int/null/string/class constants), for both the return-wrapped and assign-result forms.

Dropping the condition is only safe when evaluating it has no observable effect, so canDropCondition collapses only when every condition instruction is non-throwing and every operand is a parameter or a plain field read (IGET/SGET). foo() ? x : x and a[0] > 0 ? x : x are left as-is, and a cast operand is rejected so the erased CHECK_CAST behind String s = list.get(0) (and its ClassCastException) is never dropped.

This is scoped to same-constant branches. A same-value ternary (c ? v : v with the same variable) is left as-is.

Includes an integration test.

@obus-globus
obus-globus force-pushed the fix/ternary-same-const branch from 9f4d4a9 to e60c4dd Compare July 4, 2026 02:59
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