Skip to content

Ownership of locals decided per program point (OwnershipFlow) - #15

Merged
blacktrs merged 164 commits into
mainfrom
ownership
Oct 6, 2026
Merged

blacktrs merged 164 commits into
mainfrom
ownership

Conversation

@blacktrs

@blacktrs blacktrs commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ownership of rc locals is now decided per program point by a static dataflow, instead of "one flavor per local name, else leak it forever". The old name-level machinery is gone.

What changed

New analysis (MIR)

  • Mir\Flow\Forward + Lattice: a generic structured forward dataflow over tree-shaped MIR (if/loops/switch/match/try/goto/break N), with edge callbacks naming the predecessor.
  • Mir\Ownership: one classifier for "is this value +1" (store side and temp side), shared by the pass and the emitter. It replaces the twin predicates that had to agree character for character.
  • OwnershipFlow pass (replaces the rc track of InsertMemoryOps, which keeps only the arena scope):
    • each local is in a state Empty | Own(flavor) | Borrow;
    • at a join, Own ⊔ Borrow compensates with a retain on the borrowed edge;
    • drops sit before an overwrite and at every exit; returns move an owned local;
    • a store into a container is a move only when the local is dead after it, otherwise the container co-owns;
    • a live representation mismatch at a join is a build failure, never silent.

Emitter: executes the planned ops (drop / own_retain / own_share and fields on StoreLocal, Return_, Foreach_, LoadLocal) and no longer decides ownership for locals. The following are deleted:

  • rcObjLocals, the transfer and element-share vetoes;
  • the param entry-retain exceptions;
  • the mirrored return predicates.

Conventions

  • A declared bare/erased array return (function, method, static, closure, first-class callable) is +1 on every path, decided from the declaration, so linkonce copies and stdlib agree. Callers own the result.
  • A by-ref location owns its value: a borrowed local passed by reference is retained at the call.

Representation agreement (InferTypes): one join predicate (joinDisagrees) for statement and expression-arm joins; an erased value meeting another kind makes the local a cell. Foreach bindings are boxed back on every loop exit. A base-, interface- or union-typed read of a property declared only in subclasses is the join of their declarations.

Arena (hybrid mode)

  • Per-iteration reset only for locals whose every binding is a direct arena allocation in that loop; the verdict is computed to a fixpoint and shared by ApplyMemoryMode and the emitter.
  • Exit-edge restore; the try landing unwinds the arena mark stack. Generators opt out of the arena, since a suspended frame is not LIFO.
  • Build-time invariant: a loop holding arena allocations without a reset fails the build.

Fixed on the way (several are pre-existing on main):

  • leaks: property overwrites, mixed locals, self-boxed arrays, foreach literal iterables, nested literals, erased-array returns, by-ref stores;
  • a compiler double free (emitCellArrayToTyped moved elements the source still owned), which crashed ~⅓ of compiles of one test;
  • several silent wrong answers: null ⊔ erased joins, a ternary value join, a multi-hop ?? on a raw NULL leaf, a nullable typed array through a cell.

Later tasks landed on this branch

  • Task 5b / 8b: erased-element and temp-argument release; by-ref write-through with the retype checked (typed property to string & throws TypeError); a by-ref write that retypes a foreach value variable no longer double-frees.
  • Task 6: property reads co-own; property, static property and global overwrite release the old value (superglobals are always cells; user globals are never shared across modules).
  • Task 7: static props, globals and the catch variable are released on overwrite; cell-element overwrite/unset drops by hint; conditional array arms join to cell elements; libraries declare stdlib from .sig.
  • Task 8: cell-element ownership and by-ref write-through (true fixpoint over by-ref retypes, loud cap).
  • Task 9 (zero-cost EH, ABI 16), in stages: 9.1 landing pads and unwind tables; 9.2 finally on every exit (break/continue/return/throw) and exception chaining when a throw leaves finally; 9.3 per-frame cleanup pads (owned locals of unwound frames are released, destructors of unwound frames run in php order, an uncaught throw force-unwinds before the fatal); 9.4 finally on break/continue/return.
  • Also: cs-fixer fix round (generator object release class, nesting-mismatch box, obj-union cell box, classImplementsT iface-extends, closure capture to an unresolved-receiver call, clone port).
  • Main merges: main 2714fbae merged in (incl. dab9dc2b bucket-index copy and cbf73c0a key-before-base for isset/??); both ABI 15 lineages reconciled to ABI 16.

Numbers

  • Census on the self-build: 8138 blocked params + 423 notowned + 369 foreach names → 0 blocked.
  • Full AOT on macOS at ce0c4435: 1640 / 0. CI at ce0c4435: pending on all 6 (linux arm64/amd64, alpine arm64/amd64, arm64-native-runner, macos-arm64).
  • Task 9 budget: IR +5.1% vs cbf73c0a; self-build user +1.1% in a noisy A/B (+5.7% before the cold-helper optimisation); peak RSS +4% vs cbf73c0a. Branch vs main: max RSS +12% (open, over budget).

Closes

Fixes #17, Fixes #20, Fixes #21, Fixes #24, Fixes #25, Fixes #26, Fixes #31, Fixes #40, Fixes #42, Fixes #68, Fixes #77

The repros are promoted into tests/aot/cases/. #67 (array_eq_nested_lists_null_rows) is fixed on macOS only; it stays an xfail on Alpine, so it is not closed here.

Not in this PR (tracked)

Tasks 10 and 11 move to a new PR off main. Details: docs/ROADMAP.md ("Ownership redesign — what PR #15 leaves open").

…callbacks, and tools/ownflow_dump.php to run it on MIR stopped before InsertMemoryOps
…nside try, unresolved gotos and out-of-range break levels throw; add tests/flow fixtures with tools/ownflow_check.sh
… for InsertMemoryOps, classifyTemp arms for EmitLlvm); corpus IR byte-identical
…GEN), FFI-call drift row, ctx trimmed to what is read (moduleFns)
…t is a sentinel, not null (a nullable typed array is a cell natively and came back NaN-boxed)
…place: a typed array returned through array<K,V>|null came back NaN-boxed
…o, as the one-hop coalesce does: $n->type->element ?? X handed back a null object
…th out of the body, before each loop-leaving break/continue too, and an if/else never unplants such an exit box-back: the slot left the loop raw and var_dump($v) past it read a string pointer as a float
…local, or an erased conditional's arm, moves), a live representation mismatch fails the build with function, name and line, self-copies take no +1, the trace env is read once, and a forced round clears stale insertions
…body also stores to it: a break taken before the store left the element raw in a slot read as a cell
…the return took no +1 on moves the owned arm that ran and drops the rest by identity; the pass no longer guesses which erased returns the emitter retains
# Conflicts:
#	src/Compile/Mir/Passes/EmitLlvmExpr.php
#	src/Compile/Mir/Passes/EmitLlvmModule.php
…name-level rc track, the transfer veto and the element-share scan are deleted (container moves and buffer-only shares are decided in the pass)
…s a return takes no +1 on (Return_::ownArms), and a bare-array free function returns +1 on every path so its caller's local owns the result (erasedarr class)
… the other owned locals die at return, the taken arm stays readable by getReturn()
…ocal release ops had no emitter and are deleted
… static method and closure returns +1 (Ownership::returnRetain decides, the emitter executes), callers own erased results; container stores move a local only when it is dead, else the container takes its own +1
…in / returnBorrowsObj), not the deleted emitter copies
…-callable callees; a live container store takes its +1 on the read itself; a concrete array rebind of an erased-result local shares its release class
…kes the local a cell (if/else, loop, switch, try): the join typed unknown read a string as an array; an erased-array result boxed into that cell is owned
…retained through a probe-boxed copy: the tag retain was a no-op on a raw buffer, so $c[] = $f ? $r : [] freed $r's array with the container
…n its own family (the receiver's ancestors, interfaces and module descendants), not from every method of that name
… &&, ||, and, or, ?:, ??, ??=) is a cell: expression joins read the one joinDisagrees predicate
…narrowing reconciles its local that way, and the alias store cloned an array payload and dropped the original on every call (php-cs-fixer Token::equals with an array $other)
…r drops a freed stream as an object cell (musl SIGSEGV)
… helpers self-route on the frame header, so a join of the two is no representation mismatch
…ot drop walks elements by the static nesting
…ts name gives the slot, so an accumulator has one element repr on every path
…mon-supertype walk climbs an interface's extends list
…n Aware-extends-Iterator slot finds its iterator class as the emitter does
…after the call, which may end elsewhere (backtrace push, invoke in a try)
…se class, so a by-ref-suspect call no longer makes it owned and dropped on every call
…e clone dispatch's pass-through arm retains to match
…oto) outside its own handlers; a throw out of it chains the pending exception, a return discards it (#40)
…bel inside a finally no longer redefines its block and a goto stays inside its copy
…s cleanups before the fatal, so the unwound frames' destructors run first as in php
…or; ehLower notes its first-chunk phi assumption
…ght as its previous and the frame's other locals are still dropped; chaining falls back to none when the prelude lacks __mc_finally_chain
…yCatch_: clones run before OwnershipFlow sets them
… boundary, and the trampoline's CFI ends any unwind that reaches the fiber stack's base
… instead of inlining each release, cutting self-build IR 4.6% and clang time
…a destructor that caught its own throw during the forced unwind no longer hands the fatal a cleared or wrong @__mir_thrown
…g prelude body fails the build instead of silently not chaining
@blacktrs
blacktrs merged commit b40d04b into main Oct 6, 2026
7 checks passed
@blacktrs
blacktrs deleted the ownership branch October 7, 2026 08:33
blacktrs added a commit that referenced this pull request Oct 7, 2026
Three shipped designs had no design note: per-program-point ownership
(OwnershipFlow, #15/#104), the native fixed-width buffer runtime behind
SplFixedArray and Manticore\Ds (#108), and the pinned-release bootstrap
(#112/#114). Each is derived from the code it cites; AGENTS.md links the
stage0 note.
blacktrs added a commit that referenced this pull request Oct 7, 2026
…114)

* Remove the Zend cold seed; docs follow the pinned-release bootstrap

The compiler bootstraps from BOOTSTRAP_VERSION (#112), so the seed has no
consumer left. Removed: bin/compile, tools/compile_files_mir.php, bin/build
--seed/--auto-seed, gate.sh MC_ZEND_SEED, install.sh's Zend fallback, and the
dead tools composer_data_smoke.sh, typecheck_scan.sh, split_ll.php,
docker/iopoll/diag.sh, docker/symfony_probe.sh. selfhost_stability.sh rebuilds
through the manifest path instead of Zend; composer.json drops the php
requirement (the installer downloads the release or builds from the pin).

Docs: every guide, README and design note audited against the tree — seed
instructions removed or marked historical, ABI references point at
MemoryAbi::VERSION (18), memory-abi.md gains the 64-byte descriptor (json_fn),
the v14 BIGINT box and the v18 native buffer block, pass tables gain
NarrowScalarGuards, ResolveMethodFcc, ResolveOverloads, SpillFreshBases and
OwnershipFlow.

* docs/design: ownership flow, native buffers and stage0 bootstrap notes

Three shipped designs had no design note: per-program-point ownership
(OwnershipFlow, #15/#104), the native fixed-width buffer runtime behind
SplFixedArray and Manticore\Ds (#108), and the pinned-release bootstrap
(#112/#114). Each is derived from the code it cites; AGENTS.md links the
stage0 note.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment