Skip to content

Complete callable FnAbi descriptors and stdlib Phase 0 - #1129

Merged
ehartford merged 20 commits into
mainfrom
fnabi-phase0
Sep 14, 2026
Merged

ehartford merged 20 commits into
mainfrom
fnabi-phase0

Conversation

@ehartford

@ehartford ehartford commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Callable signatures now share FnAbi descriptors across declarations, indirect calls, closures, adapters, async entries, and destructors. This removes the separate parameter masks and per-path ABI classification that allowed callers and callees to disagree, including C va_list callbacks and aggregate arguments beyond the old 64-bit mask.

Phase 0 adds the stdlib inventory and a complexity lane, and replaces SlotMap's linear occupancy scan with a FIFO free list. Freed slots rejoin the tail, exhausted generations retire permanently, and value ownership is checked across reuse, growth, removal, and destruction. The sourcing plan and inventory include Eric's selected facade engines.

Verification also exposed and fixes collection-literal ownership, duplicate-key replacement cleanup, observer field projection through Box, modeled record field identities, string-concat validation, and a build-cache compiler-fingerprint lifetime bug. Debugger and allocator findings are recorded in docs/phase0-ownership-debug.md and docs/build-compiler-fingerprint-debug.md. Eric blessed the added --trace-alloc entry in specification §18.5.

Validation on Darwin arm64 at -O1:

  • Full build and full :test passed; test-green recorded the completed run. Behavior: 1,005 tests; compile errors: 756; codegen: 16. PCRE2 and zlib bundle drift checks passed byte-for-byte.
  • Compiler analysis audit: 2,514,772 facts, zero violations.
  • Drop audit: 119 cells passed, zero regressions. Move audit: 15 cells passed, zero differences from ground truth.
  • Final-tree fixpoint passed byte-for-byte. Pinned v0.15.2.0 seed compatibility passed by building stage1 of an isolated tree copy.

The complexity lane retains explicit expected failures for #937, #938, and #939; it does not disguise those cliffs as fixed. The selected M*LIB B+ tree retires #937 in Phase 4, while STC's Phase 3 work addresses the default hash engine and consuming iteration. Broader analysis-tool gaps are tracked in #1117, #1119, #1123, and #1127.

Closes #1106.
Closes #936.
Closes #1118.
Closes #1120.
Closes #1121.
Closes #1122.
Closes #1125.

Eric Hartford added 14 commits September 12, 2026 04:42
Compute immutable FnAbi/ArgAbi records once and share them across named
declarations, callable types, adapters, prologues, and call marshalling.
Remove parallel ABI tables and 64-bit parameter masks. Preserve owned
destructor storage across body/field cleanup without reclassifying it as
a borrow. Extend declaration/call audits to check descriptor shapes and
actual byval attributes.

LLDB evidence: raw_fn_type selected internal_abi_needs_sret=false for a
large indirect C return; declare_function_at_inner's owner-type shortcut
registered consuming parameters as references. The 65th C aggregate's
attribute was skipped at apply_c_abi_byval_attrs+120: x25=64, x8=0,
x22=0xffffffffffffffff after the out-of-range shift check.

Restore the function-level temporary frame in default trait methods.
The native allocator traced one leaked 16-byte clone through Person.name;
register_stmt_temp+36 had x0=0, local=2, type=16 and skipped registration
from generate_default_trait_method_for_impl. Track the audit's missing
synthesized-body ownership coverage in #1117.

Validation: source check and -O1 stage1 build; five-target callable and
c_va_list IR/audit matrices; 65-parameter aggregate audit; native callback
and consuming-receiver results; default-tail and consumed-field allocator
fixtures report leak count=0. Full bootstrap battery follows this commit.

Refs #1106
Register async declarations from finalized signatures, preserving inferred Unit, scalar and aggregate returns. Remove the obsolete 64-parameter default-method guard now that FnAbi uses vectors.

Proof: compiler audit identified task_cancel_point missing FnAbi; LLDB declare_async_function showed direct LLVM type construction with an i32 default and no descriptor registration. Wide method LLDB observed w8=66 at generate_default_trait_method_for_impl +1052, taking the >64 early return; IR called undef. Native regressions now return async ok and wide default ok; five-target async audits report zero violations. Audit target-coverage gap filed as #1119.
The centralized descriptor path exposed missing TY_TRAIT_OBJ branches in both semantic and MIR LLVM type mapping. Share the existing dyn layout and cover direct and callable trait-object arguments.

LLDB proof: sema_type_to_llvm and mir_sema_type_to_llvm received kind 17 and returned x0=0 into type_fallback (sealed-kind-proof.txt and dyn-mir-kind-proof.txt under out/fnabi-validation). The MIR fallback produced an i32 parameter for an actual struct{ptr,ptr} argument. Both routes now return the shared dyn type.

Validation: source check, stage1 rebuild, sealed_trait_match native test, dyn callback native run, and callable audit:all on all five targets pass.
Resolve unregistered LLVM aggregate fields through their MIR source owner,
including projected places and reordered literals. Diagnose a failed projected
assignment instead of silently emitting an unreachable body.

LLDB proof: mir_resolve_field_index returned -1 for generation with two LLVM
elements; mir_place_ptr returned zero and mir_emit_stmt took its silent false
return at the projected assignment (handle-field-proof.txt). The Handle mapper
constructs an anonymous LLVM struct with no field-name registry. SlotMap.ptr
reads also lost the field identity. Audit accepted the assignment-last repro
with zero violations; #1120 records that tool gap alongside the codegen bug.

Validation: compiler source check, -O1 stage1, native field matrix (local,
return, reordered literal, nested receiver, tuple, array, Vec), audit:all,
SlotMap generation-exhaustion test, and debug allocator pass.

Refs #1120
Inventory current engines and future algorithm families; add an optimized
N/4N complexity lane to :test with correctness checks and explicit #937/#938
expected failures. Add opt-in allocation request tracing and empty/positive
controls to measure #939's temporary buffers independently of leak reporting.

Replace SlotMap's occupancy scan with a FIFO free list and permanently retire
exhausted generations. Record the runtime header change as ABI v4. Extend
native, spec, allocator, and drop-audit coverage for reuse, growth and cleanup.

Exact baseline evidence: LLDB with_slotmap_insert_out+120 observed occupied
index zero taking the scan branch (slotmap-scan-proof.txt); with_slotmap_remove
+156 observed w20=0xffffffff entering checked-add overflow at rt_core.w:2961
(slotmap-generation-add-proof.txt). The runtime allocator route used the test
runner's retained binary with WITH_ALLOC_NO_REUSE=1 and --debug-alloc.

Validation so far: runtime source checks and -O1 objects on all five targets;
compiler/build/tool source checks; stage1; all SlotMap spec/FIFO tests; exactly
130 Drop calls with zero leaks; optimized complexity cases pass with the known
cliffs recorded, and trace controls observe 0/1/6 allocations. Full bootstrap,
fixpoint and suite verification follows this commit.

Refs #936, #1118
Fixes #1122. Allocator traps and LLDB identify the premature temporary drop, literal insertion bypass, and comparison copy in docs/phase0-ownership-debug.md. The expanded native fixture has exact destructor counts and zero leaks with and without allocator reuse. Source checks, the development build, and focused audit pass; broader audit coverage is tracked in #1123.
Fixes #1121. LLDB observed Sema.check_binary+5452 classify TY_GENERIC_INST as 14, then skip the known-nonstr rejection at +5456. Native concat interpreted a Result header as str. Both Result operand positions and a generic record now fail with the intended diagnostic; development build and focused tests pass.
LLDB observed cli_has_flag begin at argv[2], skipping --trace-alloc before -e. Scan from argv[1], keep the allocation fixture idiomatic, and report process exit codes and capture paths from the complexity lane. Correct stale bundle and sourcing status banners.
Fixes #1125. LLDB observed build_cache_current_compiler_fingerprint+200 reset its cached global from a 64-byte fingerprint to zero while the ready flag stayed set. Return an explicit clone and cache unresolved identity too. The native regression verifies repeated graph keys against the executable fingerprint; compiler source checks pass. Proof is recorded in docs/build-compiler-fingerprint-debug.md.
LLVM rejected an i32 undef versus str comparison on a Box payload. LLDB observed lower_field_base_place+204 returning the Box place through lower_observer_probe_arg; lower_expr_place now uses lower_field_access, including its recorded autoderef and payload handling.
Eric Hartford added 2 commits September 13, 2026 23:53
# Conflicts:
#	docs/stdlib_sourcing_plan.md
…les the literal

