Skip to content

General case-of-case: distribute an accessor/application into the branches it is applied to #243

Description

@Unisay

Problem

#203 pushes an if sitting in the condition of another if down into its branches. The dual is not handled: an accessor or application applied to an if ((if p then a else b).field, (if p then f else g) x) stays outside, so the projection or call is never exposed to the branch bodies where a fold could fire. Distributing the application/accessor/primop into the branch arms exposes it, gated by cheapness of the other operands (complexity ≤ Deref) to avoid code blow-up. pslua has only the narrow #180 rule (a tag-read distributed into if-branches).

Approach

A rewrite that pushes an accessor or a saturated application through an IfThenElse scrutinee into both arms: (if p then a else b).f → if p then a.f else b.f, (if p then f else g) x → if p then f x else g x. Gate on the pushed operation and any co-operands being cheap (the Deref/Trivial end of the Complexity lattice, or the isInlinableExpr test), so a branch is not duplicated with expensive work. The unrestricted form (arbitrary branch bodies) needs join points to avoid duplication and is out of scope until those exist.

Prerequisites / Relations

Relates to #203 (the condition-position dual) and reuses its evaluation-order argument. The unrestricted version wants the join points from #234 (mutual TCO), so the safe distribution here is deliberately the duplication-free subset. Sharper with #231 (the cheapness gate is complexity ≤ Deref), but can ship on the isInlinableExpr test alone.

Verification / Measurement

(if p then a else b).f distributes into the branches and the resulting a.f/b.f fold where a/b are known, in a focused test; a distribution over non-trivial co-operands is declined (the anti-blowup gate). Eval goldens unchanged; the IIFE/closure is removed where the pushed fold fires, visible in structural goldens and #172.

Metadata

Metadata

Assignees

No one assigned

    Labels

    OptimisationA Compiler Optimisationarea: irIR / optimizer / DCE / inlinerenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions