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
| Piece | Where | What it does |
|---|---|---|
drop-reuse | ir.rs, irvm.rs | tok = drop-reuse x: if x is a uniquely owned constructor, keep its cell in tok instead of freeing it |
C(..) @reuse tok | ir.rs, irvm.rs | the next allocation of the same size is built in that cell: no free, no malloc |
| pairing | perceus.rs pair_reuse | pairs 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 borrowing | perceus.rs infer_borrows | Lean'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 specialization | irvm.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.
| program | rc ops (borrow → reuse) | allocations (borrow → reuse) | cells reused |
|---|---|---|---|
| fbip (tree rebuilt 11×) | 12,282 → 1,029 | 12,286 → 1,033 | 11,253 |
| json | 55,052 → 49,579 | 78,073 → 77,159 | 914 |
| calc | 30 → 25 | 53 → 48 | 5 |
| server | 467,450 → 465,890 | 19,745 → 19,745 | 0 |
| raytrace, matmul, shapes, primes, values, hello, higher_order | unchanged | unchanged | 0 |
- The classic case is now in place. Incrementing and mirroring a 1,023-node tree eleven times allocates the tree once. The other 11,253 rebuilt nodes reuse the old ones, and rc ops fall by 92%.
- Reuse never makes anything worse. No program got more rc ops. This is enforced by
cargo test(fbip_reuse_converts_rebuilds_into_in_place_updates). - It doesn't help where there's nothing to rebuild. Most golden programs build lists by
push, which bet 1 already makes in place, or create fresh records from borrowed inputs.
Limits and what would extend them
- Raytrace gets nothing.
add(a, b)builds a newVfrom two borrowed vectors, so no cell dies insideadd. 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. - 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.
- Specialization for nested patterns is approximate. Fields bound deeper than one level are still counted as dups.
- Calls through function values take owned arguments.
sort_by(xs, key),par_map(f, xs)and anyf(x)wherefis 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 likefn((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).