Skip to content

Handle loop backedges across sibling scopes - #121

Merged
AjayBrahmakshatriya merged 1 commit into
BuildIt-lang:masterfrom
AjayBrahmakshatriya:master
Sep 23, 2026
Merged

AjayBrahmakshatriya merged 1 commit into
BuildIt-lang:masterfrom
AjayBrahmakshatriya:master

Conversation

@AjayBrahmakshatriya

Copy link
Copy Markdown
Collaborator

Summary

Fixes #119.

Loop backedges usually target a label in the current statement block or
one of its parent scopes. However, first-stage compiler optimizations
such as tail merging or loop rotation can place the label and backedge
in sibling scopes.

The existing loop finder cannot recognize this structure and may remove
the label while leaving its goto behind, producing invalid generated
code.

This PR adds a normalization pass before loop discovery. For each
sibling-scope backedge, the pass:

  • Finds the common parent of the target label and its backedges.
  • Copies the continuation following the label to each out-of-scope goto.
  • Redirects the copied continuation through a new label in the common
    parent, restoring the structure expected by the loop finder.
  • Handles nested scopes recursively and stops copying at a goto or
    return.
  • Hoists declarations from copied continuations while leaving their
    initializations on the original and copied execution paths.
  • Leaves labels intact when they still have non-local references that
    cannot be normalized.

Declaration splitting helpers previously local to the for-loop finder
are moved into a shared utility for use by the normalization logic.

Tests

Added sample67 covering:

  • A merged first iteration with the same loop body.
  • A merged first iteration with a different prefix.
  • A normalized loop followed by another loop.

Golden outputs are included for both normal variable extraction and
variable-name recovery.

Validated with:

  • make TEST=sample67 run
  • make BUILD_DIR=/tmp/buildit-varnames RECOVER_VAR_NAMES=1 TEST=sample67 run

  Add a normalization pass that copies the continuation of a loop label
  into out-of-scope backedges, restoring the structure expected by the
  loop finder.

  Hoist declarations copied during normalization, retain labels with
  non-local users, and add sample67 regression coverage.
@AjayBrahmakshatriya
AjayBrahmakshatriya merged commit 86413a8 into BuildIt-lang:master Sep 23, 2026
3 checks passed
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.

Generated C can contain a goto to an undefined label after an if followed by a loop

1 participant