18. JIT Compilation

From bytecode to native code at runtime

A bytecode VM is fast, but it's still an interpreter — every instruction goes through a switch dispatch, every value gets tagged and untagged, every function call bounces through the VM's call mechanism. JIT compilation (Just-In-Time) eliminates that overhead by translating bytecode into native machine code while the program is running. It's the technology behind V8 (JavaScript), HotSpot (Java), LuaJIT, and the .NET CLR.

The fundamental tradeoff

There are two ways to run code:

Ahead-of-time (AOT) compilation — compile everything to machine code before running. Fast execution, but you lose flexibility (no eval, no dynamic loading) and the compiler can't use runtime information.

Interpretation — read and execute instructions one at a time. Maximum flexibility, but slow because every operation pays dispatch overhead.

JIT compilation is the middle ground: start interpreting, then compile the hot parts. You get fast startup (no compile step), runtime flexibility, and near-native speed for the code that matters.

The basic idea

A JIT compiler works in three steps:

  1. Profile — run the program in an interpreter, counting how many times each function (or loop) executes.
  2. Compile — when a function crosses a "hotness" threshold, compile it to native machine code.
  3. Patch — replace the interpreted version with the compiled version so future calls go directly to machine code.
class SimpleJIT {
  constructor(bytecodeModules) {
    this.callCounts = new Map();  // function → call count
    this.compiled = new Map();    // function → native code
    this.threshold = 100;         // compile after 100 calls
  }

  call(func, args) {
    // Check if we already have compiled code
    if (this.compiled.has(func)) {
      return this.executeNative(this.compiled.get(func), args);
    }

    // Bump the counter
    const count = (this.callCounts.get(func) || 0) + 1;
    this.callCounts.set(func, count);

    // Hot enough? Compile it
    if (count >= this.threshold) {
      const nativeCode = this.compile(func);
      this.compiled.set(func, nativeCode);
      return this.executeNative(nativeCode, args);
    }

    // Otherwise interpret
    return this.interpret(func, args);
  }
}

The threshold is a tuning parameter. Too low and you waste time compiling cold functions. Too high and hot functions run interpreted for too long. V8 uses different thresholds for different tiers.

Tiered compilation

Modern JIT compilers don't have just one tier — they have several, each trading compilation speed for code quality.

V8 (JavaScript):

  • Ignition — bytecode interpreter. Runs immediately, collects profiling data.
  • Sparkplug — baseline JIT. Very fast compilation, modest speedup. Translates bytecode directly to machine code with minimal optimization.
  • Maglev — mid-tier JIT. More optimization, takes longer to compile.
  • TurboFan — optimizing JIT. Full optimization pipeline (inlining, escape analysis, type specialization). Produces the fastest code but takes the most time to compile.

Java HotSpot:

  • Interpreter — runs bytecode, profiles.
  • C1 — client compiler. Fast compilation, basic optimizations.
  • C2 — server compiler. Aggressive optimization, slow compilation.

The idea is the same everywhere: most code only runs a few times, so interpreting it is fine. The code that runs a million times gets progressively better compilation.

First call:     Interpreter (instant start)
After 100:      Baseline JIT (1.5x speedup, compiles in microseconds)
After 10,000:   Optimizing JIT (10x speedup, compiles in milliseconds)

Baseline JIT: template compilation

The simplest JIT compiler maps each bytecode instruction to a fixed template of machine code. No analysis, no optimization — just mechanical translation.

function baselineCompile(bytecode) {
  const machineCode = [];

  for (const instr of bytecode) {
    switch (instr.op) {
      case 'LOAD_CONST':
        // Template: mov rax, <immediate>; push rax
        machineCode.push({ op: 'mov', dest: 'rax', src: instr.value });
        machineCode.push({ op: 'push', src: 'rax' });
        break;

      case 'ADD':
        // Template: pop rbx; pop rax; add rax, rbx; push rax
        machineCode.push({ op: 'pop', dest: 'rbx' });
        machineCode.push({ op: 'pop', dest: 'rax' });
        machineCode.push({ op: 'add', dest: 'rax', src: 'rbx' });
        machineCode.push({ op: 'push', src: 'rax' });
        break;

      case 'RETURN':
        // Template: pop rax; ret
        machineCode.push({ op: 'pop', dest: 'rax' });
        machineCode.push({ op: 'ret' });
        break;
    }
  }
  return machineCode;
}

This produces code that's still stack-based (lots of push/pop), but it eliminates the interpreter dispatch overhead. The switch on opcodes happens at compile time instead of every execution. Even this simple approach gives a 2-5x speedup.

Type specialization

Dynamic languages like JavaScript don't know types at compile time — a + b might be integer addition, floating-point addition, or string concatenation. The interpreter has to check types on every operation.

But the JIT compiler has profiling data. If it observes that add(x, y) has received integers for its last 10,000 calls, it can specialize the compiled code for integers:

function compileSpecialized(func, profile) {
  const code = [];

  for (const instr of func.bytecode) {
    if (instr.op === 'ADD') {
      const observedTypes = profile.getTypes(instr);

      if (observedTypes === 'int+int') {
        // Fast path: integer addition, no type checks
        code.push({ op: 'pop', dest: 'rbx' });
        code.push({ op: 'pop', dest: 'rax' });
        code.push({ op: 'add_int', dest: 'rax', src: 'rbx' });  // raw integer add
        code.push({ op: 'push', src: 'rax' });
        // Guard: if types change, bail out
        code.push({ op: 'guard_int', bailout: instr.offset });
      } else {
        // Slow path: generic addition with type dispatch
        code.push({ op: 'call', target: 'generic_add' });
      }
    }
  }
  return code;
}

