Skip to content

gh-145629: Expand block inlining to enable LOAD_FAST_BORROW optimization for return ternary expressions#146503

Open
cocolato wants to merge 2 commits intopython:mainfrom
cocolato:gh-145629
Open

gh-145629: Expand block inlining to enable LOAD_FAST_BORROW optimization for return ternary expressions#146503
cocolato wants to merge 2 commits intopython:mainfrom
cocolato:gh-145629

Conversation

@cocolato
Copy link
Copy Markdown
Member

@cocolato cocolato commented Mar 27, 2026

In existing CFG optimization logic, for equivalent conditional code, ternary expressions do not get the LOAD_FAST optimization applied, unlike standard if/else statements:

# Ternary Expression
def f(a, b):
    return a if a < b else b

# if/else
def g(a, b):
    if a < b:
        return a
    else:
        return b

The return in the if/else branch is successfully optimized to LOAD_FAST_BORROW, whereas the else branch in the ternary expression can only generate a standard LOAD_FAST.

Before being passed to optimize_load_fast (the entry point for the reference checking phase), the control flow graphs of the two structures exhibit subtle differences:

For if/else, its else branch naturally belongs to a single basic block, containing both the reference being loaded and the return instruction that consumes that reference:

Block A (jump here from if failure):
    LOAD_FAST          1 (b)
    RETURN_VALUE

Because the local reference is consumed directly within this basic block, optimize_load_fast can determine that the safety constraint is satisfied and convert it into a prioritized LOAD_FAST_BORROW.

However, for a trinary expression, due to the structural characteristics of the AST, the code generator produces the following CFG, which prevents optimize_load_fast from performing the optimization:

Block A (evaluation of the else branch expression):
    LOAD_FAST          1 (b)
    || 
    \/
Block B (small exit return block):
    RETURN_VALUE

So this PR extends the inlining capabilities of basicblock_inline_small_or_no_lineno_blocks:

  • When a basic block is connected to the next block via Fallthrough and no conditional jump instructions block the path, if the target block is an extremely small exit block (e.g., containing only RETURN_VALUE), we can still safely copy it directly and inline it at the end of the underlying block.

@Fidget-Spinner
Copy link
Copy Markdown
Member

To my untrained (for the compiler) eye, this looks fine, but maybe someone else needs to review it.

@Fidget-Spinner
Copy link
Copy Markdown
Member

@mpage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants