JIT COMPILATION
Compile at runtime, optimize what matters
add(a, b) was compiled for (int, int) with no guard, nothing that checks the argument types at run time. Strings are heap objects. What does add('ab', 'cd') return?
A JIT starts every function in an interpreter that counts calls and records argument types. Once a function is hot, the JIT compiles it for the types it has seen. Int-only code is fast because it adds machine words and skips every type check.
That code is a bet. A guard checks the real types where the specialised code relies on them; here that is right after the counter increment. If they differ, the JIT deoptimises: it rebuilds the interpreter frame at the current pc, drops the compiled code, and lets the interpreter finish. Later it recompiles with the broader types.
; add(a, b) compiled for (int, int), no guard
add:
inc dword [calls] ; pc 0
mov eax, [a] ; payload word: an int... or an address
add eax, [b]
ret; add(a, b) compiled for (int, int), guarded
add:
inc dword [calls] ; pc 0 (side effect already done)
test [a], SMI_TAG ; guard: a is int?
jnz deopt_pc1
test [b], SMI_TAG ; guard: b is int?
jnz deopt_pc1
mov eax, [a]
add eax, [b]
jo deopt_pc1 ; int32 overflow: the interpreter gives the exact sum
ret
deopt_pc1: ; rebuild frame {pc: 1, a, b}, drop this code,
jmp interpreter_resume ; finish in the interpreter from pc 1 Watch the CALLS box and the invariant strip. NO GUARD, STRING ARRIVES returns 8208 for add(“ab”, “cd”). UNSAFE: DEOPT TO pc 0 guards correctly but restarts the interpreter at the top of add: every result is right, yet the calls counter runs one ahead of the invocations. FIX: GUARD + DEOPT sends the same call back to the interpreter from pc 1, right after the increment that already ran, and later recompiles for int|str.
The JIT compiled add for (int, int) with no type guard, and so far every caller passes ints. Inject one call with types the profile never saw, at a point where it produces a result the interpreter would not.
GOAL: some call returns a result the interpreter would not
Write the entry stub for compiled code. profile[i] lists the types argument i was compiled for ('int', 'float', 'str'). fn.typeOf(v) classifies a value, fn.compiled(args) runs the specialised code (wrong on any type outside the profile), and fn.interpret(args) runs the interpreter (always right, slow). Return the correct result, and use the compiled code whenever the types allow it.
V8 (Ignition and TurboFan), SpiderMonkey, JavaScriptCore, HotSpot C2, PyPy, LuaJIT. You see it as warm-up curves, “deoptimized” lines in --trace-deopt, and polymorphic call sites that never get fast. Missing or wrong guards are a classic class of browser JIT security bugs.
“How does a JIT make a dynamic language fast, and what happens when its assumptions are wrong?” Explain profiling, type specialisation, guards, deoptimisation with frame reconstruction, and why monomorphic code is faster than code that sees many types.