On this page

0036. Invisible scoped arenas with coloured scratch

Context

Harness needs cheap temporary allocation while preserving observationally immutable values. The runtime API must exist before compiler scope placement and arena colouring are implemented. M5 separates the M5.1 runtime from M5.2's compiler analysis.

Decision

Arenas are invisible: no source syntax, annotations, or lifetimes are added. Programs observe immutable values; reporting promotions and copies is their only visibility into allocation.

M5.1 provides hrt_alloc(a, n, f, l, c), hrt_mark(a), and hrt_reset(a, mark). Arena storage is reserved lazily on first allocation: try 64 GiB, halving to 1 GiB, with PROT_NONE, then commit writable memory in 1 MiB steps. Allocation bumps an 8-byte-aligned top. Reset restores a mark; when the high-water mark exceeds it by more than 4 MiB, discard committed pages above the rounded-up mark. Exhaustion traps as out of memory. Reservations use MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE; 258 BSS arenas plus a separate persistent arena perform no startup work. Reservations live until process exit; committed pages remain writable after discard.

There are three lifetime classes: scratch for function and iteration scopes; request storage, main's function scope, reset only when main returns; and persistent storage (hrt_persistent), API and C tests only until M6 or M12. No compiled code uses persistent storage before then.

M5.2 assigns scope colours. A function may write only to its own scopes and to ret, its hidden region parameter. A scope at depth d (function scope 0) has colour d+1; ret is colour 0. So K = max_depth + 2. The emitted HN_ARENAS is K; base b and colour c select (b + c) % K. HRT_COLOUR(ret, c) derives b from the hidden hrt_arena *hrt_ret; functions without allocating results use base zero. Each scope saves a mark. Iteration scopes reset at loop head (including continue), after the loop and its break label; returns reset all open scopes innermost first. All regions writable by a frame have distinct colours, so each is at the top of its arena. Proof: any scope above region r on the same arena belongs to a frame that cannot write r, and that frame can pass callees only regions it can write. Induction over the call stack.

Alternatives considered

Consequences

M5.1 changes no AST, type checker, IR, C generator, interpreter, or source syntax. It establishes the runtime API only. M5.2 adds placement, resets, and colour selection; both backends share that analysis.