Internals · 05

Cranelift Native Compilation

Inside ochre-codegen — lowering Ochre's AST to Cranelift SSA IR, short-circuit basic blocks, object file emission, and linking with cc.

ochre-codegen compiles Ochre programs to native x86_64 and AArch64 machine code using Cranelift (cranelift-codegen, cranelift-frontend, cranelift-object 0.116).

Lowering Pipeline

  1. Function Declaration: Each Ochre fn is declared in an ObjectModule with native Cranelift types (Int → I64, Float → F64, Bool → I8, Str → pointer-sized I64/I32). fn main() is exported as ochre_main.
  2. SSA Construction (FunctionBuilder): Local variables (let/var) are mapped to Cranelift Variables, which Cranelift automatically converts to SSA form with phi nodes (block parameters).
  3. Short-Circuit Logical Lowering: BinaryOp::And and BinaryOp::Or create rhs_blk and merge_blk (with an I8 block parameter). brif branches directly to merge_blk with 0 (for false && ...) or 1 (for true || ...), ensuring the right-hand operand is never evaluated when short-circuited.
  4. Control Flow: if/else, while, and for i in start..end lower to explicit basic blocks (header, body, step, exit), with a loop stack tracking break and continue jump targets.
  5. Object Emission & Linking: module.finish().emit() produces a native ELF/Mach-O/COFF .o file. build_executable writes the object and a minimal 18-line C runtime shim (ochre_print_* + int main()) to unique per-invocation temp files (pid + atomic BUILD_SEQ) and links them with cc -O2.

Differential Verification

ochre-codegen includes automated VM vs. Native AOT differential tests that run the exact same Ochre source on ochre-vm and as a compiled native binary, asserting byte-for-byte identical stdout (including side-effecting short-circuit expressions, recursion, loops, and raw strings).