Programming Search⌘K

Conceptcore

Just-in-time compilation

Also called JIT, JIT compilation, dynamic compilation, adaptive optimization, tiered compilation.

Just-in-time compilation translates code after the program starts. A runtime interprets first, counts calls, and compiles hot code for the types it saw, with guards that fall back.

Applies to
core-languages

Idea

There are two traditional ways to run a program. A compiler translates it into another language, such as machine code, before it runs. An interpreter performs the same analyses but executes the program immediately. Just-in-time (JIT) compilation is translation that happens after the program begins to execute. It tries to get the benefits of both.1

Each side has something that the other lacks. Compiled programs run faster, especially when the compiler produces code that the hardware executes directly. Interpreted programs are usually smaller and more portable. An interpreter also sees information that exists only at run time: the input, the control flow, the machine it runs on, and the types of the values.1 A JIT system starts as an interpreter and collects that information. Then it compiles the parts of the program that run often, and it uses what it saw to make the compiled code faster.

The work of translation now happens while the user waits. Aycock calls this the primary constraint on a JIT system: it must not cause long pauses in the normal execution of the program.1 Every design choice in a JIT follows from this constraint. The system compiles only the code that will repay the cost, and it compiles cheaply first and expensively later.

How it works

Find the hot code

Data from empirical studies shows that most programs spend most of their time in a small part of their code.2 A JIT system finds that part with counters. Hansen's Adaptive FORTRAN of 1974 kept a frequency-of-execution counter for each block of code. When a counter crossed a threshold, the block became a candidate for the next level of optimization.3 HotSpot works the same way: with the default option -Xmixed, the interpreter executes all bytecode except hot methods, which are compiled to native code.9

The counter answers two questions: which code to compile, and when. The Self team found that the selection of the code mattered more than the trigger. Short methods are common in object-oriented code, so the method whose counter fired is often not the right one to compile. Its caller, with the hot method inlined, can be a better choice.4

Compile for what was seen

An interpreter for a dynamically typed language checks types on every operation, because x * x can multiply two integers, two floats, or two strings. A JIT compiler can specialize. The Self compilers produced a version of each method customized to its context. They had more type information than a static compiler, and the code they produced was much faster.4 Later Self systems gathered type information while the program ran, which Aycock calls type feedback, and used it when they recompiled a method.4 V8 does the same. During execution it tracks object shapes and types, and the optimizing compiler uses this data and the bytecode to generate speculative machine code.14

Guard and deoptimize

Specialized code is a bet. The compiler assumes that the types seen so far are the types that will come. A guard at the start of the code checks the assumption. When the guard fails, the system must continue with code that makes no assumption.

Moving from optimized code back to unoptimized code is called deoptimization. Hölzle, Chambers and Ungar described it in 1992 for the debugger of Self. Optimized code can be suspended only at interrupt points. At each of those points the compiler records enough information to rebuild the source-level state, and the system can convert an optimized activation into unoptimized ones on demand.16 V8 uses the same idea for speculation. Maglev attaches the abstract state of the interpreter's frame to each node that can deoptimize. The deoptimizer reads the values from the optimized frame and the machine registers and puts them where the interpreter expects them.15

Tiers

One compiler cannot be both cheap and thorough. Hansen already applied optimizations in stages, so that each crossing of a threshold added one more optimization to a block.3 The third-generation Self compiler first compiled methods with a fast, non-optimizing compiler and kept counters to decide when to recompile them.4 HotSpot and .NET call this tiered compilation, and V8 has several tiers too:

  • HotSpot. Tiered compilation was introduced in Java SE 7. Without it, the server VM collects profiling information in the interpreter. With it, the server VM also uses the client compiler to generate compiled methods that collect profiling information about themselves. These run much faster than the interpreter during the profiling phase.8
  • .NET. Tiered compilation moves methods through two tiers. The first tier generates code quickly without optimizations (quick JIT) or loads pre-compiled ReadyToRun code. The second tier generates optimized code in the background.10
  • V8. V8 first compiles all JavaScript to Ignition bytecode and interprets it.14 Sparkplug compiles bytecode to machine code in a single linear pass, with no intermediate representation, so it can compile almost whenever it wants.13 Maglev is a fast optimizing compiler, and TurboFan is the optimizing compiler for peak performance.14

A model engine

The program below has every part of a JIT, in miniature. The function is f(x) = x * x + 1, held as a tree (see Abstract syntax tree). Values are boxed with a type tag, as a sum type of Int and Float. The interpreter walks the tree on each call and checks the tags of both operands on each operation, as a Tree-walking interpreter does.

The engine counts calls in the interpreter and records the types of the arguments, which is its profile. At the threshold of three calls, it compiles. The model compiles to Closure, not to machine code: each node becomes a function that calls the functions of its children, so the tree is no longer walked. If the profile holds only int, the compiled code unboxes the argument once and works on raw integers with no tag checks inside. A guard at the entry protects the bet. When the guard fails, the engine discards the code, goes back to the interpreter, and keeps the profile. The next compilation sees both types and produces generic code.

from dataclasses import dataclass


# Values carry their type, as boxed values do in a dynamic language.
@dataclass(frozen=True)
class Int:
    n: int
    kind = "int"

    def __str__(self):
        return str(self.n)


@dataclass(frozen=True)
class Float:
    x: float
    kind = "float"

    def __str__(self):
        return str(self.x)


# The body of f(x) = x * x + 1 as a tree.
@dataclass(frozen=True)
class Num:
    value: int


@dataclass(frozen=True)
class Arg:
    pass


@dataclass(frozen=True)
class Bin:
    op: str
    left: object
    right: object


OPS = {"+": lambda a, b: a + b, "*": lambda a, b: a * b}


def arith(op, a, b):
    """Generic arithmetic: check both tags on every operation."""
    if isinstance(a, Int) and isinstance(b, Int):
        return Int(OPS[op](a.n, b.n))
    fa = float(a.n) if isinstance(a, Int) else a.x
    fb = float(b.n) if isinstance(b, Int) else b.x
    return Float(OPS[op](fa, fb))


def interpret(node, arg):
    """The interpreter: walk the tree on every call."""
    match node:
        case Num(value):
            return Int(value)
        case Arg():
            return arg
        case Bin(op, left, right):
            return arith(op, interpret(left, arg), interpret(right, arg))


def compile_int(node):
    """Compiled code for int: closures over raw ints, no tag checks inside."""
    match node:
        case Num(value):
            return lambda n: value
        case Arg():
            return lambda n: n
        case Bin(op, left, right):
            f, l, r = OPS[op], compile_int(left), compile_int(right)
            return lambda n: f(l(n), r(n))


def compile_generic(node):
    """Compiled code for any argument: closures that still check tags."""
    match node:
        case Num(value):
            boxed = Int(value)
            return lambda a: boxed
        case Arg():
            return lambda a: a
        case Bin(op, left, right):
            l, r = compile_generic(left), compile_generic(right)
            return lambda a: arith(op, l(a), r(a))


THRESHOLD = 3


class Function:
    def __init__(self, name, body):
        self.name, self.body = name, body
        self.calls = 0  # calls in the interpreter since the last compilation
        self.seen = set()  # the profile: the kinds of the arguments
        self.code = None  # compiled code, or None
        self.counts = {"interpreter": 0, "compiled": 0, "deoptimizations": 0}

    def compile(self):
        if self.seen == {"int"}:
            raw = compile_int(self.body)

            def code(arg):
                if not isinstance(arg, Int):  # the guard
                    return None
                return Int(raw(arg.n))  # unbox once, compute, box the result

            self.code, self.kind, how = code, "int", "specialized for int"
        else:
            self.code, self.kind, how = compile_generic(self.body), "generic", "generic"
        print(f"* compile {self.name}: arguments seen: {', '.join(sorted(self.seen))}; {how}")

    def __call__(self, arg):
        if self.code is None and self.calls >= THRESHOLD:
            self.compile()
        if self.code is not None:
            result = self.code(arg)
            if result is not None:
                self.counts["compiled"] += 1
                return result, f"compiled, {self.kind}"
            print(f"* deoptimize {self.name}: guard failed, {arg} is not an int")
            self.counts["deoptimizations"] += 1
            self.code, self.calls = None, 0
        self.calls += 1
        self.counts["interpreter"] += 1
        self.seen.add(arg.kind)
        return interpret(self.body, arg), f"interpreter, call {self.calls}"


f = Function("f", Bin("+", Bin("*", Arg(), Arg()), Num(1)))
for arg in [Int(1), Int(2), Int(3), Int(4), Float(2.5), Int(6), Int(7), Int(8)]:
    result, tier = f(arg)
    print(f"f({arg}) = {result} [{tier}]")
print(", ".join(f"{k}: {v}" for k, v in f.counts.items()))
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1

The log shows the life of a function in a JIT. The first calls run in the interpreter while the profile grows. The compiled code runs f(4). The float argument fails the guard, and that call runs in the interpreter. The profile now holds two types, so the second compilation produces generic code that never deoptimizes for this reason.

The model places its guard at the entry, so the interpreter can always restart the call from the beginning. A real JIT also places guards in the middle of compiled code, for example after an inlined call. There the deoptimizer must rebuild the interpreter's frame from the optimized one, which is the hard part of the technique.1516

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNative
GoIdiom
RustIdiom
KotlinNative
SQLDoes not applyA query language has no way to compile its own code; whether queries are compiled at run time is a property of the database engine.
BashIdiomA script can generate the text of a function at run time and define it with eval, but every value is a string and the generated code runs in the same shell interpreter. Alternative: A JIT engine written in a general language, called from the script.
PowerShellIdiomA script can hold the tree in hashtables, interpret it, and build script blocks as compiled code once a function is hot; no example file because PowerShell is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup is not executed as code.
CSSDoes not applyStyle rules are not executed as code.
Regular expressionsDoes not applyA pattern language has no user code to compile; a regex engine may compile patterns at run time, as Thompson did in 1968.

JIT compilation is a property of an implementation, not of a language. The table describes the main implementation of each language. Each example builds the model engine above and prints the same log. The Java example also asks HotSpot for the name of its compilation system, and the Python example shows CPython specializing its own bytecode.

Language Verdict Form
Java native HotSpot interprets bytecode and compiles hot methods; tiered compilation is on by default in the server VM
Kotlin native on the JVM, the same HotSpot tiers as Java
C# native the runtime compiles CIL to native code; tiered compilation with quick JIT, then an optimizing JIT in the background
JavaScript native V8: Ignition bytecode interpreter, Sparkplug, Maglev and TurboFan
TypeScript native runs as JavaScript on the same engines
Python idiom CPython specializes bytecode in its interpreter (PEP 659); its JIT compiler is experimental and not in the default build (PEP 744)
Go idiom compiled ahead of time; the engine is an ordinary program
Rust idiom compiled ahead of time; an enum for values and boxed closures for compiled code
C idiom compiled ahead of time; a tagged union for values and a tree of nodes for compiled code
C++ idiom compiled ahead of time; std::variant for values and std::function for compiled code
PowerShell idiom an engine written as a script (no example: pwsh is not installed)
Bash idiom a script can generate the text of a function at run time and define it with eval
SQL n/a whether queries are compiled at run time is a property of the database engine
Regex n/a the language has no user code to compile; a regex engine may compile patterns at run time
HTML/CSS n/a markup and style rules are not executed as code
PythonGitHub
from dataclasses import dataclass


# Values carry their type, as boxed values do in a dynamic language.
@dataclass(frozen=True)
class Int:
    n: int
    kind = "int"

    def __str__(self):
        return str(self.n)


@dataclass(frozen=True)
class Float:
    x: float
    kind = "float"

    def __str__(self):
        return str(self.x)


# The body of f(x) = x * x + 1 as a tree.
@dataclass(frozen=True)
class Num:
    value: int


@dataclass(frozen=True)
class Arg:
    pass


@dataclass(frozen=True)
class Bin:
    op: str
    left: object
    right: object


OPS = {"+": lambda a, b: a + b, "*": lambda a, b: a * b}


def arith(op, a, b):
    """Generic arithmetic: check both tags on every operation."""
    if isinstance(a, Int) and isinstance(b, Int):
        return Int(OPS[op](a.n, b.n))
    fa = float(a.n) if isinstance(a, Int) else a.x
    fb = float(b.n) if isinstance(b, Int) else b.x
    return Float(OPS[op](fa, fb))


def interpret(node, arg):
    """The interpreter: walk the tree on every call."""
    match node:
        case Num(value):
            return Int(value)
        case Arg():
            return arg
        case Bin(op, left, right):
            return arith(op, interpret(left, arg), interpret(right, arg))


def compile_int(node):
    """Compiled code for int: closures over raw ints, no tag checks inside."""
    match node:
        case Num(value):
            return lambda n: value
        case Arg():
            return lambda n: n
        case Bin(op, left, right):
            f, l, r = OPS[op], compile_int(left), compile_int(right)
            return lambda n: f(l(n), r(n))


def compile_generic(node):
    """Compiled code for any argument: closures that still check tags."""
    match node:
        case Num(value):
            boxed = Int(value)
            return lambda a: boxed
        case Arg():
            return lambda a: a
        case Bin(op, left, right):
            l, r = compile_generic(left), compile_generic(right)
            return lambda a: arith(op, l(a), r(a))


THRESHOLD = 3


class Function:
    def __init__(self, name, body):
        self.name, self.body = name, body
        self.calls = 0  # calls in the interpreter since the last compilation
        self.seen = set()  # the profile: the kinds of the arguments
        self.code = None  # compiled code, or None
        self.counts = {"interpreter": 0, "compiled": 0, "deoptimizations": 0}

    def compile(self):
        if self.seen == {"int"}:
            raw = compile_int(self.body)

            def code(arg):
                if not isinstance(arg, Int):  # the guard
                    return None
                return Int(raw(arg.n))  # unbox once, compute, box the result

            self.code, self.kind, how = code, "int", "specialized for int"
        else:
            self.code, self.kind, how = compile_generic(self.body), "generic", "generic"
        print(f"* compile {self.name}: arguments seen: {', '.join(sorted(self.seen))}; {how}")

    def __call__(self, arg):
        if self.code is None and self.calls >= THRESHOLD:
            self.compile()
        if self.code is not None:
            result = self.code(arg)
            if result is not None:
                self.counts["compiled"] += 1
                return result, f"compiled, {self.kind}"
            print(f"* deoptimize {self.name}: guard failed, {arg} is not an int")
            self.counts["deoptimizations"] += 1
            self.code, self.calls = None, 0
        self.calls += 1
        self.counts["interpreter"] += 1
        self.seen.add(arg.kind)
        return interpret(self.body, arg), f"interpreter, call {self.calls}"


f = Function("f", Bin("+", Bin("*", Arg(), Arg()), Num(1)))
for arg in [Int(1), Int(2), Int(3), Int(4), Float(2.5), Int(6), Int(7), Int(8)]:
    result, tier = f(arg)
    print(f"f({arg}) = {result} [{tier}]")
print(", ".join(f"{k}: {v}" for k, v in f.counts.items()))
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1

The second program shows the same idea inside CPython. The specializing interpreter of PEP 659 rewrites a generic instruction into a form for the types that it sees, and dis.get_instructions(..., adaptive=True) shows the rewritten instructions. The instruction names depend on the version of CPython that recorded the output.

import dis
import sys


def f(x):
    return x * x + 1


def binary_ops(func):
    return [i.opname for i in dis.get_instructions(func, adaptive=True) if i.opname.startswith("BINARY_OP")]


print(f"version: {sys.version_info.major}.{sys.version_info.minor}")
print("before any call:", binary_ops(f))
for i in range(100):
    f(i)
print("after 100 int calls:", binary_ops(f))
for i in range(100):
    f(i + 0.5)
print("after 100 float calls:", binary_ops(f))
Output
version: 3.14
before any call: ['BINARY_OP', 'BINARY_OP']
after 100 int calls: ['BINARY_OP_MULTIPLY_INT', 'BINARY_OP_ADD_INT']
after 100 float calls: ['BINARY_OP_MULTIPLY_FLOAT', 'BINARY_OP_EXTEND']
  • Verdict: idiom. CPython specializes instructions in its interpreter for the types that it sees (PEP 659). Its JIT compiler is experimental, is not part of the default build, and PEP 744 says that it should not be used in production while it is experimental.
  • In the recorded adaptive output, the two BINARY_OP instructions become forms for int after the int calls. After the float calls they change again. This is the same cycle as the model: specialize for the types seen, see a type that does not fit, and specialize again.
  • dis calls the bytecode an implementation detail. A program must not depend on the names of the specialized instructions.
  • The model keeps the profile in a set and sorts it before it prints, because the order of a set of strings can change from run to run.
#include <array>
#include <functional>
#include <iostream>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include <variant>
#include <vector>

// Values carry their type, as boxed values do in a dynamic language.
using Value = std::variant<long, double>;

std::string kind(const Value& v) { return std::holds_alternative<long>(v) ? "int" : "float"; }

std::string show(const Value& v) {
    std::ostringstream out;
    std::visit([&out](auto x) { out << x; }, v);
    return out.str();
}

// The body of f(x) = x * x + 1 as a tree.
struct Node {
    enum Tag { Num, Arg, Bin } tag;
    long num = 0;
    char op = 0;
    std::shared_ptr<Node> left, right;
};

// Generic arithmetic: check both tags on every operation.
Value arith(char op, const Value& a, const Value& b) {
    return std::visit(
        [op](auto x, auto y) -> Value {
            if (op == '+') return x + y;  // long + long is long; a double makes it double
            return x * y;
        },
        a, b);
}

// The interpreter: walk the tree on every call.
Value interpret(const Node& n, const Value& arg) {
    switch (n.tag) {
    case Node::Num: return n.num;
    case Node::Arg: return arg;
    default: return arith(n.op, interpret(*n.left, arg), interpret(*n.right, arg));
    }
}

// Compiled code for int: closures over raw longs, no tag checks inside.
std::function<long(long)> compile_int(const Node& n) {
    switch (n.tag) {
    case Node::Num: return [v = n.num](long) { return v; };
    case Node::Arg: return [](long x) { return x; };
    default: {
        auto l = compile_int(*n.left), r = compile_int(*n.right);
        if (n.op == '+') return [l, r](long x) { return l(x) + r(x); };
        return [l, r](long x) { return l(x) * r(x); };
    }
    }
}

// Compiled code for any argument: closures that still check tags.
std::function<Value(const Value&)> compile_generic(const Node& n) {
    switch (n.tag) {
    case Node::Num: return [v = Value(n.num)](const Value&) { return v; };
    case Node::Arg: return [](const Value& a) { return a; };
    default: {
        auto l = compile_generic(*n.left), r = compile_generic(*n.right);
        return [op = n.op, l, r](const Value& a) { return arith(op, l(a), r(a)); };
    }
    }
}

constexpr int THRESHOLD = 3;

// Compiled code; it returns std::nullopt when the guard fails.
using Code = std::function<std::optional<Value>(const Value&)>;

class JitFunction {
public:
    JitFunction(std::string name, Node body) : name_(std::move(name)), body_(std::move(body)) {}

    std::pair<Value, std::string> call(const Value& arg) {
        if (!code_ && calls_ >= THRESHOLD) compile();
        if (code_) {
            if (auto result = code_(arg)) {
                counts_[1]++;
                return {*result, "compiled, " + code_kind_};
            }
            std::cout << "* deoptimize " << name_ << ": guard failed, " << show(arg) << " is not an int\n";
            counts_[2]++;
            code_ = nullptr;
            calls_ = 0;
        }
        calls_++;
        counts_[0]++;
        seen_.insert(kind(arg));
        return {interpret(body_, arg), "interpreter, call " + std::to_string(calls_)};
    }

    const std::array<int, 3>& counts() const { return counts_; }

private:
    void compile() {
        std::string how;
        if (seen_ == std::set<std::string>{"int"}) {
            code_ = [raw = compile_int(body_)](const Value& a) -> std::optional<Value> {
                if (auto n = std::get_if<long>(&a)) return Value(raw(*n));  // the guard
                return std::nullopt;
            };
            code_kind_ = "int";
            how = "specialized for int";
        } else {
            code_ = [generic = compile_generic(body_)](const Value& a) -> std::optional<Value> { return generic(a); };
            code_kind_ = how = "generic";
        }
        std::string kinds;
        for (const auto& k : seen_) kinds += (kinds.empty() ? "" : ", ") + k;
        std::cout << "* compile " << name_ << ": arguments seen: " << kinds << "; " << how << "\n";
    }

    std::string name_;
    Node body_;
    int calls_ = 0;               // calls in the interpreter since the last compilation
    std::set<std::string> seen_;  // the profile: the kinds of the arguments
    Code code_;                   // compiled code, or empty
    std::string code_kind_;
    std::array<int, 3> counts_{};  // interpreter, compiled, deoptimizations
};

