Foundations of ComputingVol. 1 · Part I
0 / 0

Shelves / Foundations of Computing

CS·10

Compilers & Runtimes

How source text becomes running code: lexing, parsing, ASTs, type checking, IR, optimisation, code generation, linking and loading, and the runtime models (native, VM, interpreter, JIT, AOT, tracing JIT) behind each language.

39 topics · ~48 min read · 41-question quiz
Updated Suggest a correction

Start here: how your code becomes something a CPU can run

The translation problem

From chapter 7, a CPU only understands very simple instructions: load, add, store, jump. You write total = price * qty + delivery. Something has to translate between the two, and that something is a compiler or an interpreter. Think of translating a book from English into Telugu:

  • A compiler is a translator who translates the whole book first and hands you the translated book. Running it later needs no translator. C, C++, Rust, Go and Zig compile ahead of time to machine code.
  • An interpreter is a live interpreter at a meeting, translating each sentence as it's spoken. Nothing is prepared in advance, but every run needs the interpreter present. Classic Python and shell scripts work this way.
  • Many languages do both: Java compiles your source to bytecode (instructions for an imaginary, portable machine, the JVM), and the JVM then interprets that bytecode and JIT-compiles (just-in-time) the busiest parts into real machine code while the program runs. JavaScript engines and modern Python do similar tricks.

Every translator, whatever its style, follows the same stages.

Stage 1: lexing, turning characters into tokens

Source code arrives as plain characters. The lexer (tokenizer) groups them into tokens, the "words" of the language: numbers, names, operators, punctuation, while throwing away spaces and comments.

Text
source: 2 + 3 * 4
tokens: ['2', '+', '3', '*', '4']

Stage 2: parsing, turning tokens into a tree

The parser checks the tokens follow the language's grammar and builds a syntax tree (chapter 3's trees) that records the structure, including precedence: * binds tighter than +, so 3 * 4 belongs together under the +:

2 + 3 * 4 → 14 + 2 * 3 4 (2 + 3) * 4 → 20 * + 4 2 3
Parentheses change the tree, and the tree decides the answer

Here is a complete parser for arithmetic. The grammar is written as one function per rule: an expression is terms joined by + or -; a term is numbers joined by * or /. Because expr calls term, multiplication is grouped first: that's how precedence is implemented (a recursive-descent parser, the kind used by GCC, Clang, Go, and many others):

Python
def parse(tokens):                      # grammar: expr = term (('+'|'-') term)* ; term = num (('*'|'/') num)*
    pos = 0
    def num():
        nonlocal pos
        tok = tokens[pos]; pos += 1
        if tok == "(":
            node = expr(); pos += 1; return node
        if not tok.isdigit(): raise SyntaxError(f"expected a number, found {tok!r}")
        return int(tok)
    def term():
        nonlocal pos
        node = num()
        while pos < len(tokens) and tokens[pos] in "*/":
            op = tokens[pos]; pos += 1; node = (op, node, num())
        return node
    def expr():
        nonlocal pos
        node = term()
        while pos < len(tokens) and tokens[pos] in "+-":
            op = tokens[pos]; pos += 1; node = (op, node, term())
        return node
    return expr()
Text
tree:   ('+', 2, ('*', 3, 4))
tree:   ('*', ('+', 2, 3), 4)

Stage 3: evaluating or generating code

Now there are two choices. An interpreter walks the tree and computes the answer directly. A compiler walks the same tree and emits instructions for some machine to run later. Our compiler targets a stack machine (the style used by the JVM and Python's bytecode): PUSH puts a number on a stack, and ADD/MUL pop two and push the result.

Python
def evaluate(node):                     # interpreter: walk the tree, compute
    if isinstance(node, int): return node
    op, a, b = node
    x, y = evaluate(a), evaluate(b)
    return {"+": x + y, "-": x - y, "*": x * y, "/": x // y}[op]

def compile_(node, out):                # compiler: walk the tree, emit instructions
    if isinstance(node, int): out.append(f"PUSH {node}"); return out
    op, a, b = node
    compile_(a, out); compile_(b, out); out.append({"+": "ADD", "-": "SUB", "*": "MUL", "/": "DIV"}[op]); return out
Text
source: 2 + 3 * 4
value:  14
code:   ['PUSH 2', 'PUSH 3', 'PUSH 4', 'MUL', 'ADD']

source: (2 + 3) * 4
value:  20
code:   ['PUSH 2', 'PUSH 3', 'ADD', 'PUSH 4', 'MUL']

Run the first program by hand: stack [2], [2, 3], [2, 3, 4], MUL leaves [2, 12], ADD leaves [14]. That's the whole idea of a compiler; real ones add many more kinds of statement, a type checker between parsing and code generation, and an optimiser that rewrites the code to do the same thing faster.

Real compilers, same stages

The same one-line function, translated by three real toolchains:

Text
int square(int x) { return x * x; }        →  gcc -O2 -S (x86-64 machine code, as assembly)
square:
	imull	%edi, %edi                      ; multiply the argument register by itself
	movl	%edi, %eax                      ; the result goes in the return register
	ret

static int square(int x) { return x * x; } →  javac, then javap -c (JVM bytecode)
   0: iload_0
   1: iload_0
   2: imul
   3: ireturn

def square(x): return x * x                →  Python's dis module (CPython bytecode)
   LOAD_FAST_LOAD_FAST      0 (x, x)
   BINARY_OP                5 (*)
   RETURN_VALUE

Notice the Java and Python versions are stack-machine code, just like our toy compiler's output; C goes straight to the CPU's registers.

When things go wrong: three kinds of error

Errors are reported by different stages, at different times:

Kind Found by When Real example
Syntax error: the text doesn't follow the grammar the parser before running Python: return 1 + → SyntaxError: invalid syntax; our parser: expected a number, found '*'
Type error: well-formed, but values don't fit the type checker (compiled languages) before running Java: int n = "chai"; → error: incompatible types: String cannot be converted to int
Runtime error: only detectable as it runs the running program during running Python: 10/0 → ZeroDivisionError: division by zero
Link error: a piece is missing the linker after compiling C: undefined reference to 'helper'
Logic error: runs, wrong answer you, or your tests whenever noticed average = total / count + 1

Statically-typed languages (Java, C, Go, Rust) catch type errors before the program runs; dynamically-typed ones (Python, JavaScript) find them only when that line executes. That's one of the biggest practical differences between languages, and chapter 2's full-depth sections compare it in detail. The last row is why testing exists: no compiler can know what you meant.

Linking: putting the pieces together

Real programs are split across many files and use libraries (code other people wrote: printf lives in the C standard library). Each file is compiled separately into an object file with "holes" where it refers to functions defined elsewhere. The linker joins the object files and libraries into one executable and fills in each hole with the right address. If a function is declared but never defined anywhere, the linker can't fill the hole:

Text
$ gcc m.c -o m        # main calls helper(5), but no file defines helper
m.c:(.text+0xe): undefined reference to `helper'
collect2: error: ld returned 1 exit status

Libraries can be static (copied into your executable) or dynamic (shared .so/.dll files loaded when the program starts, so many programs share one copy). Java does its "linking" lazily at run time, loading each class the first time it's used.

Runtimes and garbage collection

Even a compiled program needs support code while it runs, called its runtime: code that starts the program, manages the stack, and in many languages manages memory. Recall from chapter 2 that values that outlive a function live on the heap. Someone must give that memory back when it's no longer needed:

  • In C, you do it by hand with free. Forget and you leak memory; free too early and you get a use-after-free bug, a major source of security holes.
  • Java, Go, Python, JavaScript and C# have a garbage collector (GC): the runtime periodically finds heap objects nothing can reach any more and reclaims them. Safe and convenient, at the cost of some CPU time and occasional pauses.
  • C++ and Rust free memory automatically at well-defined points when its owner goes out of scope (RAII; Rust's ownership rules check this at compile time), giving safety without a collector.
  • Zig makes you pass an allocator explicitly, so every allocation is visible.

Check yourself

How deep to go in compilers and runtimes

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.

Level What you can do
L1 Name the compiler phases and runtime models
L2 Use build tools, read compiler errors, understand optimisation flags and linking errors
L3 Explain lexing, parsing, type checking, IR, optimisation passes, linking and loading, JIT and GC
L4 Diagnose with disassembly, compiler explorer, linker maps, JIT logs: missed optimisations, ABI and symbol problems
L5 Choose runtime models (native, VM, JIT, AOT) and build setups for products
L6 Operate toolchains at scale: reproducible builds, compiler upgrades, startup and warm-up in production

The compiler pipeline

Overview: front end, middle end, back end

A compiler translates a program from one language to another, usually from a high-level source language to machine code, bytecode or another language. An interpreter executes the program directly. The distinction is blurry in practice: most "interpreters" compile to bytecode first, and most "compiled" languages ship a runtime.

Modern compilers are organised in three parts, so that work can be shared:

FRONT END (per language)MIDDLE ENDBACK END (per target) lexer → tokensparser → ASTname resolutiontype checkingborrow check (Rust)comptime (Zig)lowering → IR IR (e.g. LLVM IR, SSA) inlining · constant foldingdead code · loop optsvectorisation · GVN instruction selectionregister allocationscheduling→ x86-64 · ARM64→ RISC-V · WebAssemblyobject file (.o)debug info (DWARF)
The classic three-part compiler. A shared intermediate representation lets M front ends and N back ends combine without M×N separate compilers.
  • The front end understands the source language. It reads text, checks that it's valid, reports errors, and produces an internal representation.
  • The middle end (optimiser) improves the program in a language- and machine-independent form.
  • The back end generates code for a specific CPU and object format.

LLVM made this structure into shared infrastructure. Clang (C, C++, Objective-C), rustc, Zig (historically; it's building its own backends), Swift, Julia and many others all emit LLVM IR and reuse its optimiser and code generators. Each new language gets decades of optimisation work and every CPU target for free. GCC has the same structure internally (GENERIC → GIMPLE → RTL). Go has its own compiler (gc), with an SSA-based middle end, chosen for compile speed. Java's javac has only a front end: it emits bytecode, and the JVM's JIT compilers (C1, C2, Graal) are the optimiser and back end, running at run time.

Roadmap project 9 is building a tiny compiler or interpreter, and every stage below is part of it.

Lexical analysis

The lexer (scanner or tokenizer) reads raw characters and groups them into tokens, the words of the language: keywords, identifiers, literals, operators and punctuation. It discards whitespace and comments (unless a formatter needs them), and records source positions for error messages.

Text
source:   let total = price * 3 + 1;  // compute
tokens:   LET  IDENT(total)  EQ  IDENT(price)  STAR  INT(3)  PLUS  INT(1)  SEMI
          (each with line:column; the comment is dropped)

Lexers are usually hand-written loops or generated from regular expressions (lex, flex, re2c), because token patterns are regular languages recognisable by a finite automaton (chapter 4's regex discussion). Subtle cases include maximal munch (>>= is one token, not three), Unicode identifiers, string escapes, nested comments, and context-sensitive lexing. In C++, >> in vector<vector<int>> was lexed as a shift operator until C++11 special-cased it.

Rust
#[derive(Debug, Clone, PartialEq)]
enum Tok { Num(f64), Ident(String), Plus, Minus, Star, Slash, LParen, RParen, Eof }

fn lex(src: &str) -> Result<Vec<Tok>, String> {
    let cs: Vec<char> = src.chars().collect();
    let (mut i, mut out) = (0, Vec::new());
    while i < cs.len() {
        let c = cs[i];
        match c {
            ' ' | '\t' | '\n' => { i += 1; }
            '+' => { out.push(Tok::Plus); i += 1; }
            '-' => { out.push(Tok::Minus); i += 1; }
            '*' => { out.push(Tok::Star); i += 1; }
            '/' => { out.push(Tok::Slash); i += 1; }
            '(' => { out.push(Tok::LParen); i += 1; }
            ')' => { out.push(Tok::RParen); i += 1; }
            d if d.is_ascii_digit() || d == '.' => {
                let start = i;
                while i < cs.len() && (cs[i].is_ascii_digit() || cs[i] == '.') { i += 1; }
                let s: String = cs[start..i].iter().collect();
                out.push(Tok::Num(s.parse().map_err(|_| format!("bad number {s}"))?));
            }
            a if a.is_alphabetic() || a == '_' => {
                let start = i;
                while i < cs.len() && (cs[i].is_alphanumeric() || cs[i] == '_') { i += 1; }
                out.push(Tok::Ident(cs[start..i].iter().collect()));
            }
            other => return Err(format!("unexpected '{other}' at {i}")),
        }
    }
    out.push(Tok::Eof);
    Ok(out)
}

Parsing and grammars

The parser checks that the token sequence follows the language's grammar and builds a tree that reflects its structure. Grammars are written in BNF/EBNF as context-free production rules:

Text
expr    → term   (("+" | "-") term)*
term    → factor (("*" | "/") factor)*
factor  → NUMBER | IDENT | "(" expr ")" | "-" factor

The grammar itself encodes precedence and associativity. Because term sits beneath expr, * binds tighter than +, and the ( … )* loops make the operators left-associative.

The main parsing strategies:

Strategy How Used by
Recursive descent (top-down, LL) One function per grammar rule, calling each other GCC's and Clang's C/C++ parsers, rustc, Go, Zig, javac, V8, most modern compilers. Hand-written, fast, with excellent error messages
Pratt parsing (precedence climbing) Each operator token has a binding power; one loop handles all binary operators Expression parsing inside recursive-descent parsers (rust-analyzer, many JS engines)
LR / LALR (bottom-up) Table-driven shift/reduce automaton, generated from the grammar yacc and bison (older GCC, PostgreSQL's SQL grammar, Ruby's MRI)
PEG / packrat Ordered choice with memoisation pest (Rust), Python's parser since 3.9
Parser combinators Small parsers composed as functions nom (Rust), Parsec (Haskell)

A recursive-descent parser for the grammar above. Note how directly it mirrors the rules:

Rust
#[derive(Debug)]
enum Expr {
    Num(f64),
    Var(String),
    Neg(Box<Expr>),
    Bin(Box<Expr>, char, Box<Expr>),
}

struct Parser { toks: Vec<Tok>, pos: usize }

impl Parser {
    fn peek(&self) -> &Tok { &self.toks[self.pos] }
    fn next(&mut self) -> Tok { let t = self.toks[self.pos].clone(); self.pos += 1; t }

    fn expr(&mut self) -> Result<Expr, String> {               // expr → term (("+"|"-") term)*
        let mut lhs = self.term()?;
        loop {
            let op = match self.peek() { Tok::Plus => '+', Tok::Minus => '-', _ => break };
            self.next();
            lhs = Expr::Bin(Box::new(lhs), op, Box::new(self.term()?));   // left-associative
        }
        Ok(lhs)
    }
    fn term(&mut self) -> Result<Expr, String> {               // term → factor (("*"|"/") factor)*
        let mut lhs = self.factor()?;
        loop {
            let op = match self.peek() { Tok::Star => '*', Tok::Slash => '/', _ => break };
            self.next();
            lhs = Expr::Bin(Box::new(lhs), op, Box::new(self.factor()?));
        }
        Ok(lhs)
    }
    fn factor(&mut self) -> Result<Expr, String> {
        match self.next() {
            Tok::Num(n) => Ok(Expr::Num(n)),
            Tok::Ident(s) => Ok(Expr::Var(s)),
            Tok::Minus => Ok(Expr::Neg(Box::new(self.factor()?))),
            Tok::LParen => {
                let e = self.expr()?;
                match self.next() { Tok::RParen => Ok(e), t => Err(format!("expected ')', got {t:?}")) }
            }
            t => Err(format!("unexpected token {t:?}")),
        }
    }
}

Good error recovery is a large part of real parsers: report an error, synchronise (skip to the next ; or }), and keep parsing so the user sees several errors at once. IDEs need parsers that tolerate broken code mid-edit and update incrementally. rust-analyzer, Roslyn and tree-sitter build lossless, error-tolerant syntax trees for exactly this reason.

Abstract syntax trees

The parser's output is an abstract syntax tree (AST): a tree of the program's meaningful structure, without punctuation, parentheses or whitespace. (A concrete syntax tree, or parse tree, keeps every token. Formatters and refactoring tools need that.)

Text
source:  price * 3 + 1

            Bin(+)
           /      \
       Bin(*)     Num(1)
       /    \
 Var(price) Num(3)          ← precedence is now structural: no parentheses needed

Once you have an AST, you can interpret it directly with a recursive tree walk, transform it, or compile it. A tree-walking interpreter for the parser above takes ten lines:

Rust
use std::collections::HashMap;

fn eval(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, String> {
    Ok(match e {
        Expr::Num(n) => *n,
        Expr::Var(v) => *env.get(v).ok_or(format!("undefined variable {v}"))?,
        Expr::Neg(x) => -eval(x, env)?,
        Expr::Bin(l, op, r) => {
            let (a, b) = (eval(l, env)?, eval(r, env)?);
            match op { '+' => a + b, '-' => a - b, '*' => a * b, '/' => a / b, _ => unreachable!() }
        }
    })
}
// eval(parse("price * 3 + 1"), {price: 10}) == 31

ASTs are everywhere in tooling, not just compilers. Linters (ESLint, Clippy, Error Prone), formatters (rustfmt, gofmt, Prettier), code generators, refactoring IDEs, go/ast-based analysers, codemods, and macro systems (Rust procedural macros receive token streams and often parse them into syntax trees with syn) all work on them.

Name resolution and semantic analysis

A syntactically valid program can still be meaningless (x + 1 where x was never declared). Semantic analysis walks the AST and:

  • Resolves names: binds each identifier use to its declaration, following scoping rules (chapter 2's lexical scope, imports, modules, shadowing). It builds symbol tables: maps from names to declarations, nested by scope.
  • Checks types (the next section).
  • Enforces language rules such as definite assignment (Java), exhaustive match (Rust, Zig), the borrow rules (Rust), unused imports and variables being errors (Go, Zig), and const correctness.
  • Desugars high-level constructs into simpler ones: for x in v becomes iterator calls, async fn becomes a state machine, a lambda becomes a synthetic class (Java uses invokedynamic + LambdaMetafactory at run time), ? becomes a match with an early return.

Type checking

The type checker verifies that every operation is applied to values of compatible types, and infers types where they weren't written (chapter 2):

  • Type checking: given annotated types, verify each expression. "a" * 3 is rejected in Rust, Go and Java.
  • Type inference: compute missing types. Local and forward inference (Go :=, Java var, C++ auto) just takes the initialiser's type. Hindley–Milner-style inference (OCaml, Haskell, and in a bidirectional, local form in Rust) generates type constraints from the code and solves them by unification, the same algorithm Prolog uses (chapter 2). let v = Vec::new(); v.push(1u8); creates an unknown ?T, and the later push adds the constraint ?T = u8.
  • Generics must be checked once (Rust, Java, Go check generic bodies against their bounds) or at each instantiation (C++ templates before concepts produced famously long errors because checking happened deep inside instantiations; Zig comptime has the same property).
  • Rust's borrow checker runs after type checking, on MIR (mid-level IR). It's a dataflow analysis proving that every reference is used only while its target is alive and not mutably aliased (non-lexical lifetimes, NLL).

Intermediate representations

Optimising directly on an AST is awkward, so compilers lower the program into one or more intermediate representations (IRs) designed for analysis:

IR Language Shape
HIR → THIR → MIR Rust Desugared tree → typed tree → control-flow graph used for borrow checking and some optimisations
LLVM IR Clang, rustc, Zig (LLVM backend), Swift Typed, SSA, target-independent "portable assembly"
ZIR → AIR Zig Untyped IR per file → analysed, typed IR after comptime evaluation
Go SSA Go gc SSA with machine-independent then machine-specific lowering
GIMPLE / RTL GCC Three-address SSA → register transfer language
JVM bytecode javac Stack-machine instructions (an IR that's also the distribution format)
C2 "sea of nodes" / Graal IR HotSpot JIT Graph-based SSA IR built from bytecode at run time

Most optimising IRs share two properties:

  1. Three-address code organised into a control-flow graph (CFG): each instruction does one operation (t3 = t1 * t2), and instructions are grouped into basic blocks (straight-line code with one entry and one exit) connected by branch edges.
  2. Static single assignment (SSA) form: every variable is assigned exactly once. Where control flow merges, a φ (phi) function selects the value depending on which branch was taken. SSA makes data flow explicit (each use has exactly one definition), and that makes most optimisations simpler and faster.
Text
source:                        SSA:
x = 1                          x1 = 1
if (c) x = x + 2               br c, then, join
else   x = x * 3               then: x2 = x1 + 2 ; br join
y = x                          else: x3 = x1 * 3 ; br join
                               join: x4 = φ(x2 from then, x3 from else)
                                     y1 = x4

Real LLVM IR for int square(int x) { return x * x; }:

LLVM IR
define dso_local i32 @square(i32 noundef %x) {
entry:
  %mul = mul nsw i32 %x, %x        ; nsw = "no signed wrap": overflow is UB (chapter 2!)
  ret i32 %mul
}

The nsw flag is how C's "signed overflow is undefined" reaches the optimiser. Rust emits the same multiply without nsw in release mode, because its overflow wraps, so LLVM must preserve wrapping semantics.

Optimisation

The optimiser rewrites IR into a faster equivalent program, under the as-if rule: any transformation is allowed if observable behaviour (output, volatile accesses, I/O, and anything that's defined) stays the same. Important passes:

Optimisation Before → after Why it matters
Inlining Replace a call with the callee's body Removes call overhead and enables most other optimisations by exposing context. The most important optimisation
Constant folding and propagation x = 4 * 1024 → x = 4096; then substitute known constants Free arithmetic
Dead code elimination Remove unused results and unreachable branches Smaller, faster code; if DEBUG {…} disappears
Common subexpression elimination / GVN Compute a*b once if used twice
Loop-invariant code motion Hoist len(v) or x*y out of a loop
Strength reduction i*8 → i<<3; x/10 → multiply by a magic reciprocal Cheaper instructions
Loop vectorisation Process 4/8/16 elements per instruction SIMD (chapter 7)
Loop unrolling Repeat the body k times per iteration Fewer branches, more ILP
Escape analysis An object that never escapes the function lives on the stack or in registers Fewer allocations: Go's heap-vs-stack decision, the JVM's scalar replacement
Devirtualisation A virtual call with a known receiver type becomes a direct call, then is inlined Essential for C++, Java and Rust dyn
Tail-call elimination Recursive tail call → jump Constant stack (chapter 2)
Bounds-check elimination Prove i < len and drop the check Makes safe languages (Rust, Java, Go) nearly as fast as unchecked C
Alias analysis Prove two pointers don't overlap Enables reordering and vectorisation. Rust's &mut gives noalias for free

Optimisation levels trade compile time and debuggability against speed: -O0 (debug: every variable lives in memory, easy to step through), -O2 (production), -O3 (more aggressive inlining and vectorisation), -Os/-Oz (size). The equivalents are Rust's --release (opt-level=3) and [profile] settings, Zig's Debug/ReleaseSafe/ReleaseFast/ReleaseSmall, and Go's single optimised mode (it doesn't expose levels). Link-time optimisation (LTO) runs the optimiser across all translation units, inlining across files and crates. PGO feeds real execution profiles back to guide inlining and layout. Go has supported PGO since 1.21 via a default.pgo file, and typically gains 2–14%.

Optimisers rely on your program having no undefined behaviour. That's why UB in C and C++ can seem to "time travel": the compiler deletes checks or entire branches, reasoning backwards from the assumption that UB never happens (chapter 2).

Code generation

The back end turns optimised IR into machine code for one target:

  1. Instruction selection: map IR operations onto target instructions, often by tree or DAG pattern matching (LLVM SelectionDAG and GlobalISel). On x86, a + b*4 + 16 can become one lea instruction.
  2. Instruction scheduling: order instructions to avoid pipeline stalls and expose ILP (chapter 7). This matters most on in-order cores.
  3. Register allocation: assign unlimited virtual registers to 16 or 31 physical ones, using graph colouring (chapter 5) or linear scan (fast, and used by JITs). Values that don't fit are spilled to the stack.
  4. Emission: encode machine instructions into bytes, plus relocations (placeholders for addresses resolved later by the linker), symbol tables, unwind tables for exceptions and panics (chapter 2), and debug info (DWARF on Linux, PDB on Windows), which maps machine addresses back to source lines and variables for debuggers and profilers.

The result is an object file (.o or .obj) in the platform format: ELF (Linux, BSDs), Mach-O (macOS, iOS) or PE/COFF (Windows). Inspect them with readelf -a, objdump -d, nm (symbols), otool (macOS) or dumpbin (Windows).

Linking

A program spans many object files and libraries. The linker (ld, lld, gold, mold, link.exe) combines them into an executable or library:

  1. Symbol resolution: each object file defines some symbols (main, square) and references others (printf). The linker matches every reference to exactly one definition. Errors here are the familiar "undefined reference to foo" (a missing library or definition) and "multiple definition of foo" (two definitions, which violates C's one-definition rule).
  2. Relocation: lay out the sections (.text, .rodata, .data, .bss) at final addresses, then patch every placeholder address in the code.

Static versus dynamic linking:

Static Dynamic (shared libraries: .so, .dylib, .dll)
When Library code is copied into the executable at link time Code is loaded and bound at run time
Binary Large, self-contained Small; needs the right library versions installed
Updates Rebuild to get a library fix Update the library once, and every program benefits (security patches to OpenSSL)
Memory Each process has its own copy One copy shared in RAM by all processes (chapter 8's page sharing)
Startup Fast Symbol binding cost
Problems Licensing (LGPL); bloat "DLL hell" / dependency version conflicts; "library not found"; ABI breakage
Defaults Go (fully static unless cgo is used), Zig, Rust with musl C/C++ on Linux and macOS (libc), Rust's default against glibc, the JVM itself

Go's and Zig's static binaries are a big reason they're popular for CLIs and containers. A FROM scratch or distroless image with one binary has no OS packages to patch. Zig also works as a drop-in cross-compiling C/C++ toolchain (zig cc -target aarch64-linux-musl), because it ships libc headers for many targets.

Symbol visibility and name mangling. C exports function names as is (square). C++, Rust and Swift mangle names to encode namespaces, overloads, generics and crate hashes (_ZN5mycrate6square17h3a…E; c++filt and rustfilt demangle them). To call between languages, you agree on the C ABI: extern "C" in C++ and Rust, export fn in Zig, //export with cgo in Go, and JNI or the FFM API (Panama, final in JDK 22) in Java. The C ABI is the lingua franca for FFI between all six languages.

ABI stability. A library's ABI covers calling conventions, struct layouts, name mangling and vtable layouts. C has a stable ABI on each platform, so a 1995 binary can call today's libc. C++ is ABI-stable only within one compiler and standard library. Changing a class's private fields breaks binary compatibility, which is why the pImpl idiom exists. Rust and Zig deliberately have no stable ABI (beyond C interop): all crates are compiled together from source, which lets the compiler reorder struct fields and change layouts freely. Java's ABI is bytecode plus class-file structure, which is very stable, and binary compatibility rules (JLS chapter 13) say which source changes are safe.

Loading

When you run a program, the OS loader (part of the kernel's execve, plus the dynamic linker in user space) prepares it:

  1. execve reads the ELF header, maps the program's segments into a fresh address space (code r-x, data rw-, with ASLR choosing randomised bases), sets up the stack with argv, envp and the auxiliary vector, and finds the interpreter named in the ELF: the dynamic linker, /lib64/ld-linux-x86-64.so.2.
  2. The dynamic linker (ld.so) loads every required shared library (ldd ./prog lists them), maps each into memory, performs relocations, and resolves symbols. Calls into shared libraries go through the PLT (procedure linkage table) and GOT (global offset table). With lazy binding, each function's address is looked up on its first call. Security hardening (-z now, full RELRO) resolves everything at startup and makes the GOT read-only, so attackers can't overwrite it.
  3. Run initialisers: C++ static constructors, __attribute__((constructor)), Rust has none by design (statics must be constant-initialised), Go's package init() functions, Zig's comptime-initialised globals.
  4. Jump to _start (from crt1.o), which calls __libc_start_main, which calls main.
Terminal
$ file ./server          # ELF 64-bit LSB pie executable, x86-64, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2
$ ldd ./server           # the shared libraries it will load
$ readelf -l ./server    # program headers: what gets mapped where
$ LD_DEBUG=bindings ./server 2>&1 | head    # watch the dynamic linker work
$ go build -o server . && file server       # Go: statically linked (without cgo)

Position-independent executables (PIE) and shared libraries are compiled so their code works at any load address (rip-relative addressing, chapter 7), which is what makes ASLR possible. Most Linux distributions build everything as PIE by default.

Java's version of linking and loading

Java defers linking and loading to run time, class by class (roadmap chapter 40 goes deeper):

  1. Loading: a class loader finds the .class bytes (from the module path or class path, JARs, the network, or generated at run time) and creates a Class object. Loaders form a delegation hierarchy (bootstrap → platform → application → custom). Application servers and OSGi use separate loaders to isolate applications, which is also the source of ClassCastException: com.x.Foo cannot be cast to com.x.Foo when the same class is loaded by two loaders.
  2. Linking: verification (the bytecode verifier proves type safety and stack discipline, so malformed bytecode can't corrupt the JVM), preparation (allocating static fields), and resolution (symbolic references to other classes, methods and fields turn into direct references, usually lazily on first use).
  3. Initialisation: run static initialisers (<clinit>) on first active use, exactly once, thread-safely.

That laziness is why Java starts slowly (thousands of classes are loaded, verified and interpreted at startup) and why a missing dependency shows up as NoClassDefFoundError at run time rather than at build time. Mitigations include CDS/AppCDS (class-data sharing: pre-parsed class archives mapped at startup), and Project Leyden's AOT cache (JDK 24+: -XX:AOTCache), which stores loaded, linked classes and profiling data from a training run. There's also GraalVM native-image, which compiles everything ahead of time, under a closed-world assumption.

Runtime models

The spectrum of execution models

How a language executes is a design choice that drives startup time, peak speed, memory use, portability and observability. Here are the main models, and where each language sits on them:

Model Translate when? Output Startup Peak speed Languages / systems
Native AOT Before running Machine code Instant High, fixed at build C, C++, Rust, Zig, Go, Swift; GraalVM native-image
Tree-walking interpreter Never: walk the AST — Instant Very slow (10–100× native) Early Ruby, many DSLs, shells, your first interpreter
Bytecode interpreter At load: source → bytecode Bytecode for a VM Fast Slow-moderate CPython, Lua (PUC), Ruby YARV, the JVM before JIT kicks in
Method JIT At run time, for hot methods Machine code Slower (warm-up) Very high (uses live profiles) HotSpot (C1/C2), V8 (Maglev/TurboFan), .NET RyuJIT
Tracing JIT At run time, for hot loop traces Machine code for one path Warm-up Very high on loopy code LuaJIT, PyPy, early Firefox (TraceMonkey)
AOT to bytecode + AOT/JIT hybrid Mixed Tunable Android ART, .NET ReadyToRun, Java + Leyden AOT cache
Transpilation Before running Another high-level language Depends on target Depends TypeScript → JS, Kotlin/JS, early C++ (Cfront → C)

Native code

Native compilation produces machine code for one target ahead of time. The program starts immediately with no warm-up, and its performance is predictable. The binary contains only what it needs, and memory overhead is low. The costs: one build per OS and CPU target (cross-compilation is a first-class feature in Go and Zig, and needs target toolchains or cross for C, C++ and Rust); optimisation decisions are fixed at build time unless you use PGO; and introspection is limited to what debug info and symbols provide.

"Native" languages still have runtimes of varying size:

Runtime contents
C crt0 startup, libc (malloc, stdio), the dynamic linker
C++ C runtime + libstdc++/libc++, exception unwinder, RTTI, static constructors
Rust Thin: panic machinery and unwinding (or panic=abort), the allocator, std on top of libc. #![no_std] drops almost all of it for embedded and kernels (Linux kernel Rust code is no_std)
Zig Very thin. Can produce binaries with no libc at all; a "hello world" can be a few KB
Go Substantial: a concurrent GC, the goroutine scheduler, the netpoller, growable stacks, maps and channels, reflection data. That's why minimal Go binaries are about 1–2 MB, and why Go needs no OS threads per connection

Bytecode virtual machines

A bytecode VM executes instructions for an idealised machine that hides the real CPU. The JVM, CPython, Lua, the .NET CLR, the Erlang BEAM and WebAssembly all work this way. Bytecode is compact and portable ("write once, run anywhere"), and it can be verified before running, which makes the JVM and Wasm sandboxes safe for untrusted code.

There are two VM designs:

  • Stack machines (JVM, CPython, .NET CIL, WebAssembly): instructions push and pop an operand stack. The code is compact and simple to generate.
  • Register machines (Lua 5, Dalvik on old Android, BEAM): instructions name virtual registers. They need fewer instructions per operation, so they're faster to interpret.

Java bytecode for return x * x + 1:

Terminal
$ javac Calc.java && javap -c Calc
  static int f(int);
    Code:
       0: iload_0        // push local 0 (x)
       1: iload_0        // push x again
       2: imul           // pop two, push x*x
       3: iconst_1       // push 1
       4: iadd           // pop two, push x*x + 1
       5: ireturn

An interpreter's core is a dispatch loop: fetch the next opcode, jump to its handler, repeat. Interpreters spend much of their time in dispatch overhead and unpredictable indirect branches (chapter 7). Techniques that speed them up include threaded code (each handler jumps directly to the next one; GCC's computed goto), superinstructions, register-based bytecode, and inline caches. CPython 3.11+ added a specialising adaptive interpreter that rewrites hot bytecodes into type-specialised forms (BINARY_OP becomes BINARY_OP_ADD_INT). CPython 3.13+ also includes an experimental JIT.

C
// The heart of every bytecode interpreter: a dispatch loop over an operand stack
enum { OP_PUSH, OP_ADD, OP_MUL, OP_PRINT, OP_HALT };

void run(const int *code) {
    int stack[256], sp = 0;
    for (const int *ip = code;;) {
        switch (*ip++) {
        case OP_PUSH:  stack[sp++] = *ip++; break;
        case OP_ADD:   sp--; stack[sp - 1] += stack[sp]; break;
        case OP_MUL:   sp--; stack[sp - 1] *= stack[sp]; break;
        case OP_PRINT: printf("%d\n", stack[sp - 1]); break;
        case OP_HALT:  return;
        }
    }
}
// run((int[]){OP_PUSH, 6, OP_PUSH, 7, OP_MUL, OP_PRINT, OP_HALT});   → 42

WebAssembly (Wasm) deserves its own mention: a portable, sandboxed, stack-based bytecode with a well-defined binary format, designed to be compiled (AOT or JIT) to native speed. It runs in browsers (chapter 29), and outside them through runtimes like Wasmtime and WasmEdge for plugins (Envoy filters, Shopify Functions, database UDFs) and edge compute (Cloudflare Workers, Fastly Compute). C, C++, Rust, Zig and Go all compile to it, with Go through GOOS=wasip1 or TinyGo. WASI is the system interface standard that gives Wasm modules files, clocks and sockets.

Interpreters

A pure interpreter executes source (or an AST) directly with no separate compile step: shells (Bash), many configuration and template languages, early Lisps and BASIC, and the tree-walking evaluator earlier in this chapter. They're simple to build, start instantly, make it easy to inspect and modify running programs, and suit REPLs. They're also slow, because every operation re-examines the tree.

In practice "interpreted language" usually means bytecode-compiled at load time and then interpreted, as in Python, Ruby and Lua. And in "compiled vs interpreted," the language isn't the thing being compiled or interpreted; implementations are. C has interpreters (Cling, PicoC), Python has compilers (PyPy, Cython, Nuitka), and Java has both an interpreter and three compilers in one JVM.

JIT compilation

A just-in-time compiler compiles code to native machine code while the program runs, focusing on code that's actually hot. Its unique advantage over AOT is speculation based on observed behaviour:

  • Profile-guided decisions for free: the JIT knows which branches are taken, which types appear at each call site, and which methods are hot, from the real workload, not a training run.
  • Speculative optimisation: if a virtual call site has only ever seen ArrayList, the JIT inlines ArrayList.get behind a cheap type check (a guard). If a branch has never been taken, it compiles only the other side and inserts an uncommon trap.
  • Deoptimisation: when a speculation turns out wrong (a new subclass loads, the "never" branch is taken), the JIT throws away the optimised code and transfers the running frame back to the interpreter mid-method, then may recompile with the new information. Deoptimisation is what makes aggressive speculation safe.
  • On-stack replacement (OSR): a long-running loop that started in the interpreter can switch to compiled code in the middle of the loop.

HotSpot's tiered compilation, the JVM default:

tier 0interpreter+ basic counters tier 3: C1fast compile+ full profiling tier 4: C2slow, aggressivespeculative opts tier 1: C1, trivial methods ~200 calls/loops ~thousands + profile deoptimise when a speculation fails
HotSpot tiered compilation. Code starts interpreted, moves to quick C1 code with profiling, and hot code is recompiled by C2 using the profiles. Failed speculation deoptimises back to tier 0.

Practical consequences for Java services (roadmap chapters 40–41 go deeper):

  • Warm-up: a freshly started service runs slowly for seconds to minutes, until hot paths reach C2. Benchmarks must warm up first (that's why JMH exists). Rolling deploys can produce latency spikes as new pods start cold, so use readiness probes, warm-up traffic, CDS/Leyden AOT caches, or CRaC (checkpoint/restore of a warmed JVM).
  • Megamorphic call sites: a call site that sees many receiver types (3+) can't be inlined behind a simple guard. Performance-sensitive code sometimes keeps hot call sites monomorphic on purpose.
  • Code cache: compiled code lives in a fixed-size code cache. If it fills, the JIT stops compiling ("CodeCache is full. Compiler has been disabled"), and performance falls off a cliff.
  • Observing it: -XX:+PrintCompilation, JFR compilation events, and JITWatch.
  • Graal is a JIT written in Java. It can replace C2, and it's the basis of GraalVM native-image and Truffle (a framework for building fast language interpreters that JIT-compile themselves through partial evaluation).

JavaScript engines push the same ideas further, because JS is dynamically typed. V8 has the Ignition interpreter, then Sparkplug (a quick baseline compiler), then Maglev (a mid-tier optimiser), then TurboFan (top tier). They speculate on object "shapes" (hidden classes) with inline caches, and deoptimise when shapes change. That's why JS code that keeps object shapes consistent runs faster (chapter 15).

AOT compilation in managed languages

Ahead-of-time compilation means translating to native code before running. For C, C++, Rust, Zig and Go that's simply the normal model. The interesting case is AOT for languages designed around VMs:

  • GraalVM native-image (Java, Kotlin, Scala): static analysis from main finds all reachable code under a closed-world assumption, initialises some classes at build time, and emits a single native executable. Startup takes milliseconds instead of seconds, memory footprint is much smaller, and no JIT warm-up is needed. That's ideal for serverless, CLIs and scale-to-zero. The costs: reflection, dynamic proxies, resources and JNI must be declared in configuration (frameworks generate it: Spring Boot AOT, Quarkus, Micronaut); build times are long; and peak throughput is often lower than C2 unless you use PGO (Oracle GraalVM).
  • Project Leyden (OpenJDK, landing incrementally since JDK 24): instead of giving up dynamism, it shifts work earlier. An AOT cache records class loading, linking and method profiles from a training run, which cuts startup substantially while keeping full Java semantics and the JIT.
  • .NET Native AOT and ReadyToRun, and Android ART (AOT plus JIT plus profile-guided recompilation in the background on the device).

Tracing JITs

A method JIT compiles whole methods. A tracing JIT records the actual path the program takes through a hot loop, including across function calls, which are inlined automatically into the trace. It compiles just that linear trace, with guards wherever execution could leave the recorded path. If a guard fails often, a side trace is recorded from that exit.

Text
hot loop detected → record one iteration:
  load i → guard(i is int) → load arr[i] → guard(arr[i] is float) → add → call f (inlined) → i++ → guard(i < n) → loop
compile this straight-line trace with type guards; exits fall back to the interpreter

Tracing JITs excel at loop-heavy, dynamically typed code. LuaJIT is legendary for its speed, and PyPy often runs pure-Python code 4–10× faster than CPython. They struggle with branchy code that has many different paths (trace explosion). Mozilla abandoned its tracing JIT, TraceMonkey, for method JITs. The idea lives on in PyPy and LuaJIT, and in meta-tracing (PyPy's RPython traces the interpreter executing the user program, which yields a JIT for any language written as an RPython interpreter).

Garbage collection as a runtime service

A runtime's other big job, alongside execution, is memory management (chapter 2's ownership models, chapter 8's heap). For the GC languages here:

Java (HotSpot) Go
Algorithm Generational (most objects die young), several collectors: Serial, Parallel, G1 (default), ZGC, Shenandoah Non-generational, concurrent, tri-colour mark-sweep, non-moving
Moves objects? Yes: compaction, bump-pointer allocation No (size-segregated spans instead)
Pauses G1: tens of ms target; ZGC/Shenandoah: sub-millisecond, independent of heap size Typically well under 1 ms
Tuning -Xmx, -XX:MaxGCPauseMillis, collector choice GOGC (heap growth %) and GOMEMLIMIT (a soft memory cap)
Trade-off Highly tunable; throughput vs latency vs footprint Few knobs; trades CPU for low latency

Key concepts that apply to all tracing collectors: roots (stacks, globals, registers) → mark everything reachable → sweep or copy the rest. Tri-colour marking (white, grey, black) lets marking run concurrently with the program, using write barriers that record pointer changes made by the running code. Stop-the-world phases still exist briefly, and safepoints are the points where threads can be stopped. GC adds CPU overhead and needs memory headroom (GC'd heaps typically need 2–3× the live data to run efficiently), and those are the real costs. Roadmap chapters 40–41 cover JVM GC tuning in production.

Reference counting (Swift ARC, Python's primary mechanism, Rc/Arc/shared_ptr) frees memory deterministically when the last reference goes. It costs counter updates (atomic ones if shared across threads), and it leaks cycles unless it's supplemented by a cycle collector, as Python's is, or by weak references.

How the six languages compare end to end

C C++ Java Rust Zig Go
Compiler GCC, Clang, MSVC GCC, Clang, MSVC javac → JIT (C1/C2/Graal) rustc (LLVM; Cranelift for fast debug builds) zig (LLVM + self-hosted backends) gc (own); gccgo
Output Native Native Bytecode (.class/.jar) Native Native Native, static
Compile speed Fast per file Slow (headers, templates) Fast (javac); JIT at run time Slow (monomorphisation, LLVM) Fast and improving (incremental compilation, own x86 backend) Very fast (a design goal)
Startup Instant Instant Slow without CDS/Leyden/native-image Instant Instant Instant (~ms; runtime init)
Peak performance Highest tier Highest tier High after warm-up Highest tier Highest tier High (GC and less aggressive optimisation cost some)
Metaprogramming Preprocessor Templates, constexpr, (C++26 reflection) Annotations + reflection + bytecode generation Macros (declarative + procedural) comptime go generate, reflection
Cross-compiling Toolchain per target Toolchain per target Not needed (bytecode) --target + linker/sysroot Built in (-target), including C/C++ via zig cc Built in (GOOS/GOARCH)
Debug info / tooling gdb, lldb, perf gdb, lldb, perf JDWP, JFR, JMX, async-profiler gdb, lldb, perf, Miri gdb, lldb Delve, pprof, trace

Lab: inside the toolchain

Compilers and runtimes are programs you can watch. This lab follows code through Clang/LLVM 18 (IR and optimisation), HotSpot (JDK 21 JIT warm-up), the Linux dynamic linker, and a tiny language implemented three ways in Python 3.13. Every output is real.

A loop becomes a formula: LLVM IR and SSA

C
unsigned long sum_to(unsigned long n) {
    unsigned long s = 0;
    for (unsigned long i = 0; i < n; i++) s += i;
    return s;
}

Stage 1: naive IR (clang -O0 -emit-llvm). Every variable is a stack slot (alloca) that is stored and reloaded on every use:

LLVM IR
define dso_local i64 @sum_to(i64 noundef %0) #0 {
  %2 = alloca i64, align 8          ; n
  %3 = alloca i64, align 8          ; s
  %4 = alloca i64, align 8          ; i
  store i64 %0, ptr %2, align 8
  store i64 0, ptr %3, align 8
  store i64 0, ptr %4, align 8
  br label %5
5:
  %6 = load i64, ptr %4, align 8
  %7 = load i64, ptr %2, align 8
  %8 = icmp ult i64 %6, %7
  br i1 %8, label %9, label %16
9:
  %10 = load i64, ptr %4, align 8
  %11 = load i64, ptr %3, align 8
  %12 = add i64 %11, %10
  store i64 %12, ptr %3, align 8
  ...

Stage 2: SSA form (after the mem2reg pass). Each value is assigned exactly once; where control flow merges, a φ (phi) node picks the value according to which block we came from:

LLVM IR
define dso_local i64 @sum_to(i64 noundef %0) #0 {
  br label %2
2:                                   ; loop header
  %.01 = phi i64 [ 0, %1 ], [ %5, %6 ]   ; s: 0 on entry, %5 from the previous iteration
  %.0 = phi i64 [ 0, %1 ], [ %7, %6 ]    ; i
  %3 = icmp ult i64 %.0, %0
  br i1 %3, label %4, label %8
4:
  %5 = add i64 %.01, %.0                 ; s + i
  br label %6
6:
  %7 = add i64 %.0, 1                    ; i + 1
  br label %2
8:
  ret i64 %.01
}

SSA makes data flow explicit: to know where %5 comes from, there is exactly one definition. Almost every modern optimiser (LLVM, GCC's GIMPLE, HotSpot C2, V8 TurboFan, Go's compiler) works on SSA for this reason.

Stage 3: optimised (-O2). The loop is gone:

LLVM IR
define dso_local i64 @sum_to(i64 noundef %0) local_unnamed_addr #0 {
  %2 = icmp eq i64 %0, 0
  br i1 %2, label %13, label %3
3:
  %4 = add i64 %0, -1
  %5 = zext i64 %4 to i65                ; widen to 65 bits so the product can't overflow
  %6 = add i64 %0, -2
  %7 = zext i64 %6 to i65
  %8 = mul i65 %5, %7
  %9 = lshr i65 %8, 1                    ; (n-1)(n-2)/2
  %10 = trunc i65 %9 to i64
  %11 = add i64 %10, %0
  %12 = add i64 %11, -1                  ; + n - 1  =  n(n-1)/2
  br label %13
13:
  %14 = phi i64 [ 0, %1 ], [ %12, %3 ]
  ret i64 %14
}
x86-64 asm
sum_to:                         ; x86-64 at -O2: constant time, no loop
        testq   %rdi, %rdi
        je      .LBB0_1
        leaq    -1(%rdi), %rax
        leaq    -2(%rdi), %rcx
        mulq    %rcx
        shldq   $63, %rax, %rdx
        leaq    (%rdi,%rdx), %rax
        decq    %rax
        retq

LLVM's scalar evolution analysis recognised that s follows a polynomial recurrence in i and replaced the O(n) loop with Gauss's O(1) formula n(n−1)/2, carefully computed in 65-bit arithmetic so the intermediate product can't overflow before the division. This is why naive micro-benchmarks lie (the code you think you're timing may not exist) and why you inspect what the compiler produced, in Compiler Explorer (godbolt.org) or with -S/-emit-llvm, before drawing conclusions.

JIT warm-up, measured

The same method timed in batches of 200 calls as HotSpot compiles it:

Java
static long work(int n) { long h = 0; for (int i = 0; i < n; i++) h = h * 31 + (i ^ (h >>> 7)); return h; }
Text
batch 1:   68.4 us per call
batch 2:   20.0 us per call
batch 3:   12.0 us per call
batch 4:   15.9 us per call
batch 5:   11.8 us per call
batch 6:   11.5 us per call
batch 7:   11.8 us per call
batch 8:   12.6 us per call
--- interpreter only (-Xint):
batch 8:  187.0 us per call
--- compilation log (-XX:+PrintCompilation) for work():
44    6 %     3       Warm::work @ 4 (31 bytes)
45    7       3       Warm::work (31 bytes)
45    8 %     4       Warm::work @ 4 (31 bytes)
47    6 %     3       Warm::work @ 4 (31 bytes)   made not entrant
47    9       4       Warm::work (31 bytes)

Reading the log: at 44 ms the hot loop inside work is compiled by C1 (tier 3) via on-stack replacement (%, @ 4 = the loop at bytecode index 4), letting the currently running invocation switch to compiled code mid-loop; then the whole method at tier 3; then C2 (tier 4) versions, after which the tier-3 OSR version is "made not entrant" (retired). The timings show the effect: the first batch averages 68 µs (mostly interpreted and profiling), and steady state is about 12 µs, 5.7× faster; the pure interpreter (-Xint) takes 187 µs, 15× slower than C2 code. Production consequences: the first requests after a deploy are slow (warm-up), benchmarks must discard warm-up iterations (JMH does this properly), and techniques like CDS, Leyden's AOT cache, CRaC or GraalVM native images exist to shorten or skip this phase (Volume 17, ch. 194B).

Dynamic linking and symbol interposition

When a dynamically linked program calls malloc, the dynamic linker resolves the name to the first definition in its search order. LD_PRELOAD puts a library first, so it can wrap any libc function:

C
static size_t calls, bytes;
static void *(*real_malloc)(size_t);
void *malloc(size_t n) {
    if (!real_malloc) real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");   // find libc's malloc, next in search order
    calls++; bytes += n;
    return real_malloc(n);
}
__attribute__((destructor)) static void report(void) {
    char m[96]; int k = snprintf(m, sizeof m, "[shim] malloc called %zu times for %zu bytes\n", calls, bytes);
    write(2, m, k);                                     // write(2), not printf: printf may itself call malloc
}
Terminal
$ gcc -O2 -shared -fPIC -o libcount.so count_malloc.c -ldl
$ LD_PRELOAD=./libcount.so ./hello_dyn          # main: strdup("tiffin"), malloc(100), printf, free both
[shim] malloc called 2 times for 4103 bytes
dynamic hello tiffin
$ LD_PRELOAD=./libcount.so python3 -c "pass"
[shim] malloc called 2340 times for 1582020 bytes
$ LD_PRELOAD=./libcount.so ./hello_static       # statically linked: nothing to interpose
static hello 0x1

Three details reward a close look. 4103 bytes in 2 calls = strdup (7 bytes) + stdio's 4,096-byte output buffer; the program's own malloc(100) never happened, because GCC saw it was freed without being used and deleted the allocation (compilers treat malloc/free as built-ins). Python's interpreter makes 2,340 allocations just to start up. And the statically linked binary ignores LD_PRELOAD entirely: its malloc was resolved at link time. This mechanism is how memory profilers (heaptrack), alternative allocators (jemalloc, mimalloc, tcmalloc via LD_PRELOAD), and fault-injection tools work, and also why it's a security-sensitive feature (the loader ignores LD_PRELOAD for setuid programs).

One language, three execution models

A tiny language (assignments, arithmetic, comparisons, while), implemented as a lexer, a recursive-descent parser with precedence climbing, and then three back ends: a tree-walking interpreter, a compiler to stack bytecode with a VM loop, and a compiler to Python source (which CPython then compiles to its own bytecode).

Python
SRC = "s = 0; i = 0; while i < n { s = s + i * i % 7; i = i + 1 }"
PREC = {"<": 1, "+": 2, "-": 2, "*": 3, "%": 3}
def expr(s, min_p=1):                                  # precedence climbing
    left = s.atom()
    while s.peek()[0] == "op" and s.PREC.get(s.peek()[1], 0) >= min_p:
        op = s.take()[1]; right = s.expr(s.PREC[op] + 1); left = ("bin", op, left, right)
    return left
def walk(node, env):                                   # 1. tree-walking interpreter
    k = node[0]
    if k == "num": return node[1]
    if k == "var": return env[node[1]]
    if k == "bin": return OPS[node[1]](walk(node[2], env), walk(node[3], env))
    ...
def vm(code, env):                                     # 2. bytecode VM
    stack, pc = [], 0
    while pc < len(code):
        op, arg = code[pc]; pc += 1
        if op == "CONST": stack.append(arg)
        elif op == "LOAD": stack.append(env[arg])
        elif op == "BIN": b = stack.pop(); a = stack.pop(); stack.append(arg(a, b))
        elif op == "JUMP_IF_FALSE":
            if not stack.pop(): pc = arg
        ...
Text
tokens: [('name', 's'), ('op', '='), ('num', 0), ('op', ';'), ('name', 'i'), ('op', '='), ('num', 0), ('op', ';')] ...
AST: ('set', 'i', ('num', 0)) | while condition: ('bin', '<', ('var', 'i'), ('var', 'n'))
bytecode: 21 instructions, e.g. [('LOAD', 'i'), ('LOAD', 'n'), ('BIN', '<op>'), ('JUMP_IF_FALSE', 21), ('LOAD', 's'), ('LOAD', 'i')]
tree-walking         s = 399999    370.2 ms
bytecode VM          s = 399999    517.6 ms
compiled to Python   s = 399999     52.8 ms

All three agree on the answer. The timings carry a lesson that surprises people: the bytecode VM was slower than tree-walking here. Bytecode wins in real VMs because their dispatch loop is tight native code (a C switch or computed goto, operands in registers, compact instruction encoding); written in Python, each VM instruction costs several Python-level operations (tuple unpacking, list pushes and pops, comparisons in the if chain), more than a recursive call on the AST. Compiling to the host's representation and letting CPython's own C-implemented bytecode loop run it was 7× faster than either. That's the general pattern behind fast language implementations: lower the code to a level whose execution engine is already fast, whether that's machine code (native compilers, JITs), another VM's bytecode (Kotlin, Scala and Clojure targeting the JVM), or WebAssembly.

Revision sheet: compilers and runtimes

Key ideas

  • Pipeline: lexing (tokens) → parsing (syntax tree) → semantic analysis (names, types) → intermediate representation (IR, often SSA) → optimisation → code generation → assembly → linking.
  • Ahead-of-time compilation (C, C++, Rust, Go, Zig), interpretation (CPython's bytecode loop), JIT (HotSpot, V8), and mixtures (GraalVM native image is AOT Java).
  • Grammars define syntax; recursive descent and Pratt parsing handle precedence; parser generators exist but most production compilers hand-write parsers.
  • Type checking and type inference (local in Java/Go, Hindley-Milner style in ML/Haskell, bidirectional in Rust) happen before code generation.
  • Optimisations: constant folding, inlining, dead-code elimination, common subexpression elimination, loop-invariant motion, vectorisation, escape analysis. Undefined behaviour licenses C/C++ compilers to assume it never happens.
  • Linking: object files with symbols and relocations; static vs dynamic libraries; Java and .NET link lazily at class-load time.
  • Runtimes provide start-up, stacks, threads, exceptions and memory management. Garbage collectors: reference counting (CPython, Swift), tracing mark-sweep/compact, generational collection; concurrent low-pause collectors (Java ZGC, Shenandoah; Go's concurrent mark-sweep). Ownership/RAII frees deterministically without a collector.
  • JITs profile at run time, compile hot methods with speculative assumptions, and deoptimise when assumptions break; hence warm-up in benchmarks.

Numbers to remember

  • HotSpot compiles a method with C1 after a few thousand invocations or loop iterations and with C2 after roughly 10,000+ (tiered compilation; exact thresholds vary by version and flags).
  • Go GC targets: GOGC=100 lets the heap grow to about twice the live set before collecting.
  • ZGC pause times: typically under a millisecond, independent of heap size.

Pitfalls

  • Benchmarking JIT-compiled code without warm-up (use JMH in Java).
  • Relying on undefined behaviour because "it works at -O0".
  • Assuming a GC language can't leak: anything still reachable (caches, listeners, static maps) stays alive.
  • Mixing incompatible library versions at link or class-load time (NoSuchMethodError).
  • Reading optimised assembly without -g or source interleaving and misattributing time.

Glossary

  • Token: the smallest meaningful unit of source text.
  • AST: abstract syntax tree.
  • IR: intermediate representation, the compiler's internal language between source and machine code.
  • SSA: static single assignment, an IR where every variable is assigned exactly once.
  • Symbol / relocation: a named address in an object file / a place the linker must patch.
  • Safepoint: a point where a managed thread can be paused safely, e.g. for GC.