Wado

WEP: NIR Optimizer Architecture

Status: Complete. The architecture below is what the optimizer runs on. What it does not do is a known gap, with no claim that it will be closed.

The NIR optimizer is a two-tier IR: a structured effect skeleton, plus a pool of hash-consed pure values that some of its operands name. A worklist engine rewrites it one function at a time, a per-function dirty-set gate schedules the passes, and the result is extracted once into WIR.

This WEP records decisions, the measurements that settled them, the obligations they impose, and what is still open. It names an identifier only when the decision is about that identifier. Everything else is the code's to say: node kinds, rule predicates, pass order, and which function holds what live in nir_arena.rs, nir_value_graph.rs, nir_engine.rs, and optimize/, and the pass inventory in docs/optimizer.md. A decision does not go stale. A description of the code does, the moment the code moves, so a detail a reader needs in order to act belongs in a doc comment beside the code.

Terms

Context

The optimizer was about 31 independent passes. Each was a full mutating walk over an owned tree body, inside a global fixed-point loop. That shape had two costs.

Decision

Layer 1: the skeleton arena (nir_arena.rs)

A function body is a per-function arena, Body. It is the canonical post-lower form: lower::translate builds it and wir_build reads it. A closure's call method and a non-trivial global initializer are bodies too, so every pass reaches them without a special case.

Layer 2: the value pool (nir_value_graph.rs)

Pure values are hash-consed into a per-function ValuePool, indexed by ValueId. Two structurally equivalent pure values share one id.

The pool holds values. It does not hold flow. No per-function structure records which value a local has at a point, or what a field read sees at a heap version: a scoped walk derives that for the region a query asks about, on a scratch copy of the pool, and the answer is constants and field values, not ids a later pass may hold. See Not a persistent value graph.

The operand bridge

A skeleton child slot is Operand = Expr(ExprId) | Value(ValueId). An effectful or control-flow operand is always Operand::Expr. A pure one is Operand::Value once a freeze has promoted it, and most are not promoted; see The value tier stays small.

No expression-keyed value map is persisted. An unpromoted skeleton leaf therefore resolves to no value. That is sound because "no value" is the finest partition: a consumer skips the expression rather than over-merging.

A rule about a pure value is written against Operand, once. A promoted operand is the same computation as the skeleton node it replaced, so it has to answer to the same rules — and the two tiers spell that computation differently, so a rule written once per tier drifts. The interpreter's arithmetic folding takes this shape: one set of rules over a view that resolves the tier at the leaves. A rule that reaches for ExprKind and ValueKind in two places is the shape to avoid.

Promotion is staged. A freeze is sound only where nothing later re-contextualizes the operand it plants. Lowering interns all-literal arithmetic, which names nothing outside the pool. Field reads freeze once the structural passes have settled the shape they read. The arithmetic freeze runs after every pass that walks arithmetic. No freeze runs before or inside the loop.

Extraction

One pass materialises each promoted operand back into concrete form, at WIR build. It reads each value's type from the pool and recurses on composites. The optimizer can extract a constant on its own, so a pass can read a frozen value without waiting for the backend.

A scalar value is re-materialised at each use. That is always correct, and for a constant always cheaper than sharing. A multi-use field read may be shared.

The engine (nir_engine.rs)

Local rewrites run as Rules on a worklist over one function's Body, to a local fixed point. A node is revisited only when an edit may have made it reducible, never by a whole-tree sweep.

The position-flexible local rules share one session per function. It runs pre-inline and post-inline, so each rule sees the instruction window the other exposes. Which rules those are is the inventory's.

Two things stay outside the engine. A flow-sensitive pass that needs per-block dataflow keeps its own walker over the arena. The interprocedural stages run as distinct steps.

Per-function gating

Each function carries a monotonic revision and each pass a per-function watermark. A gated pass visits a function only when its revision has passed the watermark. A pass that changes a function bumps its revision and, conservatively, that of its immediate call-graph neighbours in both directions. An interprocedural pass pulls its candidates from the dirty set rather than scanning every function, and re-marks the callers of a callee it shrinks. The loop's iteration cap is the quiescence bound. A pass whose summary a call-graph change invalidates cannot be gated on the callee's revision alone, and stays explicit.

An empty column skips the pass before its whole-program setup rather than after. A pass builds its catalogs, callee maps, effect summaries and call-site censuses before it reaches its first function, so a late round that visits nothing would otherwise spend all its time there.

Gating changes only which functions a pass visits, never the result of a visit. Every loop pass is an optimization, so an imprecise gate costs optimization quality, never correctness. The same one-sided argument covers the interprocedural over-approximation.

The heap-effect summaries are the exception. Several passes read them, so they are held across the loop rather than rebuilt by each reader. They are keyed by each function's write count, which every mutable access to its body bumps. A reader re-solves only the call-graph components that hold a function written since, or that call one whose summary moved. A stale summary is unsound rather than imprecise, which is why the key is the access and not a pass's report of a change. A debug build re-checks one summary on each read.

The value tier stays small

The value pool is a constant pool and a post-loop extractor. It is not the home of every pure value, and no work is committed to make it one.

The design this WEP started from was Cranelift's aegraph: every pure position an operand, flow resolved into a graph once, and CSE, GVN, copy propagation and store-load forwarding falling out of shared ids. That design was built as far as the measurements below, and they say the remainder does not pay.

So the tier is kept at the size that earns its place: the pool, the two freezes after the loop, post-scalarize store-load forwarding, and extraction. Growing it is a known gap.

Soundness invariants

Standing invariants: do not reintroduce

These are settled by measurement and re-derived at a cost.

Rejected

Not sea-of-nodes

Sea-of-nodes, and dropping the skeleton, stay rejected.

Not equality saturation

Saturation over the pool would unlock algebraic exploration: re-association, the distributive law, strength reduction per use, cost-based share-versus-duplicate. Wado's output is Wasm, which the host runtime JITs again, and the host redoes most of that algebra. Cranelift's aegraph reports 5–10 % on native AOT, and the JIT-target number is much smaller. The optimizations Wado carries are single-direction structural rewrites that saturation does not help: allocation elimination, structural cleanup, dense Match lowering, bounds-check elimination, inlining.

Not a persistent value graph

A graph built once per function and maintained across every edit was the centre of the original design: flow resolved at build, each read fixed to the value dominant at its point, a snapshot of every local's value at each loop entry.

It was built, and it was removed. Its goal was to halve the optimize phase, and that was declared not met once the build had been made single. By then every consumer had moved off it or been ablated to no diff: the bounds-check path that read it was deleted, the union-find went, and an in-loop freeze under it promoted nothing. What remained read it for one bit: whether a local held a value at a loop's entry, which LICM's in-loop CSE asks before it shares an expression.

The graph answered that bit by the history of the function. The snapshots were taken at the first value query, before inlining, and never retaken. Inlining cleared them after any splice of a call that was impure or carried a loop, and loop versioning cleared them every time. The CSE therefore stopped reaching a function once either had touched it. The skeleton now answers, the same for every loop: the local is a parameter, or its let dominates the loop. Against the graph, node benchmark/fuel.ts check moves three regions, and 133 of 3 496 WIR goldens change, 138 KB smaller and 5 KB larger.

Region Fuel
codec/zlib/compress −0.65 %
gale/sqlite/parse +1.19 %
gale/sqlite/highlight +1.44 %

Keeping it meant every structural pass maintaining it. Inlining ran a whole-program immutability analysis per round to decide whether a splice preserved the caller's values. That obligation is what bred defects: the promoted tier and the graph account for 52 fix commits between June and November 2026.

Folding the build into lower is rejected with it. The build's inputs, the alias sets and the per-call purity verdicts, are derived over the whole lowered package, and an empty alias set is the optimistic direction, so building without them is unsound.

Not a session index carried across passes

Opening a session rebuilds the parent map and use index, 18 % of the loop when measured. Carrying the index across passes was built and measured. 91 % of sessions reuse it and the derivation drops 68 %, but the loop total does not move, and reuse changes the output by 3.3 KB, so the carried state is not equivalent. Soundness would rest on every pass invalidating it by hand, each omission a silent miscompile.

The prerequisite that would change this verdict is closing the arena's mutation surface, so that the type system rather than a reviewer carries the invariant that every edit goes through the API.

Not incremental rebuild, and not a richer cache

Both were prototyped and measured, and both are the wrong shape. They make re-deriving a derived analysis cheaper, when the analysis needs re-deriving only because it is derived. See Measured dead ends.

Where it stands

Measured in November 2026 on a dev build, which is the compiler developer's inner loop, so every figure includes debug_assert!s. The figures in this section predate the removal of the persistent graph.

Compile time

wado compile -O2 under the span trace, warm.

Share of the compile sqlite_parse json_twitter
optimize 82 % 86 %
the fixed-point loop 63 % 65 %

The loop converges in 8 or 9 iterations, with a long tail: iterations 4 to 6 visit functions of which over 90 % come out unchanged.

Self CPU on json_twitter, sampled with samply.

Where Share of the compile
Engine 15.5 %
allocation 13.7 %
const_fold (niri) 12.4 %
copy_prop 10.2 %
the generic arena walks 9.6 %
licm 9.3 %
Engine::is_held_from_root, a debug_assert!-only audit 8.3 %
heap-effect summaries 4.8 %
the value tier 4–5 %

What the value tier buys

WADO_SKIP_PASS=<pass> wado test -O2 --allocator freelist --report-fuel over twenty fuel regions of ten benchmarks, and the size of four compiled benchmarks. A positive figure is a loss when the pass is skipped. Nine regions move under none of them.

Skipped Fuel, the regions that move Code size
promote_fields −0.02 to −0.19 % in nine regions −8 to +493 B
freeze_pure_arith json/canada/de +0.12 % +3 B
store_load_forward_post_scalarize cbor/canada/de +1.05 %, json/canada/de +0.36 % +0.03 to +0.80 %
all three at most +1.05 % +0.04 to +0.82 %
value_pool/fold_const none none

What the pool reaches

WADO_TRACE=arena_census.

At end-of-optimize sqlite_parse json_twitter
Pure kinds among reachable expressions 77 % 70 %
Arena expressions per reachable expression 2.15 × 2.78 ×
Arena statements per reachable statement 2.64 × 3.51 ×

WADO_TRACE=freeze_refusals. These describe the program the optimizer sees, not its output: how much a freeze promotes, and how many local reads a flow-free value query could resolve.

Share sqlite_parse json_twitter
Pure kinds promote_fields promotes 9.9 % 11.8 %
Pure kinds freeze_pure_arith promotes 4.7 % 7.8 %
Local reads whose local is assigned exactly once 75 % 85 %

Known gaps

The value tier

Compile time

Precision

Measured dead ends

Each was built, verified, and reverted. Do not retry as-is.

Consequences

See also