Skip to content

const-init lowering misplaces reset-on-move blank: Vec field zeroed before struct build when followed by HashMap move #719

Closed

Description

@ehartford

18-line repro (derived from behav_comptime_aggregate_freeze, which stays red on this):

type P { values: Vec[i32], table: HashMap[str, i32] }

comptime fn build() -> P:
    var v = Vec[i32].new()
    v.push(4)
    var t = HashMap[str, i32].new()
    t.insert("left", 11)
    P { values: v, table: t }

const PK: P = comptime build()

fn main:
    assert(PK.values.get(0) == 4)      // panic: Vec index out of bounds
    assert(PK.table.get("left").unwrap() == 11)

Matrix (all verified): top-level const Vec OK; top-level const HashMap OK; {Vec, i64} struct OK; {HashMap} OK; {HashMap, i64} OK; {Vec, HashMap} FAILS; the identical body as an ordinary runtime fn OK. So the bug is specific to the __with_init_const_* path (CodegenTraits.emit_module_runtime_init_fn:1406), which builds a fresh MirBuilder and lowers the comptime body inline.

IR evidence (with ir on the repro, __with_init_const_PK): the vec local %9 is pushed into at mir.bb1, but at mir.bb3 — the block where the MAP local moves (%7→%6) — the lowering emits BOTH memset(%7, 0, 8) (correct: t's reset-on-move) AND memset(%9, 0, 32) (wrong: v's blank, scheduled two statements before v's actual move into the struct at mir.bb4). bb4 then loads the zeroed %9 into P.values → runtime OOB. The map field materializes correctly.

Root area: reset-on-move blank scheduling inside the synthesized init MirBuilder (possibly interaction with pop_scope_inline/missing per-fn init the normal pipeline does). This is drop/blank-scheduling — isolation rule applies; candidate for its own batch alongside/after #716's batch B.

Activity

  1. ehartford commented on Jul 25, 2026

    @ehartford
    ContributorAuthor

    Narrowed (no rebuild needed): the defect is NOT in MirLower's reset-on-move scheduling.

    --dump-mir on the repro shows the ordinary lowering of the same body is correctly ordered:

    bb4: {
        _7 = aggregate(kind=0, tag=0, fields=[move _1, move _4]);
        StorageDead(_4); StorageDead(_1);
        _0 = move _7;
        _1 = const zst(ty93);      // blanks AFTER the aggregate read
        _4 = const zst(ty106);
        return;
    }
    

    The bad ordering appears only in __with_init_const_PK, which is synthesized separately by CodegenTraits.emit_module_runtime_init_fn (~1511): it creates a fresh MirBuilder, calls lower_expr(value_node), then assign_operand_to_place / pop_scope_inline / terminate — without the statement-temp frame discipline (flush_stmt_temp_frame → flush_pending_resets) that a normal function body gets. Pending reset-on-move blanks therefore flush at an inner boundary (the block split created by the insert call terminator) instead of after the aggregate reads its operands.

    Fix direction: give the synthesized init body the same frame discipline as an ordinary body (or hold all pending resets until after the return-place assignment). Test both field orders — {Vec, HashMap} and {HashMap, Vec} — since the trigger is a droppable field whose move is separated from its blank by a call terminator.

  2. ehartford commented on Jul 25, 2026

    @ehartford
    ContributorAuthor

    Hypothesis DISPROVED — recording so the next attempt doesn't repeat it.

    I added the ordinary statement-temp frame discipline around the synthesized init lowering (push_stmt_temp_frame / finish_stmt_temp_frame around lower_expr + assign_operand_to_place in CodegenTraits.emit_module_runtime_init_fn), rebuilt, and the emitted IR for __with_init_const_PK is byte-identical in the relevant ordering: the vec local's blank still precedes the aggregate that reads it.

    call void @llvm.memset.p0.i64(ptr %9, i8 0, i64 32, i1 false)   ; vec blanked
    call void @llvm.memset.p0.i64(ptr %7, i8 0, i64 8,  i1 false)   ; map blanked
    ...
    %27 = getelementptr inbounds nuw %P, ptr %2, i32 0, i32 0        ; aggregate reads the ZEROED vec
    

    So the misplaced blank is NOT caused by the missing statement frame, and the change has been reverted (unproven drop-scheduling edits don't stay in the tree).

    What the evidence still supports: the ordinary lowering of the same body is correctly ordered (--dump-mir shows aggregate(move _1, move _4) then the blanks), so the defect remains specific to the synthesized init path. The next step needs the SYNTHESIZED body's MIR, which --dump-mir does not print because it is built during codegen — so this likely wants a temporary dump of init_body (or an analyze request that exposes codegen-synthesized bodies) to see which move queues the vec's reset before bb3 ends.

    Test status: behav_comptime_aggregate_freeze remains the single red in an otherwise green 905-test lane.

  3. ehartford commented on Jul 25, 2026

    @ehartford
    ContributorAuthor

    ROOT CAUSE — identified at MIR/instruction level, with the exact mechanism.

    Made codegen-synthesized bodies dumpable (WITH_DUMP_INIT_MIR=1, since --dump-mir only prints the Sema-lowered module). The synthesized body for the repro:

    bb2: { StorageDead(_1);                 <-- vec binding killed here
           StorageLive(_4); call HashMap.new }
    bb3: { _4 = move _5;
           _1 = const zst(ty93);            <-- vec BLANKED
           _5 = const zst(ty106);
           call t.insert(...) }
    bb4: { StorageDead(_4);
           _7 = aggregate(fields=[move _1, move _4]);   <-- reads the ZEROED _1
           _0 = move _7; }
    

    The ordinary lowering of the identical source is correctly ordered (aggregate first, then StorageDead, then the blanks).

    LLDB on the emission proves who and why:

    push_stmt(bb=2, kind=StorageDead, local=1)
      <- MirBuilder.pop_scope_inline
      <- MirBuilder.lower_block_mode
      <- MirBuilder.lower_expr
      <- Codegen.emit_module_runtime_init_fn
    

    and tracing block lowerings vs scope pops shows the initializer lowers as two sequential blocks on one MirBuilder:

    lower_block_mode #1 -> pop_scope_inline #1     (kills _1: StorageDead + queues its reset)
    lower_block_mode #2 -> pop_scope_inline #2     (its tail is the aggregate that READS _1)
                           pop_scope_inline #3     (outer scope from emit_module_runtime_init_fn)
    

    So v is bound in block #1's scope, block #1's scope-exit marks it dead and blanks it, and block #2's tail then reads it. The {Vec, HashMap} shape is required only because two droppable bindings straddle the block split — the field ORDER is irrelevant; what matters is a binding created in block #1 being consumed by block #2's tail.

    This also explains why the earlier statement-temp-frame hypothesis changed nothing: pending-reset flushing was never the problem; the binding's SCOPE LIFETIME is. The reset is correct behaviour for a binding whose scope genuinely ended — the defect is that the scope ends while a later block still references the binding.

    Fix direction: the const initializer must be lowered under ONE scope, so bindings live until the initializer's value has been materialized into the return place — i.e. inner block scopes in this synthesized path must not run scope-exit for bindings the initializer's tail still consumes. Open sub-question for the implementer: why lower_expr(value_node) produces two sequential blocks here at all (comptime materialization splitting the body); if that split is itself unintended, removing it fixes the bug at its source.

  4. ehartford commented on Jul 25, 2026

    @ehartford
    ContributorAuthor

    Attempt 3 FAILED and is reverted. Recording it so it is not retried.

    The AST is now fully characterized. ComptimeTransform.ct_build_vec_value_tree / ct_build_map_value_tree materialize a frozen comptime container as a value-position BLOCK whose tail is a bare identifier naming a temp binding:

    { var __ct_vec_N: Vec[i32] = Vec.new()
      __ct_vec_N.push(4)
      __ct_vec_N }            <- tail: bare ident
    

    Scope trace (WITH_TRACE_SCOPES=1) confirms these are two SIBLING blocks inside the init scope, and that the first one's pop is what kills the binding:

    [scope] push depth=0 bb=0
    [scope] block node=6531 stmts=2 tail=6530 want=1 bb=0     (tail = ident __ct_vec_6471_765)
    [scope] push depth=1 bb=0
    [scope] pop  depth=1 bb=2      <- blanks _1 here
    [scope] block node=6547 stmts=2 tail=6546 want=1 bb=2     (tail = ident __ct_map_6471_766)
    [scope] push depth=1 bb=2
    [scope] pop  depth=1 bb=4      <- the aggregate that reads _1 is in this block
    [scope] pop  depth=0 bb=4
    

    Tried: make the tail move __ct_vec_N (NK_MOVE_ARG) so ownership leaves the binding before the scope blanks it. Result: the target repro still panics AND a previously-PASSING control regressed (a single-{Vec} const const started panicking). So an explicit move at the tail makes the blank happen earlier, not later. Reverted.

    Also tried and reverted earlier (see above comments): a statement-temp frame around the init lowering (no IR change), and materializing the block result into a temp before pop_scope_inline in lower_block_mode (no effect — the aggregate consumes the block's tail VALUE, so the operand rewrite did not reach it).

    What is now certain and should anchor attempt 4:

    • The miscompile is _1 = const zst (bb3) preceding aggregate([move _1, ...]) (bb4).
    • StorageDead is NOT the killer; the zero-fill blank is (the passing control has StorageDead before its read and works).
    • The binding is created and blanked inside block Type resolution corruption when single source file exceeds ~14K lines #1's scope while block with ast/check segfault on examples/nebula/src/schema.w #2's tail consumes it.
    • A use-after-kill MIR validator now catches this class (see the linked commit): it proves the blank dominates the read via single-successor chains, is silent on both passing controls, and reports the repro. It runs on synthesized const-init bodies and in audit:mir.
  5. ehartford commented on Jul 27, 2026

    @ehartford
    ContributorAuthor

    Fixed by d2e2284 (flush_stmt_temp_frame now flushes only its own statement's pending resets — 25-line MirLower change, verified minimal). The issue's repro passes on the current tree (v0.15.1-g1d9ae6e35) and is pinned as test/behavior/behav_const_vec_hashmap_struct.w. Batteries including move/drop audits have been green across many runs since the fix landed.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions