JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2

Preface

The previous article covered four kinds of Node inherited from ScopeNode: ProgramNode, EvalNode, FunctionNode, and ModuleProgramNode. Their bytecode generation eventually reaches emitStatementsBytecode.

Bytecode Instruction Set

Before continuing the analysis, let’s first get a rough sense of what bytecode looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"section" : "Bytecodes", "emitInHFile" : true, "emitInASMFile" : true,
"macroNameComponent" : "BYTECODE", "asmPrefix" : "llint_",
"bytecodes" : [
{ "name" : "op_enter", "length" : 1 },
{ "name" : "op_get_scope", "length" : 2 },
{ "name" : "op_create_direct_arguments", "length" : 2 },
{ "name" : "op_create_scoped_arguments", "length" : 3 },
{ "name" : "op_create_cloned_arguments", "length" : 2 },
{ "name" : "op_create_this", "length" : 5 },
{ "name" : "op_to_this", "length" : 4 },
{ "name" : "op_check_tdz", "length" : 2 },
{ "name" : "op_new_object", "length" : 4 },
{ "name" : "op_new_array", "length" : 5 },
{ "name" : "op_new_array_with_size", "length" : 4 },
{ "name" : "op_new_array_buffer", "length" : 5 },
{ "name" : "op_new_regexp", "length" : 3 },
{ "name" : "op_mov", "length" : 3 },
{ "name" : "op_not", "length" : 3 },
{ "name" : "op_eq", "length" : 4 },
...

You can see the instruction name and length. The final bytecode is a collection of instructions like these. The complete instruction set can be found in JavaScriptCore/bytecode/BytecodeList.json.

emitStatementsBytecode

Now let’s look at the long-awaited emitStatementsBytecode. It is a method on ScopeNode.

1
2
3
4
5
inline void ScopeNode::emitStatementsBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
if (!m_statements) return;
m_statements->emitBytecode(generator, dst);
}

The type of m_statements is SourceElements. Its definition is shown below. It is a singly linked list whose node type is StatementNode. This means the stored nodes can be StatementNode itself or subclasses of StatementNode. It also tells us that a ScopeNode is composed of linked StatementNode instances.

1
2
3
4
5
6
7
8
9
10
class SourceElements final : public ParserArenaFreeable {
public:
SourceElements();
void append(StatementNode*);
void emitBytecode(BytecodeGenerator&, RegisterID* destination);

private:
StatementNode* m_head;
StatementNode* m_tail;
};

The list is traversed, and bytecode is generated for every node:

1
2
3
4
5
6
7
8
9
10
11
inline void SourceElements::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
for (StatementNode* statement = m_head; statement; statement = statement->next())
generator.emitNodeInTailPosition(dst, statement);
}

void emitNodeInTailPosition(RegisterID* dst, StatementNode* statementNode)
{
// Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
statementNode->emitBytecode(*this, dst);
}

The actual type of statementNode can be any of the following Node types, all inherited from StatementNode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
IfElseNode
DoWhileNode
WhileNode
ForNode
SwitchNode
ClassDecNode
DeclarationStatement
ForInNode
ForOfNode
ContinueNode
BreakNode
ReturnNode
FuncDeclNode
BlockNode
ModuleDeclarationNode
...

StatementNode

JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2: StatementNode (figure 1)

StatementNode mainly describes language structures:

  1. Sequential structures: ClassDeclNode, DeclarationStateMentNode, and so on.
  2. Conditional structures: IFElseNode, SwitchNode, and so on.
  3. Loop structures: WhileNode, ForNode, DoWhileNode, and so on.

Next, I will pick several representative nodes and analyze how their bytecode is generated.

Backpatching

Unlike sequential structures, conditional and loop structures do not directly produce concrete logical instructions. They mainly generate jump instructions to control program flow.

When a jump instruction is generated, its destination may not be known immediately. So the target label is left unspecified for the moment. Once the correct target label can be determined, the instruction is patched with that target label. This technique is called backpatching.

Conditional Structures