int main() {
    auto x = std::make_shared<Node>(Node{.tag = Node::Arg});
    auto one = std::make_shared<Node>(Node{.tag = Node::Num, .num = 1});
    auto square = std::make_shared<Node>(Node{Node::Bin, 0, '*', x, x});
    JitFunction f("f", Node{Node::Bin, 0, '+', square, one});

    std::vector<Value> inputs{1L, 2L, 3L, 4L, 2.5, 6L, 7L, 8L};
    for (const auto& arg : inputs) {
        auto [result, tier] = f.call(arg);
        std::cout << "f(" << show(arg) << ") = " << show(result) << " [" << tier << "]\n";
    }
    auto [i, c, d] = f.counts();
    std::cout << "interpreter: " << i << ", compiled: " << c << ", deoptimizations: " << d << "\n";
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: idiom. C++ compiles ahead of time to machine code, so a JIT is something a program builds, as here.
  • Value is a std::variant<long, double>, a sum type from the standard library. std::get_if<long> is the guard: it returns a null pointer when the value holds a double.
  • arith calls std::visit with a generic lambda. The compiler makes one copy of the lambda for each pair of types, and the usual arithmetic conversions make long * double a double.
  • Compiled code is a std::function that holds a lambda. Each lambda captures the code of its children by value, so the tree of closures owns itself.
JavaGitHub
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.function.LongBinaryOperator;
import java.util.function.LongUnaryOperator;
import java.util.function.UnaryOperator;

public class Main {
    // Values carry their type, as boxed values do in a dynamic language.
    sealed interface Value permits IntV, FloatV {}
    record IntV(long n) implements Value { public String toString() { return Long.toString(n); } }
    record FloatV(double x) implements Value { public String toString() { return Double.toString(x); } }

    // The body of f(x) = x * x + 1 as a tree.
    sealed interface Node permits Num, Arg, Bin {}
    record Num(long value) implements Node {}
    record Arg() implements Node {}
    record Bin(char op, Node left, Node right) implements Node {}

    static LongBinaryOperator intOp(char op) { return op == '+' ? Long::sum : (a, b) -> a * b; }

    static double asDouble(Value v) {
        return switch (v) {
            case IntV i -> i.n();
            case FloatV f -> f.x();
        };
    }

    // Generic arithmetic: check both tags on every operation.
    static Value arith(char op, Value a, Value b) {
        if (a instanceof IntV(long x) && b instanceof IntV(long y)) return new IntV(intOp(op).applyAsLong(x, y));
        double x = asDouble(a), y = asDouble(b);
        return new FloatV(op == '+' ? x + y : x * y);
    }

    // The interpreter: walk the tree on every call.
    static Value interpret(Node node, Value arg) {
        return switch (node) {
            case Num n -> new IntV(n.value());
            case Arg a -> arg;
            case Bin(char op, Node l, Node r) -> arith(op, interpret(l, arg), interpret(r, arg));
        };
    }

    // Compiled code for int: closures over raw longs, no tag checks inside.
    static LongUnaryOperator compileInt(Node node) {
        return switch (node) {
            case Num n -> { long v = n.value(); yield x -> v; }
            case Arg a -> x -> x;
            case Bin(char op, Node l, Node r) -> {
                LongBinaryOperator f = intOp(op);
                LongUnaryOperator cl = compileInt(l), cr = compileInt(r);
                yield x -> f.applyAsLong(cl.applyAsLong(x), cr.applyAsLong(x));
            }
        };
    }

    // Compiled code for any argument: closures that still check tags.
    static UnaryOperator<Value> compileGeneric(Node node) {
        return switch (node) {
            case Num n -> { Value boxed = new IntV(n.value()); yield a -> boxed; }
            case Arg a -> x -> x;
            case Bin(char op, Node l, Node r) -> {
                UnaryOperator<Value> cl = compileGeneric(l), cr = compileGeneric(r);
                yield a -> arith(op, cl.apply(a), cr.apply(a));
            }
        };
    }

    static final int THRESHOLD = 3;

    static final class JitFunction {
        final String name;
        final Node body;
        int calls = 0; // calls in the interpreter since the last compilation
        final TreeSet<String> seen = new TreeSet<>(); // the profile: the kinds of the arguments
        UnaryOperator<Value> code = null; // compiled code; it returns null when the guard fails
        String kind = "";
        final Map<String, Integer> counts = new LinkedHashMap<>();

        JitFunction(String name, Node body) {
            this.name = name;
            this.body = body;
            for (String k : List.of("interpreter", "compiled", "deoptimizations")) counts.put(k, 0);
        }

        void compile() {
            String how;
            if (seen.equals(new TreeSet<>(List.of("int")))) {
                LongUnaryOperator raw = compileInt(body);
                code = a -> a instanceof IntV(long n) ? new IntV(raw.applyAsLong(n)) : null; // the guard
                kind = "int";
                how = "specialized for int";
            } else {
                code = compileGeneric(body);
                kind = how = "generic";
            }
            System.out.println("* compile " + name + ": arguments seen: " + String.join(", ", seen) + "; " + how);
        }

        String[] call(Value arg) {
            if (code == null && calls >= THRESHOLD) compile();
            if (code != null) {
                Value result = code.apply(arg);
                if (result != null) {
                    counts.merge("compiled", 1, Integer::sum);
                    return new String[] {result.toString(), "compiled, " + kind};
                }
                System.out.println("* deoptimize " + name + ": guard failed, " + arg + " is not an int");
                counts.merge("deoptimizations", 1, Integer::sum);
                code = null;
                calls = 0;
            }
            calls++;
            counts.merge("interpreter", 1, Integer::sum);
            seen.add(arg instanceof IntV ? "int" : "float");
            return new String[] {interpret(body, arg).toString(), "interpreter, call " + calls};
        }
    }

    public static void main(String[] args) {
        JitFunction f = new JitFunction("f", new Bin('+', new Bin('*', new Arg(), new Arg()), new Num(1)));
        List<Value> inputs = List.of(new IntV(1), new IntV(2), new IntV(3), new IntV(4),
                new FloatV(2.5), new IntV(6), new IntV(7), new IntV(8));
        for (Value arg : inputs) {
            String[] r = f.call(arg);
            System.out.println("f(" + arg + ") = " + r[0] + " [" + r[1] + "]");
        }
        List<String> parts = new ArrayList<>();
        f.counts.forEach((k, v) -> parts.add(k + ": " + v));
        System.out.println(String.join(", ", parts));
    }
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1

The second program asks the running JVM about its own compilation system. getCompilationMXBean returns null when the JVM has no compilation system, for example when it runs with -Xint.

import java.lang.management.CompilationMXBean;
import java.lang.management.ManagementFactory;

public class Main {
    public static void main(String[] args) {
        CompilationMXBean jit = ManagementFactory.getCompilationMXBean();
        System.out.println("compiler: " + (jit == null ? "none" : jit.getName()));
        System.out.println("mode: " + System.getProperty("java.vm.info"));
    }
}
Output
compiler: HotSpot 64-Bit Tiered Compilers
mode: mixed mode, sharing
  • Verdict: native. HotSpot interprets bytecode and compiles hot methods to native code. This mixed mode is the default, and -Xint turns compilation off.
  • The name that HotSpot reports for its compilation system says that the compilers are tiered. Tiered compilation is on by default in the server VM.
  • Sealed interfaces and record patterns model the values and the tree. a instanceof IntV(long n) is the guard: it tests the tag and unboxes the value in one step.
  • LongUnaryOperator works on primitive long values, so the compiled code for int does not box its intermediate results.
#include <stdio.h>
#include <stdlib.h>

/* Values carry their type, as boxed values do in a dynamic language. */
typedef enum { INT, FLOAT } Kind;
typedef struct {
    Kind kind;
    union {
        long i;
        double f;
    } as;
} Value;

static Value int_value(long i) { return (Value){INT, {.i = i}}; }
static Value float_value(double f) { return (Value){FLOAT, {.f = f}}; }
static double as_double(Value v) { return v.kind == INT ? (double)v.as.i : v.as.f; }

static void print_value(Value v) {
    if (v.kind == INT) printf("%ld", v.as.i);
    else printf("%g", v.as.f);
}

/* The body of f(x) = x * x + 1 as a tree. */
typedef enum { NUM, ARG, BIN } Tag;
typedef struct Node {
    Tag tag;
    long num;
    char op;
    const struct Node *left, *right;
} Node;

/* Generic arithmetic: check both tags on every operation. */
static Value arith(char op, Value a, Value b) {
    if (a.kind == INT && b.kind == INT)
        return int_value(op == '+' ? a.as.i + b.as.i : a.as.i * b.as.i);
    double x = as_double(a), y = as_double(b);
    return float_value(op == '+' ? x + y : x * y);
}

/* The interpreter: walk the tree on every call. */
static Value interpret(const Node *n, Value arg) {
    switch (n->tag) {
    case NUM: return int_value(n->num);
    case ARG: return arg;
    default: return arith(n->op, interpret(n->left, arg), interpret(n->right, arg));
    }
}

/* Compiled code: a tree of nodes, each with a pointer to the function that
   runs it. The int code works on raw longs and has no tag checks inside. */
typedef struct Code {
    long (*run_int)(const struct Code *, long);
    Value (*run_generic)(const struct Code *, Value);
    long num;
    char op;
    struct Code *left, *right;
} Code;

static long int_num(const Code *c, long x) { (void)x; return c->num; }
static long int_arg(const Code *c, long x) { (void)c; return x; }
static long int_add(const Code *c, long x) { return c->left->run_int(c->left, x) + c->right->run_int(c->right, x); }
static long int_mul(const Code *c, long x) { return c->left->run_int(c->left, x) * c->right->run_int(c->right, x); }

static Value gen_num(const Code *c, Value a) { (void)a; return int_value(c->num); }
static Value gen_arg(const Code *c, Value a) { (void)c; return a; }
static Value gen_bin(const Code *c, Value a) {
    return arith(c->op, c->left->run_generic(c->left, a), c->right->run_generic(c->right, a));
}

static Code *compile(const Node *n, int for_int) {
    Code *c = calloc(1, sizeof *c);
    if (c == NULL) abort();
    c->num = n->num;
    c->op = n->op;
    if (n->tag == BIN) {
        c->left = compile(n->left, for_int);
        c->right = compile(n->right, for_int);
    }
    if (for_int) /* choose the int function for each node now, once */
        c->run_int = n->tag == NUM ? int_num : n->tag == ARG ? int_arg : n->op == '+' ? int_add : int_mul;
    else
        c->run_generic = n->tag == NUM ? gen_num : n->tag == ARG ? gen_arg : gen_bin;
    return c;
}

static void free_code(Code *c) {
    if (c == NULL) return;
    free_code(c->left);
    free_code(c->right);
    free(c);
}

enum { THRESHOLD = 3 };

typedef struct {
    const char *name;
    const Node *body;
    int calls;       /* calls in the interpreter since the last compilation */
    int seen_int;    /* the profile: the kinds of the arguments */
    int seen_float;
    Code *code;      /* compiled code, or NULL */
    int code_is_int; /* 1 if the code is specialized for int */
    int counts[3];   /* interpreter, compiled, deoptimizations */
} Function;

static void jit_compile(Function *f) {
    f->code_is_int = f->seen_int && !f->seen_float;
    f->code = compile(f->body, f->code_is_int);
    printf("* compile %s: arguments seen: %s; %s\n", f->name,
           f->seen_float ? (f->seen_int ? "float, int" : "float") : "int",
           f->code_is_int ? "specialized for int" : "generic");
}

/* Calls f and writes the tier that ran it into tier. */
static Value call(Function *f, Value arg, char *tier, size_t size) {
    if (f->code == NULL && f->calls >= THRESHOLD) jit_compile(f);
    if (f->code != NULL) {
        if (!f->code_is_int) {
            f->counts[1]++;
            snprintf(tier, size, "compiled, generic");
            return f->code->run_generic(f->code, arg);
        }
        if (arg.kind == INT) { /* the guard */
            f->counts[1]++;
            snprintf(tier, size, "compiled, int");
            return int_value(f->code->run_int(f->code, arg.as.i));
        }
        printf("* deoptimize %s: guard failed, ", f->name);
        print_value(arg);
        printf(" is not an int\n");
        f->counts[2]++;
        free_code(f->code);
        f->code = NULL;
        f->calls = 0;
    }
    f->calls++;
    f->counts[0]++;
    if (arg.kind == INT) f->seen_int = 1;
    else f->seen_float = 1;
    snprintf(tier, size, "interpreter, call %d", f->calls);
    return interpret(f->body, arg);
}

int main(void) {
    const Node x = {ARG, 0, 0, NULL, NULL};
    const Node one = {NUM, 1, 0, NULL, NULL};
    const Node square = {BIN, 0, '*', &x, &x};
    const Node body = {BIN, 0, '+', &square, &one};
    Function f = {"f", &body, 0, 0, 0, NULL, 0, {0, 0, 0}};

    Value inputs[] = {int_value(1), int_value(2), int_value(3), int_value(4),
                      float_value(2.5), int_value(6), int_value(7), int_value(8)};
    char tier[32];
    for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; i++) {
        Value result = call(&f, inputs[i], tier, sizeof tier);
        printf("f(");
        print_value(inputs[i]);
        printf(") = ");
        print_value(result);
        printf(" [%s]\n", tier);
    }
    printf("interpreter: %d, compiled: %d, deoptimizations: %d\n", f.counts[0], f.counts[1], f.counts[2]);
    free_code(f.code);
    return 0;
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: idiom. C compiles ahead of time to machine code, so a JIT is something a program builds, as here.
  • C has no closures. Compiled code is a tree of Code structs, and each struct holds a pointer to the function that runs it. compile chooses that function once, so the run does not test the node tag again.
  • Value is a tagged union, the C form of a sum type. The guard is a test of the tag, arg.kind == INT, before the code reads arg.as.i.
  • The program owns the memory of the compiled code. A deoptimization frees the old tree with free_code before the function returns to the interpreter.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

var f = new JitFunction("f", new Bin('+', new Bin('*', new Arg(), new Arg()), new Num(1)));
Value[] inputs = [new IntV(1), new IntV(2), new IntV(3), new IntV(4), new FloatV(2.5), new IntV(6), new IntV(7), new IntV(8)];
foreach (var arg in inputs)
{
    var (result, tier) = f.Call(arg);
    Console.WriteLine($"f({arg}) = {result} [{tier}]");
}
Console.WriteLine(string.Join(", ", f.Counts.Select(kv => $"{kv.Key}: {kv.Value}")));

// Values carry their type, as boxed values do in a dynamic language.
abstract record Value;
record IntV(long N) : Value { public override string ToString() => N.ToString(CultureInfo.InvariantCulture); }
record FloatV(double X) : Value { public override string ToString() => X.ToString(CultureInfo.InvariantCulture); }

// The body of f(x) = x * x + 1 as a tree.
abstract record Node;
record Num(long Value) : Node;
record Arg : Node;
record Bin(char Op, Node Left, Node Right) : Node;

static class Engine
{
    public static Func<long, long, long> IntOp(char op) => op == '+' ? (a, b) => a + b : (a, b) => a * b;

    static double AsDouble(Value v) => v switch
    {
        IntV i => i.N,
        FloatV x => x.X,
        _ => throw new ArgumentException("unknown value"),
    };

    // Generic arithmetic: check both tags on every operation.
    public static Value Arith(char op, Value a, Value b)
    {
        if (a is IntV x && b is IntV y) return new IntV(IntOp(op)(x.N, y.N));
        double p = AsDouble(a), q = AsDouble(b);
        return new FloatV(op == '+' ? p + q : p * q);
    }

    // The interpreter: walk the tree on every call.
    public static Value Interpret(Node node, Value arg) => node switch
    {
        Num n => new IntV(n.Value),
        Arg => arg,
        Bin b => Arith(b.Op, Interpret(b.Left, arg), Interpret(b.Right, arg)),
        _ => throw new ArgumentException("unknown node"),
    };

    // Compiled code for int: delegates over raw longs, no tag checks inside.
    public static Func<long, long> CompileInt(Node node)
    {
        switch (node)
        {
            case Num n: { long v = n.Value; return _ => v; }
            case Arg: return x => x;
            case Bin b:
                var f = IntOp(b.Op);
                var l = CompileInt(b.Left);
                var r = CompileInt(b.Right);
                return x => f(l(x), r(x));
            default: throw new ArgumentException("unknown node");
        }
    }

    // Compiled code for any argument: delegates that still check tags.
    public static Func<Value, Value> CompileGeneric(Node node)
    {
        switch (node)
        {
            case Num n: { Value boxed = new IntV(n.Value); return _ => boxed; }
            case Arg: return a => a;
            case Bin b:
                var l = CompileGeneric(b.Left);
                var r = CompileGeneric(b.Right);
                return a => Arith(b.Op, l(a), r(a));
            default: throw new ArgumentException("unknown node");
        }
    }
}

class JitFunction(string name, Node body)
{
    const int Threshold = 3;
    int calls; // calls in the interpreter since the last compilation
    readonly SortedSet<string> seen = new(StringComparer.Ordinal); // the profile: the kinds of the arguments
    Func<Value, Value?>? code; // compiled code; it returns null when the guard fails
    string kind = "";
    public Dictionary<string, int> Counts { get; } = new() { ["interpreter"] = 0, ["compiled"] = 0, ["deoptimizations"] = 0 };

    void Compile()
    {
        string how;
        if (seen.SetEquals(["int"]))
        {
            var raw = Engine.CompileInt(body);
            code = a => a is IntV i ? new IntV(raw(i.N)) : null; // the guard
            kind = "int";
            how = "specialized for int";
        }
        else
        {
            code = Engine.CompileGeneric(body);
            kind = how = "generic";
        }
        Console.WriteLine($"* compile {name}: arguments seen: {string.Join(", ", seen)}; {how}");
    }

    public (Value, string) Call(Value arg)
    {
        if (code is null && calls >= Threshold) Compile();
        if (code is not null)
        {
            var result = code(arg);
            if (result is not null)
            {
                Counts["compiled"]++;
                return (result, $"compiled, {kind}");
            }
            Console.WriteLine($"* deoptimize {name}: guard failed, {arg} is not an int");
            Counts["deoptimizations"]++;
            code = null;
            calls = 0;
        }
        calls++;
        Counts["interpreter"]++;
        seen.Add(arg is IntV ? "int" : "float");
        return (Engine.Interpret(body, arg), $"interpreter, call {calls}");
    }
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: native. The .NET runtime compiles CIL to native code just in time. With tiered compilation, which is on by default, a method gets quick code first and optimized code later, generated in the background.
  • a is IntV i is the guard. The pattern tests the type and binds the unboxed value in one step.
  • Func<long, long> delegates over long values keep the compiled code for int free of boxing.
  • The records print their numbers with CultureInfo.InvariantCulture, so 2.5 prints the same way under every culture setting of the machine.
JavaScriptGitHub
// Values carry their type, as boxed values do inside a JavaScript engine.
const int = (n) => ({ kind: "int", n });
const float = (x) => ({ kind: "float", x });
const show = (v) => String(v.kind === "int" ? v.n : v.x);

// The body of f(x) = x * x + 1 as a tree.
const num = (value) => ({ type: "num", value });
const arg = { type: "arg" };
const bin = (op, left, right) => ({ type: "bin", op, left, right });

const OPS = { "+": (a, b) => a + b, "*": (a, b) => a * b };

// Generic arithmetic: check both tags on every operation.
function arith(op, a, b) {
  if (a.kind === "int" && b.kind === "int") return int(OPS[op](a.n, b.n));
  const fa = a.kind === "int" ? a.n : a.x;
  const fb = b.kind === "int" ? b.n : b.x;
  return float(OPS[op](fa, fb));
}

// The interpreter: walk the tree on every call.
function interpret(node, x) {
  switch (node.type) {
    case "num": return int(node.value);
    case "arg": return x;
    case "bin": return arith(node.op, interpret(node.left, x), interpret(node.right, x));
  }
}

// Compiled code for int: closures over raw numbers, no tag checks inside.
function compileInt(node) {
  switch (node.type) {
    case "num": { const v = node.value; return () => v; }
    case "arg": return (n) => n;
    case "bin": {
      const f = OPS[node.op], l = compileInt(node.left), r = compileInt(node.right);
      return (n) => f(l(n), r(n));
    }
  }
}

// Compiled code for any argument: closures that still check tags.
function compileGeneric(node) {
  switch (node.type) {
    case "num": { const boxed = int(node.value); return () => boxed; }
    case "arg": return (a) => a;
    case "bin": {
      const op = node.op, l = compileGeneric(node.left), r = compileGeneric(node.right);
      return (a) => arith(op, l(a), r(a));
    }
  }
}

const THRESHOLD = 3;

class JitFunction {
  constructor(name, body) {
    this.name = name;
    this.body = body;
    this.calls = 0; // calls in the interpreter since the last compilation
    this.seen = new Set(); // the profile: the kinds of the arguments
    this.code = null; // compiled code, or null
    this.counts = { interpreter: 0, compiled: 0, deoptimizations: 0 };
  }

  compile() {
    let how;
    if (this.seen.size === 1 && this.seen.has("int")) {
      const raw = compileInt(this.body);
      this.code = (a) => (a.kind === "int" ? int(raw(a.n)) : null); // the guard
      this.kind = "int";
      how = "specialized for int";
    } else {
      this.code = compileGeneric(this.body);
      this.kind = how = "generic";
    }
    console.log(`* compile ${this.name}: arguments seen: ${[...this.seen].sort().join(", ")}; ${how}`);
  }

  call(a) {
    if (this.code === null && this.calls >= THRESHOLD) this.compile();
    if (this.code !== null) {
      const result = this.code(a);
      if (result !== null) {
        this.counts.compiled++;
        return [result, `compiled, ${this.kind}`];
      }
      console.log(`* deoptimize ${this.name}: guard failed, ${show(a)} is not an int`);
      this.counts.deoptimizations++;
      this.code = null;
      this.calls = 0;
    }
    this.calls++;
    this.counts.interpreter++;
    this.seen.add(a.kind);
    return [interpret(this.body, a), `interpreter, call ${this.calls}`];
  }
}

const f = new JitFunction("f", bin("+", bin("*", arg, arg), num(1)));
for (const a of [int(1), int(2), int(3), int(4), float(2.5), int(6), int(7), int(8)]) {
  const [result, tier] = f.call(a);
  console.log(`f(${show(a)}) = ${show(result)} [${tier}]`);
}
console.log(Object.entries(f.counts).map(([k, v]) => `${k}: ${v}`).join(", "));
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: native. V8, the engine of Chrome and Node.js, interprets Ignition bytecode first and compiles hot functions with Sparkplug, Maglev and TurboFan.
  • Every JavaScript number is a double in the language, so the model needs its own kind tag to tell int from float. V8 tracks the types of values itself while the program runs.
  • The compiled code is a tree of closures. Each closure captures the closures of its children, so a call runs no switch on the node type.
TypeScriptGitHub
// Values carry their type: a discriminated union with a tag.
type Value = { kind: "int"; n: number } | { kind: "float"; x: number };
const int = (n: number): Value => ({ kind: "int", n });
const float = (x: number): Value => ({ kind: "float", x });
const show = (v: Value): string => String(v.kind === "int" ? v.n : v.x);

// The body of f(x) = x * x + 1 as a tree.
type Op = "+" | "*";
type Node =
  | { type: "num"; value: number }
  | { type: "arg" }
  | { type: "bin"; op: Op; left: Node; right: Node };

const OPS: Record<Op, (a: number, b: number) => number> = {
  "+": (a, b) => a + b,
  "*": (a, b) => a * b,
};

const asNumber = (v: Value): number => (v.kind === "int" ? v.n : v.x);

// Generic arithmetic: check both tags on every operation.
function arith(op: Op, a: Value, b: Value): Value {
  if (a.kind === "int" && b.kind === "int") return int(OPS[op](a.n, b.n));
  return float(OPS[op](asNumber(a), asNumber(b)));
}

// The interpreter: walk the tree on every call.
function interpret(node: Node, x: Value): Value {
  switch (node.type) {
    case "num": return int(node.value);
    case "arg": return x;
    case "bin": return arith(node.op, interpret(node.left, x), interpret(node.right, x));
  }
}

// Compiled code for int: closures over raw numbers, no tag checks inside.
function compileInt(node: Node): (n: number) => number {
  switch (node.type) {
    case "num": { const v = node.value; return () => v; }
    case "arg": return (n) => n;
    case "bin": {
      const f = OPS[node.op], l = compileInt(node.left), r = compileInt(node.right);
      return (n) => f(l(n), r(n));
    }
  }
}

// Compiled code for any argument: closures that still check tags.
function compileGeneric(node: Node): (a: Value) => Value {
  switch (node.type) {
    case "num": { const boxed = int(node.value); return () => boxed; }
    case "arg": return (a) => a;
    case "bin": {
      const op = node.op, l = compileGeneric(node.left), r = compileGeneric(node.right);
      return (a) => arith(op, l(a), r(a));
    }
  }
}

const THRESHOLD = 3;
type Code = (a: Value) => Value | null; // null means that the guard failed

class JitFunction {
  readonly name: string;
  readonly body: Node;
  calls = 0; // calls in the interpreter since the last compilation
  seen = new Set<Value["kind"]>(); // the profile: the kinds of the arguments
  code: Code | null = null;
  kind = "";
  counts = { interpreter: 0, compiled: 0, deoptimizations: 0 };

  constructor(name: string, body: Node) {
    this.name = name;
    this.body = body;
  }

  compile(): void {
    let how: string;
    if (this.seen.size === 1 && this.seen.has("int")) {
      const raw = compileInt(this.body);
      this.code = (a) => (a.kind === "int" ? int(raw(a.n)) : null); // the guard
      this.kind = "int";
      how = "specialized for int";
    } else {
      this.code = compileGeneric(this.body);
      this.kind = how = "generic";
    }
    console.log(`* compile ${this.name}: arguments seen: ${[...this.seen].sort().join(", ")}; ${how}`);
  }

  call(a: Value): [Value, string] {
    if (this.code === null && this.calls >= THRESHOLD) this.compile();
    if (this.code !== null) {
      const result = this.code(a);
      if (result !== null) {
        this.counts.compiled++;
        return [result, `compiled, ${this.kind}`];
      }
      console.log(`* deoptimize ${this.name}: guard failed, ${show(a)} is not an int`);
      this.counts.deoptimizations++;
      this.code = null;
      this.calls = 0;
    }
    this.calls++;
    this.counts.interpreter++;
    this.seen.add(a.kind);
    return [interpret(this.body, a), `interpreter, call ${this.calls}`];
  }
}

const f = new JitFunction("f", { type: "bin", op: "+", left: { type: "bin", op: "*", left: { type: "arg" }, right: { type: "arg" } }, right: { type: "num", value: 1 } });
for (const a of [int(1), int(2), int(3), int(4), float(2.5), int(6), int(7), int(8)]) {
  const [result, tier] = f.call(a);
  console.log(`f(${show(a)}) = ${show(result)} [${tier}]`);
}
console.log(Object.entries(f.counts).map(([k, v]) => `${k}: ${v}`).join(", "));
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: native. TypeScript compiles to JavaScript, and the JavaScript engine does the JIT compilation.
  • Value is a discriminated union. After a.kind === "int", the type checker narrows a and allows a.n. The guard in the compiled code is the same test at run time.
  • The switch statements over node.type cover every member of Node, so the functions need no default case to satisfy --strict.
  • The type annotations do not reach the engine. The engine collects its own type feedback while the program runs.
package main

import (
	"fmt"
	"slices"
	"strconv"
	"strings"
)

// Values carry their type, as boxed values do in a dynamic language.
type Value interface{ Kind() string }
type IntV struct{ N int64 }
type FloatV struct{ X float64 }

func (IntV) Kind() string     { return "int" }
func (FloatV) Kind() string   { return "float" }
func (v IntV) String() string { return strconv.FormatInt(v.N, 10) }
func (v FloatV) String() string {
	return strconv.FormatFloat(v.X, 'g', -1, 64)
}

// The body of f(x) = x * x + 1 as a tree.
type Node interface{}
type Num struct{ Value int64 }
type Arg struct{}
type Bin struct {
	Op          byte
	Left, Right Node
}

func intOp(op byte) func(a, b int64) int64 {
	if op == '+' {
		return func(a, b int64) int64 { return a + b }
	}
	return func(a, b int64) int64 { return a * b }
}

func asFloat(v Value) float64 {
	if i, ok := v.(IntV); ok {
		return float64(i.N)
	}
	return v.(FloatV).X
}

// Generic arithmetic: check both tags on every operation.
func arith(op byte, a, b Value) Value {
	x, xok := a.(IntV)
	y, yok := b.(IntV)
	if xok && yok {
		return IntV{intOp(op)(x.N, y.N)}
	}
	p, q := asFloat(a), asFloat(b)
	if op == '+' {
		return FloatV{p + q}
	}
	return FloatV{p * q}
}

// The interpreter: walk the tree on every call.
func interpret(node Node, arg Value) Value {
	switch n := node.(type) {
	case Num:
		return IntV{n.Value}
	case Arg:
		return arg
	case Bin:
		return arith(n.Op, interpret(n.Left, arg), interpret(n.Right, arg))
	}
	panic("unknown node")
}

// Compiled code for int: closures over raw int64 values, no tag checks inside.
func compileInt(node Node) func(int64) int64 {
	switch n := node.(type) {
	case Num:
		v := n.Value
		return func(int64) int64 { return v }
	case Arg:
		return func(x int64) int64 { return x }
	case Bin:
		f, l, r := intOp(n.Op), compileInt(n.Left), compileInt(n.Right)
		return func(x int64) int64 { return f(l(x), r(x)) }
	}
	panic("unknown node")
}

// Compiled code for any argument: closures that still check tags.
func compileGeneric(node Node) func(Value) Value {
	switch n := node.(type) {
	case Num:
		boxed := IntV{n.Value}
		return func(Value) Value { return boxed }
	case Arg:
		return func(a Value) Value { return a }
	case Bin:
		op, l, r := n.Op, compileGeneric(n.Left), compileGeneric(n.Right)
		return func(a Value) Value { return arith(op, l(a), r(a)) }
	}
	panic("unknown node")
}

const threshold = 3

type JitFunction struct {
	name   string
	body   Node
	calls  int                       // calls in the interpreter since the last compilation
	seen   map[string]bool           // the profile: the kinds of the arguments
	code   func(Value) (Value, bool) // compiled code; false means that the guard failed
	kind   string
	counts [3]int // interpreter, compiled, deoptimizations
}

func (f *JitFunction) compile() {
	kinds := make([]string, 0, len(f.seen))
	for k := range f.seen {
		kinds = append(kinds, k)
	}
	slices.Sort(kinds)
	how := "generic"
	if len(kinds) == 1 && kinds[0] == "int" {
		raw := compileInt(f.body)
		f.code = func(a Value) (Value, bool) {
			i, ok := a.(IntV) // the guard
			if !ok {
				return nil, false
			}
			return IntV{raw(i.N)}, true
		}
		f.kind, how = "int", "specialized for int"
	} else {
		generic := compileGeneric(f.body)
		f.code = func(a Value) (Value, bool) { return generic(a), true }
		f.kind = "generic"
	}
	fmt.Printf("* compile %s: arguments seen: %s; %s\n", f.name, strings.Join(kinds, ", "), how)
}

func (f *JitFunction) Call(arg Value) (Value, string) {
	if f.code == nil && f.calls >= threshold {
		f.compile()
	}
	if f.code != nil {
		if result, ok := f.code(arg); ok {
			f.counts[1]++
			return result, "compiled, " + f.kind
		}
		fmt.Printf("* deoptimize %s: guard failed, %v is not an int\n", f.name, arg)
		f.counts[2]++
		f.code, f.calls = nil, 0
	}
	f.calls++
	f.counts[0]++
	f.seen[arg.Kind()] = true
	return interpret(f.body, arg), fmt.Sprintf("interpreter, call %d", f.calls)
}

func main() {
	f := &JitFunction{name: "f", body: Bin{'+', Bin{'*', Arg{}, Arg{}}, Num{1}}, seen: map[string]bool{}}
	for _, arg := range []Value{IntV{1}, IntV{2}, IntV{3}, IntV{4}, FloatV{2.5}, IntV{6}, IntV{7}, IntV{8}} {
		result, tier := f.Call(arg)
		fmt.Printf("f(%v) = %v [%s]\n", arg, result, tier)
	}
	fmt.Printf("interpreter: %d, compiled: %d, deoptimizations: %d\n", f.counts[0], f.counts[1], f.counts[2])
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: idiom. Go compiles ahead of time to machine code, so a JIT is something a program builds, as here.
  • i, ok := a.(IntV) is the guard. The type assertion with two results tests the dynamic type without a panic.
  • A Go map has no order, so compile sorts the kinds of the profile before it prints them.
  • Go has no sum types. The interfaces Value and Node stand in for them, and each switch ends in a panic for a case that the compiler cannot rule out.
RustGitHub
use std::collections::BTreeSet;
use std::fmt;

// Values carry their type, as boxed values do in a dynamic language.
#[derive(Clone, Copy)]
enum Value {
    Int(i64),
    Float(f64),
}

impl Value {
    fn kind(self) -> &'static str {
        match self {
            Value::Int(_) => "int",
            Value::Float(_) => "float",
        }
    }
    fn as_f64(self) -> f64 {
        match self {
            Value::Int(n) => n as f64,
            Value::Float(x) => x,
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::Int(n) => write!(f, "{n}"),
            Value::Float(x) => write!(f, "{x}"),
        }
    }
}

// The body of f(x) = x * x + 1 as a tree.
enum Node {
    Num(i64),
    Arg,
    Bin(char, Box<Node>, Box<Node>),
}

fn int_op(op: char) -> fn(i64, i64) -> i64 {
    if op == '+' {
        |a, b| a + b
    } else {
        |a, b| a * b
    }
}

// Generic arithmetic: check both tags on every operation.
fn arith(op: char, a: Value, b: Value) -> Value {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => Value::Int(int_op(op)(x, y)),
        _ if op == '+' => Value::Float(a.as_f64() + b.as_f64()),
        _ => Value::Float(a.as_f64() * b.as_f64()),
    }
}

// The interpreter: walk the tree on every call.
fn interpret(node: &Node, arg: Value) -> Value {
    match node {
        Node::Num(v) => Value::Int(*v),
        Node::Arg => arg,
        Node::Bin(op, l, r) => arith(*op, interpret(l, arg), interpret(r, arg)),
    }
}

type IntCode = Box<dyn Fn(i64) -> i64>;
type GenericCode = Box<dyn Fn(Value) -> Value>;

// Compiled code for int: closures over raw i64 values, no tag checks inside.
fn compile_int(node: &Node) -> IntCode {
    match node {
        Node::Num(v) => {
            let v = *v;
            Box::new(move |_| v)
        }
        Node::Arg => Box::new(|x| x),
        Node::Bin(op, l, r) => {
            let (f, l, r) = (int_op(*op), compile_int(l), compile_int(r));
            Box::new(move |x| f(l(x), r(x)))
        }
    }
}

// Compiled code for any argument: closures that still check tags.
fn compile_generic(node: &Node) -> GenericCode {
    match node {
        Node::Num(v) => {
            let boxed = Value::Int(*v);
            Box::new(move |_| boxed)
        }
        Node::Arg => Box::new(|a| a),
        Node::Bin(op, l, r) => {
            let (op, l, r) = (*op, compile_generic(l), compile_generic(r));
            Box::new(move |a| arith(op, l(a), r(a)))
        }
    }
}

const THRESHOLD: u32 = 3;

// Compiled code; it returns None when the guard fails.
type Code = Box<dyn Fn(Value) -> Option<Value>>;

struct JitFunction {
    name: String,
    body: Node,
    calls: u32,                   // calls in the interpreter since the last compilation
    seen: BTreeSet<&'static str>, // the profile: the kinds of the arguments
    code: Option<(Code, &'static str)>, // compiled code and its kind
    counts: [u32; 3],             // interpreter, compiled, deoptimizations
}

impl JitFunction {
    fn compile(&mut self) {
        let (code, kind, how): (Code, _, _) = if self.seen.len() == 1 && self.seen.contains("int") {
            let raw = compile_int(&self.body);
            let guarded = move |a| match a {
                Value::Int(n) => Some(Value::Int(raw(n))), // the guard
                Value::Float(_) => None,
            };
            (Box::new(guarded), "int", "specialized for int")
        } else {
            let generic = compile_generic(&self.body);
            (Box::new(move |a| Some(generic(a))), "generic", "generic")
        };
        let seen: Vec<_> = self.seen.iter().copied().collect();
        println!(
            "* compile {}: arguments seen: {}; {how}",
            self.name,
            seen.join(", ")
        );
        self.code = Some((code, kind));
    }

    fn call(&mut self, arg: Value) -> (Value, String) {
        if self.code.is_none() && self.calls >= THRESHOLD {
            self.compile();
        }
        if let Some((code, kind)) = &self.code {
            if let Some(result) = code(arg) {
                self.counts[1] += 1;
                return (result, format!("compiled, {kind}"));
            }
            println!(
                "* deoptimize {}: guard failed, {arg} is not an int",
                self.name
            );
            self.counts[2] += 1;
            self.code = None;
            self.calls = 0;
        }
        self.calls += 1;
        self.counts[0] += 1;
        self.seen.insert(arg.kind());
        (
            interpret(&self.body, arg),
            format!("interpreter, call {}", self.calls),
        )
    }
}

fn main() {
    use Node::*;
    let body = Bin(
        '+',
        Box::new(Bin('*', Box::new(Arg), Box::new(Arg))),
        Box::new(Num(1)),
    );
    let mut f = JitFunction {
        name: "f".into(),
        body,
        calls: 0,
        seen: BTreeSet::new(),
        code: None,
        counts: [0; 3],
    };
    let inputs = [1, 2, 3, 4]
        .map(Value::Int)
        .into_iter()
        .chain([Value::Float(2.5)])
        .chain([6, 7, 8].map(Value::Int));
    for arg in inputs {
        let (result, tier) = f.call(arg);
        println!("f({arg}) = {result} [{tier}]");
    }
    let [i, c, d] = f.counts;
    println!("interpreter: {i}, compiled: {c}, deoptimizations: {d}");
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: idiom. Rust compiles ahead of time to machine code, so a JIT is something a program builds, as here.
  • Value is an enum, a sum type. The guard is a match on the variant, and the compiler rejects a match that leaves a variant out.
  • Compiled code is a Box<dyn Fn>, a closure on the heap with its captured children. move gives each closure ownership of what it captures.
  • BTreeSet keeps the profile sorted, so the log prints the kinds in the same order on every run.
KotlinGitHub
// Values carry their type, as boxed values do in a dynamic language.
sealed interface Value
data class IntV(val n: Long) : Value { override fun toString() = n.toString() }
data class FloatV(val x: Double) : Value { override fun toString() = x.toString() }

val Value.kind get() = when (this) { is IntV -> "int"; is FloatV -> "float" }

// The body of f(x) = x * x + 1 as a tree.
sealed interface Node
data class Num(val value: Long) : Node
data object Arg : Node
data class Bin(val op: Char, val left: Node, val right: Node) : Node

fun intOp(op: Char): (Long, Long) -> Long = if (op == '+') Long::plus else Long::times

fun Value.toDouble() = when (this) { is IntV -> n.toDouble(); is FloatV -> x }

// Generic arithmetic: check both tags on every operation.
fun arith(op: Char, a: Value, b: Value): Value =
    if (a is IntV && b is IntV) IntV(intOp(op)(a.n, b.n))
    else if (op == '+') FloatV(a.toDouble() + b.toDouble())
    else FloatV(a.toDouble() * b.toDouble())

// The interpreter: walk the tree on every call.
fun interpret(node: Node, arg: Value): Value = when (node) {
    is Num -> IntV(node.value)
    Arg -> arg
    is Bin -> arith(node.op, interpret(node.left, arg), interpret(node.right, arg))
}

// Compiled code for int: closures over raw longs, no tag checks inside.
fun compileInt(node: Node): (Long) -> Long = when (node) {
    is Num -> { val v = node.value; { _ -> v } }
    Arg -> { n -> n }
    is Bin -> {
        val f = intOp(node.op)
        val l = compileInt(node.left)
        val r = compileInt(node.right);
        { n -> f(l(n), r(n)) }
    }
}

// Compiled code for any argument: closures that still check tags.
fun compileGeneric(node: Node): (Value) -> Value = when (node) {
    is Num -> { val boxed = IntV(node.value); { _ -> boxed } }
    Arg -> { a -> a }
    is Bin -> {
        val l = compileGeneric(node.left)
        val r = compileGeneric(node.right);
        { a -> arith(node.op, l(a), r(a)) }
    }
}

const val THRESHOLD = 3

class JitFunction(val name: String, val body: Node) {
    var calls = 0 // calls in the interpreter since the last compilation
    val seen = sortedSetOf<String>() // the profile: the kinds of the arguments
    var code: ((Value) -> Value?)? = null // compiled code; it returns null when the guard fails
    var kind = ""
    val counts = linkedMapOf("interpreter" to 0, "compiled" to 0, "deoptimizations" to 0)

    fun compile() {
        val how: String
        if (seen == setOf("int")) {
            val raw = compileInt(body)
            code = { a -> if (a is IntV) IntV(raw(a.n)) else null } // the guard
            kind = "int"
            how = "specialized for int"
        } else {
            code = compileGeneric(body)
            kind = "generic"
            how = "generic"
        }
        println("* compile $name: arguments seen: ${seen.joinToString(", ")}; $how")
    }

    fun call(arg: Value): Pair<Value, String> {
        if (code == null && calls >= THRESHOLD) compile()
        code?.let { compiled ->
            val result = compiled(arg)
            if (result != null) {
                counts["compiled"] = counts.getValue("compiled") + 1
                return result to "compiled, $kind"
            }
            println("* deoptimize $name: guard failed, $arg is not an int")
            counts["deoptimizations"] = counts.getValue("deoptimizations") + 1
            code = null
            calls = 0
        }
        calls++
        counts["interpreter"] = counts.getValue("interpreter") + 1
        seen.add(arg.kind)
        return interpret(body, arg) to "interpreter, call $calls"
    }
}

fun main() {
    val f = JitFunction("f", Bin('+', Bin('*', Arg, Arg), Num(1)))
    for (arg in listOf(IntV(1), IntV(2), IntV(3), IntV(4), FloatV(2.5), IntV(6), IntV(7), IntV(8))) {
        val (result, tier) = f.call(arg)
        println("f($arg) = $result [$tier]")
    }
    println(f.counts.entries.joinToString(", ") { "${it.key}: ${it.value}" })
}
Output
f(1) = 2 [interpreter, call 1]
f(2) = 5 [interpreter, call 2]
f(3) = 10 [interpreter, call 3]
* compile f: arguments seen: int; specialized for int
f(4) = 17 [compiled, int]
* deoptimize f: guard failed, 2.5 is not an int
f(2.5) = 7.25 [interpreter, call 1]
f(6) = 37 [interpreter, call 2]
f(7) = 50 [interpreter, call 3]
* compile f: arguments seen: float, int; generic
f(8) = 65 [compiled, generic]
interpreter: 6, compiled: 2, deoptimizations: 1
  • Verdict: native. On the JVM, Kotlin code runs as bytecode under HotSpot, with the same interpreter and tiered compilers as Java.
  • if (a is IntV) is the guard. After the test, the smart cast lets the code read a.n with no explicit cast.
  • when over a sealed interface needs no else branch, so the compiler reports a missing case in interpret, compileInt or compileGeneric.
  • Invocation, executability and concurrency. Aycock classifies JIT systems by three properties. A JIT compiler is explicitly invoked if the user must act to cause compilation, and implicitly invoked if compilation is invisible. A system is polyexecutable if it can execute both the source and the target representation, so it can choose when compiling is worth it. A concurrent JIT compiler runs alongside the program, for example in a separate thread, instead of pausing it.6 HotSpot is polyexecutable, because it can run a method in the interpreter or as compiled code.9 .NET generates its second tier in the background, which makes that part concurrent.10
  • Compile only, no interpreter. Burke and colleagues built a Java system with a compile-only strategy and no interpreter at all.5 A baseline compiler such as Sparkplug plays a similar role inside V8, because it compiles almost immediately.13
  • Mixed code and throw-away compiling. Mixed code, proposed in 1973, implemented the frequent parts of a program in native code and the rest in interpreted code, to save memory. Throw-away compiling compiled parts of the program on demand and discarded some or all of the compiled code when memory ran out.2
  • Specializing interpreters. Specialization does not require machine code. CPython replaces generic instructions with specialized ones while it runs, and replaces them back when the inputs change (PEP 659).18 This is the same bet and the same deoptimization, at the size of one instruction.
  • On-stack replacement. A function that is stuck in a hot loop never returns, so the next call never sees the compiled code. V8 replaces the running interpreted function with optimized code for the loop, and it uses the same mechanism in the other direction when optimized code deoptimizes.13
  • Bytecode as the input. A JIT usually compiles Bytecode, not source text. V8 generates optimized code directly from Ignition bytecode, and the bytecode gives a simpler baseline for deoptimization.12

Pitfalls

Compiled code without a guard

The specialized code is correct only for the types in the profile. Without the guard, a value of another type reaches code that assumes the wrong layout. In this Python model the mistake raises an exception.

This code raises AttributeError, on purpose.

from dataclasses import dataclass


@dataclass(frozen=True)
class Int:
    n: int


@dataclass(frozen=True)
class Float:
    x: float


def compiled_for_int(arg):
    # No guard: the compiler assumed that every argument is an Int.
    n = arg.n
    return Int(n * n + 1)


print(compiled_for_int(Int(3)))
print(compiled_for_int(Int(4)))
print(compiled_for_int(Float(2.5)))

The fix is a guard that checks the assumption and sends other values to code that makes no assumption.

from dataclasses import dataclass


@dataclass(frozen=True)
class Int:
    n: int


@dataclass(frozen=True)
class Float:
    x: float


def generic(arg):
    # The slow path: check the tag, then compute.
    if isinstance(arg, Int):
        return Int(arg.n * arg.n + 1)
    return Float(arg.x * arg.x + 1)


def compiled_for_int(arg):
    if not isinstance(arg, Int):  # the guard
        return generic(arg)  # deoptimize: fall back to the generic path
    n = arg.n
    return Int(n * n + 1)


print(compiled_for_int(Int(3)))
print(compiled_for_int(Int(4)))
print(compiled_for_int(Float(2.5)))
Output
Int(n=10)
Int(n=17)
Float(x=7.25)

Measuring before the warm-up ends

A JIT system runs slowly while it finds and compiles the hot code, and this phase is called warm-up. In the log above, the first three calls ran in the interpreter. A benchmark that measures only those calls measures the interpreter, and a benchmark that mixes them with later calls measures neither tier. Benchmark methods for JIT systems therefore run a benchmark many times in one process and discard the data from before the warm-up.17

That method assumes that the program reaches a steady state of peak performance. Barrett and colleagues tested the assumption on small, deterministic microbenchmarks in a tightly controlled environment. Only 30.0% to 43.5% of the pairs of virtual machine and benchmark consistently reached a steady state of peak performance, and none of the seven virtual machines that they studied did so consistently. Many benchmarks slowed down, never reached a steady state, or behaved differently from one run to the next.17 Report all the iterations, not only the fast ones. Repeat the measurement in fresh processes, and check whether a steady state exists before you report one.

The examples on this page print no timings for the same reason. A timing changes on each run, and the log of tiers does not.

Compiling too early

A low threshold compiles before the profile is stable, and the code deoptimizes when the types change. The V8 team wrote that it could not start optimizing earlier because it would not yet have stable feedback about object shapes.13 A compiler that is cheap to run makes a wrong bet cheap. The V8 team deploys Maglev earlier than TurboFan because deoptimizing and recompiling Maglev code costs little if the feedback was not yet stable.15 In the model, the threshold of 3 is low on purpose, so that the log shows a deoptimization.

Cost

  • Compile time at run time. Every compilation takes time from the program. A JIT must not cause long pauses, so it compiles only hot code and uses cheap tiers first.1 In short sessions, much of the work happens before the optimizing compiler has a chance to start.13
  • Memory. Compiled code occupies memory in addition to the bytecode. The V8 team built Ignition to reduce this overhead, because baseline machine code used memory even for code that ran only once.11 HotSpot multiplies the default size of its code cache by 5 when tiered compilation is on, to hold the extra profiled code.8
  • Profiling. Counters and type feedback cost time in the lower tiers. HotSpot moves the profiling into compiled code of the first tier, which is faster than profiling in the interpreter.8
  • Complexity. A JIT has two or more execution paths that must behave identically: the interpreter and each compiler.2 Deoptimization must be able to rebuild the interpreter's state at any guard.16
  • Predictability. The same program runs at different speeds at different times, as the tiers change. This makes performance hard to measure.17

History

  • 1960. John McCarthy's paper on LISP mentioned compiling functions into machine language, fast enough that the output need not be saved. Aycock suggests that this is the earliest published work on JIT compilation.7
  • 1968. Ken Thompson compiled regular expressions into IBM 7094 code, which was then executed to perform the match.7
  • 1974. Hansen's Adaptive FORTRAN kept frequency counters for blocks of code and optimized hot blocks at run time, one stage at a time.3
  • 1984. Deutsch and Schiffman translated Smalltalk virtual machine code into native code on demand, and cached the native code.7
  • 1992. Hölzle, Chambers and Ungar described dynamic deoptimization in Self, to debug optimized code at the source level.16
  • 1994. Hölzle's adaptive optimization for Self compiled methods first with a fast, non-optimizing compiler, recompiled hot ones, and used type feedback gathered at run time.4
  • 2003. Aycock surveyed forty years of JIT work in "A Brief History of Just-In-Time". He noted that Java brought the term just-in-time into common use, and that the pressure for fast Java implementations started a renaissance in JIT research.5
  • 2017. Barrett and colleagues showed that many VMs do not reach a steady state of peak performance, even on small deterministic benchmarks.17 V8 launched its pipeline of the Ignition interpreter and the TurboFan compiler.12
  • 2021. V8 added Sparkplug, a non-optimizing compiler between Ignition and TurboFan.13 PEP 659 proposed a specializing adaptive interpreter for CPython.18
  • 2023. The V8 team described Maglev, a fast optimizing compiler between Sparkplug and TurboFan.14
  • 2024. PEP 744 described the experimental JIT compiler that had been merged into CPython's main development branch.19

References

  1. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, pages 97 to 113, section 1, Introduction, pages 97 to 98
  2. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, section 2.4, Mixed Code, Throw-Away Code, and BASIC, pages 99 to 100
  3. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, section 2.5, FORTRAN, pages 100 to 101
  4. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, section 2.7, Self, pages 101 to 103
  5. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, section 2.14, Java, pages 107 to 108
  6. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, section 3, Classification of JIT Systems, page 108
  7. John Aycock, A Brief History of Just-In-Time, ACM Computing Surveys 35(2), June 2003, section 2.1, Genesis, page 98; section 2.6, Smalltalk, page 101
  8. Java Virtual Machine Guide, Java SE 25, Java HotSpot Virtual Machine Performance Enhancements, Tiered Compilation
  9. The java Command, Java SE 25 tool specifications, Extra Options for Java, -Xint and -Xmixed
  10. Microsoft Learn, Runtime configuration options for compilation, Tiered compilation; Quick JIT
  11. Ross McIlroy, Firing up the Ignition interpreter, V8 blog, 23 August 2016, introduction
  12. Launching Ignition and TurboFan, V8 blog, 15 May 2017, A long journey
  13. Leszek Swirski, Sparkplug, a non-optimizing JavaScript compiler, V8 blog, 27 May 2021, introduction; A fast compiler; Interpreter-compatible frames
  14. Maglev, V8's Fastest Optimizing JIT, V8 blog, 5 December 2023, Background
  15. Maglev, V8's Fastest Optimizing JIT, V8 blog, 5 December 2023, Deoptimization
  16. Urs Hölzle, Craig Chambers and David Ungar, Debugging Optimized Code with Dynamic Deoptimization, ACM SIGPLAN '92 Conference on Programming Language Design and Implementation, June 1992, Abstract; section 3, Deoptimization
  17. Edd Barrett, Carl Friedrich Bolz-Tereick, Rebecca Killick, Sarah Mount and Laurence Tratt, Virtual Machine Warmup Blows Hot and Cold, Proceedings of the ACM on Programming Languages 1 (OOPSLA), 2017, Abstract; section 1, Introduction
  18. Mark Shannon, PEP 659, Specializing Adaptive Interpreter, Abstract; Motivation; Implementation, Overview and Specialization
  19. Brandt Bucher and Savannah Ostrowski, PEP 744, JIT Compilation, Abstract; Motivation; Specification
  20. The Python Standard Library, dis, Disassembler for Python bytecode, Python 3.14, module introduction (changed in version 3.11); dis.dis and dis.get_instructions, parameter adaptive
  21. Java SE 25 API, java.lang.management.ManagementFactory, getCompilationMXBean()

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/S005MC/text.yaml