
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
ADR 0043: A Core optimiser: simplifier, specialisation, fusion, constructed product results
Status: Proposed (2026-10-14, epic #195); needs engineering review (#44) — in particular panics and divergence being imprecise and TRMC moving out of lowering (Pipeline).
Context
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.
The questions a Core optimiser must answer here are not the ones GHC answered:
- Louise is strict and effectful. Fusing
map(xs, f)into afilterchanges the order in whichfand the predicate run. That is observable when they perform effects — and effect rows (ADR 0008) say exactly when they cannot. - 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. - 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).
This ADR settles the passes, their order and what may be fused; the sub-issues #196–#200 record the work.
Decision
Pipeline
A pass pipeline louise_core::opt on Core, after lowering, before Perceus:
lower → evidence → simplify ⇄ fuse ⇄ specialise → cpr → trmc → [native: perceus]
- Evidence specialisation moves into the shared pipeline. It ran natively only; both back ends run it now, first in the pipeline (its copies are ordinary functions to the later passes). Two reasons: the interpreter gets the devirtualised direct calls too, and fusion's purity gate (below) must see the same code in both back ends — a dictionary call that is opaque before evidence is an
Intaddition after it, and a pipeline that fused natively but not in the interpreter would break the "same optimised Core" rule that keeps panic imprecision invisible to the differential tests.LOUISE_NO_SPECIALISEstill disables evidence alone;LOUISE_NO_OPTdisables the whole pipeline including it. - 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,filterandfold; after TRMC those functions are context loops. TRMC still runs before Perceus, and still applies to what optimisation leaves — an unfused effectfulmap, say. Running before TRMC and Perceus also means the optimiser's grammar has noCtxExtend/CtxApply/Dup/Drop/Release/Reusenodes: those passes' invariants are structurally unaffected. - Both back ends run it.
optruns on the functions reachable from the entries (issue #114), for the interpreter too: both back ends run the same optimised Core, sotests/runoracles every pass, and the interpreter gets faster as well (issue #196). - 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.shtracks the compile-time cost (issue #61). - Escape hatches and reporting.
LOUISE_NO_OPTdisables the whole pipeline (alongsideLOUISE_NO_SPECIALISEandLOUISE_NO_TRMC).louise coreprints the optimised Core (--no-optprints it as lowered); with-vit lists on stderr each rewrite that fired, with the rule's name and the span it fired at (issue #198's reporting question).
The simplifier (issue #196)
To a fixed point, per function:
- 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. Inlining stays within a module (ADR 0029): a unit's C must not come to depend on another module's body, or an edit there would recompile it — with two exceptions: generated code (dictionaries, the passes' copies) has no module and may inline anything, and std's functions may be inlined anywhere (std ships with the toolchain, so its units' stability is the toolchain's own). Other cross-module calls are specialisation's and fusion's business (issues #197, #198), whose copies have a unit of their own.
- Case-of-known-constructor: a
switchon a value built in the same function takes its branch at compile time; a projection of a known construction becomes the field. Case-of-case: aswitchon a value that a nested block computed by aswitchmoves into the inner arms (the inner block pure and panic-free, the scrutinee used only there), where each arm's construction is then known — this is what dissolves a stream-fused pipeline's per-pullStepblocks (issue #199). - Dead lets and sinking: a
letof a pure value nothing uses is removed; a pureletsinks toward its single use — never across an effect, aperformor ahandle. (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.) - Copy propagation:
let v = usubstitutes.
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.
Specialisation (issue #197)
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.
Fusion, and purity (issue #198)
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:
map(map(xs, f), g)→map(xs, fn(x) { g(f(x)) });each(map(xs, f), g)likewisefold(map(xs, f), z, g)→fold(xs, z, fn(a, x) { g(a, f(x)) })fold(filter(xs, p), z, g)→fold(xs, z, fn(a, x) { if p(x) { g(a, x) } else { a } })fold(range(a, b), z, g)→ a counting looplength(map(xs, f))→length(xs)
There is no filter ∘ map rule: filter(map(xs, f), p) is not filter(xs, p ∘ f) — the map changes the elements, not just the predicate. (The epic's pipeline fuses completely anyway: fold of a filter of a map of a range fires fold ∘ filter, then fold ∘ map, then fold ∘ range.) Fusing a map through a filter is stream fusion's business (issue #199).
Not fused: an effectful stage, try_map, flat_map, zip, or an intermediate used twice. A perform, handle, region or defer anywhere in a stage's function makes it effectful for this gate — any handle, even one that masks its own effect and so would be pure: the purity analysis is deliberately conservative there, and can be refined if real pipelines need it.
- Purity is computed on Core (
opt::pure), not threaded from the type checker: Core is untyped, and after inlining the body is the truth. A function is pure when it has noperform,handle,regionordefer, calls directly only pure functions, calls no unknown closure (after evidence specialisation, dictionary calls are direct calls or externs), and calls only externs the runtime extern table marks effect-free (externs::runtime_extern(..).effect_free) — 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. (This bullet first described a finer gate — handles that mask their own effect, known pure closures,louise_perceus::fip::ALLOCATION_FREE— that was not what was built:louise_corecannot depend onlouise_perceus, and the extern table records effect-freedom itself. Corrected 2026-10-15, issue #227.) - Panics are effects here; divergence is imprecise. A crash is observable in Louise — a monitor sees
Crashed(message), a supervisor restarts (ADR 0004's "let it crash") — so a stage that can panic is never fused, whether the rule would reorder its panic or skip it. Divergence is imprecise, as in GHC: a pure stage that loops hangs fused or not (andlength ∘ mapcan turn a hang into a result — nobody writes an intentionally divergent mapper). What may still change is when allocation happens, which nothing observes. The gate (opt::pure) requires: noperform/handle/region/defer, direct calls only to pure functions, externs only effect-free ones, and no panic — with a pragmatic carve-out the epic's own pipeline needs: division or a shift by a nonzero literal cannot panic (x % 3fuses). Since both back ends run the same optimised Core, they cannot disagree with each other. - Built-in rules, not a
@ruleattribute. 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 recognise thestd/listfunctions by their module and qualified name as lowering records them (std/list.map,opt::fuse::std_list); a specialised copy has no module, so it is not mistaken for the original. (This bullet first said they would key onWellKnown, as builtin effects do; names were what was built, and a user module cannot be namedstd/list. Corrected 2026-10-15, issue #227.)
Constructed product results (issue #200)
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:
- 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; - CPR runs after the fixed point, before TRMC and Perceus, so Perceus counts the components and the tuple is never built on worker paths;
- 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'smusttailguarantee rests on; a worker tail-calls only a same-shaped worker, so tail calls staymusttail; - the interpreter ignores workers and runs the wrapper, unchanged.
TRMC'd functions are never eligible (their returns go through contexts), and @fip functions keep their meaning: a worker builds nothing either.
std/iter (issue #199)
Not a pass: a library the passes optimise well. std/iter's Iter<a, e> is an existential state with a step function (ADR 0041), over type Step<s, a> { Done, Skip(s), Yield(a, s) }; the step's effect row is a parameter carried through unchanged (ADR 0041's Revision 1), so a stage's function may perform effects and runs when the element is pulled. A pipeline range(1, n) |> map(f) |> filter(p) |> fold(0, add) then compiles to one loop by specialisation, inlining, case-of-known-constructor and case-of-case on Step — stream fusion (Coutts, Leshchinskiy and Stewart, 2007) without rewrite rules. Done when the loop allocates nothing, by the leak oracle's allocation counts.
Consequences
- 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.
louise coreprints the optimised Core. The lowering snapshots lose their$trmcfunctions: the TRMC tests calltrmc::runthemselves.- Panic and divergence imprecision is documented in the language reference when fusion lands.
- Compile time: the passes run on reachable functions only, and
scripts/bench-compile.shtracks the cost. - Code size: inlining and specialisation grow code, bounded by their budgets; reported on hello and
http_demoin the specialisation PR. - The bar for every PR of the epic is the owner's usual one: nothing in
tests/benchmore than 5% slower.
Note — 2026-10-15: what checks the optimiser
Status: Proposed; needs engineering review (#44). Issue #219.
"Both back ends run it" made the interpreter oracle the optimiser's results against the native backend, not the optimiser itself: a miscompilation shows the same in both, and the //> expectations catch it only if a program happens to print the difference — and an expectation written after the optimiser landed may have been copied from its output. So:
- every
tests/runprogram also runs unoptimised, in the interpreter (louise_interp/tests/run.rs, with the unit tests) and natively (louise_codegen_c/tests/native.rs, an ignored test thatscripts/ci.shruns; leaks counted as for the optimised run), against the same expectations: an expectation is then confirmed by code the optimiser never touched; - the benchmarks (
tests/bench), whose checksums predate the optimiser and which go through evidence specialisation, inlining and CPR at realistic sizes, are built natively both ways in CI and must print their checksums. Nothing ran them in CI before:scripts/bench.shonly times them.
The coverage stays that of the programs. A planted bug in the fold ∘ range loop (a step of 2) was caught by tests/run alone: no rewrite rule fires in any benchmark or in tests/compare (the comparison's pipeline goes through std/iter), and only tests/run/fusion.lse, bigint.lse and dict.lse fire one. Generated programs, compared optimised against unoptimised, would reach shapes the hand-written ones don't; that is left for later. Unoptimised is what LOUISE_NO_OPT gives — no evidence specialisation, no simplify/fuse/specialise rounds, no CPR, TRMC still — passed as a value (opt::Optimise, opt::run_with, louise_codegen_c::generate_with), since a test cannot set the variable without racing the others. Panic imprecision (above) is not a problem for the comparison: fusion never fires on a stage that can panic, so a program's panic is the same either way.
Note — 2026-10-23: evidence at dictionaries built from constant ones (issue #278)
Status: Proposed; needs engineering review (#44).
Evidence knew constant dictionaries only (ADR 0013's "not specialised: dictionaries built from constraints"). A constrained impl's dictionary, Describe<Box<a>> from Describe<a>, is built by a function of its constraints' dictionaries whose closures capture them, so a call through it stayed indirect, and a method too big to inline was never specialised: its own trait calls stayed indirect too. The pass, still first in the pipeline and shared by both back ends, now:
- gives each dictionary function with parameters (a body of closures over its parameters, constant dictionary reads and tuples) a shape: a call through the dictionary it builds calls the method directly, its captures first, and the method is copied for the constant dictionaries among them, however big its body;
- keys copies on such built dictionaries too, when their arguments are constant (
twice [dict Describe<Box> [dict Describe<Int>]]); inside a copy, those constant dictionaries are read again for the captures, a static read natively; - leaves deeper nesting alone (a dictionary built from a built one, inside a copy, is not rebuilt), so no dictionary is allocated that was not; calls through it stay indirect;
- removes unused calls of dictionary functions, as it removed unused constant reads.
The budget is unchanged (copies per function of the program, in total). Measured against main: the Core of every benchmark in tests/bench is unchanged, since none builds a constrained dictionary from constant ones (arith and dict use constant ones only), so their times cannot move; http_demo's program code is 1.2% smaller (233,388 bytes of text against 236,169) and hello's unchanged. tests/run/built_dictionaries.lse covers nesting, tuples and lists in both back ends.
Alternatives considered
- 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.
- A
@ruleattribute from the start: rejected above; the built-in table first, a language feature later if it earns it. - 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/iteris the general mechanism. - 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.
- 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
ReturnNis a bigger change for the same result. - 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.
Note — 2026-10-24: interpreted tests run unoptimised (issue #316)
Status: Proposed; needs engineering review (#44).
louise test in the interpreter optimised the program once for every
test's entry: on toki2 (372 tests), 4.5–5 s of a run that otherwise takes
about one second, paid on every run whatever changed. Interpreted tests
now run unoptimised Core by default (Optimise::No: TRMC still runs,
so deep recursion stays in constant stack), and --opt runs the
optimised Core as before. Native tests (--native) and native builds are
unchanged.
What the optimiser does is still checked: every tests/run program runs
both ways (the note above), native tests run optimised Core, and --opt
gives a package's own tests the same check. Programs differ only where
the note above says they may: divergence (a fused pipeline can return
where the unfused one would loop) and how actors interleave (fewer calls
after inlining, so preemption falls elsewhere), neither of which a passing
test may depend on. On toki2 the run phase is no slower unoptimised.