1
2
3
4
// Returns the next available temporary register. Registers returned by
// newTemporary require a modified form of reference counting: any
// register with a refcount of 0 is considered "available", meaning that
// the next instruction may overwrite it.

IfElseNode

As mentioned in the parsing article, the parser normalizes IfStatement inside parseIfStatement. Now let’s see how it generates bytecode.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
void IfElseNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
// generator.newLabel creates a new temporary label variable L and returns its address.
RefPtr<Label> beforeThen = generator.newLabel();
RefPtr<Label> beforeElse = generator.newLabel();
RefPtr<Label> afterElse = generator.newLabel();

Label* trueTarget = beforeThen.get();
Label* falseTarget = beforeElse.get();
FallThroughMode fallThroughMode = FallThroughMeansTrue;

// If this is break or continue.
bool didFoldIfBlock = tryFoldBreakAndContinue(generator, m_ifBlock, trueTarget, fallThroughMode);

// Generate bytecode for condition expression m_condition.
// It may generate goto-like instructions:
// if m_condition is true, jump to trueTarget; otherwise jump to falseTarget.
// At this point, trueTarget and falseTarget may not yet be known. They are
// resolved after the whole if-else block is complete. This uses backpatching.
generator.emitNodeInConditionContext(m_condition, trueTarget, falseTarget, fallThroughMode);

// Backpatch the address of beforeThen, marking the target for m_condition == true.
// Notice this only changes beforeThen's value; it does not add an instruction.
generator.emitLabel(beforeThen.get());

// Normal if-else.
if (!didFoldIfBlock) {
// Generate bytecode for the if block.
generator.emitNodeInTailPosition(dst, m_ifBlock);

// After the if block finishes, jump to afterElse, which is the next
// instruction after the whole if-else block.
// Notice: this is a jump instruction, goto afterElse.
if (m_elseBlock)
generator.emitJump(afterElse.get());
}

// Fill beforeElse's address, marking the false branch target.
generator.emitLabel(beforeElse.get());

// Generate bytecode for the else block if it exists.
if (m_elseBlock) {
generator.emitNodeInTailPosition(dst, m_elseBlock);
}

// Backpatch afterElse as the next instruction after the whole if-else block.
generator.emitLabel(afterElse.get());
}

Here is the SDT for IfElseNode:

JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2: IfElseNode (figure 2)

SwitchNode

SwitchNode is familiar enough. Let’s look at how it generates bytecode.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void SwitchNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
LabelScopePtr scope = generator.newLabelScope(LabelScope::Switch);

RefPtr<RegisterID> r0 = generator.emitNode(m_expr);

// Push itself as a scope.
generator.pushLexicalScope(this, BytecodeGenerator::TDZCheckOptimization::DoNotOptimize, BytecodeGenerator::NestedScopeType::IsNested);

// Generate bytecode inside switch{}.
m_block->emitBytecodeForBlock(generator, r0.get(), dst);

// Pop scope.
generator.popLexicalScope(this);

// Backpatch the scope address. The jump target for break inside switch
// is the address after the switch block. Since SwitchNode has now been
// fully analyzed, its address can be patched.
generator.emitLabel(scope->breakTarget());

}

switch {} contains multiple case clauses and possibly a default clause.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
enum SwitchType 
{
SwitchNone,
SwitchImmediate,
SwitchCharacter,
SwitchString
};

