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
- Function Declaration: Each Ochre
fnis declared in anObjectModulewith native Cranelift types (Int→I64,Float→F64,Bool→I8,Str→ pointer-sizedI64/I32).fn main()is exported asochre_main. - SSA Construction (
FunctionBuilder): Local variables (let/var) are mapped to CraneliftVariables, which Cranelift automatically converts to SSA form with phi nodes (block parameters). - Short-Circuit Logical Lowering:
BinaryOp::AndandBinaryOp::Orcreaterhs_blkandmerge_blk(with anI8block parameter).brifbranches directly tomerge_blkwith0(forfalse && ...) or1(fortrue || ...), ensuring the right-hand operand is never evaluated when short-circuited. - Control Flow:
if/else,while, andfor i in start..endlower to explicit basic blocks (header,body,step,exit), with a loop stack trackingbreakandcontinuejump targets. - Object Emission & Linking:
module.finish().emit()produces a native ELF/Mach-O/COFF.ofile.build_executablewrites the object and a minimal 18-line C runtime shim (ochre_print_*+int main()) to unique per-invocation temp files (pid+ atomicBUILD_SEQ) and links them withcc -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).