| @@ -0,0 +1,85 @@ |
| 1 | +# ADR 0043: A Core optimiser: simplifier, specialisation, fusion, constructed product results |
| 2 | + |
| 3 | +**Status:** Proposed (2026-10-14, epic #195); needs engineering review (#44) — in particular [panics and divergence being imprecise](#fusion-and-purity-issue-198) and TRMC moving out of lowering ([Pipeline](#pipeline)). |
| 4 | + |
| 5 | +## Context |
| 6 | +Core goes from lowering (TRMC included, ADR 0039) straight to Perceus and C, with evidence specialisation (ADR 0013) on the way natively. Nothing optimises Core itself, so higher-order code pays for a closure per lambda, an indirect call per element and an intermediate list per pipeline stage. Issue #195 measures it: a `map`/`filter`/`fold` pipeline over 1M integers, run ten times, is 0.43 s in Louise (68 MB), 0.08 s in Rust, and 0.00 s in GHC, which fuses the pipeline into one loop. |
| 7 | + |
| 8 | +The questions a Core optimiser must answer here are not the ones GHC answered: |
| 9 | + |
| 10 | +- **Louise is strict and effectful.** Fusing `map(xs, f)` into a `filter` changes the order in which `f` and the predicate run. That is observable when they perform effects — and effect rows (ADR 0008) say exactly when they cannot. |
| 11 | +- **The back ends must keep agreeing.** The interpreter is the native backend's test oracle (`tests/run`); an optimisation only one of them runs would make them disagree wherever the optimisation is visible. |
| 12 | +- **Existing passes have shapes to preserve:** Perceus' matched values (ADR 0040), TRMC's contexts (ADR 0039), guaranteed tail calls (ADR 0003) and the one C signature they rest on (the runtime ABI). |
| 13 | + |
| 14 | +This ADR settles the passes, their order and what may be fused; the sub-issues #196–#200 record the work. |
| 15 | + |
| 16 | +## Decision |
| 17 | + |
| 18 | +### Pipeline |
| 19 | +A pass pipeline `louise_core::opt` on Core, after lowering and — natively — after evidence specialisation, before Perceus: |
| 20 | + |
| 21 | +``` |
| 22 | +lower → [native: evidence] → simplify ⇄ specialise ⇄ fuse → cpr → trmc → [native: perceus] |
| 23 | +``` |
| 24 | + |
| 25 | +- **TRMC moves out of lowering** to after optimisation (ADR 0039's "at the end of lowering" is amended; it gains a note in the PR that lands the move). Specialisation and fusion recognise the pristine recursion of `map`, `filter` and `fold`; after TRMC those functions are context loops. TRMC still runs before Perceus, and still applies to what optimisation leaves — an unfused effectful `map`, say. Running before TRMC and Perceus also means the optimiser's grammar has no `CtxExtend`/`CtxApply`/`Dup`/`Drop`/`Release`/`Reuse` nodes: those passes' invariants are structurally unaffected. |
| 26 | +- **Both back ends run it.** `opt` runs on the functions reachable from the entries (as evidence does natively, issue #114), for the interpreter too: both back ends run the same optimised Core, so `tests/run` oracles every pass, and the interpreter gets faster as well (issue #196). |
| 27 | +- **Budgets.** The fixed point of simplify/specialise/fuse stops when a function stops changing or grows past a node budget; specialisation copies are bounded in total, as evidence's are. `scripts/bench-compile.sh` tracks the compile-time cost (issue #61). |
| 28 | +- **Escape hatches and reporting.** `LOUISE_NO_OPT` disables the whole pipeline (alongside `LOUISE_NO_SPECIALISE` and `LOUISE_NO_TRMC`). `louise core` prints the optimised Core (`--no-opt` prints it as lowered); with `-v` it lists on stderr each rewrite that fired, with the rule's name and the span it fired at (issue #198's reporting question). |
| 29 | + |
| 30 | +### The simplifier (issue #196) |
| 31 | +To a fixed point, per function: |
| 32 | + |
| 33 | +- **Inlining:** a direct call of a small non-recursive function (a node-count threshold), or of a known lambda called once, becomes the body; a call in tail position stays in tail position. Wrappers (a function that only calls another) are always inlined. Recursive functions are never inlined. |
| 34 | +- **Case-of-known-constructor:** a `switch` on a value built in the same function takes its branch at compile time; a projection of a known construction becomes the field. |
| 35 | +- **Dead lets and sinking:** a `let` of a pure value nothing uses is removed; a pure `let` sinks toward its single use — never across an effect, a `perform` or a `handle`. (Sinking pure code past a call is sound: pure code is unobservable, and its divergence is imprecise, below. The C backend's yield checks come later, on code whose effect order is fixed here.) |
| 36 | +- **Copy propagation:** `let v = u` substitutes. |
| 37 | + |
| 38 | +Constraints carried from the issue: effects never move across each other or across `perform`/`handle`; tail calls stay tail calls (ADR 0003); Perceus still sees matched values — the pass keeps `FnDecl::shapes` for the variables it keeps and records none for the ones it makes (ADR 0040's "empty for code made up later"); spans move with the code they annotate, so `#line` directives stay right. |
| 39 | + |
| 40 | +### Specialisation (issue #197) |
| 41 | +A direct call of a recursive higher-order function whose closure argument is a known lambda or top-level function gets a copy `map$k`: the closure parameter is removed, its captured variables become parameters, and the call inside is direct. Copies are keyed by (function, lambda), shared across call sites, bounded in total, and recursion reuses the copy in progress — as evidence's copies do. The composition lambdas fusion builds are ordinary lambdas and specialise too. It works on user code as on std; dictionaries stay evidence's business, whose copies are ordinary functions this pass can specialise further. Code size is reported on hello and `http_demo` in the PR. |
| 42 | + |
| 43 | +### Fusion, and purity (issue #198) |
| 44 | +Rules on `std/list` pipeline shapes, fired only when every function argument of the stages involved is pure and the intermediate list is used once: |
| 45 | + |
| 46 | +- `map(map(xs, f), g)` → `map(xs, fn(x) { g(f(x)) })` |
| 47 | +- `fold(map(xs, f), z, g)` → `fold(xs, z, fn(a, x) { g(a, f(x)) })` |
| 48 | +- `fold(filter(xs, p), z, g)` → `fold(xs, z, fn(a, x) { if p(x) { g(a, x) } else { a } })` |
| 49 | +- `fold(range(a, b), z, g)` → a counting loop |
| 50 | +- `length(map(xs, f))` → `length(xs)`, and `each(map(xs, f), g)` likewise |
| 51 | + |
| 52 | +Not fused: an effectful stage, `try_map`, `flat_map`, `zip`, or an intermediate used twice. |
| 53 | + |
| 54 | +- **Purity is computed on Core**, not threaded from the type checker: Core is untyped, and after inlining the body is the truth. A function is pure when it performs no effect a `handle` of its own doesn't mask (the clauses recursively pure), opens no region, defers nothing, calls directly only pure functions and known pure closures, and calls externs only from the allocation-free list (`louise_perceus::fip::ALLOCATION_FREE`) plus the boxing float arithmetic — allocation is not observable (reference counting has no hooks), so it is not an effect. A greatest fixed point, so recursion between pure functions is pure. |
| 55 | +- **Panics and divergence are imprecise.** Optimisation may reorder them, replace one with another, or skip one: `length(map(xs, f))` never runs `f`. A run that finishes normally computes the same value as before. That matches errors-as-values (ADR 0024 — a program that relies on *which* panic fires is already wrong) and GHC's imprecise exceptions; and since both back ends run the same optimised Core, they cannot disagree with each other. |
| 56 | +- **Built-in rules, not a `@rule` attribute.** The shapes are few and stable; a user-facing rule language has a soundness surface of its own (confluence, ordering, proving LHS ≡ RHS) that a later ADR can bring. GHC's RULES are the precedent in both directions. Rules key on the std functions' identity as lowering records it (`WellKnown`, the way builtin effects are identified), not on names. |
| 57 | + |
| 58 | +### Constructed product results (issue #200) |
| 59 | +A function whose exit paths all build the same tuple or single-constructor value (of arity 2 to 4), whose direct callers destructure it at once, and whose exit paths tail-call only functions of the same shape (or none), gets a worker/wrapper split: |
| 60 | + |
| 61 | +- the worker returns the components — Core gains a multi-value return, `ReturnN(atoms)`; the wrapper keeps the original body and signature, and serves closures and unknown callers; |
| 62 | +- CPR runs after the fixed point, before TRMC and Perceus, so Perceus counts the components and the tuple is never built on worker paths; |
| 63 | +- the C backend emits the worker with a second signature: a small struct returned by value (two words come back in registers on SysV amd64 and on aarch64). Everything else keeps the one `tl_value`-returning signature the ABI's `musttail` guarantee rests on; a worker tail-calls only a same-shaped worker, so tail calls stay `musttail`; |
| 64 | +- the interpreter ignores workers and runs the wrapper, unchanged. |
| 65 | + |
| 66 | +TRMC'd functions are never eligible (their returns go through contexts), and `@fip` functions keep their meaning: a worker builds nothing either. |
| 67 | + |
| 68 | +### std/iter (issue #199) |
| 69 | +Not a pass: a library the passes optimise well. `std/iter`'s `Iter<a>` is an existential state with a step function (ADR 0041), over `type Step<s, a> { Done, Skip(s), Yield(a, s) }`. A pipeline `range(1, n) |> map(f) |> filter(p) |> fold(0, add)` then compiles to one loop by specialisation, inlining and case-of-known-constructor on `Step` — stream fusion (Coutts, Leshchinskiy and Stewart, 2007) without rewrite rules. Effects are allowed and run in pull order: a stage's function runs when the element is pulled. Whether the step's effect row is a parameter of `Iter` or existential is an implementation detail (ADR 0041 has no row-kind indices). Done when the loop allocates nothing, by the leak oracle's allocation counts. |
| 70 | + |
| 71 | +## Consequences |
| 72 | +- The pipeline order changes: TRMC after optimisation, evidence before it (natively). ADR 0039 gains a note in the implementing PR. The optimiser never sees Perceus or TRMC nodes. |
| 73 | +- `louise core` prints the optimised Core. The lowering snapshots lose their `$trmc` functions: the TRMC tests call `trmc::run` themselves. |
| 74 | +- Panic and divergence imprecision is documented in the language reference when fusion lands. |
| 75 | +- Compile time: the passes run on reachable functions only, and `scripts/bench-compile.sh` tracks the cost. |
| 76 | +- Code size: inlining and specialisation grow code, bounded by their budgets; reported on hello and `http_demo` in the specialisation PR. |
| 77 | +- The bar for every PR of the epic is the owner's usual one: nothing in `tests/bench` more than 5% slower. |
| 78 | + |
| 79 | +## Alternatives considered |
| 80 | +- **Native-only optimisation:** the back ends would diverge exactly where panics are imprecise, and the interpreter would keep paying an indirect call per element. One optimised Core keeps the oracle property. |
| 81 | +- **A `@rule` attribute from the start:** rejected above; the built-in table first, a language feature later if it earns it. |
| 82 | +- **foldr/build (GHC's short-cut deforestation):** relies on non-strictness; in a strict language the same rewrite is unsound without the purity gate, and the recognised-shapes table covers std's pipelines directly. Stream fusion through `std/iter` is the general mechanism. |
| 83 | +- **Type-directed purity** (lowering records each call's effect row): stale as soon as a pass rewrites the code. Purity recomputed on Core improves as specialisation makes closures known, and needs no new metadata. |
| 84 | +- **CPR in the C backend only** (out-parameters, no Core change): Perceus would still reference-count a tuple that is never built; in Core before Perceus, the counts follow the components. A continuation form instead of `ReturnN` is a bigger change for the same result. |
| 85 | +- **An LLVM backend as the optimiser:** the generated C is deliberately simple so any C compiler builds it fast (issue #61); an LLVM backend is a separate decision. |