Sub topic 1
From Source Text to Bytecode: The Engine Pipeline
A JavaScript engine never runs your source text directly. It turns the text into something it can execute in several steps, and each step leaves behind data that later optimizations depend on. This chapter follows that path in V8, from the moment a script's characters arrive to the moment bytecode exists for a function. Later chapters cover how the bytecode runs, how it gets compiled to machine code, and how objects are laid out in memory.
Prerequisites
This chapter assumes you can:
- Write JavaScript functions, objects, classes, and arrays.
- Explain the difference between compiling a program ahead of time and interpreting it.
- Run scripts with Node.js from the command line, including passing flags such as
node --flag script.js. - Work with JavaScript's dynamic typing, where a variable can hold a number at one moment and a string the next.
You will need a recent Node.js release (v18 or later) to try the commands. The output format of V8's debug flags changes between versions, so your output may differ slightly from what is shown here.
The Pipeline at a Glance
V8 processes a script in a fixed order. The scanner reads characters and groups them into tokens. The parser reads tokens and builds an abstract syntax tree (AST) along with scope information. The bytecode generator walks the AST and emits bytecode for the Ignition interpreter. Optimizing compilers enter later, and only for code that turns out to be hot.
Scanning: Characters to Tokens
The scanner, also called the lexer, reads the source as a stream of UTF-16 characters. It produces tokens: identifiers, keywords, punctuators, and string, number, and template literals. For let total = price * 2; the scanner emits let, total, =, price, *, 2, and ;.
The scanner handles some of the language's awkward details. It decides whether / begins a regular expression or is a division operator, using context supplied by the parser. It also records line terminators so the parser can apply automatic semicolon insertion. Scanning is fast, but large bundles still spend measurable time here, so V8 tunes its scanner heavily, for example by checking for plain ASCII identifiers first.
Parsing: Tokens to an AST
The parser consumes tokens and checks them against the ECMAScript grammar. Its output is an AST, a tree whose nodes stand for constructs such as function literals, binary operations, and property accesses. price * 2 becomes a binary-operation node with a variable-reference child and a literal child.
The parser also does scope analysis. It works out which declarations belong to which scope and resolves each identifier to a local variable, a parameter, a variable captured from an outer function, or a global lookup. This matters for performance. A variable that no inner function captures can live in a fast interpreter register. A captured variable has to live in a heap-allocated context object that outlives the function call.
Early errors abort the whole script
The parser reports syntax errors before any code runs. A syntax error inside a function that is never called still stops the entire script:
const src = "console.log('start'); function never() { return (; }";
try {
eval(src);
} catch (e) {
console.log(e.name); // SyntaxError
}
// 'start' is never printed: parsing failed before execution began.This shows that the engine looks at all of the source before it executes any of it, even code it will never run.
Lazy Parsing and the Preparser
Building a full AST for every function is wasteful. A typical web page ships far more code than it runs during startup. V8 therefore parses lazily. Top-level code gets a full parse. A function declared inside it goes through the preparser, which checks syntax and records a small amount of scope data, such as which outer variables the function references. The preparser builds no AST and generates no bytecode.
When a lazily parsed function is first called, V8 parses it fully and compiles it. The scope data from the preparse lets V8 skip re-analyzing the outer scopes.
| Mode | When it is used | What it produces | Cost |
|---|---|---|---|
| Full parse | Top-level code, functions being compiled | AST and full scope information | Higher |
| Preparse | Inner functions not yet called | Syntax check and variable-reference summary | Lower |
| Re-parse on first call | A preparsed function runs for the first time | AST for that function only | Paid once per function |
When laziness backfires
If a function is preparsed and then called right away, V8 has done the parsing work twice. V8 uses heuristics to avoid this. The best known one treats a function expression wrapped in parentheses, such as an immediately invoked function expression (IIFE), as likely to run immediately, and parses it eagerly.
Bytecode Generation
The bytecode generator walks a function's AST and emits Ignition bytecode. This is a compact instruction set for a register machine with an accumulator, which is an implicit register that most instructions read from or write to. Bytecode is much smaller than machine code, which is one reason V8 interprets first instead of compiling everything to native code.
Along with the bytecode, the generator allocates feedback slots. These are numbered places where the interpreter will later record what it sees at runtime, such as the types of operands at a + or the object shapes seen at a property access. The slots start empty. Later chapters show how the optimizing compilers use what they collect.
You can watch the generator work. Save this as pipeline.js:
function add(a, b) {
return a + b;
}
function neverCalled(x) {
return x * 2;
}
console.log(add(2, 3));Run it with a filter so only one function is printed:
node --print-bytecode --print-bytecode-filter=add pipeline.jsThe output looks roughly like this:
[generated bytecode for function: add (0x... <SharedFunctionInfo add>)]
Bytecode length: 6
Parameter count 3
Register count 0
Frame size 0
Ldar a1
Add a0, [0]
ReturnLdar a1 loads the second argument into the accumulator. Add a0, [0] adds the first argument to it and records type feedback in slot [0]. Return returns the accumulator. The parameter count is 3 because the receiver this is counted as well.
Now run the same command with --print-bytecode-filter=neverCalled. Nothing is printed for that function. It was preparsed, never called, and so never compiled. This is lazy compilation working as described above.
Caching Bytecode
Parsing and compiling cost time on every page load or process start. V8 can serialize compiled bytecode into a code cache and reuse it later. Browsers do this automatically for scripts that run repeatedly. Node.js uses it for its own built-in modules and exposes it through vm.Script:
const vm = require('vm');
const code = 'function sq(n) { return n * n; } sq(7);';
const first = new vm.Script(code);
const cache = first.createCachedData();
const second = new vm.Script(code, { cachedData: cache });
console.log(second.cachedDataRejected); // false: the cache was accepted
console.log(second.runInThisContext()); // 49The cache is rejected if the source text or the V8 version changes, so treat it as an optimization and never as a source of truth.
What the Pipeline Hands On
By the end of the front end, each compiled function has bytecode, scope and context layout, and empty feedback slots. These are what the rest of the tutorial builds on: the interpreter runs the bytecode, fills the feedback slots, and passes hot functions to the JIT tiers.
Exercise
A script defines 200 helper functions at top level, but only 5 are called during startup. Which pipeline work happens for the other 195, and which work is skipped?
Show answer
All 200 are scanned and checked for syntax, so a syntax error in any of them still aborts the script. The 195 uncalled functions are only preparsed, which records a scope summary but builds no AST and generates no bytecode. Full parsing and bytecode generation happen for each of them only if it is called later.
Exercise
Running node --print-bytecode --print-bytecode-filter=add pipeline.js shows Add a0, [0]. What does [0] refer to, and why does the bytecode generator create it before the code has ever run?
Show answer
[0] is a feedback slot index. The generator reserves it at compile time so the interpreter has a place to record the operand types it observes each time the addition runs. The optimizing compilers later read that recorded feedback to decide how to specialize add.
Exercise
Why can a variable captured by an inner closure be slower to access than one that is not captured, and which pipeline stage decides where it lives?
Show answer
Scope analysis during parsing decides this. A variable that no closure captures can live in an interpreter register in the function's stack frame. A captured variable has to live in a heap-allocated context object so it survives after the outer call returns, and reading it takes extra loads through that context.