void CaseBlockNode::emitBytecodeForBlock(BytecodeGenerator& generator, RegisterID* switchExpression, RegisterID* dst)
{
RefPtr<Label> defaultLabel;
Vector<RefPtr<Label>, 8> labelVector;
Vector<ExpressionNode*, 8> literalVector;
int32_t min_num = std::numeric_limits<int32_t>::max();
int32_t max_num = std::numeric_limits<int32_t>::min();

// Determine switchType.
SwitchInfo::SwitchType switchType = tryTableSwitch(literalVector, min_num, max_num);

if (switchType != SwitchInfo::SwitchNone)
{
// For SwitchImmediate, SwitchCharacter, and SwitchString, generate
// corresponding case jump labels and the default label.
for (uint32_t i = 0; i < literalVector.size(); i++)
labelVector.append(generator.newLabel());
defaultLabel = generator.newLabel();

// Generate op_switch_imm, op_switch_char, or op_switch_string
// instruction for comparison.
generator.beginSwitch(switchExpression, switchType);
}
else
{
// For SwitchNone, generate normal conditional jumps.
for (ClauseListNode* list = m_list1; list; list = list->getNext())
{
RefPtr<RegisterID> clauseVal = generator.newTemporary();
// Generate bytecode for the constant expression.
generator.emitNode(clauseVal.get(), list->getClause()->expr());
// Generate bytecode to compare the switch expression with the clause value.
generator.emitBinaryOp(op_stricteq, clauseVal.get(), clauseVal.get(), switchExpression, OperandTypes());
// Generate a label for jumping.
labelVector.append(generator.newLabel());
// If comparison succeeds, jump to the corresponding label.
generator.emitJumpIfTrue(clauseVal.get(), labelVector[labelVector.size() - 1].get());
}

// Same as above.
for (ClauseListNode* list = m_list2; list; list = list->getNext()) {
RefPtr<RegisterID> clauseVal = generator.newTemporary();
generator.emitNode(clauseVal.get(), list->getClause()->expr());
generator.emitBinaryOp(op_stricteq, clauseVal.get(), clauseVal.get(), switchExpression, OperandTypes());
labelVector.append(generator.newLabel());
generator.emitJumpIfTrue(clauseVal.get(), labelVector[labelVector.size() - 1].get());
}

// Set jump for the default label.
defaultLabel = generator.newLabel();
generator.emitJump(defaultLabel.get());
}

size_t i = 0;
// Cases before default.
for (ClauseListNode* list = m_list1; list; list = list->getNext()) {
// Backpatch case label address.
generator.emitLabel(labelVector[i++].get());
// Generate bytecode for the case clause.
list->getClause()->emitBytecode(generator, dst);
}

if (m_defaultClause) {
// Backpatch default label address.
generator.emitLabel(defaultLabel.get());
// Generate bytecode for the default clause.
m_defaultClause->emitBytecode(generator, dst);
}

// Cases after default.
for (ClauseListNode* list = m_list2; list; list = list->getNext()) {
generator.emitLabel(labelVector[i++].get());
list->getClause()->emitBytecode(generator, dst);
}

// If there is no default, set its jump address to the end of switch.
if (!m_defaultClause)
generator.emitLabel(defaultLabel.get());

if (switchType != SwitchInfo::SwitchNone) {
generator.endSwitch(labelVector.size(), labelVector.data(), literalVector.data(), defaultLabel.get(), min_num, max_num);
}
}
1
2
3
4
5
6
7
8
switch E
begin
case V1 : S1
case V2 : S2
...
case Vn-1 : Sn-1
default : Sn
end

In the ordinary case, SwitchNode might be translated sequentially like this, which is relatively inefficient:

JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2: SwitchNode (figure 3)

JavaScriptCore uses another translation strategy for SwitchNode. During code generation, if the number of branches falls within a relatively small range, the conditional jump sequence can be translated into a more efficient n-way branch.

JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2: SwitchNode (figure 4)

You can see that the jump table for SwitchNone differs from the other three modes. Its jump table appears earlier, but there is no essential difference.

Loop Structures

WhileNode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void WhileNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
// Generate a scope label for continue and break.
LabelScopePtr scope = generator.newLabelScope(LabelScope::Loop);

// Generate the start-address label for the loop body.
RefPtr<Label> topOfLoop = generator.newLabel();

// Generate bytecode for the condition expression. If true, jump to topOfLoop;
// otherwise jump to breakTarget.
generator.emitNodeInConditionContext(m_expr, topOfLoop.get(), scope->breakTarget(), FallThroughMeansTrue);

// Backpatch the start address.
generator.emitLabel(topOfLoop.get());

// Insert the op_loop_hint instruction.
generator.emitLoopHint();

// Generate bytecode for the loop body.
generator.emitNodeInTailPosition(dst, m_statement);

// Backpatch continueTarget.
generator.emitLabel(scope->continueTarget());

