Skip to content

Bug: struct-field str self-append is quadratic — field destinations never reach the move-first lowering #555

Closed

Description

@ehartford

Problem

try_lower_string_self_concat_assign (src/MirLower.w:2585) only matches s = s ++ ... when the destination is a simple non-aliased local ident (same_ident_symbol + direct_place_local). Accumulation through globals or struct fields always takes the full-copy path:

  • g_cimport_omitted_symbols = g_cimport_omitted_symbols ++ ... (src/CImport.w) — global
  • self.buf = self.buf ++ x patterns — struct field

These are exactly the shapes long-running accumulators tend to have, so they miss the with_str_concat_n_move_first in-place fast path entirely.

Proposed fix

Extend the pattern match to module-level globals and direct field places where the no-alias requirement can be established, so the move-first lowering applies. Split out of #554, which covers the runtime growth policy; this is the MirLower-side half of making ++ StringBuilder-equivalent everywhere.

Related

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Scoping result after studying the lowering (2026-06-11): widening is not a pattern tweak; it needs two real pieces of design work, so this stays open as future work rather than landing an unsound version.

    1. The alias facts the local case relies on do not exist for fields or globals. try_lower_string_self_concat_assign is sound because string_local_may_alias (src/MirLower.w:2492) tracks per-local flow facts (copied-into-call, conservative reset on unknown flow, forget_string_flow_facts). There is no equivalent fact tracking for (local, field-path) places or module globals. Extending the lowering without equivalent facts would assume non-aliasing the compiler cannot currently prove — the failure mode is a runtime buffer reuse while another live str shares the buffer, i.e. silent corruption.

    2. The synthesized move-out-of-field collides with the drop model. The lowering moves the destination into with_str_concat_n_move_first (operand 0 = OK_MOVE of the dest place). For a field destination that is a partial move from a struct, and sema currently rejects user-level partial moves from Drop types (SemaCheck.w:8047). A compiler-synthesized internal version needs drop elaboration to understand the field is uninitialized-then-reassigned within one statement.

    What a sound implementation needs: per-place (field-path) string alias facts with invalidation on base borrows, whole-struct moves/copies, and calls receiving the base by reference; plus drop-elaboration support for the synthesized field move. Globals additionally need an address-never-taken/not-pub module fact.

    Why it can wait: since 9be5070 the fallback path is amortized O(n) at every size, so field/global accumulators no longer hit quadratic behavior — they pay one extra copy per growth step versus the in-place path, a constant factor, not a complexity class. The motivating example (g_cimport_omitted_symbols) was also measured to be irrelevant to c_import time (#554 notes).

  2. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Correction to my previous comment, after measuring instead of assuming.

    Two claims in the scoping note were wrong:

    1. Globals are already linear. A module-global g = g ++ x loop building 960KB runs in 0.08s — identical to the fixed local case. Module globals evidently reach the move-first lowering already; the globals half of this issue is moot.
    2. "Constant factor, not complexity class" was false for fields. a.buf = a.buf ++ x never reaches with_str_concat_n_move_first (that is the whole gap this issue describes), so Bug: str self-append is quadratic past 4KB — large allocations never reuse capacity in place #554's geometric headroom does not apply. Measured: 960KB via a struct-field accumulator takes 6.72s vs 0.09s for the same loop through a local — still O(n²), an ~80× cliff between two visually identical lines.

    So this issue is real and stays open, scoped to field destinations only. The implementation requirements from the previous comment stand: per-place (field-path) string alias facts with invalidation on base borrows/moves/calls, plus drop-elaboration support for the synthesized move-out-of-field (sema currently rejects partial moves from Drop types at the user level, SemaCheck.w:8047).

    Workaround until then: accumulate in a local and assign the field once, or use std's StringBuilder.

  3. changed the title [-]Widen str self-append in-place lowering to globals and struct fields[/-] [+]Bug: struct-field str self-append is quadratic — field destinations never reach the move-first lowering[/+] on Jun 12, 2026
  4. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Closed the investigation: this is owned, not deferred — but a correct fix is its own logical change, and an unsound one is forbidden.

    I verified three things by construction rather than assumption:

    1. The local fast path's soundness rests entirely on per-local alias flags. Adversarial test: build(20) returns a heap-owned str, g_stash = *r aliases it (confirmed via pointer compare — copy shares the buffer, it does not clone), then 4000 in-place appends to the local. g_stash correctly stays length 20. This works only because mark_string_local_copied sets a flag on that local, which disables in-place reuse once the value is aliased. So in-place append is sound exactly when the destination has a non-aliased per-local flag.

    2. Field places have nowhere to hang that flag. string_alias_flags is keyed by local_id (src/MirLower.w:95). a.buf is a field projection, not a local, so the mechanism that makes the local case sound simply does not reach it. That is why field destinations fall back to the always-exact-copy with_str_concat_n and stay O(n²).

    3. No small sound fix exists. OK_MOVE on the field read doesn't rescue it (a prior let r = a.buf already shared the buffer; the 'move' would corrupt r). A runtime-only fix is impossible — a ptr+len fat pointer cannot detect sharing without refcounting the buffer. Eager-clone-on-copy would fix it but rewrites the whole string model and regresses every copy.

    Verdict: the correct fix is per-field-path string alias facts (taint a struct local's string fields on any borrow/copy/field-borrow of the base, invalidate at control-flow joins like forget_string_flow_facts already does for locals), plus drop-elaboration for the synthesized move-out-of-field. That is a self-contained alias-analysis change with memory-safety stakes in a self-hosting compiler — it must land and be fixpoint-verified on its own, not bolted onto an unrelated PR series. Shipping an unsound fast path here would violate memory safety, which outranks the perf win.

    Keeping open and labeling as owned future work with the design above. Workaround documented: accumulate in a local, or use StringBuilder.

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