The action runner is compiled by the pinned seed (v0.15.2.0), which has
#1122: a collection literal with moved element temporaries frees them
before the collection is used. argv[0] (the compiler path) was a freed
string: exit 127 on POSIX (reproduced locally with the pinned seed as the
driver), the interior-NUL panic on the CI Linux/macOS lanes, and
CreateProcessW's FILE_NOT_FOUND (-2) on Windows aarch64. 9ccd1e2 fixed
the compiler in this tree, but build-layer code runs on the seed
(D14; the seed-gated build-layer rule), so the literal cannot be used
there until the seed carries the fix.
@ehartford

Copy link
Copy Markdown
Contributor Author

Root cause of the four red lanes: the build action runner is compiled by the pinned seed (v0.15.2.0), which has #1122 — a collection literal with moved element temporaries frees them before use. run_stdlib_complexity_action built its argv as [compiler.clone(), "build", ...], so argv[0] was a freed string: the interior-NUL panic on Linux/macOS, CreateProcessW FILE_NOT_FOUND (rc -2) on Windows aarch64. It passed locally only because the locally installed seed was newer than the pin. Reproduced with the pinned asset as the driver (WITH=<v0.15.2.0> <v0.15.2.0> build :stdlib-complexity → exit 127), fixed by building argv with push (188d9dc), and the pinned-seed battery (build, :fixpoint, :test) is green locally. Also merged main (docs conflict resolved to main's text).

The Windows x86_64 stage2 timeout (1801 s vs ~380 s on main) is not explained by this; watching this run. If it reproduces, it is a Windows x86_64-only stage1 miscompile or hang and needs the lane's captures.

Eric Hartford added 4 commits September 14, 2026 01:25
… timed probes on failure

The Windows x86_64 lane's stage2 has timed out at 1801 s on every run of
this branch (main: ~380 s) with no capture uploaded. The build now runs
under WITH_PROFILE so a hung stage leaves its last completed phase in
out/command/<stage>/stderr.txt; on failure the lane prints those captures,
runs stage1 check on the compiler source (Sema/MIR alone) and a
single-codegen-unit build (no emit threads), and uploads out/command.
…ore taking its address

