docs/torque/architecture.md
This document describes Torque, V8's domain-specific language for implementing built-in functions.
Torque is a language developed specifically for V8 to make it easier and safer to write built-in functions (like Array.prototype.map, Promise.prototype.then, etc.).
Before Torque, builtins were written in:
Torque provides a higher-level, strongly-typed syntax that compiles down to CSA or the newer Turboshaft Assembler (TSA).
The Torque compiler is a standalone executable (built from src/torque/) that runs during the V8 build process. The translation from .tq to C++ involves several stages:
TorqueParser (src/torque/torque-parser.cc).TypeOracle manages and finalizes types, including resolving class fields and calculating layout offsets.ImplementationVisitor (src/torque/implementation-visitor.cc) translates the AST into a Control Flow Graph (CFG).Branch, Goto, CallBuiltin).Torque supports multiple backends, with some differences in how they process the IR:
CSAGenerator iterates over the generated CFG instructions and translates them into C++ code that calls V8's CodeStubAssembler (CSA) API. This produces *-tq-csa.cc and *-tq-csa.h files.CCGenerator also iterates over the CFG to generate standard C++ code for class definitions, debug readers, and verifiers, producing *-tq.inc, *-tq-inl.inc, and *-tq.cc files.TSAGenerator) visits the AST directly (using AstVisitor) to generate code using the Turboshaft Assembler API, bypassing the CFG generation in ImplementationVisitor.The generated C++ files are placed in the build output directory (e.g., out/x64.debug/gen/torque-generated/) and are compiled into the V8 binary.
Torque has a strong type system that understands V8's object model:
Object, Smi, JSArray).intptr, int32, bool).Torque does not have traditional exceptions. Instead, it uses Labels for non-local control flow. Macros can take labels as arguments and "emit" them to transfer control to a handler in the caller. This maps efficiently to machine code jumps.
Here is a conceptual example of a Torque macro:
// Torque definition
macro IsZero(x: int32): bool {
if (x == 0) {
return true;
} else {
return false;
}
}
The CSA backend might generate C++ code similar to this:
// Generated CSA C++ code
TNode<BoolT> IsZero(CodeStubAssembler* ca_, TNode<Int32T> x) {
compiler::CodeAssemblerLabel label_true(ca_);
compiler::CodeAssemblerLabel label_false(ca_);
ca_->Branch(ca_->Word32Equal(x, ca_->Int32Constant(0)), &label_true, &label_false);
ca_->Bind(&label_true);
return ca_->TrueConstant();
ca_->Bind(&label_false);
return ca_->FalseConstant();
}
With the introduction of the Turboshaft compiler, V8 is transitioning Torque to generate Turboshaft Assembler (TSA) code instead of CSA.
V8_ENABLE_EXPERIMENTAL_TQ_TO_TSA macro.src/torque/tsa-generator.cc) acts as an AstVisitor and generates code directly from the AST.src/torque/: Torque compiler source code.src/builtins/: Torque builtin definitions.