Skip to content

refactor(codegen): hoist AllocationStatement allocas to function entry#1656

Open
volsa wants to merge 13 commits intomasterfrom
vosa/hoisted-allocas
Open

refactor(codegen): hoist AllocationStatement allocas to function entry#1656
volsa wants to merge 13 commits intomasterfrom
vosa/hoisted-allocas

Conversation

@volsa
Copy link
Copy Markdown
Member

@volsa volsa commented Apr 2, 2026

This PR changes the behavior of AllocationStatement hoisting them at the function entry block rather than in-place where they were defined. For example

FUNCTION foo
  WHILE TRUE
    alloca tmp: DINT;
    tmp := 5;
  END_WHILE
END_FUNCTION

will roughly (in codegen) translate to

FUNCTION foo
  VAR_TEMP
    tmp: DINT;
  END_VAR

  WHILE TRUE
    tmp := 5;
  END_WHILE
END_FUNCTION

The example also provides the motivation for that behavioral change, i.e. not doing so will eventually "overflow" the stack reaching the maximum stack-memory limit (which on my machine was something like ~8MB)

volsa and others added 12 commits March 30, 2026 17:18
This reverts commit 2bd0bee.
This changes `AllocationStatement` AST semantics globally in codegen: stack
storage is now created in the function entry block instead of at the current
insertion point. Initialization still happens at the original statement
location, so only the allocation is hoisted while reset/store semantics remain
local to the lowered statement.

This is a broader codegen refactor, but it also fixes the regression from the
new loop desugaring. FOR and REPEAT lowering introduces synthetic
AllocationStatement temporaries such as ran_once_N and is_incrementing_N. In
nested lowered loops those allocas previously ended up inside outer loop
bodies, and at -Onone each iteration reserved fresh stack space. Nested FOR
loops with large iteration counts could therefore exhaust the stack and crash
with SIGSEGV.

By hoisting AllocationStatement storage to the entry block, nested lowered
loops now allocate those temporaries once per function invocation while still
reinitializing them at the original control-flow location.

Add codegen and lit regression coverage for the nested loop reproducer and
update affected snapshots.
@volsa volsa mentioned this pull request Apr 2, 2026
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