Instead of checking types every time, the compiled code inserts a guard — a lightweight check that verifies the assumption still holds. If it does (the common case), execution flies through the fast path. If it doesn't, the guard triggers deoptimization.

Deoptimization

What happens when a type guard fails? The compiled code assumed integers, but suddenly gets a string. The JIT can't just crash — it has to deoptimize: throw away the compiled code and fall back to the interpreter.

class JITRuntime {
  deoptimize(compiledFunc, bailoutPoint) {
    // 1. Reconstruct the interpreter state from the compiled frame
    const interpreterState = this.reconstructState(compiledFunc, bailoutPoint);

    // 2. Invalidate the compiled code
    this.compiled.delete(compiledFunc.name);

    // 3. Resume in the interpreter at the bailout point
    return this.interpret(compiledFunc, interpreterState);
  }
}

Deoptimization is expensive but rare. In a well-behaved program, types are stable and guards almost never fail. This is the bet that JIT compilers make: optimize for the common case and pay a penalty for the uncommon one.

V8's TurboFan compiles code with dozens of speculative assumptions. If any of them break, the entire compiled function is thrown away and the system falls back to a lower tier. The profiler then gathers new data and may recompile later with different assumptions.

Tracing JIT

An alternative to method-based JIT is the tracing JIT, used by LuaJIT and early TraceMonkey (Firefox's first JS JIT).

Instead of compiling entire functions, a tracing JIT:

  1. Records a trace — follows the actual execution path through the code, recording every bytecode instruction that runs (including through function calls and branches).
  2. Compiles the trace — the recorded trace is a straight-line sequence of instructions with no branches (all branches were resolved during recording). This is extremely easy to optimize.
  3. Guards — at each point where the trace took a branch, insert a guard. If the guard fails, exit the trace and fall back to the interpreter.
// Original code:
for (let i = 0; i < 1000; i++) {
  if (arr[i] > 0) sum += arr[i];
  else sum -= arr[i];
}

// Recorded trace (assuming arr[i] > 0 was always true):
loop_start:
  guard i < 1000
  t = arr[i]
  guard t > 0         // assumes the if-branch
  sum = sum + t
  i = i + 1
  jump loop_start

The trace has no branches at all — just guards and straight-line code. The compiler can optimize it aggressively: keep everything in registers, eliminate bounds checks it can prove safe, unroll iterations.

The tradeoff: tracing works brilliantly for hot loops with predictable branches. It works poorly for code with many unpredictable branches (each different path needs its own trace).

Inline caches

Even without a full JIT compiler, inline caches (ICs) can dramatically speed up dynamic dispatch. The idea: at each call site, cache the result of the last method lookup.

In a dynamic language, obj.method() requires looking up method in the object's prototype chain — a hash table lookup that traverses multiple objects. With an inline cache:

// Without IC (every call):
//   1. Look up obj's type
//   2. Search prototype chain for "method"
//   3. Call the found function

// With IC (after first call):
//   1. Check: is obj's type the same as last time? (one comparison)
//   2. If yes: call the cached function directly
//   3. If no: slow lookup, update the cache

class InlineCache {
  constructor() {
    this.cachedType = null;
    this.cachedMethod = null;
  }

  lookup(obj, name) {
    if (obj.type === this.cachedType) {
      return this.cachedMethod;  // fast path: one comparison
    }
    // Slow path: full lookup
    const method = obj.lookupMethod(name);
    this.cachedType = obj.type;
    this.cachedMethod = method;
    return method;
  }
}

V8 takes this further with polymorphic inline caches that remember the last 2-4 types seen at a call site, and megamorphic caches that fall back to a hash table when too many types appear.

How the engines work

Here's how the major JavaScript engines put it all together:

V8 (Chrome, Node.js): Source is parsed to an AST, compiled to bytecode (Ignition), profiled, then hot functions are compiled by Sparkplug (baseline), Maglev (mid-tier), or TurboFan (optimizing). TurboFan uses a "sea of nodes" IR and performs type specialization, inlining, escape analysis, and register allocation before emitting machine code.

SpiderMonkey (Firefox): Bytecode interpreter with profiling, baseline JIT (for quick compilation), and IonMonkey optimizing JIT. IonMonkey does type inference across the whole script to guide specialization.

JavaScriptCore (Safari): Four tiers — LLInt (interpreter), Baseline JIT, DFG JIT (data flow graph, mid-tier optimization), and FTL JIT (faster than light, uses LLVM-style backend). JSC is notable for its use of concurrent compilation — the JIT runs on a background thread while the interpreter keeps going.

All three engines share the same core ideas: profiling, tiered compilation, type specialization, speculative optimization, and deoptimization. The differences are in implementation details and heuristics.

The JIT compilation pipeline

Putting it all together, here's the full lifecycle of code in a JIT-compiled language:

source code
  → parse → AST → bytecode
  → interpreter (profile types, count calls)
  → baseline JIT (template compile, fast)
  → optimizing JIT (inline, specialize, allocate registers)
  → native machine code
  → [guard fails] → deoptimize → back to interpreter
  → [re-profile] → recompile with new assumptions

It's a feedback loop. The runtime continuously adapts, compiling and decompiling code as the program's behavior evolves. A function that starts by processing integers and switches to strings will be deoptimized and recompiled. This adaptability is what makes JIT compilation so powerful — and so complex.

The next time your JavaScript runs at near-C speed, you'll know why: somewhere deep in the engine, a JIT compiler watched your code run, figured out what it actually does (not just what it might do), and generated machine code tailored to that specific behavior.

Try It Yourself — JIT Simulator

Enter a program with function calls and loops. The simulator shows how a JIT compiler profiles execution, promotes hot functions through compilation tiers, and handles deoptimization when type assumptions break.

Result