High-Level Intermediate Representation (HIR)
Relevant source files
The following files were used as context for generating this wiki page:- compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
- compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts
- compiler/packages/babel-plugin-react-compiler/src/HIR/PrintHIR.ts
- compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts
- compiler/packages/babel-plugin-react-compiler/src/HIR/Environment.ts
The High-Level Intermediate Representation (HIR) is a control-flow graph (CFG) based representation of React components used within the React Compiler. It serves as the initial intermediate representation, lowered from the Babel Abstract Syntax Tree (AST). The primary purpose of HIR is to model the component's logic in a way that is amenable to analysis and optimization, by making control flow explicit and representing JavaScript expressions as a sequence of instructions.
HIR is designed to be close to the original source code but structured as a CFG. Each function or component is represented as a collection of basic blocks, where each block contains a linear sequence of instructions and is terminated by a control-flow instruction (a "terminal"). This structure facilitates subsequent analysis passes, such as data flow analysis, before the HIR is lowered into a more optimized, lower-level representation.
Core Architecture
The HIR is fundamentally a Control Flow Graph. The main components are the HIR container, BasicBlock nodes, Instructions within each block, and Terminals that define control flow between blocks.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:251-258
Key Data Structures
The core data structures of the HIR are defined in HIR.ts. The relationship between them is illustrated below.
This diagram shows that an HIR object contains multiple BasicBlocks. Each BasicBlock contains a list of Instructions and concludes with a single Terminal. Instructions operate on Places, which are backed by Identifiers.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
HIR
The top-level container for a single function's control-flow graph. It holds a map of all basic blocks and a reference to the entry block.
| Property | Type | Description |
|---|---|---|
entry | BlockId | The ID of the first block to be executed. |
blocks | Map<BlockId, BasicBlock> | A map from block IDs to the BasicBlock objects. |
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:255-258
BasicBlock
A basic block is a straight-line sequence of code with no jumps in or out, except at the beginning and end.
| Property | Type | Description |
|---|---|---|
id | BlockId | A unique identifier for the block. |
kind | BlockKind | The kind of block, e.g., block, value, loop. |
instructions | Array<Instruction> | A list of instructions executed in order. |
terminal | Terminal | The instruction that terminates the block and directs control flow. |
preds | Set<BlockId> | The set of predecessor block IDs. |
phis | Set<Phi> | A set of Phi nodes for merging values from different predecessor blocks. |
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:223-232
Instruction and Terminal
Instructions represent individual operations, while Terminals are special instructions that end a basic block and determine the next block to execute.
- Instruction: Has an
lvalue(Place) where the result is stored and avalue(InstructionValue) representing the operation (e.g.,LoadConstant,StoreLocal,BinaryExpression). - Terminal: Represents control flow, such as
Goto,If,Switch, orReturn.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:161-171, compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:234-249
HIR Construction
The process of converting a Babel AST into HIR is managed by the HIRBuilder class. This process, often referred to as "lowering," traverses the AST and generates the corresponding CFG.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts, compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts
HIRBuilder
The HIRBuilder is a stateful class responsible for constructing the HIR graph. It maintains the current block being built, manages scopes (like loops and switches), and resolves variable bindings.
Key responsibilities include:
- Creating and managing basic blocks (
WipBlockfor in-progress blocks,BasicBlockfor completed ones). - Pushing new
Instructions into the current block. - Terminating blocks with
Terminalinstructions to link the CFG. - Managing a stack of scopes (
loop,switch,label) to correctly resolvebreakandcontinuestatements. - Resolving Babel identifiers to unique HIR
Identifiers to handle variable shadowing correctly. - Modeling exception handling by tracking
try...catchblocks.
The overall flow of building the HIR is depicted below.
This diagram shows the lifecycle of HIR construction, from the initial AST to the final, post-processed HIR graph.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts
Scope and Binding Management
A critical function of the HIRBuilder is to manage JavaScript's lexical scoping.
- Binding Resolution: The
resolveIdentifiermethod maps a BabelIdentifiernode to a unique HIRIdentifier. This ensures that variables with the same name in different scopes are treated as distinct entities. It maintains aBindingsmap to track this resolution. - Scope Handling: The builder uses a stack (
#scopes) to manage nested control-flow structures. When encounteringfor,while,switch, or labeled statements, it pushes aScopeobject onto the stack. This allowsbreakandcontinuestatements to be resolved to the correct target block bylookupBreakandlookupContinue.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:208-283, compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:468-560
Exception Handling
The HIR explicitly models exception handling. The HIRBuilder can operate in two modes for instruction generation:
ThrowExceptions: The default mode where any error is assumed to be thrown out of the function.CatchExceptions: Used inside atryblock. In this mode, every instruction that can potentially throw is terminated with aMaybeThrowterminal, which directs control flow to either a continuation block (on success) or a handler block (on exception).
The enterTryCatch method manages this by pushing the handler block's ID onto an internal stack (#exceptionHandlerStack).
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:90-104, compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:133-137
Post-Processing
After the initial CFG is built, several post-processing steps are applied to clean up and normalize the HIR. These are typically invoked within the HIRBuilder.build() method.
Reverse Post-order Traversal
The blocks in the final HIR are sorted in reverse post-order. This ordering ensures that, except for loop back-edges, a block always appears before its successors. This is a standard representation for CFGs that simplifies many subsequent analyses and transformations.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:634-712
Pruning and Cleanup
Several functions exist to prune dead or unnecessary structures from the graph:
removeUnreachableForUpdates: Removes references toupdateblocks inforloops if the block itself is unreachable.removeDeadDoWhileStatements: Converts ado-whileloop into a simplegotoif its test condition is unreachable.removeUnnecessaryTryCatch: If atryterminal's handler block is unreachable, thetryis converted into a simplegoto.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:572-581, compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:583-601, compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts:747-771
HIR Utilities
Printing HIR
For debugging and logging, PrintHIR.ts provides functionality to serialize the HIR into a human-readable string format. The printFunction() and printInstruction() functions are used throughout the compiler for logging and in tools like the React Compiler Playground.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/PrintHIR.ts
Environment
The Environment class encapsulates the configuration and context for the compilation of a single function. It manages the generation of unique IDs for blocks and identifiers, tracks compiler flags, and holds references to parent scopes, which is essential for the HIRBuilder to perform its tasks.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/Environment.ts
Summary
The High-Level Intermediate Representation (HIR) is the React Compiler's first structured, graph-based view of a component's code. By transforming the nested structure of the AST into a flat CFG of basic blocks, instructions, and terminals, it exposes control flow and makes the code's behavior explicit. This representation is crucial for the compiler's ability to analyze, optimize, and ultimately memoize React components automatically. The HIRBuilder orchestrates this complex lowering process, carefully managing state, scope, and bindings to produce a correct and analyzable HIR.