// Generate bytecode for the condition expression again. If true, jump to
// topOfLoop; otherwise jump to breakTarget.
generator.emitNodeInConditionContext(m_expr, topOfLoop.get(), scope->breakTarget(), FallThroughMeansFalse);

// Backpatch breakTarget.
generator.emitLabel(scope->breakTarget());

}

Here is the SDT for WhileNode:

JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2: WhileNode (figure 5)

break and continue appear often in loops. Let’s see how their bytecode is generated.

BreakNode

1
2
3
4
5
6
void BreakNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
LabelScopePtr scope = generator.breakTarget(m_ident);
generator.emitPopScopes(generator.scopeRegister(), scope->scopeDepth());
generator.emitJump(scope->breakTarget());
}

ContinueNode

1
2
3
4
5
6
void ContinueNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
LabelScopePtr scope = generator.continueTarget(m_ident);
generator.emitPopScopes(generator.scopeRegister(), scope->scopeDepth());
generator.emitJump(scope->continueTarget());
}

Both eventually add a jump instruction, jumping to the breakTarget or continueTarget of their owning scope.

You can also see that scopes are popped. This is easy to understand: break and continue are only valid in specific contexts, such as loop structures and switch structures. Once either is triggered, execution may leave the current switch or loop scope directly.

Sequential Structures

Unlike the previous two categories, sequential structures produce more concrete and detailed bytecode.

ClassDeclNode

The bytecode-generation statement for class declaration node ClassDeclNode is only one familiar line:

1
2
3
4
void ClassDeclNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
generator.emitNode(dst, m_classDeclaration);
}

The type of m_classDeclaration is ClassExprNode, a subclass of ExpressionNode. The bytecode generation of this expression will be analyzed in detail later.

ReturnNode

1
2
3
4
5
6
7
8
9
10
11
12
13
void ReturnNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
// Ignore return value.
if (dst == generator.ignoredResult()) dst = 0;

// Generate bytecode for the expression after return.
RefPtr<RegisterID> returnRegister = m_value ?
generator.emitNodeInTailPosition(dst, m_value) :
generator.emitLoad(dst, jsUndefined());

...
generator.emitReturn(returnRegister.get());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
{
// There is actually special handling here for constructors.
...

// Generate bytecode for a unary operator.
return emitUnaryNoDstOp(op_ret, src);
}
RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
{
emitOpcode(opcodeID);
instructions().append(src->index());
return src;
}

You can see that an op_ret instruction is inserted into instructions, and the following src->index() is the offset of src in the virtual register VirtualRegister.

LabelNode

The bytecode for LabelNode is simple. It mainly generates a jump label.

1
2
3
4
5
6
void LabelNode::emitBytecode(BytecodeGenerator& generator, RegisterID* dst)
{
LabelScopePtr scope = generator.newLabelScope(LabelScope::NamedLabel, &m_name);
generator.emitNodeInTailPosition(dst, m_statement);
generator.emitLabel(scope->breakTarget());
}

FuncDeclNode

A function declaration is essentially function registration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void FuncDeclNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
generator.hoistSloppyModeFunctionIfNecessary(metadata()->ident());
}

void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
{
if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl()))
{
Variable currentFunctionVariable = variable(functionName);
RefPtr<RegisterID> currentValue;
if (RegisterID* local = currentFunctionVariable.local())
currentValue = local;
else
{
RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
}

// Locate the symbol table.
SymbolTableStackEntry& varScope = m_symbolTableStack[*m_varScopeSymbolTableIndex];
SymbolTable* varSymbolTable = varScope.m_symbolTable;

// Lock.
ConcurrentJITLocker locker(ConcurrentJITLocker::NoLockingNecessary);

// Find the function's symbol entry.
SymbolTableEntry entry = varSymbolTable->get(locker, functionName.impl());
bool isLexicallyScoped = false;

emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
}
}

To Be Continued

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 2

Author:lingyun

Published:2018-08-15 00:34

Updated:2026-10-08 00:23

Original link:https://tsuijunxi.github.io/en/2018/08/15/javascriptcore-deep-dive-5-bytecode-generation-part-2/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.