Native backend (roadmap #23)
trine build program.tr -o program # native executable (C compiled with -O2)
trine build program.tr --debug # re-verify erased bounds checks; TRINE_LEAKCHECK=1 counts leaks
trine build program.tr --emit-c out.c # keep the generated C
trine run program.tr --native # build and run
Done when: all golden programs run natively with identical output. Status: done.
How it works
src/cgen.rs transcribes the ownership IR into C after the Perceus pass (borrowing and drop-reuse) and the bounds verifier. runtime/trine_rt.h (about 600 lines of C) supplies values, reference counting, and builtins.
| IR | C |
|---|---|
dup x / move x / borrowed operand | cpy(x) (rc++) / x / x: exactly the analysis's decisions, no policy in the runtime |
drop x | drop(x): rc--, free at zero (recursively) |
tok = drop-reuse x … C(..) @reuse tok | keep a unique cell, rewrite it in place: no free, no malloc |
| index proven in bounds | l->items[i]: a plain load, no check |
match | an if-chain (never switch, so break still leaves the loop) |
| function | a C function. Each slot is a local, so the C compiler allocates registers. |
Values are tagged (16 bytes). String literals, nullary constructors, and single-character strings are immortal objects with no reference counting. Integer overflow is checked (__builtin_*_overflow), recursion depth is limited to 20,000 as in the other engines, and every user-visible behaviour (printing, including Rust's float formatting, and error messages and positions) matches the interpreter byte for byte.
for x in range(..) now lowers to a counting loop instead of building the list. This helps every engine.
Validation
- Golden programs: all 11 produce byte-identical output natively.
- No leaks: the debug build counts live objects; every golden program ends with 0.
- Erased checks verified: debug builds re-check every access the verifier proved in bounds. None fails.
- Native differential fuzzing:
trine fuzz --nativecompiles each random program in debug mode and compares it with the interpreter. 3,000 programs: no disagreements, leaks, or verifier failures. The VM differential fuzzer was re-run on 100,000 fresh programs after the lowering change: clean. - Errors: out-of-bounds, overflow and runaway recursion give the same message and position as the interpreter.
- Locked into
cargo test(native_backend_matches_golden_output_without_leaks,native_errors_match_interpreter).
Speed
Whole-process time, best of several runs (docs/PERF.md has the tracked baseline):
| workload | Trine native | Rust (-O) | CPython | native vs Rust | native vs Python |
|---|---|---|---|---|---|
| fib(32) | 20 ms | 10 ms | 238 ms | 2.0× slower | 12× faster |
| sieve to 3,000,000 | 118 ms | 21 ms | 483 ms | 5.6× slower | 4× faster |
| golden programs (json, raytrace, server, fbip) | 1.8–3.1 ms | — | — | — | 20–40× faster than the VM |
Where the remaining gap comes from (measured with callgrind): every value is a 16-byte tagged union, so the sieve's list of 3 million booleans takes 48 MB where Rust's Vec<bool> takes 3 MB. The gap is memory bandwidth, not instruction count. Closing it needs type-directed unboxing: lists of Bool as bytes, Int as raw int64, no tag checks on proven-Int arithmetic. That needs the type checker's types carried into the IR, and it is now on the roadmap.
Limits
- It needs a C compiler (
cc, or setCC). Compile time is about 0.1–0.2 s per program, dominated by compiling the runtime header. Cranelift for fast debug builds is still planned. - Values are tagged and every operation checks tags, which is what costs on numeric code (see above).
- Reference counts are not atomic. That is fine until concurrency (roadmap #28–30).
Update: type-directed unboxing (roadmap #41)
Done when: the sieve is within 2× of Rust. Status: done (1.15×).
Two complementary techniques:
- Unboxed scalars, directed by types. The type checker records a representation for every expression and binding (
Int,Float,Bool, orAnyfor anything else, including types still polymorphic inside generic functions). The IR carries it on every slot and return value. Natively: -Int/Float/Boolslots are plainint64_t/double/intC variables; - function parameters and returns use those C types; - arithmetic and comparisons are direct C. Overflow (__builtin_*_overflow), division by zero, and "can't compare NaN" are still checked. Values are boxed only where they cross into generic territory: list storage, constructor fields, closures, generic functions, builtins. Calls through function values unbox and box in a generated dispatch. - Adaptive list storage (after PyPy's list strategies). A list's storage follows its contents: raw
int64for all-Int lists, rawdoublefor all-Float, one byte per element for all-Bool, and tagged values otherwise. It's decided at run time, so it works inside generic code (map,fold) with no type plumbing. Trine lists are homogeneous by typing, so aList[Int]never leaves raw storage, and typed reads (rt_index_i) are direct loads.
Also: the recursion limit now uses a hidden depth argument passed in a register, not a global counter updated around every call. That cost about 30% on call-heavy code. The limit is still exactly 20,000, identical in all three engines (checked at the boundary: f(19,998) succeeds and f(19,999) fails everywhere).
| workload | before #41 | after #41 | Rust | CPython |
|---|---|---|---|---|
| sieve to 3,000,000 | 118 ms (5.6×) | 23 ms (1.15×) | 20 ms | 492 ms |
| fib(32) | 20 ms (2.0×) | 12 ms (1.2×) | 10 ms | 236 ms |
| raytrace (golden) | 3.1 ms | 1.7 ms | — | — |
Where fib's remaining 20% goes: measured by removing each piece from the generated C. Overflow checks account for most of it. They stay: "Ints never silently wrap" is a safety guarantee. With them removed the code is faster than rustc -O (7 ms vs 10 ms). The principled way to remove their cost is to prove ranges and erase the checks (roadmap #27), the same way bounds checks are erased.
Validation: all 12 golden programs are identical natively with 0 leaks. A new golden program, lists.tr, targets every storage kind: copy-on-write per kind, equality, NaN and -0.0 in raw double storage, Bool lists, and nested lists. 3,000 random programs were compiled with typed code and compared against the untyped VM: no disagreements. 60,000 more VM differential runs after the lowering change: clean.
Update: typed data access (speed plan step 2, 2026-11-27)
Profiling n-body's generated C showed the time going to checks the types already answer, not to the data layout itself. Three changes, all driven by facts the type checker or the match already established:
- Single-variant types need no constructor test.
match b: Body(x, ..)on a type with one constructor used to test the tag and the constructor id on every field read (eachb.xis a match after lowering). Now the arm is irrefutable: no test, no failure branch. (−10%) - Lists of heap values skip the storage test. When a list's element type is a record, string, list, map or set, its storage is always tagged objects once non-empty, so
xs[i], the take-then-store pair ofxs[i] = f(xs[i]), andxs[i] = vusert_index_o/rt_index_take_o/rt_set_index_o: no list-kind or storage test, and no range test when the verifier proved the index. Debug builds assert the storage kind. (−12%) - **
r.with(..)on a unique record writes only the changed fields.** Inout[i] = out[i].with(vx: ..), the cell is reused in place (drop-reuse). Its scalar fields aren't touched by the drop, so when the rebuilt record copies a field straight from the pattern that took it apart (and that binding is never reassigned), the store is skipped: updating 3 of 7 fields writes 3. The reuse also skips the kind test (insidematch v: C(..),vis aC). Applied only within one block after the drop-reuse, so the token can't come from another path; otherwise the general code runs. (−32%)
n-body: 132 → 70 ms (C 30 ms, Rust 24 ms): from 4.3× to about 2.3× C. The remaining gap is the 16-byte tagged fields and list cells (loads of tags, reference count traffic on let c = out[j]), which a true unboxed layout (#45 proper) would remove.
The fuzzer gained a single-variant record with scalar and string fields, updated in place in a list with partial .with updates, a full rebuild, and a borrowed read, so all three paths run in every native fuzz case that uses it, including sanitized builds.
Release builds (25a)
trine build f.tr --release compiles the generated C with -O3; --pgo adds profile-guided optimization: it builds an instrumented executable, runs it once (with any grants and the program arguments after --), and rebuilds with the recorded profile. Results are unchanged (no fast-math, contraction stays off); tools/conform.py checks the release tier like the others. Measured on bench/v1 (noisy machine, best of 5): fib 8.9 → 4.5 ms (-O3) → 3.7 ms (PGO), spectral 128 → 92 → 90, strings 99 → 82, trees 339 → 308 → 299, nbody 143 → 118; sieve showed no gain. trine run keeps caching -O2 builds (faster to compile).
Immediate one-field constructors (42a)
Some(3), Ok(2.5), Box(7): a constructor with exactly one field that holds an Int, Float, Bool or Unit is stored in the value itself (tag T_IMM: constructor id and field tag in aux, the field in the payload) instead of a heap cell. Returning Option[Int] from a hot function no longer allocates. Every reader goes through CTOR_IS / CTOR_F / CTOR_ID, which accept both representations, so values built by the runtime and by generated code mix freely; equality, hashing and printing treat them alike. When the field's type is known to be scalar the choice is made at compile time; otherwise one tag test at construction. A drop-reuse token that the rebuilt value no longer needs is freed (rt_tok_free). Benchmark: a loop returning Some(a / b) / None 20M times went from 133 ms to 64 ms.
All-Float records as C structs (45a)
A type with one constructor and two to four fields, all Float (type Vec3 = V(Float, Float, Float), Particle(x: Float, y: Float, vx: Float, vy: Float)), is Repr::Rec in native code: a typedef struct { double f[N]; } TRi; held in locals, passed and returned by value. Building one, reading its fields, .with, == and match are plain C, with no allocation and no reference counts. It becomes a constructor cell (box_TRi) only where a V is needed: in a list, a map, a closure's environment, a generic function's parameter. It is read back out (unbox_TRi, or unbox_take_TRi when the box is owned) on the way in. A value lent to an operation that wants a V (print(v), str(v)) gets a box that lives for that one line.
Lists stay lists of cells (that's 45b), but storing a record back where it came from refills the old element's cell in place when the list and the cell are unique (set_index_TRi), so ps[i] = step(ps[i], dt) allocates nothing. A read marked as a take reads in place instead, so that the cell is still there to refill.
Measured at 1200×600 pixels: the ray tracer goes from 115 ms to 43 ms. The particle benchmark (records in a list) goes from 15 ms to 13 ms. Without the in-place refill it was 30 ms, because each store allocated a new cell. TRINE_NO_STRUCTS=1 turns the representation off; a test checks that the output is the same. The VM and the interpreter are unchanged: they don't use representations. Perceus still treats these records as values with cells, so the VM's in-place updates are unaffected.
Lists of them as flat arrays (45b)
A list built in compiled code by pushing such records (push_TRk) gets storage ST_R0 + k: the fields side by side, N doubles per element, with no cells. Reading an element (index_TRk), storing one (set_index_TRk, in place when the list is unique) and appending are a memcpy of N doubles. A shared list is copied once, and keeps its flat storage, before an append. Code that doesn't know the element type (printing, ==, in, a generic function the specializer couldn't reach) goes through list_get. That first turns the list into tagged storage, boxing every element once; this is unobservable, because elements are values. The runtime learns each record kind's field count and constructor from two tables the compiler emits.
Particles (1,000 records, 3,000 steps): 15 ms with cells, 13 ms with in-place refills (45a), 10 ms flat. The benchmark suite's particles drops from 2.8 ms to 1.9 ms. The fuzzer's all-Float record now goes through flat lists, shared appends, ==, in, printing and generic loops. Mutation checks are caught: appending to a shared list without copying it, and boxing fields in the wrong order when generalizing.
Wide records and plain counts (M5)
Records of two to eight Floats are structs now (it was four). Wider ones used to be slower than cells because every element read and write was a memcpy of the whole record, which the C compiler left as a library call: nbody's 7-field bodies spent 442 M of 1.24 G instructions in memcpy. Element reads, writes and appends in flat lists now copy field by field, so the compiler keeps the fields in registers and drops the loads of fields nothing reads, and the rare slow paths (a list that isn't flat, unique or in bounds) are out-of-line cold functions, so the hot path is a few loads. Records wider than eight stay cells: they are passed and returned by value, which costs more as they grow.
A program that never starts a task (no spawn, no par_map) is compiled with TRINE_ONE_THREAD: no object can be shared between threads, so reference counts are read with plain loads instead of relaxed atomic ones. An atomic load, even a relaxed one, stopped GCC from keeping list storage and counts in registers across a loop. Programs with tasks keep the atomic reads.
nbody went from 3.7× C to about 1.2–1.5× C on this machine (1.24 G → 0.65 G instructions); the other benchmarks are unchanged. The regression gate (tools/bench.py) now covers bench/v1, which is how the earlier nbody regression was missed.
Platforms and cross-compiling (M0)
Native builds run on Linux (x86-64, arm64), macOS (arm64, x86-64), Windows (x86-64) and WebAssembly (WASI); CI checks every push on the first five, and the conformance runner checks WASI (python3 tools/conform.py --wasi). Everything the runtime needs from the operating system is in runtime/rt_platform.h.
- C compiler.
trine toolchainshows which one native builds use:$CC, elsecc,clangorgccon the PATH, else (Windows) the Clang from Visual Studio's "C++ Clang tools" or from the LLVM installer. MSVC'sclcan't compile the generated C (it uses GNU extensions Clang and GCC share). - Cross-compiling.
trine build prog.tr --target Tbuilds withzig cc -target T(zig carries a C library for each target; install it withpip install ziglangor from ziglang.org). Tested targets:wasm32-wasi,x86_64-windows-gnu,aarch64-macos,x86_64-macos,aarch64-linux-gnu,x86_64-linux-gnu.-o namegets the target's suffix (.exe,.wasm). - WebAssembly (WASI). One thread:
spawnruns each task at its spawn andpar_mapruns in order (the meaning is the same; only the speed differs). No Python bridge (no processes).--max-memis enforced by the allocator. Run with any WASI runtime, for examplewasmtime --dir examples prog.wasm --allow-read=examples, orpython3 tools/wasi_run.py. - **
extern fnand C'slong.**Intis C'sint64_t. The allowlisted math functions are called through their real C prototypes, solabsorlround(Clong) are converted correctly wherelongis 32 bits (Windows, wasm32): results outside 32 bits are cut there.