Last updated: 2026-11-15

U
Undergraduate level
FDN
Foundational โ€” Knowledge that endures for decades โ€” core principles

The v2 IR and the Readers That Build From It

For new readers

Between PatLang source and machine code, v2 holds every program in an intermediate representation (IR): a short list of simple instructions over numbered slots. v2 can write that IR out as a text file, and the format is specified precisely enough that a small program in another language, called a reader, can turn it into a working executable. That is how PatLang is bootstrapped on a machine that has nothing of PatLang yet: a Python script reads the compiler's own IR and builds the compiler. The same IR also becomes a WebAssembly module that runs in a browser, threads and all.slots are registers no stack needed

The format and its meaning are specified in docs/spec/ir.md, which section 2.6 of the values-and-memory specification refers to. This page summarises it, with an example, and describes the two readers and the browser host.

Writing the IR Applied / MethodologicalKnowledge with a 5โ€“10 year half-life โ€” stable practice

v2.exe SRC.patlang OUT.ir --ir

This writes every function the program can reach, the runtime's included, after the ownership stage, and writes no executable. The IR is the same for every build of the same source. A four-line program gives 608 functions and 2.8 MB of text, almost all of it the runtime; the compiler's own IR is about 7 MB.

The text form FoundationalKnowledge that endures for decades โ€” core principles

The IR is UTF-8 text with LF line endings. Line 1 is v2-ir 1. Line 2 is plus_events 0 or plus_events 1, which is 1 when some when handles int's added or added_to events. Each further line is one function, in the order the compiler builds them:

["Fn" NAME NPARAMS NSLOTS [INSTR ...] [VARS ...]]

Only three kinds of value appear: integers in decimal, possibly wider than 64 bits; strings between double quotes, with any byte outside 32 to 126, and any " or \, written as \ and two hex digits; and lists in square brackets with their values separated by one space. That is all a reader has to parse.

Here is a function from a real program, and its IR:

make a function called twice takes x returns y
  return x + x
end
["Fn" "twice" 1 5 [["clear" 1] ["clear" 2] ["op" 3 "+" 0 0] ["release" 1]
  ["move" 1 3] ["unwound" 1 0] ["retain" 1] ["release" 1] ["release" 2]
  ["return" 1] ["const" 4 "unit" ""] ["release" 2] ["move" 2 4] ["retain" 2]
  ["release" 1] ["release" 2] ["return" 2]
  ["label" 0] ["release" 1] ["release" 2] ["unwind"]] [0]]

(Line breaks added.) The function has one parameter, slot 0, and five slots. Slots 1 and 2 start cleared to unit. The sum goes to temporary 3 and moves into slot 1, the result variable; unwound jumps to label 0 if the sum came back as the unwinding mark; and the function returns slot 1 after its retains and releases, which the ownership stage inserted. The code after the first return is the implicit fall-off-the-end path, giving unit. Label 0 is the unwind tail: release every slot the function may own, then unwind. The parameter, slot 0, is borrowed and never released.unit is the empty value, the type with one inhabitant

Instructions FoundationalKnowledge that endures for decades โ€” core principles

Every slot holds one two-word value, a type word and a data word (see Inside a compiled program). Since the ownership stage has already run, a reader counts nothing on its own; it does what the instructions say and nothing more.

InstructionMeaning
["const" d KIND TEXT]An int, float, bool, unit or str literal into slot d
["copy" d s], ["move" d s], ["clear" s]Copy two words; copy and clear the source's type word; clear a type word to unit
["call" d NAME [s ...]]Call a PatLang function, user's or runtime's alike
["callv" d [c s ...]]Call the closure in c, passing c and then each argument
["op" d OP a b], ["un" d OP a]A binary or unary operator: inline for ints, a runtime call otherwise
["prim" d NAME [s ...]]A machine primitive
["extern" d LIB FUNC [s ...]], ["externf" ...]A Windows x64 call to LIB!FUNC, with integer or floating-point registers
["label" N], ["jump" N], ["branch" s T F]Control flow; a branch on a class above 2 asks rt_truthy
["return" s]Return a slot
["retain" s], ["release" s]Count a heap value up or down atomically; the last release calls rt_release_last
["list" d [s ...]], ["closure" d FN [s ...]]Allocate a list or a closure and store retained values into it
["unwound" s N], ["unwind"]Jump to N if s holds the unwinding mark; return the mark

Operators

For two ints, +, -, *, the comparisons, band, bor, bxor, shl, shr and % are the machine's instructions. Otherwise each calls its runtime function: op_add, op_sub, op_mul, op_lt and so on. / is never inline. The runtime is also called when +, - or * overflows 64 bits, when % has a zero divisor, and for + when plus_events is 1 and the runtime's event flag is set. Two variants of + exist for the runtime's own use: q+, which raises no events, and a+, which may append to a string in place because its left operand was given to it.a+ avoids copying the left-hand string

Primitives

What PatLang cannot say in terms of other PatLang is a primitive: a fixed set, part of the language, compiled inline. They are what the runtime is written on.

GroupPrimitives
Valuesvalue_class, value_data, value_type_word, value_make(t, d), value_live
Memorymem_load, mem_store, mem_load_byte, mem_store_byte, mem_load_value, mem_take_value, mem_init_value, mem_store_value
Wordsword_add, word_sub, word_mul, word_and, word_or, word_xor, word_shl, word_shr, word_div, word_rem, with no overflow promotion
Floatsint_to_float, float_to_int, float_add, float_sub, float_mul, float_div, float_lt, float_eq
Runtimeruntime_state, thread_entry_address, atomic_add
Constant-time marksct_secret, ct_public, ct_reveal, which do nothing at run time

The first reader, and the fixpoint FoundationalKnowledge that endures for decades โ€” core principles