The FnAbi call path evaluated every IndirectPlace operand (a whole-aggregate
load) and then discarded the value for the place address. SROA scalarizes
that dead load into one load per leaf: 1660 for Compilation, before every
in-place receiver call; run_cli carried 26 such chains. marshal_ref_operand
applies the same address policy without materializing a place operand.
A struct move was 'store (load %T)'; SROA rewrites that first-class
aggregate into a load and a store per leaf, so a function moving a few
large records carried tens of thousands of scalar stores in one block and
SelectionDAG's store merging went quadratic on them: one unit of the
windows_x86_64 stage2 build took 635 s (checkMergeStoreCandidatesForDependencies,
the #1129 CI timeout), and every other unit 5-70 s. wl_lower_aggregate_copies
runs before the per-function cleanup: a store of a loaded aggregate of 64
bytes or more becomes llvm.memmove, a store of a zero aggregate llvm.memset,
and a load left without uses is erased. Every windows_x86_64 unit now emits
in under 3 s.

The hand-declared memcpy/memset intrinsics reuse an existing declaration
(LLVM declares them itself once a pass forms one; a second declaration under
the same name gets a .N suffix the verifier rejects).
…lace address

d7c75f2's no-eval marshal sent every non-transparent place operand to
mir_try_place_ptr_for_ref, which returns the place ADDRESS for a projected
place with no load. For an operand whose type is itself &T/*mut T (a
JsonView.source field passed to json_str(js: &str), print(v.source)) the
value IS the pointer the ref param wants; the callee received &&str and
read through it as the str (behav_derive_deserialize and the jq-scalar
one-liner exited 134 in the #1129 battery; IR showed json_str called with
the field GEP where main emits a load). Evaluate reference/raw-pointer
operands — one scalar load, never the aggregate copy the no-eval path
exists to avoid — and let marshal_ref_addr pass the pointer through.
@ehartford

Copy link
Copy Markdown
Contributor Author

Windows x86_64 stage2 timeout: root-caused and fixed (d7c75f2, 92bf398, 503b3c3).

Cause. Reproduced from macOS with WITH_CODEGEN_UNITS=16 WITH_PROFILE=1 ./out/release/bin/with build out/gen/main.w --target windows_x86_64 -O1: one codegen unit's optimize+emit took 635 s (the others 5–70 s; main's units take 2–65 s). sample of the stuck thread: LLVMTargetMachineEmitToFile → SelectionDAGISel → DAGCombiner::visitSTORE → checkMergeStoreCandidatesForDependencies — LLVM's store merging is quadratic in the stores of one block. Codegen moves a struct as store (load %T), and the gen-time per-function sroa,mem2reg cleanup scalarizes that first-class aggregate into a load and a store per leaf (Compilation has 1660); run_cli in this branch carried 30 whole-Compilation copies against main's 4, because the FnAbi call path evaluated every in-place receiver operand and then discarded the value for the place address — a dead 1660-leaf load before every comp.configure(...)-style call. The x86 backend's store merging tripped over the block; aarch64 and Darwin did not.

Fixes.

  • d7c75f2: a ref/share-place argument no longer evaluates its place before taking its address (marshal_ref_operand).
  • 503b3c3: a reference/raw-pointer typed operand still evaluates (its value IS the pointer the callee wants; the place-address shortcut handed json_str a &&str, the one behavior fixture that went red).
  • 92bf398: large aggregate moves (≥ 64 bytes) lower to llvm.memmove/llvm.memset before SROA (wl_lower_aggregate_copies), the way every LLVM front end emits them; hand-declared memcpy/memset intrinsics reuse an existing declaration instead of adding a .N-suffixed duplicate the verifier rejects.

Evidence. Every windows_x86_64 unit now emits in under 3 s. Battery at 503b3c3, local: with build, :fixpoint (stage2 == stage3), :test (1015 behavior, 756 compile-error, 16 codegen, 210 spec, 56 phase), :test-green, :last-green, :drop-audit (119 cells, 0 non-PASS, 0 regressions), :move-audit (15 cells, 0 FAIL, 0 DIFF) all green. Not reseeded.

@ehartford
ehartford merged commit 936c1a0 into main Sep 14, 2026
5 checks passed
ehartford added a commit that referenced this pull request Sep 14, 2026
* Centralize callable, closure, and destructor ABI descriptors

Compute immutable FnAbi/ArgAbi records once and share them across named
declarations, callable types, adapters, prologues, and call marshalling.
Remove parallel ABI tables and 64-bit parameter masks. Preserve owned
destructor storage across body/field cleanup without reclassifying it as
a borrow. Extend declaration/call audits to check descriptor shapes and
actual byval attributes.

LLDB evidence: raw_fn_type selected internal_abi_needs_sret=false for a
large indirect C return; declare_function_at_inner's owner-type shortcut
registered consuming parameters as references. The 65th C aggregate's
attribute was skipped at apply_c_abi_byval_attrs+120: x25=64, x8=0,
x22=0xffffffffffffffff after the out-of-range shift check.

Restore the function-level temporary frame in default trait methods.
The native allocator traced one leaked 16-byte clone through Person.name;
register_stmt_temp+36 had x0=0, local=2, type=16 and skipped registration
from generate_default_trait_method_for_impl. Track the audit's missing
synthesized-body ownership coverage in #1117.

Validation: source check and -O1 stage1 build; five-target callable and
c_va_list IR/audit matrices; 65-parameter aggregate audit; native callback
and consuming-receiver results; default-tail and consumed-field allocator
fixtures report leak count=0. Full bootstrap battery follows this commit.

Refs #1106

* Complete async and wide default-method ABI declarations

Register async declarations from finalized signatures, preserving inferred Unit, scalar and aggregate returns. Remove the obsolete 64-parameter default-method guard now that FnAbi uses vectors.

Proof: compiler audit identified task_cancel_point missing FnAbi; LLDB declare_async_function showed direct LLVM type construction with an i32 default and no descriptor registration. Wide method LLDB observed w8=66 at generate_default_trait_method_for_impl +1052, taking the >64 early return; IR called undef. Native regressions now return async ok and wide default ok; five-target async audits report zero violations. Audit target-coverage gap filed as #1119.

* Lower bare trait objects consistently in FnAbi descriptors

The centralized descriptor path exposed missing TY_TRAIT_OBJ branches in both semantic and MIR LLVM type mapping. Share the existing dyn layout and cover direct and callable trait-object arguments.

LLDB proof: sema_type_to_llvm and mir_sema_type_to_llvm received kind 17 and returned x0=0 into type_fallback (sealed-kind-proof.txt and dyn-mir-kind-proof.txt under out/fnabi-validation). The MIR fallback produced an i32 parameter for an actual struct{ptr,ptr} argument. Both routes now return the shared dyn type.

Validation: source check, stage1 rebuild, sealed_trait_match native test, dyn callback native run, and callable audit:all on all five targets pass.

* Preserve source field identity for compiler-modeled records

Resolve unregistered LLVM aggregate fields through their MIR source owner,
including projected places and reordered literals. Diagnose a failed projected
assignment instead of silently emitting an unreachable body.

LLDB proof: mir_resolve_field_index returned -1 for generation with two LLVM
elements; mir_place_ptr returned zero and mir_emit_stmt took its silent false
return at the projected assignment (handle-field-proof.txt). The Handle mapper
constructs an anonymous LLVM struct with no field-name registry. SlotMap.ptr
reads also lost the field identity. Audit accepted the assignment-last repro
with zero violations; #1120 records that tool gap alongside the codegen bug.

Validation: compiler source check, -O1 stage1, native field matrix (local,
return, reordered literal, nested receiver, tuple, array, Vec), audit:all,
SlotMap generation-exhaustion test, and debug allocator pass.

Refs #1120

* Add stdlib complexity gates and constant-time SlotMap reuse

Inventory current engines and future algorithm families; add an optimized
N/4N complexity lane to :test with correctness checks and explicit #937/#938
expected failures. Add opt-in allocation request tracing and empty/positive
controls to measure #939's temporary buffers independently of leak reporting.

Replace SlotMap's occupancy scan with a FIFO free list and permanently retire
exhausted generations. Record the runtime header change as ABI v4. Extend
native, spec, allocator, and drop-audit coverage for reuse, growth and cleanup.

Exact baseline evidence: LLDB with_slotmap_insert_out+120 observed occupied
index zero taking the scan branch (slotmap-scan-proof.txt); with_slotmap_remove
+156 observed w20=0xffffffff entering checked-add overflow at rt_core.w:2961
(slotmap-generation-add-proof.txt). The runtime allocator route used the test
runner's retained binary with WITH_ALLOC_NO_REUSE=1 and --debug-alloc.

Validation so far: runtime source checks and -O1 objects on all five targets;
compiler/build/tool source checks; stage1; all SlotMap spec/FIFO tests; exactly
130 Drop calls with zero leaks; optimized complexity cases pass with the known
cliffs recorded, and trace controls observe 0/1/6 allocations. Full bootstrap,
fixpoint and suite verification follows this commit.

Refs #936, #1118

* Preserve collection literal ownership and shared insertion cleanup

Fixes #1122. Allocator traps and LLDB identify the premature temporary drop, literal insertion bypass, and comparison copy in docs/phase0-ownership-debug.md. The expanded native fixture has exact destructor counts and zero leaks with and without allocator reuse. Source checks, the development build, and focused audit pass; broader audit coverage is tracked in #1123.

* Reject instantiated generic containers as string concat operands

Fixes #1121. LLDB observed Sema.check_binary+5452 classify TY_GENERIC_INST as 14, then skip the known-nonstr rejection at +5456. Native concat interpreted a Result header as str. Both Result operand positions and a generic record now fail with the intended diagnostic; development build and focused tests pass.

* Recognize leading one-liner flags and report complexity launch failures

LLDB observed cli_has_flag begin at argv[2], skipping --trace-alloc before -e. Scan from argv[1], keep the allocation fixture idiomatic, and report process exit codes and capture paths from the complexity lane. Correct stale bundle and sourcing status banners.

* Retain the compiler identity across build cache lookups

Fixes #1125. LLDB observed build_cache_current_compiler_fingerprint+200 reset its cached global from a 64-byte fingerprint to zero while the ready flag stayed set. Return an explicit clone and cache unresolved identity too. The native regression verifies repeated graph keys against the executable fingerprint; compiler source checks pass. Proof is recorded in docs/build-compiler-fingerprint-debug.md.

* Use the shared field projection path for observer places

LLVM rejected an i32 undef versus str comparison on a Box payload. LLDB observed lower_field_base_place+204 returning the Box place through lower_observer_probe_arg; lower_expr_place now uses lower_field_access, including its recorded autoderef and payload handling.

* spec: record allocation tracing CLI flag blessed by Eric

* docs: select stdlib facade engines and align migration phases

* docs: align inventory with selected stdlib engines

* docs: record completed Phase 0 verification

* Preserve C record identity, empty statements, and valid module paths

Closes #1124. LLDB observed underscore tags branch to c_void and NullStmt return zero into lower_for_stmt_ir+428; the parser rejected generated use probe.a-b. See docs/c-algorithms-migration-debug.md for the exact evidence and regression scope.

* Resolve generic layout applications through the active type bindings

LLDB observed Codegen.resolve_type+952 discard NK_INDEX type application node 7425 after frozen Sema returned zero. Both application syntax forms now share the substitution-aware resolver; add nested-record and multi-parameter layout coverage.

* Add pinned c-algorithms migration and upstream test targets

* fix: retain restored C scope entries and owned generic call results

* fix: preserve reference identities and contextualize pointer null comparisons

* fix(migrate): distinguish diagnostic macros from stringification

* migrate: lower assertion effects and recover Clang string literals

Native LLDB stops prove the missing __builtin_expect structural branch, filtered __assert_rtn binding, and StringLiteral cursor 897 returning invalid IR despite a valid Clang spelling. Preserve these paths without weakening upstream assertions. Compiler source check and dev build pass for the effect/builtin paths; final literal recovery and native fixture verification remain pending.

* mir: retain concrete closure and async bodies before codegen

LLDB proved Codegen.gen_closure lowered node 889 using the last generic specialization type, sending the i32 comparator to with_str_cmp_ref. Prepare anonymous bodies in the concrete lowering context, validate their retained contracts, and read them in codegen. Mixed-width/string comparator and ordinary closure/async captures pass on the dev compiler. LLVM also proved an async result-buffer state leak into nested closure returns; save and restore it across anonymous functions. Full self-host verification follows.

* fix: retain declaration identity for visibility and C initializers

LLDB proves generic declaration validation reads private Entry from the importing context (#1130), and the C initializer scanner classifies variable2 as initialized from variable1’s equals sign. Use declaring-module context and Clang’s per-variable initializer cursor. Source checking passes; regression and upstream pipeline verification follow.

* Reserve complete record field ranges before nested layout resolution

Native LLDB proof: monomorphize_struct_nodes recurses at +2184 while resolving an enclosing record; get_llvm_field_index receives source index 1 and returns slot 0. The Trie constructor IR overwrites its engine pointer with the empty entries pointer. Reserve all parallel field columns before resolving nested fields in generic, ordinary, union, and generator records.

Source checking passes. Regression covers returned nested generic records, reordered initialization, and owned strings. Native verification follows in the batch; layout audit gap tracked in #1131.

* Reject private generic type applications across module boundaries

LLDB at resolve_generic_type +404 observed lookup_named_type_visible returning zero from check_let_binding. The declaration-table contains branch at +884 then returned a concrete type (138), bypassing privacy. Check the private symbol path before the declaration-presence fallback. Preserve the negative annotation regression and repair its public marker signature; create the migration fixture output directory. Compiler source check passes; multi-declarator native regression passes.

* Bind atoi through std.libc for migrated calls and function values

The pinned upstream hash-table test stopped at atoi(val): ci_libc_symbol_kind_mask omitted atoi despite the text call mapper recognizing it. Add the concrete foreign ABI binding and structural allowlist entry, with direct-call and function-pointer coverage. Compiler source check passes; native migration verification follows.

* Preserve callback signatures and null sentinels during C migration

The upstream test_alloc_testing output contained integer 0 in a function-pointer array and a vacuous unsafe strcmp call. The atoi regression also emitted a local unsafe callback with an unconverted str argument. Coerce array elements against their element types, classify direct function references by canonical Clang type, and use the callable signature for all argument conversions. Stage nested callable parameters before appending their shared extra range.

Apply the existing Sema std-module extern policy to every std shared-defs corpus, replacing the pcre2-only migrator condition. Source check passes; regressions include callback arrays, typedefs, local and field callbacks, and nested callback parameters. Native verification follows.

* Preserve borrowed dereference places in non-Copy bindings

Native allocator trap and LLDB observed str.cmp freeing a live SortedVec element through rt_core.w:2730. MIR copied the shared pointee into an owning local and scheduled drop#10; retain the Sema projection and bind its place instead. Reject owned mutable bindings and clone the two compiler fields that require independent mutable storage.

Stage 1: reduced repro, repeated string comparisons, SortedVec, BinaryHeap and eight custom destructor checks pass with debug allocation and zero leaks. Consuming and mutable borrowed bindings reject. Validator gap tracked in #1132.

* Load callable values through reference places before invocation

Native LLDB stopped at the callbacks data symbol: the array slot address was used as the branch target instead of its stored atoi pointer. Normalize callable reference projections in shared MIR call lowering; FnAbi remains the argument/result authority. Add raw C callback, reference parameter and With closure collection coverage. Validator gap: #1133.

* Preserve macro null callbacks and their safety contracts

LLDB observed ci_c_initializer_is_null_pointer_cast return true for (void *)0, then the source initializer path only recognized pointer/Option destinations and emitted integer zero for a function pointer. Route macro nulls through the common target coercion. Only wrap indirect calls whose rendered callable contract is unsafe. Compile the raw upstream corpus without the application prelude, matching migration and bundle options.

* migrate: render a record forward-declared without a definition as opaque, not an empty struct

A TU that only sees a record's forward declaration has an incomplete
type with no size. Rendering it as an empty { __pad0 } struct registered
a concrete body in the shared defs, so a later TU's real definition
could not upgrade it and the corpus lost the fields whenever the
incomplete TU sorted first (c-algorithms: test-trie.c before trie.c,
_Trie lost root_node). Render it 'type X = opaque' so the definition
upgrades it in either order; fixture covers the order.

* build: migrate each c-algorithms test as its own program

Upstream links each test as a separate program with independent
globals (list's variable1 is 50, arraylist's is zero), so a migrate-one
pass sharing one defs module cannot represent them. Each test is now a
whole migration of engine, framework and test into tests/<name>/, and
the test target compiles each from its own module tree. All 17 upstream
programs pass under With.

* build: c-algorithms is the third .wo bundle

The migrated corpus is promoted to lib/std/c_algorithms (generated, never
hand-edited) with a bundle.w root, a generated-output check, a root check
and a drift lane whose harness is upstream's test-cpp smoke over every
module. calg_wo mirrors zlib's plan at every build.w site: stage2/3 and
fixpoint links, the release binary and cross plans embed it, stage1 keeps
an empty slot. The corpus is excluded from the embedded stdlib and listed
as an internal module; :test gains c-algorithms-test as the corpora lane.

* std: SortedVec, BinaryHeap and Trie facades over the c-algorithms engines

Phase 1 of docs/stdlib_sourcing_plan.md. The engines index void* slots; the
facade owns every value in one heap slot (std.collections.engine_slot),
observes through &T, transfers on remove/pop, and drops every held value
before freeing the engine. Ordered facades compare through one C
trampoline that calls the With comparator stored beside each value
(#1135 keeps a generic closure from crossing into C directly). Behavior
tests, complexity rows and drop-audit cells cover each facade; the corpus
global and item-import workarounds are marked for #1136.

* sema: ordering two views of a type without an operator method is an error

Both operands of < on &T fell through as pointer-like and compiled to an
address comparison of the references (#1137; the comparator closure of a
sorted facade disassembled to cmp x1, x2, so every insertion kept address
order). A view compares the value it observes; only raw pointers compare
by address. The diagnostic names the missing method (§11.7).

* docs: Phase 1 status of the stdlib sourcing plan and the handoff for it

* mir: refresh the eager type caches after registering generic Drop specializations

Checking a generic Drop body creates its dependent types (a *mut Slot[T]
only the drop mentions) after the loop's preregistration, and
lower_concrete_specialization's own refresh compares against a count
taken later, so a generic type whose only use was being dropped hit
'is_copy_frozen miss' in lower_let_binding (the facades' empty drop-audit
cells). The miss message now names the type.

* sema: a source type declaration wins over a same-named bundle interface alias

The demand loader collected any interface declaration whose name the
program mentions, so c-algorithms' 'pub type Trie = _Trie' and
'BinaryHeap = _BinaryHeap' shadowed the facades' Trie[V] and BinaryHeap[T]
whenever the bundle was embedded (the facade tests passed under stage1 and
failed under the release binary with 'cannot infer generic method type
parameter'). A type name the program's own source declares never demands
the interface alias. The views-ordering diagnostic (#1137) now fires only
for a declared struct, enum or instantiation target; a template body's
&T is rechecked per instantiation.

* docs: Phase 1 handoff — verified state, the bisected pre-facade regressions, what remains

* mir: lower closure arguments of generic and machinery calls; statement-bodied closures return the implicit default

A closure argument to a GENERIC_CALL (the spawn worker, a monomorphized
method's callback) was replaced by a placeholder constant, so its body
was never prelowered and codegen's gen_closure phase-bugged ('anonymous
expression lacks MIR constant') on every scope/spawn fixture since
31a347d. A closure whose body is a statement but whose type returns a
value (item => xs.push(item) as fn(i32) -> i32) now returns the implicit
default, as Sema already accepts and as a bare return does; the typed-MIR
validator rejected the unit operand.

* std, tests: conform to D22 §13.6 where 88f0ad3's view rule found bit-copies of non-Copy values

JsonWriter.value_str observes its argument, so it takes &str (Serialize
for str passed *self, a str view, by value: str owns its buffer, D28).
cd_unary's Acc opts into Copy, which is what its deref-copy checks assume.
The #1043 fixture's unannotated 'var inferred = h.text' bit-copied an
owning str; the typed clones it also checks are the conforming spelling.

* std: the collection iterator and place types are pub; tests import the ones they name

92c0c01 closed the privacy bypass through which user code named VecIter
and FilterIter without an import. They are user-nameable surface (the type
of xs.iter()), so they are pub, and under D29's staged rule a non-prelude
std name needs its explicit use.

* migrate: read call parameter types from the sugared callable type

ci_callable_cxtype canonicalized the callee's type, which erases the
va_list typedef the #1104 parameter model keys on (Darwin's canonical
va_list is char *), so every argument to a va_list parameter was cast to
*mut c_char and the migrated program failed to type-check
(behav_migrate_va_list). The canonical type now serves only a callee whose
sugared type is not a function or a pointer to one.

* sema: only a real type declaration displaces a same-named bundle interface alias

std.libc's 'pub type c_int = i32' and the interface's identical alias must
coexist (std.regex reaches c_ulong through the interface); a source alias
no longer suppresses the interface's, only a struct, enum or generic
declaration does (the facades' Trie[V] and BinaryHeap[T]).

* abi: re-record the ABI source hash after TypeLayout's diagnostic text change

Only the is_copy_frozen phase-bug message changed (it now names the
type); no layout or passing convention moved, so WITH_ABI_VERSION stays.
Every .wo rebuilds once.

* migrate: a declared callee's parameter types come from its declaration; the callable type is the fallback

8a250bc read every call's parameter types from the callee's callable type,
which is canonical and erases the va_list typedef identity on Darwin (a
'va_list *' behind a typedef became *mut *mut c_char, behav_migrate_va_list).
The declaration's translated parameter type is the renderer that follows
typedef identity (#1104), so a declared callee uses it as before e7ddf11;
the canonical callable type now serves only a callee without a declaration
(a local function pointer, a nested callback parameter), which is what
e7ddf11 added it for.

* build: the c-algorithms corpora lane compiles checked-in test programs with the release binary

A migrate workspace runs in the build driver's own compiler, and the
battery's driver is the seed (CI: src/main build :test), whose migrator
predates this branch's assert lowering and bails on Darwin's assert. The
lane therefore never migrates: c-algorithms-promote-tests promotes the
ALLOC_TESTING migration into test/corpora/c_algorithms (one shared engine/,
per-program defs.w + test module, all byte-identical engine copies
verified), and c-algorithms-test assembles each program under its own
project root, compiles it with out/release/bin/with build --no-prelude and
runs it. The programs migrate under std.calg_testing: a compiler that
embeds the c_algorithms bundle resolves std.c_algorithms.* to the interface
first, and only a std package lets std.libc reach c_void under
--no-prelude. Re-migration needs a tree compiler as the driver
(WITH=out/release/bin/with out/release/bin/with build :c-algorithms-promote).
The regenerated corpus reflects the declaration-first parameter typing.

* docs: Phase 1 regressions root-caused; the corpora lane's driver rule

* migrate: recognize an unnamed record member by its cursor spelling

b0434ad made the bridge ask Clang about anonymity instead of matching the
type spelling, so the translated text of an unnamed union field became
c_void and no longer carried the '(unnamed at' marker the anonymous-record
lookup keyed on. The field's record was then not found, the struct was
demoted to opaque and its initializer flattened
(c-migrator-core-tests: anon_union_init_not_flattened). The lookup now
reads the marker from the declaration cursor's spelling.

* drop-audit: a cell the baseline could not run and the candidate passes is FIXED, not a regression

The three empty facade cells phase-bugged under the seed (the generic
Drop-only type, fixed in 27ed60c) and pass under the candidate; the
classifier read any difference as a regression. A candidate PASS against a
non-PASS baseline is printed as FIXED and never red.

* docs: Phase 1 battery green

* D41: Ord.cmp(&self, &other) backs <, <=, >, >=; Eq.eq(&self, &other) backs ==, !=; fixed-name methods override

Eric's ruling (decisions.md D41). Sema selects the family's primitive when
neither operand type defines the fixed-name method and records the
derivation (operator_method_derived); MirLower lowers cmp(...) <op> 0 and
not eq(...), flipping the ordering's sign when the primitive lives on the
right operand's type. The operator sidecars are cleared per recheck: a
generic body rechecked per instantiation kept the first T's method (the
str/i32 specializations of a T: Ord body called Tag.cmp). Eq.eq and
Ord.cmp take other: &Self and every impl in the tree conforms; the
facades' element types need only Ord; #1137's diagnostic names the
primitive. Fixture behav_ord_cmp_operators covers owned and view
operands, the derived four, an override, and a reversed selection.

* docs: D41 recorded; the proposed §11.7 wording awaits Eric's blessing

* build: the corpora and complexity lanes build their argv by push; the seed miscompiles the literal

Same #1122 seed miscompile as the base branch's fix: build-layer code runs
on the pinned seed, so a collection literal with moved element temporaries
(the compiler path, the program path) is a freed string there.

* build: the complexity lane builds its argv by push; the seed miscompiles the literal

The action runner is compiled by the pinned seed (v0.15.2.0), which has
#1122: a collection literal with moved element temporaries frees them
before the collection is used. argv[0] (the compiler path) was a freed
string: exit 127 on POSIX (reproduced locally with the pinned seed as the
driver), the interior-NUL panic on the CI Linux/macOS lanes, and
CreateProcessW's FILE_NOT_FOUND (-2) on Windows aarch64. 9ccd1e2 fixed
the compiler in this tree, but build-layer code runs on the seed
(D14; the seed-gated build-layer rule), so the literal cannot be used
there until the seed carries the fix.

* ci(windows): phase profiling during the build, stage captures and two timed probes on failure

The Windows x86_64 lane's stage2 has timed out at 1801 s on every run of
this branch (main: ~380 s) with no capture uploaded. The build now runs
under WITH_PROFILE so a hung stage leaves its last completed phase in
out/command/<stage>/stderr.txt; on failure the lane prints those captures,
runs stage1 check on the compiler source (Sema/MIR alone) and a
single-codegen-unit build (no emit threads), and uploads out/command.

* spec: §11.7 — comparison derives from Ord.cmp and Eq.eq over borrowed operands; fixed-name methods override (D41, blessed by Eric 2026-09-14)

* codegen: a ref/share-place argument no longer evaluates its place before taking its address

The FnAbi call path evaluated every IndirectPlace operand (a whole-aggregate
load) and then discarded the value for the place address. SROA scalarizes
that dead load into one load per leaf: 1660 for Compilation, before every
in-place receiver call; run_cli carried 26 such chains. marshal_ref_operand
applies the same address policy without materializing a place operand.

* codegen: large aggregate copies lower to memmove/memset before SROA

A struct move was 'store (load %T)'; SROA rewrites that first-class
aggregate into a load and a store per leaf, so a function moving a few
large records carried tens of thousands of scalar stores in one block and
SelectionDAG's store merging went quadratic on them: one unit of the
windows_x86_64 stage2 build took 635 s (checkMergeStoreCandidatesForDependencies,
the #1129 CI timeout), and every other unit 5-70 s. wl_lower_aggregate_copies
runs before the per-function cleanup: a store of a loaded aggregate of 64
bytes or more becomes llvm.memmove, a store of a zero aggregate llvm.memset,
and a load left without uses is erased. Every windows_x86_64 unit now emits
in under 3 s.

The hand-declared memcpy/memset intrinsics reuse an existing declaration
(LLVM declares them itself once a pass forms one; a second declaration under
the same name gets a .N suffix the verifier rejects).

* codegen: a reference-typed ref argument marshals its value, not its place address

d7c75f2's no-eval marshal sent every non-transparent place operand to
mir_try_place_ptr_for_ref, which returns the place ADDRESS for a projected
place with no load. For an operand whose type is itself &T/*mut T (a
JsonView.source field passed to json_str(js: &str), print(v.source)) the
value IS the pointer the ref param wants; the callee received &&str and
read through it as the str (behav_derive_deserialize and the jq-scalar
one-liner exited 134 in the #1129 battery; IR showed json_str called with
the field GEP where main emits a load). Evaluate reference/raw-pointer
operands — one scalar load, never the aggregate copy the no-eval path
exists to avoid — and let marshal_ref_addr pass the pointer through.

* std.libc: the assert.h reporters are modeled portably

__assert_rtn (Darwin) and __assert_fail (glibc) were bare externs, so a
corpus migrated on macOS could not link on Linux or Windows (#1138:
c_algorithms-wo-drift and c-algorithms-test, 'undefined symbol:
__assert_rtn'). Both are With functions now: the same report to stderr,
then abort, on every target.

* migrate: a record named only through a member type renders opaque

72e1067 stopped rendering every underscore-tagged record as c_void, so
glibc's __locale_struct now names __locale_data — a record declared only
inside a member's type, never at file scope. It had no cursor in the
top-level walk and no 'type __locale_data = opaque' was emitted
(spec_ss16_ffi_and_c_import under use c_import("time.h") on Linux,
#1138). After the declaration walk the session walks every collected
declaration's types and appends each undefined record it names, so it
renders opaque next to its users. Fixture: behav_migrate_member_only_record.

* docs: handoff for Phases 0/1/2 (2026-09-14)

* test: the member-only record fixture reads the migrated module and calls the migrated name

read_file returns a Result, and the migrated function keeps its C name;
the __with_cabi_ prefix is only for runtime-borrow bridges.

* test: the assert-macro migration fixture skips on Windows (#1140)

UCRT's assert.h expands to _wassert with wide string literals, which the
migrator does not lower; corpora migrated elsewhere run on Windows since
the reporters are modeled portably.

* Phase 2: TommyDS corpus as the fourth .wo bundle, header-inline ownership in the migrator, HashIndex facade (#1141)

* migrate: bit builtins lower to integer methods; a pointer to a function typedef is a function pointer

__builtin_clz/ctz/popcount (and the l/ll forms) lower structurally to
(x as u32).clz() / u64 for the wide forms; __builtin_bswapN to
.swap_bytes() on the N-bit unsigned (TommyDS tommy_ilog2/tommy_ctz).
A CIE_FIELD with d2=2 is a method selected on a value and prints as
base.method. A pointer whose pointee is a typedef of a function
prototype (tommy_compare_func*) canonicalizes to the function pointer
instead of *mut fn. Fixtures: behav_migrate_bit_builtins,
behav_migrate_fn_typedef_pointer.

* rt: with_libc_mach_absolute_time, the monotonic clock in nanoseconds

The runtime seam behind std.libc's portable mach_absolute_time (next
commit): the same value on every target.

* std.libc: qsort, rand, srand; Darwin's mach clock modeled portably

The migrator's libc allowlist admits qsort/rand/srand and
mach_absolute_time/mach_timebase_info(_data_t)/kern_return_t (previous
migrate commit). mach_absolute_time is the runtime's monotonic clock in
nanoseconds and mach_timebase_info reports 1/1, so TommyDS's check.c
timing code migrated on macOS computes nanoseconds on every target.
Fixtures: behav_migrate_libc_qsort_clock (portable),
behav_migrate_libc_mach_clock (darwin-only migration).

* build: the TommyDS corpus as the fourth .wo bundle (Phase 2)

build/tommyds.w pins amadvance/tommyds 1f3727fc, migrates the 13 units
(tommy.c, the amalgamation, excluded) plus check.c as the harness
(module check_: check collides with the prelude), promotes to
lib/std/tommyds/, and runs tommycheck as the corpora lane tommyds-test.
tommy_wo is wired at every site calg_wo is; the corpus leaves the
embedded stdlib in build.w and build/runtime.w; std.tommyds is an
internal module. The corpus is the migration's output, never
hand-edited.

* migrate: a header's static inline definitions are published by the unit of the same name

A `static inline` function defined in a header is that header's API
(TommyDS keeps tommy_hashdyn_search, tommy_hashlin_search and the
tommy_inthash family in its headers); every includer compiled a private
copy, so nothing outside the corpus could call them. The project scan now
registers such a definition as owned by the unit whose stem matches the
header's (tommyhashdyn.c for tommyhashdyn.h); that unit publishes it and
every other unit imports it. A header no unit owns keeps a private copy per
includer as before. Fixture: behav_migrate_header_inline_owner.

* migrate: only a header's inline definitions are published; calls to an imported inline get their unsafe context

The ownership rule from ff4c58b also published a unit's own static
inline helpers (tommyhashdyn.c's hashdyn_grow_step) because their
location stem matched the unit; a definition is a header's API only
when it sits in a header. And a consumer unit's calls to an imported
header inline with raw parameters were emitted without an unsafe
context, because the unsafe-callee scan skipped every static function;
a header-owned one is treated like any imported raw function. The
fixture covers both: user_probe runs through the published engine_peek,
engine_scale stays private.

* tommyds: corpus re-promoted with the header-inline rule; bundle root

tommy_hashdyn_search, tommy_hashlin_search, tommy_hashtable_search and
the tommy_list/tommy_inthash inlines are published by their units and
imported by every other unit (1,469 lines of private copies gone);
check_.w resolves them through the imports. bundle.w is the root the
migrate action writes. tommycheck passes.

* std.collections.hash_index: HashIndex[K, V] over the TommyDS hashdyn engine

Node ownership for an intrusive engine (docs/stdlib_sourcing_plan.md,
Phase 2): the facade owns every node in one heap slot per entry: the
node first, so the engine's node pointer is the slot, then the key
comparator the one C trampoline reads, then the key and value. get
observes, remove and a replacing insert transfer, clear and drop walk
the buckets and release every slot exactly once; lookups reuse one
probe slot. Behavior test, complexity row (hash-index, linear),
drop-audit cells, and test/benchmark/hash_engines.w (facade vs raw
engines vs rt_core HashMap).

* docs: Phase 2 status (TommyDS bundle, header-inline rule, HashIndex, benchmark table)

* docs: handoff for Phases 0/1/2 (2026-09-14, evening)

* docs: handoff — Phase 2 battery green, PR #1141

---------

Co-authored-by: Eric Hartford <[email protected]>

---------

Co-authored-by: Eric Hartford <[email protected]>
ehartford pushed a commit that referenced this pull request Sep 16, 2026
…nd the two open decisions

Replaces the stdlib-sourcing/corpus-registry handoff (that work is merged:
#1129, #1142, #1151). Records the release state at 4ecfddb: what each
Release leg failed on and which fix addresses it, the evidence on this
commit (battery green through last-green; :release-uat red on openssl
alone), the two decisions blocking the cut (#1158 openssl double free,
windows-aarch64 placement), the exact publish sequence, the issues filed
today, and the environment traps that cost rebuild cycles to find.
ehartford added a commit that referenced this pull request Sep 16, 2026
…th SDKs on all platforms) (#1155)

* release: make every Release leg able to go green (linux-aarch64 host map, windows-aarch64 NM, reproducible Windows links)

The Release workflow has failed on every platform since 2026-09-12; v0.15.2.1
shipped SDKs for three of five platforms because its Windows legs never
finished. Three of the causes, each verified against the failed run
35102512299:

- build.w: release_asset_for_host() / supported_release_platform_tag() had
  no linux-aarch64 case and fell through to the darwin asset, so on that
  host the seed-driver, test-green, last-green and seed targets — and the
  SDK asset name — all keyed on darwin ("the driving compiler ... is not the
  pinned seed v0.15.2.0 (79a63ff...)" compared the linux-aarch64 seed to the
  darwin digest). Add the case.

- nightly-release.yml, windows-aarch64: the toolchain step never exported
  NM, so cli-selfhost-object-symbol-tests and bundle-interface-tests ran
  the runner's MSYS nm, which cannot parse an arm64 COFF image ("nm failed
  for emit_obj_globals"). Point NM at the SDK's llvm-nm.exe, as
  selfhost-windows-aarch64.yml already does.

- src/compiler/Link.w: pass /Brepro on the COFF link. The seed-driven gates
  relink the release compiler in every step on every platform (a separate
  inefficiency), and only on Windows did the bytes change, because lld-link
  stamps the PE header and PDB GUID from the wall clock; fixpoint compares
  emitted objects, never the linked image, so it never saw the churn. That
  is the "last-green: stale test pass marker" failure on windows-x86_64:
  the marker's compiler sha256 was taken before the relink.

* release: c_import generator fixes for the UAT packages, local-first release process, linux-aarch64 Docker host

The release UAT's zlib, sqlite3 and openssl legs broke because `with get`
now fetches zlib 1.3.2 and OpenSSL 4.0.2, whose headers reach three latent
gaps in the c_import modeler (the 09-06 compiler fails on them identically):

- src/CImport.w: an object-like macro whose value is a call is recorded
  untranslated, like a function alias — a known C function would be a raw
  call at program start (`#define zlib_version zlibVersion()`, "raw c_import
  function call requires unsafe context"), and a callee this import never
  emitted leaves a dangling name (`#define OSSL_DEPRECATEDIN_4_0
  OSSL_DEPRECATED(4.0)`, "undefined variable"). Referencing such a macro is
  the loud, allow-gated omission error.
- src/CImport.w: every type position now spells a raw C function pointer
  `unsafe extern "C" fn(...)` — the constant-probe emitter, the typedef
  alias resolver and ci_infer_cast_return_type had kept the safe spelling,
  so sqlite3's `#define SQLITE_STATIC ((sqlite3_destructor_type)0)` became
  `let SQLITE_STATIC: extern "C" fn(...) = (0 as unsafe extern "C"
  fn(...))`, a binding type mismatch.
- build/release_uat_fixtures/openssl_main.w: `write` is import-gated
  (#750); add `use std.builtins.write`.
- test/spec/spec_ss14_11_await_combinator_cancel_joins.w: `skip-on:
  linux-aarch64` — #916 does not reproduce there, so the known-issue gate
  reported "expected red but passed" (the one red file of 210 on that leg).

The openssl UAT still fails on darwin/linux until #1158 (a double free in
compile_source_frontend_mode while modeling OpenSSL 4.0.2's evp.h; a main
regression since v0.15.2.1, layout-dependent).

Process (Eric, 2026-09-16): the Mac builds and publishes darwin-aarch64 and
linux-aarch64; CI builds and appends the rest.
- tools/docker/linux-aarch64/Dockerfile: the native linux/arm64 release
  host (an Apple Silicon Mac runs it natively); bakes in what a bare
  ubuntu:24.04 lacks and fails silently without (g++, libxml2).
- tools/release_local.w: `with run tools/release_local.w vX.Y.Z` — the
  darwin gates, :release-uat, packaging and publish-first, then the same
  inside the container for linux-aarch64 (pins from seed.lock and the
  linux-aarch64 lane).
- .github/workflows/nightly-release.yml: darwin-aarch64 leaves the unix
  matrix for its own job; it and build-linux-aarch64 run only when
  github.event_name != 'push', so a tag push builds linux-x86_64,
  windows-x86_64 and windows-aarch64 and the nightly/test channels still
  exercise all five.
- docs/with-release-runbook.md: "Linux aarch64 Release Host (Docker on
  Apple Silicon)" and "Local-first: the Mac publishes darwin and
  linux-aarch64; CI appends the rest".

* docs: handoff — cutting v0.15.2.2, the local-first release process, and the two open decisions

Replaces the stdlib-sourcing/corpus-registry handoff (that work is merged:
#1129, #1142, #1151). Records the release state at 4ecfddb: what each
Release leg failed on and which fix addresses it, the evidence on this
commit (battery green through last-green; :release-uat red on openssl
alone), the two decisions blocking the cut (#1158 openssl double free,
windows-aarch64 placement), the exact publish sequence, the issues filed
today, and the environment traps that cost rebuild cycles to find.

---------

Co-authored-by: Eric Hartford <[email protected]>
ehartford added a commit that referenced this pull request Sep 26, 2026
…tween the load and the store can write memory (#1689) (#1693)

wl_lower_aggregate_copies rewrote `store (load %T, src), dst` into a
memmove positioned at the store, so the source was read after everything
between the load and the store had run. Vec.remove loads the element,
calls with_vec_remove to shift the buffer, then stores the result: for an
element of 64 bytes or more the memmove copied the shifted slot, so
`remove(0)` returned the wrong element and consuming iteration yielded the
last element at every position. The rewrite now requires the load and the
store to share a block with no store, call, fence or atomic between them
— the adjacent bulk-move shape the pass exists for (#1129).

Co-authored-by: Eric Hartford <[email protected]>
ehartford pushed a commit that referenced this pull request Oct 17, 2026
… is a move; a held copy of a large aggregate goes through memory (D120 stage 3)

Three defects the self-build surfaced once Sema, Zcu and their kin became
values (stage 2's build was clean; stage 3's peaked at 8.6 GB against the
2 GB tripwire, LLVM's unit emit 61 s against 15 s, one unit's `llc` 41 s
against 2 s on same-sized IR). Found by WITH_KEEP_BITCODE + llvm-dis +
opt/llc standalone, and the per-function IR size tables.

1. Codegen: the copy glue of a struct (or a generic struct instance) is a
   cached per-type `__copy_struct_<ty>(ptr)` (ensure_structural_copy_fn,
   the twin of ensure_structural_drop_fn, #691): inlined at every consumed
   copy, Sema's hundreds of collection fields put 5,000 retains into one
   function.

2. MirLower: `move x` of a local binding whose type has drop glue lowers as
   OK_MOVE of the place (the rule the field arm already had), never as a
   retained copy: read as a copy, a moved Sema stayed live across every
   exit path and the drop plan dropped it field by field at each one
   (4,400 drop statements in run_mir_lower). Sema already refuses a later
   use of an explicitly moved binding (#691).

3. Codegen: a held copy (retain or take) of an aggregate of 64 bytes or
   more is memcpy'd into a slot, the glue or the blank runs on the source,
   and the consumer loads the slot — so its load and store stay the
   adjacent pair wl_lower_aggregate_copies turns into a memmove. Read as a
   first-class value with the glue call between load and store, the pass
   could not match, SROA scalarized the 2,378 leaves of a Zcu into a load
   and an insertvalue each, and SelectionDAG's store merging went
   quadratic (the #1129 class).

Also: WITH_TRACE_COW_COPIES=<bytes> (rt_core.w) reports every
copy-on-write copy of a List buffer or map table at or above that size
with a backtrace, and the `taken_zcu` double declaration in
Compilation.compile_bundle_interface_root is a reassignment (the old
compiler accepted it because the first binding had been moved out).

Self-build after: peak RSS 2.3 GB (main 2.2 GB), llvm.units_total 16.1 s
(main 14.9 s).
ehartford added a commit that referenced this pull request Oct 17, 2026
…td identity types declared resource (#2442)

* D120 stage 3: a struct of values is a value (no impl Copy written); std identity types declared resource

A struct whose fields are all values is a value (§2.3, §4.3): it copies
with no `impl Copy` written (one stays legal and redundant), unless it
implements Drop or is declared `resource type`. The same for an instance of
a generic struct whose instantiated fields are values, so a BTreeMap or
BTreeSet of values is a value through its List field. An enum stays opt-in;
a generator's state struct is a running producer, consumed once (§13.4),
never a value of its fields. A struct of integers copies by its bits; one
holding a str, a List or a map copies by retaining each field (the
field-by-field copy glue, now also for generic struct instances), and the
first write through a copy makes that field's buffer unique.

Sema: is_copy's TY_STRUCT branch falls back to fields_all_copy after the
explicit impl; the TY_GENERIC_INST branch does the same for a struct base
with no Drop impl, not a resource, not a SlotMap (its handles are its
identity and the runtime keeps no count), not an Atomic (a cell other
threads address; compiler-modeled by name like the channel ends, because
the pinned seed cannot parse `resource type` in std.collections). The walk
is memoized per resolved type once exact (struct_copy_cache: no unresolved
field, no cycle met): uncached it walked every field of every struct at
every query — type_needs_drop stops at the first droppable field, this
walk must see them all — and `check` of hello world took 23 s against 1.

std: the identity types without a Drop impl are declared `resource type`:
Task, ScopedTask (std.task), JoinHandle, ScopedJoinHandle (std.thread),
MutexGuard, MutexGuardMut, RwReadGuard, RwWriteGuard (std.sync).

Fixtures: the two D87 fixtures whose non-Copy `Ctx` was a struct of a str
declare it `resource type` (the ruling's spelling for a non-Copy struct of
values). Tests: behav_d120_struct_value_copy (ints, str + List fields, a
generic struct, a BTreeMap, passing by value), da_d120_struct_shared_drop
(three holders, one written: freed once, no leak),
err_d120_resource_struct_still_moves.

* test/compile_errors: the struct that pinned a move is declared resource type (D120 stage 3)

23 fixtures used a plain struct of value fields as the canonical non-Copy
type (`Thing { vals: List[i32] }`, `Counter { value: i32 }`, `Buffer {
text: str }`, …): a use-after-move, a `copy` refused, a `&T` argument to a
plain `T` parameter, a mut-receiver escape, a Copy/Clone derive refused
for a non-Copy field or payload, an effect pin too narrow for an escape.
Under D120 such a struct is a value and the pinned error no longer
occurs; each struct is declared `resource type` (the ruling's spelling
for a struct whose meaning forbids duplication) so the pin stands on a
type with identity. Mechanical: the first `type` line of each file, with
a comment saying why (scratchpad d120_struct_sweep.w).

* test/behavior/behav_effect_pin: the pinned Resource is declared resource type (D120 stage 3)

Its `Resource { id: i32 }` carried an inherent `fn drop(move self)`, which
was never a destructor (verified under main: it does not run at scope
end); the type was non-Copy only by the old default. Under D120 it is a
value, `take(r) -> Resource: return r` no longer escapes it, and the
pinned `escape_value` contract no longer matches. Declared `resource type`,
like its sibling err_pin_ceiling in the sweep.

* Compilation: reassign taken_zcu instead of declaring it twice (D120 stage 3 surfaced it)

compile_bundle_interface_root declared `var taken_zcu` twice in one
scope. The old compiler let it through because the first binding had been
moved into self.zcu; under D120 stage 3 Zcu is a struct of values, that
assignment copies, the binding stays live, and the shadowing rule refuses
the second declaration. The second is a reassignment of the first.

* Copy glue of a struct is one per-type function; `move x` of a binding is a move; a held copy of a large aggregate goes through memory (D120 stage 3)

Three defects the self-build surfaced once Sema, Zcu and their kin became
values (stage 2's build was clean; stage 3's peaked at 8.6 GB against the
2 GB tripwire, LLVM's unit emit 61 s against 15 s, one unit's `llc` 41 s
against 2 s on same-sized IR). Found by WITH_KEEP_BITCODE + llvm-dis +
opt/llc standalone, and the per-function IR size tables.

1. Codegen: the copy glue of a struct (or a generic struct instance) is a
   cached per-type `__copy_struct_<ty>(ptr)` (ensure_structural_copy_fn,
   the twin of ensure_structural_drop_fn, #691): inlined at every consumed
   copy, Sema's hundreds of collection fields put 5,000 retains into one
   function.

2. MirLower: `move x` of a local binding whose type has drop glue lowers as
   OK_MOVE of the place (the rule the field arm already had), never as a
   retained copy: read as a copy, a moved Sema stayed live across every
   exit path and the drop plan dropped it field by field at each one
   (4,400 drop statements in run_mir_lower). Sema already refuses a later
   use of an explicitly moved binding (#691).

3. Codegen: a held copy (retain or take) of an aggregate of 64 bytes or
   more is memcpy'd into a slot, the glue or the blank runs on the source,
   and the consumer loads the slot — so its load and store stay the
   adjacent pair wl_lower_aggregate_copies turns into a memmove. Read as a
   first-class value with the glue call between load and store, the pass
   could not match, SROA scalarized the 2,378 leaves of a Zcu into a load
   and an insertvalue each, and SelectionDAG's store merging went
   quadratic (the #1129 class).

Also: WITH_TRACE_COW_COPIES=<bytes> (rt_core.w) reports every
copy-on-write copy of a List buffer or map table at or above that size
with a backtrace, and the `taken_zcu` double declaration in
Compilation.compile_bundle_interface_root is a reassignment (the old
compiler accepted it because the first binding had been moved out).

Self-build after: peak RSS 2.3 GB (main 2.2 GB), llvm.units_total 16.1 s
(main 14.9 s).

* rt_core: dbg_puts takes a str; the runtime's literal-cast-and-count sites swept; the census counts rt/ and the pattern

`dbg_puts("…" as *const u8, 11)` spelled, 124 times, what a literal already
is: a str, {ptr, len}, immortal, no count traffic. The signature predated
str-as-value and every caller counted its literal's length by hand (Eric,
2026-10-16: "why are we casting absolutely everything to *const u8"). No
language feature is needed: dbg_puts takes `&str` (as with_eprint twenty
lines away always did), dbg_put_bytes keeps the pointer-and-length form
for the seven sites that only have bytes (an origin tag, a payload), and
make_str("…" as *const u8, N) is the literal. Swept with a `with -p`
regex; cow_trace_copy follows.

The ceremony census gains the pattern (lit-ptr-len: a string literal, `as
*const u8`, a comma, an integer) and counts rt/ — the runtime is written
With, not a migrated corpus. The counts that stand today (the byte-level
seams left: rt_write, rt_buf_write_ascii, dbg_cstr_eq_lit, the platform
files; 36 c_strncmp/bridge sites in src/compiler; rt's existing
let-underscore, len-cast and move-arg) are granted against the bar of 0
until the reseed records them.

* MirLower: an irrefutable destructure of a value subject keeps the subject's drop (D120 stage 3)

`var Bag { items, name, n } = make_bag()` with Bag a struct of values:
the parts are copied out with their own holds (carrier_read_kind, D111's
rule for a Copy carrier with drop glue), so the subject still holds its
own and must keep its drop — retire_decomposed_carrier's rule. The
irrefutable-destructure path cancelled it unconditionally, assuming
moved-out parts, and the subject's holds leaked
(da_var_destructure_owned_moves_once: LEAK size=32 origin=List). A
subject that moves its parts out (a resource, a struct with Drop) is
retired as before.

* A derived clone calls a Copy field's own clone; the fixtures D120 stage 3 reaches (phase, spec, bundle interface, §11.8's example comments)

A derived Clone copied every Copy field and called `clone` on the rest.
Under D120 a struct of values is Copy without a declaration, and one that
also writes its own `clone` means it (Leaf's adds one in
spec_ss11_8_derive): a Copy field copies only when its type declares no
clone of its own (type_declares_clone: an impl Clone or an inherent
method; same for enum payloads).

Fixtures the ruling reaches, updated under it: the prelude-free Task of
test/phase/dump_abi_async_owned_capture.w is a `resource type` as
std.task's is; spec_ss11_8_derive asserts Pixel (a struct of u8s) IS Copy;
test/bundle_interface/wi_demo.wi carries the `impl Copy for Packet` and
`impl Copy for Pair` lines the emitter now writes for its value structs.
docs/spec/011_traits.md's two example comments "NOT Copy — aggregate
types require explicit Copy opt-in" are the projection §2.3/§4.3 (D120)
superseded; repaired to "Copy is not derived: a struct of values is
already a value".

* Bundle interface: a resource type crosses as `resource type` (D120); the demo bundle's Pair is one

The .wi emitter spelled every struct `pub type …`, and wrote `impl Copy`
for a Copy one. Under D120 a struct of values is a value with no
declaration, so a `resource type` struct of values crossing a bundle as a
plain struct would be a value to the consumer's compiler: the emitter now
writes `pub resource type …` (the parser reads it).

test/bundle_interface: the demo bundle's `take(p: Pair)` is the case
"consumed by declaration, though the source body only reads p" — with
Pair a struct of two i32 that is now a value to both sides and consumed by
neither, so Pair is declared a resource (the property the case tests), and
wi_demo.wi carries the emitted spelling.

* build/selfhost.w: the bundle-interface drop-field mutation names Pair by its resource spelling (D120)

* MirLower: a direct raw-pointer pointee read is bitwise, not retained (D120)

`*p = v` and `p[i] = v` through a raw pointer (`TY_PTR`) skip drop-before-
overwrite (`assign_target_is_raw_pointer_store`), so `let v = *p` is how
`Box.drop`, `Box.into_inner`, and `comptime_try_eval_expr_result` (`var sema =
*sema_ptr` ... `*sema_ptr = synced_sema`) take a value out of raw memory.
When D120 stage 3 made a struct of values Copy with drop glue,
`retain_consumed_copy` set `MIR_HOLD_RETAIN` on `*p`: every boxed value
collection/struct leaked its payload on drop/into_inner, and the first
comptime evaluation during `sema.bodies` retained `Sema`'s ~130 tables without
a matching drop on write-back, forcing CoW copies across the rest of the
self-check (a 19.8% regression on `check src/main.w`).

`place_is_raw_pointer_pointee` leaves a direct `PK_DEREF` / `PK_INDEX` on a
`TY_PTR` local unretained while keeping retains on `&T` derefs and field
projections through pointers. `check src/main.w` returns to 51.60 s vs
50.80 s on main (ratio 1.0158, within the 5% gate).

---------

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment