Drop-reuse: "functional but in-place" (roadmap #11)

Goal. Code that takes a data structure apart and rebuilds it (simplify, map over a tree) should update the structure in place when nobody else holds it, instead of freeing the old cell and allocating a new one.

Done when: rebuilds like simplify convert frees + allocations into reuse. Status: done.

What was built

PieceWhereWhat it does
drop-reuseir.rs, irvm.rstok = drop-reuse x: if x is a uniquely owned constructor, keep its cell in tok instead of freeing it
C(..) @reuse tokir.rs, irvm.rsthe next allocation of the same size is built in that cell: no free, no malloc
pairingperceus.rs pair_reusepairs each allocation with the nearest earlier drop in the same block, preferring the matched value of the same size; never pairs across a return or break
reuse-aware borrowingperceus.rs infer_borrowsLean's rule: a parameter that is matched as C(k fields) and rebuilt with k fields stays owned, because borrowing it would make reuse impossible
drop specializationirvm.rs (match), cgen.rs (since #48)when an arm drops a unique scrutinee, its fields move into the binders (no dups), and the cell is freed or reused without releasing them

The pass is safe by construction. Whether reuse happens is decided at run time (unique? same size?). A shared or wrong-sized cell is simply released and a fresh one allocated.

fn inc(t):
  match t:
    Node(l, x, r) =>
      reuse.11 = drop-reuse t              # t is unique -> keep its cell
      t6 = call #1(move l)                 # children moved out, not dup'ed
      t9 = call #1(move r)
      t10 = Node(move t6, move t8, move t9) @reuse reuse.11

Results

perceus+borrow is the bet 1 strategy. perceus+reuse adds everything above.

programrc ops (borrow → reuse)allocations (borrow → reuse)cells reused
fbip (tree rebuilt 11×)12,282 → 1,02912,286 → 1,03311,253
json55,052 → 49,57978,073 → 77,159914
calc30 → 2553 → 485
server467,450 → 465,89019,745 → 19,7450
raytrace, matmul, shapes, primes, values, hello, higher_orderunchangedunchanged0

Limits and what would extend them

  1. Raytrace gets nothing. add(a, b) builds a new V from two borrowed vectors, so no cell dies inside add. Koka reuses here by making all parameters owned by default. Trine would need an interprocedural rule ("own a parameter if the callee allocates the same size and callers often pass temporaries"). That is future work, and it trades against bet 1's borrowing.
  2. Pairing is size-blind at compile time. The IR carries no types, so a drop may be paired with an allocation of a different size. That is safe (the run-time check falls back), but it wastes a pairing. Typed IR fixes this.
  3. Specialization for nested patterns is approximate. Fields bound deeper than one level are still counted as dups.
  4. Calls through function values take owned arguments. sort_by(xs, key), par_map(f, xs) and any f(x) where f is a value can't know whether the function would borrow its parameter, so the caller hands over a reference: one dup per call, and a drop in the callee when it doesn't keep the value. A key like fn((w, n)) => (-n, w) pays that plus a shared string per element (examples/sorting.tr, 88% of overhead removed; the bet-1 guard gives it its own 85% floor). Lifting it needs a borrowed-parameter flag on function values, checked at the call.

Counting correction (found while doing this)

Building the tree benchmark exposed a counting gap: the VM counted freeing an object as one drop and ignored the releases of the references the object holds. Freeing a 1,023-node tree counted as 1 operation. Compiled code would do a release per child. The VM now counts cascading releases recursively (release_children), for every strategy. As a check, frees now track allocations closely in every row. All bet 1 numbers were re-measured; see the correction section in BET1.md. Bet 1 still passes on every program.

Update (#48): drop specialization in native code

Until #48, drop specialization existed only in the VM, which is what the bet 1 reference-count tables measure. Native code bound fields with a dup and then dropped the scrutinee (releasing the same fields). So the tables credited an optimization compiled programs didn't perform. Found while investigating why examples/text.tr missed the 90% bar.

Now cgen.rs does the same: for an arm whose pattern is flat (C(a, _, b): binders and wildcards) and whose first action drops the scrutinee, it tests uniqueness once, binds owned fields without dup when unique (s = u ? f : cpy(f)), and then frees only the cell (dropping the fields nobody bound), or keeps it for reuse. The VM now applies the same conditions (flat patterns, borrowed scrutinee), so the tables and native code agree. calc's figure moved from 100% to 97% because of that: its nested patterns were being credited.

Second finding: the VM's borrowed aliases (x = &xs[i], borrowed parameters) hold real Rc clones, which made it report "not the last reference" for drops that free in native code. It now discounts aliases held by the current frame and its callers' frames when deciding whether a drop frees an object.

examples/text.tr went from 77% to 90% overhead removed, and the test exception for it is gone. What remains there is real: r.name + ": " takes the name out of a record that is still alive (a dup), then appends to a copy (and drops the dup).