py -3 bootstrap/ir_reader.py bootstrap/v2_compiler.ir self_hosting/build/v2.exe

bootstrap/ir_reader.py is written in Python 3 using only its standard library, and builds a Windows x64 PE32+ executable from IR text. bootstrap/v2_compiler.ir is the compiler's own IR, checked into the repository, so a machine with Python and nothing of PatLang's builds the compiler in about three seconds. That compiler then builds the compiler from source, and the result builds it again. The last two are byte-identical.

flowchart LR accTitle: Bootstrapping v2 from its IR accDescr: The compiler's IR, a checked-in text file, is read by ir_reader.py, a Python script using only its standard library, which writes a first compiler executable. That compiler builds the compiler from its PatLang source, giving generation a. Generation a builds the compiler again, giving generation b. Generations a and b are byte-identical, and the gates also rewrite the IR from the new compiler and check the chain again whenever the compiler's sources or the reader change. IR[("v2_compiler.ir
text")] --> PY["ir_reader.py
Python stdlib only"] PY --> C0["first v2.exe"] C0 -->|"builds from source"| CA["generation a"] CA -->|"builds from source"| CB["generation b"] CA <-. "byte-identical" .-> CB CB -->|"--ir"| IR

The project's test gates do this whenever the compiler's sources or the reader change: they rewrite v2_compiler.ir with --ir, build a compiler from it with the reader, and check that this compiler builds the compiler byte for byte as v2.exe does. A gates scenario also builds a program that reaches every kind of instruction from its IR, with an operator event, a fiber, a thread and a broken contract, and checks it prints what v2's own build prints.

v1 had a bootstrap too, a Python interpreter for the old compiler's IR. It took 37.7 minutes to compile a four-line program, because it interpreted the whole compiler instruction by instruction. The v2 reader compiles, so the cost is a few seconds plus one ordinary build of the compiler. What a reader is trusted with is the subject of the toolchain as part of the trust story.the reader is untrusted code

The WebAssembly form Applied / MethodologicalKnowledge with a 5โ€“10 year half-life โ€” stable practice

v2.exe SRC.patlang OUT.wasm --wasm
py -3 bootstrap/ir_wasm.py IN.ir OUT.wasm

self_hosting/v2/wasm.patlang builds a WebAssembly module from the IR with its own encoder, no rustc and no LLVM, and bootstrap/ir_wasm.py builds the same module, byte for byte, from the IR text. The two agree on the compiler's own module, 8.5 MB when first compared, and the gates check that whenever either writer changes. The module uses multiple results, bulk memory and threads (shared memory and atomics).

  • Slots. Each slot is a pair of i64 locals, type word then data word, and every function returns two i64 results. Slots that are never live at the same time share a pair, so a function's locals grow with how many slots are live at once, not with its length. When this was built, the compiler's 913 functions needed 16,960 pairs for 62,487 slots.
  • Control flow. WebAssembly has no jumps, only nested blocks and loops. A jump back becomes a branch to a loop that begins at the target and ends after the last segment jumping back to it; a jump forward becomes a branch out of a block that ends just before the target. Where two of these cross, a loop's end moves later or a block's start earlier until all nest. Every function v2 makes fits, since its lowering never jumps into the middle of a loop; a writer that met such a jump would stop with an error naming the function.
  • Code addresses. A function's address is its index in the module's table, and callv calls through it with call_indirect.
  • Memory. The module imports one shared memory. The runtime's state sits at 65,536, string constants at 131,072, and the heap above the module's initial pages, grown by the host as the runtime commits it.
  • Externs. Each LIB!FUNC becomes an import named for it, so the host implements the handful of Windows calls the runtime makes.

The browser host Applied / MethodologicalKnowledge with a 5โ€“10 year half-life โ€” stable practice

node self_hosting/v2/wasm/run_node.mjs PROGRAM.wasm [ARGS...]
py -3 self_hosting/v2/wasm/run_browser.py PROGRAM.wasm [ARGS...]

The host in self_hosting/v2/wasm/ runs a module in Node or in a browser. Its launcher never runs the program, so it can stay on a browser's main thread, which may not block. The program runs on executors, each a Web Worker over the one shared memory: the main executor runs main, CreateThread makes one that calls the thread entry, and CreateFiber makes one that waits until it is switched to. SwitchToFiber opens the target's gate and waits on its own, so one executor of a thread runs at a time, and a fiber uses the thread-local slots of whichever thread resumed it, as on Windows.

Output goes into a shared buffer under a lock, so it keeps the order the threads wrote it in. A browser has no processes or sockets, but the launcher may be given a read-only bundle of files, a map from paths to bytes, which read_file, file_exists, list_dir and include then see. That is enough for the compiler's front end to run in a page, and so for the playground to compile and run a program's text in a world, in the browser. Shared memory needs a cross-origin isolated page; where the server sends no isolation headers, a service worker on the site supplies them.

One limit remains. A function with thousands of slots live at once is slow to start in V8's first compiler tier, where each branch costs time in proportion to the locals: one test fixture's top level with 3,000 if statements takes 26 seconds there and 1.1 seconds once optimised. No program that size has needed to run in a browser yet.V8 tiering: fast startup, slower optimization

See also

Inside a compiled program describes the machine code the native reader produces. The swarm compiler explains why the IR is deterministic. The v2 toolchain covers the compiler stages that produce it.

Graduate Attributes

Modelled on this page

  • Researcher: Test gates verify that independent builds produce byte-identical results to confirm correctness.
  • Subject Specialist: The intermediate representation is defined with precise rules for values, slots and instructions.
  • Critical Thinker: Performance limitations in browser environments are identified and quantified with specific test data.

University of Reading Graduate Attributes framework.