Runtime internals
The runtime is freestanding C, about 7,700 lines in runtime/, linked into every program. This page describes the data structures and algorithms behind the arena: the pool allocator, the allocation log and its hash table, promotions, the string machinery, the compiler-side analyses that remove scopes, huge pages, and the crash reporter. Numbers refer to the self-hosted compiler precompiling a mid-size source file (49,000 allocations) or its own source (286,000 allocations).
1. The pool allocator
rt_alloc(size) returns a block of at least size bytes from a pool of chunks. A chunk is TOTAL_BLOCKS (4096) blocks of SINGLE_BLOCK_SIZE_HEAP_BSS (512) bytes, i.e. 2 MB, plus a bitmap of one byte per block: 0 free, non-zero occupied. An occupied run is a ramp: 1 on its first block, then 2, 3, ... up to 255, so the first block of the allocation that contains any block is one subtraction away (rt_alloc_base_of, below). The ramp is also the allocation's size: freeing counts it, the header does not store it.
bitmap [1][2][0][0][1][0][0][0]... one byte per block
data [##][##][ ][ ][##][ ][ ][ ]... 512 bytes per block
^ header (16 bytes) then the payload; the pointer returned is header + 16
[p-16] qword string length (sealed strings only), 0 otherwise
[p-8] dword type id: a class id written by 'new', STR_TYPE_ID for a sealed string, 0 otherwise
[p-4] dword references and state (§3)
- Sizing.
get_num_blocks_reqroundssize + 8(header)+ 16(margin) up to whole blocks. The 16-byte margin is what letsrt_strlenandrt_simd_memcpyread and write 16 bytes at a time past the logical end of a string without leaving the allocation. - Chunk 0 lives in the BSS (
buffer_heap_bss, aligned to 2 MB): small programs never callmmap. When no chunk has a long enough free run,pool_new_chunkmaps a new one with bitmap, data and a 32-byte SIMD margin at the end; the data area is 2 MB-aligned and advised as a huge page (see §6). A chunk is never moved or unmapped: pointers stay valid for the life of the process. - Next-fit scan.
bitmap_takelooks fornconsecutive zero bytes in the bitmap starting from a per-chunk hint, 32 bytes at a time (vpcmpeqb/vpmovmskbon x86-64), wrapping around once. The hint moves forward on allocation and is lowered on free to the freed block, so holes left by frees are found again without scanning the whole chunk.rt_alloc_pool_last_chunk_hintremembers which chunk succeeded last. - Occupied blocks per chunk. Each chunk counts its occupied blocks (
alloc_chunk0_used,pool_chunk_used), so a chunk with fewer free blocks than the request is skipped without touching its bitmap. Before the count, a full chunk cost a scan of all its 4096 bytes every time it was tried, and the last-chunk hint kept pointing at it: 8,500 such scans, 14 M instructions, on the self-precompile. - Free.
rt_free_poolfinds the chunk of a pointer in O(1) through the region tablepool_region_tab: since every chunk's data is 2 MB-aligned,(ptr >> 21) mod MAX_POOL_CHUNKSindexes a small table that maps each 2 MB region to its chunk (verified against the chunk's real range, with a linear fallback on collision). It clears the run in the bitmap, lowers the scan hint and zeroes the memory with AVX2, so a new allocation always starts zeroed. Measured on the self-precompile: 134,000 frees over 40 chunks cost 46 M instructions before the table; the table removed almost all of it. - Recently freed single blocks. Most allocations take one block. A freed one also goes on
pool_free1_stack, a LIFO of up toPOOL_FREE1_MAX(1024) entries, and the next one-block allocation takes the top entry instead of scanning, while the block is still in the cache. The bitmap stays the only source of truth: a stacked block is free there and a longer run may take it in the meantime, so a pop checks that the block is still free and drops the entry otherwise. Unlike the old free-run list, push and pop are O(1). On the self-precompile the stack serves about five allocations in six; together with the per-chunk count,bitmap_takewent from 31 M to 3 M instructions and the whole run from 431 M to 406 M, about 3% of the time.
Under --noheap the same code path stops at chunk 0 (rt_alloc_raw): running out of blocks is a fatal arena full, never an mmap.
2. The allocation log and its hash table
Every allocation is appended to alloc_log (an array of pointers that starts in the BSS and grows by doubling through mmap when the number of live allocations exceeds --bss-size). Scopes are bookmarks into it (see The arena). Promotions and explicit frees need the index of a pointer in the log, which used to be a linear scan and dominated regex-heavy programs (89% of the time in one profile). Now:
- The index next to the bitmap. Every chunk has an array
logidxwith one 32-bit value per block, reached from its descriptor inpool_spans.alloc_log_index(ptr, i)writesiat the first block ofptr, and every write of a pointer into the log goes through it (the push, the swaps of promotions,rt_release_local).rt_alloc_log_find(ptr)reads the value back and accepts it only if the log entry there is exactlyptr, so the stale values that freed or moved allocations leave behind are harmless. That is one load next to memory the lookup touches anyway, instead of an average of 2.6 hash probes, each a random access into the log. On the self-precompile it saved 12% of the time (55.7 to 49.2 ms) and 1.9 MiB of resident memory, the hash table's huge page. - Under
--check-arenaallocations are not in the pool, and a hash table does the same job:alloc_log_index(ptr, index)mirrors every log entry intort_hash_table, an open-addressing table that starts at 2RT_HASH_MIN_BITS (64 K) slots and can grow to 2RT_HASH_BITS (1 M). The hash is Fibonacci hashing: multiply the address by the 64-bit golden-ratio constant and keep the top bits, oneimuland no division, which spreads pointer-like inputs (aligned, clustered) well. rt_alloc_log_find(ptr)probes linearly up toRT_HASH_MAX_PROBE(64) slots and checks the candidate against the log (ignoring the pin bit, see §3); if the probe budget is exhausted it falls back to a linear scan of the log, so the table is an accelerator, never the source of truth. It answers-1for a pointer that is not in the log and-2for a pinned one.rt_alloc_base_of(p)finds the allocation that contains an interior pointer: the chunk throughpool_spans(one descriptor per chunk, found by the same 2 MB region trick as the region table of §1), the block by a shift, then back along the ramp of the bitmap to the first block of the run;0ifpis in no chunk, and a freed block stops the walk so a dangling pointer never resolves to a neighbour.rt_alloc_log_find_interior(p)isrt_alloc_log_findon that base, and every promotion tries it after an exact miss. Under--check-arenathe base comes from the allocation record instead.- Frees leave stale slots behind. Every time inserts reach half the table in use,
rt_hash_rebuildclears it and reinserts the live entries, which keeps chains short. If more than one slot in eight would be live, the rebuild first doubles the table in use. The array is reserved at full size in.bss, but only the part in use is touched: a program with a few thousand live allocations pays 512 KB instead of 8 MB (before the rebuild existed, a long-running precompile spent 97% of its time in the fallback scan).
3. Promotion and pinning
rt_promote(ptr, n): find the index, read the bookmarknlevels down, free every live entry between that bookmark and the index (the siblings, which would otherwise be unreachable by any futurearena_exit), then raise theninnermost bookmarks toindex + 1.rt_promote_bounded(ptr, n): the same without freeing siblings (used when siblings are still owned by someone); the siblings below the raised bookmarks leak into the parent scope.rt_promote_move(ptr, n): what a loop assignment to an outer local compiles to. Only the value's own entry moves out through thenscopes; what the value points to is kept alive by its counts, so nothing else leaves the loop. A value with no entry (read from a container) is recorded as a borrow of the local instead.rt_promote_swap(ptr, n): promotion by swap, O(1). The entry is exchanged with the one sitting at the bookmarkcof the outermost of thenscopes, then every bookmark among thosenthat equalscbecomesc + 1: positioncnow belongs to the parent, the former occupant sits whereptrwas and is freed with its own scope. Both pointers get a fresh slot in the hash table; the stale slots fail the log comparison and are dropped at the next rebuild. This is what areturncompiles to, withnthe number of scopes the function opened (its own plus the loops open at thereturn): the value lands in the caller's current scope. In practice the returned value is usually already the first entry of the function's scope, so no swap happens and only the bookmarks move (259 real swaps in 72,000 returns of a precompile).rt_promote_to_root(ptr): makes the allocation immortal. Bit 31 of the reference word in its header ([p-4]) is set; neitherarena_exitnor the reference count frees it again, and a lookup of an immortal pointer answers-2at once. Under--check-arenathe first pin also records its call site in the allocation's record, for the report at exit. An earlier design raised a global watermark instead, which pinned every older allocation as a side effect: 49,000 allocations and only 808 frees per precompile, 199 MB of RSS on the self-precompile. Pinning per entry brought frees back (RSS 205 → 119 MB, 87 → 78 ms); moving returned values into the caller's scope instead of pinning them brought it to 92 MB.arena_exitfrees its range withrt_free_batch, walking the log from the newest entry down; an explicitrt_freealso scrubs duplicate entries with an AVX2 scan of the log.- Class ids. The code generated for
newstores the id of the class (1, 2, ... in declaration order) in the high dword of the allocation header, next to the block count.ref as Classloads it and compares it inline; on a mismatchrt_downcast_slowasksrt_alloc_base_ofwhether the pointer is the start of a pool allocation at all (an embedded object, an interior pointer or C memory is not, and passes) and otherwise prints the two class names, taken from a table the compiler emits, before the crash report.
4. Strings
- Sealed strings. The allocation header has room for a string length:
rt_str_seal(p, len)writesSTR_TYPE_ID(0xD5545253) into the type-id dword and the length into the first qword, 64 bits wide, so a string can exceed 4 GB.rt_strlenchecks the tag and answers from the header; otherwise it scans (rt_strlen_scan: 16 bytes per step,pcmpeqbagainst zero,pmovmskb,tzcnt). An interior pointer or a C string has arbitrary bytes where the header would be, and the tag alone can be forged by text (its bytes53 52 54 D5areSRTand the first byte of an Armenian letter): a string is sealed only if the length is also at most 231 − 2, whose four high bytes are zero, which no text contains. The same test is instrlenof libstd and in the compiler's bounds checks; any other pointer is scanned; a literal is emitted by the compiler with the header in front of it ([K+16 x i8], pointer at +16). Under--check-arenathe fast path also checks that the terminator is still ats[len]and reports a string that grew without being sealed again ("header stantio"); a NUL byte inside a sealed string is data, as in the normal build, and==compares it too.rt_simd_memcpycopies 16 bytes per step and moves its last block back so it never writes pastdst + nwhenn ≥ 16; both rely on the 16-byte margin of every allocation. rt_strcat(a, b)takes both lengths (O(1) when sealed), allocateslen(a) + len(b) + 1, copies and seals the result;itoa/ftoaseal too.rt_strcmpanswers "different" at once for two sealed strings of different lengths, then compares contents.rt_strcat_n(parts, n)builds a chaina + b + c + ...with one allocation: the compiler stores the parts in an array in the entry block (a pointer, or a character by value below 256), the runtime measures them all and copies once.rt_imulstrimplementss * nin one sealed buffer.- Self-concatenation. For
x = x + termthe compiler switchesxto a growable buffer from a separate pool (rt_strbuf_new): a 32-byte header holds capacity, an exclusive bit and the common allocation header, so the buffer is a sealed string at all times.rt_strcat_selfconcatappends in place while the buffer is exclusive and has room (nostrlenof the growing prefix: the length is cached, so 300,000 appends stay O(n)), doubles when it is full, and copies to a fresh buffer when the old one is no longer exclusive. When a local's pointer is copied elsewhere (an assignment, a call argument the callee may keep, variadic ones too,return, a field or element, a list or dict literal), a buffer the local still owns becomes an arena string first (rt_strbuf_detach): the local and the destination share an ordinary value that its scope or the reference counts free, and the buffer itself is freed after the statement, since a temporary of the same statement may still read it. Pointer arithmetic on the buffer, casts,&s, globals and bodies withasminlineorunsafemark it shared instead (rt_strbuf_mark_sharedflips the bit for good, and a shared buffer is never freed).x = x + a + b + ...goes throughrt_strcat_selfconcat_n: every length is measured before writing, then one capacity check, so a term may bexitself. From 1 MiB a buffer leaves the pool for an address range of its own (strbuf_big_new: 64 MiB, or 16 times its size), committed page by page as it grows: growing copies nothing and leaves no old buffer behind, and freeing it returns the memory to the system. Past the end of its range it moves once to a range 16 times larger. Building 20 million lines (601 MB) in one string peaks at 589 MB instead of 1.65 GB (benchmark/bench_kernel_lines.tryc). - Freeing abandoned buffers. When a variable leaves its growable buffer (it is reassigned, an outer loop runs
s = ""again, or the function returns) the buffer is freed if it is still exclusive (rt_strbuf_drop): every copy of the pointer would have marked it shared, so nobody else holds it. A new value pointing inside the buffer keeps it, and bodies withasminlineorunsafefree nothing.return xcopies a buffer that is still exclusive into an arena string and frees it at once (rt_strbuf_settle). Until 19 October 2026 every one of these copies marked the buffer shared instead, and it lived until the program exited even after its container died: one buffer per call. A call argument is marked shared only when the callee may keep it: on demand, for the functions actually called with such an argument and the functions they call, the compiler works out which parameters a function stores, returns or passes on to a parameter that does (strlenandfprintkeep nothing). A variadic tail is followed into itsVarargboxes: it keeps nothing whenargsonly goes tolist_length/list_get, each box lands in a local whose fields are only read, and eachrpayloadis used where it does not stay, soprint(s)does not markseither. Sostrlen(s)in a loop that growssno longer copies it, andbenchmark/bench_strbuf_leak.trycpeaks at 4.9 MB instead of 628 MB. - Self-concatenation on globals. A global gets the same buffer, with its ownership flag in a global (
@scflag.name). Any function can read it, so the compiler builds the call graph first: a global passed by address (&g) or named in anasminlinekeeps the generic path;g = g + f()stays generic whenfcan writeg, sogis read beforefruns; and when a call in a statement can append togwhile the old value sits in a temporary (t = g + f()), the read marks the buffer shared first.
5. Scope elision in the compiler
An arena_enter/arena_exit pair per loop iteration costs two calls even when the body allocates nothing. The compiler proves, per loop and per function, whether a scope is needed:
- Loops (
loop_needs_scope): the body is walked statement by statement; a scope is required only if a statement may allocate (a concatenation,new, a call to a function that may allocate) or reassigns an arena-tracked name with a fresh value. Assignments that are provably not fresh need nothing: a literal, an alias of another local, pointer arithmetic on an owned base,list_get(...) as str, a call whose result is known not to be a new allocation. - Not-fresh tracking: the analysis and the emitter share the same seed of names known to hold non-fresh values (parameters, literals, aliases), computed before the loop and updated on each assignment, so the decision "this store needs no promotion" (
skip_promotion) is taken from the same facts that decided "this loop needs no scope". - Functions (
compute_scope_free_functions): a fixpoint over the call graph marks functions whose body cannot allocate, taking into account integer-only locals, readable globals, functions that never return (they end inexit) and whether a function's return value escapes. Such functions get no scope at all.
Measured on the self-precompile: arena_enter calls 555,000 → 285,000, instructions 123 M → 110 M. TRYC_DEBUG_SCOPE=name prints the reasoning for a function or loop. The rule that keeps this safe: every fresh str assigned to a local is promoted to the function level, parameters belong to the caller, fields and globals go to the root, so an alias or an interior pointer never needs a promotion of its own; and when one is promoted anyway (a return s + n), the runtime promotes its base.
A related mechanism is the nursery (rt_nursery_alloc): a bump allocator for values the compiler proves never escape the function that creates them, reset in one step at arena_exit, with no log entry. Library functions such as substrget have a _nursery twin that the compiler substitutes when the analysis allows it.
6. Huge pages and page faults
Profiling the self-hosted compiler showed a quarter of its time in the kernel's page-fault path: every freshly mapped 2 MB chunk was touched one 4 KB page at a time (513 traps per chunk). pool_chunk_map now over-maps by 2 MB, trims the ends so the data area is 2 MB-aligned, and calls madvise(MADV_HUGEPAGE): one fault per chunk and one TLB entry (minor faults 15,336 → 5,201, wall 82 → 68 ms). --hugepages extends the same treatment to the three large BSS buffers (hash table, chunk 0, string-builder chunk 0), which brings the faults to 153; it is opt-in because a tiny program then pays for zeroing whole 2 MB pages.
Loading libLLVM.so dynamically cost another fixed 12 ms per process (350,000 relocations, copy-on-write of 8 MB of .data.rel.ro, 590 constructors); --llvm-static links the needed LLVM components statically instead (41 → 31 ms per compile, faults 3,700 → 1,300).
7. The crash reporter
_start installs a SIGSEGV handler on an alternate stack (init_protect_segv). arena_enter receives the address of the function being entered (loops pass 0) and pushes it on bt_stack_addr (BT_STACK_DEPTH = 500; deeper frames are simply not recorded); arena_exit pops it after freeing, so a fault during a free still shows the function that was leaving. The report prints the signal, the faulting address and whether the page was unmapped or protected, the kind of access, the function history from innermost to outermost, then RIP, the instruction bytes and every register. Addresses are hexadecimal; the check_arena_syms.py helper shipped with the runtime annotates them with function names using nm:
./program 2>&1 | python3 check_arena_syms.py ./program
An out-of-bounds array index deliberately triggers the same path after printing Error! array index out of bounds, so it gets the full report instead of a bare message.
8. Numbers to keep in mind
| Workload (self-hosted compiler) | Time | Memory |
|---|---|---|
precompile of a mid-size file (--dbi) | ~23 ms | 49,000 allocations, ~30,000 live at exit |
| full compile of the same file (in-process LLVM) | ~30 ms | 51 MB RSS |
| precompile of its own source | ~78 ms | 286,000 allocations, 119 MB RSS |
| hello world | 0.2 ms (1.4 ms with --hugepages) | chunk 0 only, no mmap |