JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 1

Preface

After JavaScript source code goes through lexical analysis and syntax analysis, it produces a syntax tree. The next task is to convert that syntax tree into bytecode, which is the subject of this article.

This whole process is essentially a step every programming language must go through: compilation. But unlike many languages such as C, C++, and Objective-C, after JavaScript compilation finishes, it does not generate object code or an executable file stored on disk. The generated bytecode may be interpreted line by line by the virtual machine immediately, or it may be cached and later converted into native code through JIT.

CodeCache

In the opening article, we mentioned the following diagram:

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

After syntax analysis finishes, it is time for CodeCache to show up. As the name suggests, it is responsible for caching CodeBlock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CodeCache {
public:
CodeCache();
~CodeCache();

UnlinkedProgramCodeBlock* getProgramCodeBlock(VM&, ProgramExecutable*, const SourceCode&, JSParserBuiltinMode, JSParserStrictMode, DebuggerMode, ParserError&);
UnlinkedEvalCodeBlock* getEvalCodeBlock(VM&, EvalExecutable*, const SourceCode&, JSParserBuiltinMode, JSParserStrictMode, DebuggerMode, ParserError&, EvalContextType, const VariableEnvironment*);
UnlinkedModuleProgramCodeBlock* getModuleProgramCodeBlock(VM&, ModuleProgramExecutable*, const SourceCode&, JSParserBuiltinMode, DebuggerMode, ParserError&);
UnlinkedFunctionExecutable* getFunctionExecutableFromGlobalCode(VM&, const Identifier&, const SourceCode&, ParserError&);

private:
template <class UnlinkedCodeBlockType, class ExecutableType>
UnlinkedCodeBlockType* getGlobalCodeBlock(VM&, ExecutableType*, const SourceCode&, JSParserBuiltinMode, JSParserStrictMode, DebuggerMode, ParserError&, EvalContextType, const VariableEnvironment*);

CodeCacheMap m_sourceCode;
};
  • m_sourceCode is a container used to store CodeBlock.
  • CodeCache has four getXXXCodeBlock methods for retrieving different kinds of CodeBlock. The first three eventually call getGlobalCodeBlock.
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
template <class UnlinkedCodeBlockType, class ExecutableType>
UnlinkedCodeBlockType* CodeCache::getGlobalCodeBlock(VM& vm, ExecutableType* executable, const SourceCode& source, JSParserBuiltinMode builtinMode, JSParserStrictMode strictMode, DebuggerMode debuggerMode, ParserError& error, EvalContextType evalContextType, const VariableEnvironment* variablesUnderTDZ)
{
...

// Generate key.
SourceCodeKey key(source, String(), CacheTypes<UnlinkedCodeBlockType>::codeType, builtinMode, strictMode, derivedContextType, evalContextType, isArrowFunctionContext);

// Look up cache.
SourceCodeValue* cache = m_sourceCode.findCacheAndUpdateAge(key);

// If hit, return UnlinkedCodeBlock directly.
if (cache && canCache) {
UnlinkedCodeBlockType* unlinkedCodeBlock = jsCast<UnlinkedCodeBlockType*>(cache->cell.get());
...
return unlinkedCodeBlock;
}

...

// Otherwise, define an UnlinkedCodeBlock to store bytecode generated by BytecodeGenerator.
UnlinkedCodeBlockType* unlinkedCodeBlock = UnlinkedCodeBlockType::create(&vm, executable->executableInfo(), debuggerMode);
unlinkedCodeBlock->recordParse(rootNode->features(), rootNode->hasCapturedVariables(), rootNode->firstLine() - source.firstLine(), lineCount, unlinkedEndColumn);
unlinkedCodeBlock->setSourceURLDirective(source.provider()->sourceURL());
unlinkedCodeBlock->setSourceMappingURLDirective(source.provider()->sourceMappingURL());

// Call BytecodeGenerator to generate bytecode.
error = BytecodeGenerator::generate(vm, rootNode.get(), unlinkedCodeBlock, debuggerMode, variablesUnderTDZ);

// Add cache for later lookup.
m_sourceCode.addCache(key, SourceCodeValue(vm, unlinkedCodeBlock, m_sourceCode.age()));

// Return UnlinkedCodeBlock.
return unlinkedCodeBlock;
}

getFunctionExecutableFromGlobalCode is special:

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
UnlinkedFunctionExecutable* CodeCache::getFunctionExecutableFromGlobalCode(VM& vm, const Identifier& name, const SourceCode& source, ParserError& error)
{
bool isArrowFunctionContext = false;
// Define key.
SourceCodeKey key(
source, name.string(), SourceCodeType::FunctionType,
JSParserBuiltinMode::NotBuiltin,
JSParserStrictMode::NotStrict,
DerivedContextType::None,
EvalContextType::None,
isArrowFunctionContext);

// Look up cache.
SourceCodeValue* cache = m_sourceCode.findCacheAndUpdateAge(key);

// If hit.
if (cache) {
UnlinkedFunctionExecutable* executable = jsCast<UnlinkedFunctionExecutable*>(cache->cell.get());
source.provider()->setSourceURLDirective(executable->sourceURLDirective());
source.provider()->setSourceMappingURLDirective(executable->sourceMappingURLDirective());
return executable;
}

JSTextPosition positionBeforeLastNewline;

// Generate ProgramNode.
std::unique_ptr<ProgramNode> program = parse<ProgramNode>(
&vm, source, Identifier(), JSParserBuiltinMode::NotBuiltin,
JSParserStrictMode::NotStrict, SourceParseMode::ProgramMode, SuperBinding::NotNeeded,
error, &positionBeforeLastNewline);
if (!program) {
return nullptr;
}

// This function assumes an input string that would result in a single function declaration.
StatementNode* statement = program->singleStatement();
if (!statement || !statement->isBlock())
return nullptr;

StatementNode* funcDecl = static_cast<BlockNode*>(statement)->singleStatement();
if (!funcDecl || !funcDecl->isFuncDeclNode())
return nullptr;

FunctionMetadataNode* metadata = static_cast<FuncDeclNode*>(funcDecl)->metadata();
if (!metadata)
return nullptr;

metadata->overrideName(name);
metadata->setEndPosition(positionBeforeLastNewline);
// The Function constructor only has access to global variables, so no variables will be under TDZ.
VariableEnvironment emptyTDZVariables;

// Define UnlinkedFunctionExecutable.
UnlinkedFunctionExecutable* functionExecutable = UnlinkedFunctionExecutable::create(&vm, source, metadata, UnlinkedNormalFunction, ConstructAbility::CanConstruct, emptyTDZVariables, DerivedContextType::None);

functionExecutable->setSourceURLDirective(source.provider()->sourceURL());
functionExecutable->setSourceMappingURLDirective(source.provider()->sourceMappingURL());

// Add cache.
m_sourceCode.addCache(key, SourceCodeValue(vm, functionExecutable, m_sourceCode.age()));

// Return.
return functionExecutable;
}

It does not return a CodeBlock; it returns an UnlinkedFunctionExecutable. However, inside UnlinkedFunctionExecutable, the method generateUnlinkedFunctionCodeBlock also calls BytecodeGenerator::generate:

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
static UnlinkedFunctionCodeBlock* generateUnlinkedFunctionCodeBlock(
VM& vm, UnlinkedFunctionExecutable* executable, const SourceCode& source,
CodeSpecializationKind kind, DebuggerMode debuggerMode,
UnlinkedFunctionKind functionKind, ParserError& error, SourceParseMode parseMode)
{
JSParserBuiltinMode builtinMode = executable->isBuiltinFunction() ? JSParserBuiltinMode::Builtin : JSParserBuiltinMode::NotBuiltin;
JSParserStrictMode strictMode = executable->isInStrictContext() ? JSParserStrictMode::Strict : JSParserStrictMode::NotStrict;

std::unique_ptr<FunctionNode> function = parse<FunctionNode>(
&vm, source, executable->name(), builtinMode, strictMode, executable->parseMode(), executable->superBinding(), error, nullptr);

if (!function) {
return nullptr;
}

function->finishParsing(executable->name(), executable->functionMode());
executable->recordParse(function->features(), function->hasCapturedVariables());

bool isClassContext = executable->superBinding() == SuperBinding::Needed;

// Generate an UnlinkedFunctionCodeBlock.
UnlinkedFunctionCodeBlock* result = UnlinkedFunctionCodeBlock::create(&vm, FunctionCode, ExecutableInfo(function->usesEval(), function->isStrictMode(), kind == CodeForConstruct, functionKind == UnlinkedBuiltinFunction, executable->constructorKind(), executable->superBinding(), parseMode, executable->derivedContextType(), false, isClassContext, EvalContextType::FunctionEvalContext), debuggerMode);

// Call BytecodeGenerator to generate bytecode.
error = BytecodeGenerator::generate(vm, function.get(), result, debuggerMode, executable->parentScopeTDZVariables());

if (error.isValid()) return nullptr;
return result;
}

After following this path, it becomes clear that exploring BytecodeGenerator is especially important.

BytecodeGenerator

BytecodeGenerator means exactly what its name says: it generates bytecode. It exposes a class method named generate. Inside, it calls the constructor to create a temporary BytecodeGenerator, then calls its parameterless generate method. The return value indicates whether a parse error occurred, while the actual bytecode result is stored in the third parameter, CodeBlock.

1
2
3
4
5
6
template<typename... Args>
static ParserError generate(VM& vm, Args&& ...args)
{
auto bytecodeGenerator = std::make_unique<BytecodeGenerator>(vm, std::forward<Args>(args)...);
return bytecodeGenerator->generate();
}

Next, let’s look at several of its private constructors:

1
2
3
4
5
6
7
8
9
10
11
12
13
class BytecodeGenerator 
{
BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, const VariableEnvironment*);
BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, const VariableEnvironment*);
BytecodeGenerator(VM&, ModuleProgramNode*, UnlinkedModuleProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);

~BytecodeGenerator();
...

private:
Strong<UnlinkedCodeBlock> m_codeBlock;
}

BytecodeGenerator needs the following parameters. Except for DebuggerMode, any one of them could easily take an entire article to explain, so I will keep this brief.

  • VM: the virtual machine.
  • Node: one of ProgramNode, FunctionNode, EvalNode, or ModuleProgramNode.
  • UnlinkedCodeBlock: corresponding to the node, one of UnlinkedProgramCodeBlock, UnlinkedFunctionCodeBlock, UnlinkedEvalCodeBlock, or UnlinkedModuleProgramCodeBlock.
  • DebuggerMode: whether it is in debug mode.
  • VariableEnvironment: the variable environment.

Parameter Analysis

VM

As shown by the VMType enum, there are three types of VM:

1
enum VMType { Default, APIContextGroup, APIShared };
1
2
3
4
5
6
7
// WebCore has a one-to-one mapping of threads to VMs;
// either create() or createLeaked() should only be called once
// on a thread, this is the 'default' VM .
// API contexts created using the new context group aware interface
// create APIContextGroup objects which require less locking of JSC
// than the old singleton APIShared VM created for use by
// the original API.

The definition of VM is shown below. Its constructor is private and cannot be accessed externally. I also list several members that I consider important:

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
class VM : public ThreadSafeRefCounted<VM> {
public:

// APIShared creation mode: singleton.
bool isSharedInstance() { return vmType == APIShared; }
bool usingAPI() { return vmType != Default; }
JS_EXPORT_PRIVATE static bool sharedInstanceExists();
JS_EXPORT_PRIVATE static VM& sharedInstance();

// Default creation mode.
JS_EXPORT_PRIVATE static Ref<VM> create(HeapType = SmallHeap);
JS_EXPORT_PRIVATE static Ref<VM> createLeaked(HeapType = SmallHeap);

// APIContextGroup creation mode.
static Ref<VM> createContextGroup(HeapType = SmallHeap);
...

private:
// Lock.
RefPtr<JSLock> m_apiLock;

public:
ExecutableAllocator executableAllocator;
Heap heap;
VMType vmType;
VMEntryFrame* topVMEntryFrame;
ExecState* topCallFrame;

// A large number of Structure objects.
Strong<Structure> structureStructure;
Strong<Structure> structureRareDataStructure;
Strong<Structure> terminatedExecutionErrorStructure;
Strong<Structure> stringStructure;
Strong<Structure> propertyNameIteratorStructure;
Strong<Structure> propertyNameEnumeratorStructure;
Strong<Structure> customGetterSetterStructure;
Strong<Structure> scopedArgumentsTableStructure;
Strong<Structure> apiWrapperStructure;
Strong<Structure> JSScopeStructure;
Strong<Structure> executableStructure;
Strong<Structure> nativeExecutableStructure;
Strong<Structure> evalExecutableStructure;
Strong<Structure> programExecutableStructure;
Strong<Structure> functionExecutableStructure;
...

PrototypeMap prototypeMap;
SourceProviderCacheMap sourceProviderCacheMap;
Interpreter* interpreter;
...

ExecState* newCallFrameReturnValue;
ExecState* callFrameForCatch;

...

ExecState is the object that executes scripts. It is managed by GlobalObject and records the script execution context.

Node

In the syntax-analysis article, we mentioned the inheritance graph of Node. The four kinds of Node discussed here all inherit from ScopeNode, and ScopeNode inherits from StatementNode. Obviously, these four node types are basic statements and are related to scope.

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

UnlinkedCodeBlock

UnlinkedCodeBlock is a code-management class. It mainly has four variants: UnlinkedProgramCodeBlock, UnlinkedFunctionCodeBlock, UnlinkedEvalCodeBlock, and UnlinkedModuleProgramCodeBlock. It stores compiled bytecode. Its inheritance hierarchy is shown below:

JavaScriptCore Deep Dive 5 - Bytecode Generation, Part 1: UnlinkedCodeBlock (figure 3)

There is also a corresponding CodeBlock, mainly used by LLInt and JIT. Its inheritance hierarchy is extremely similar to UnlinkedCodeBlock; later articles in the series will cover it.

VariableEnvironment

VariableEnvironment has a very important member variable, m_map, which stores marked variables:

1
Map m_map;

Its key is of type UniquedStringImpl*, and its value is the enum type Traits:

1
2
3
4
5
6
7
8
9
10
11
12
13
enum Traits : uint16_t 
{
IsCaptured = 1 << 0,
IsConst = 1 << 1,
IsVar = 1 << 2,
IsLet = 1 << 3,
IsExported = 1 << 4,
IsImported = 1 << 5,
IsImportedNamespace = 1 << 6,
IsFunction = 1 << 7,
IsParameter = 1 << 8,
IsSloppyModeHoistingCandidate = 1 << 9
};

It also has several important methods for capturing and marking variables:

1
2
3
4
5
6
7
8
bool hasCapturedVariables() const;
bool captures(UniquedStringImpl* identifier) const;

void markVariableAsCapturedIfDefined(const RefPtr<UniquedStringImpl>& identifier);
void markVariableAsCaptured(const RefPtr<UniquedStringImpl>& identifier);
void markAllVariablesAsCaptured();
void markVariableAsImported(const RefPtr<UniquedStringImpl>& identifier);
void markVariableAsExported(const RefPtr<UniquedStringImpl>& identifier);

From these method names and enum values, we can roughly infer that it marks variable context: whether a variable is captured by a closure, imported, exported, and so on.

generate

Now it is time to analyze the core generate function.

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
ParserError BytecodeGenerator::generate()
{
// Set this register.
m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());

// Set the special arguments parameter and ordinary parameters.
if (m_needToInitializeArguments)
initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
if (m_restParameter)
m_restParameter->emit(*this);

...

// If this is not a constructor, call emitBytecode to generate bytecode.
bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
if (!callingClassConstructor)
m_scopeNode->emitBytecode(*this);

....

// Store the generated bytecode instructions into m_codeBlock.
m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
m_codeBlock->shrinkToFit();

// Exception handling.
if (m_expressionTooDeep)
return ParserError(ParserError::OutOfMemory);
return ParserError(ParserError::ErrorNone);
}

emitBytecode

The four node types mentioned above all inherit from ScopeNode, so we can analyze this through polymorphism.

ProgramNode

1
2
3
4
void ProgramNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
emitProgramNodeBytecode(generator, *this);
}
1
2
3
4
5
6
7
8
static void emitProgramNodeBytecode(BytecodeGenerator& generator, ScopeNode& scopeNode)
{
RefPtr<RegisterID> dstRegister = generator.newTemporary();
generator.emitLoad(dstRegister.get(), jsUndefined());
generator.emitProfileControlFlow(scopeNode.startStartOffset());
scopeNode.emitStatementsBytecode(generator, dstRegister.get());
generator.emitEnd(dstRegister.get());
}

Call stack:

1
2
3
ProgramNode::emitBytecode
└──emitProgramNodeBytecode
└──emitStatementsBytecode

ModuleProgramNode

1
2
3
4
void ModuleProgramNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
emitProgramNodeBytecode(generator, *this);
}

ModuleProgramNode and ProgramNode therefore share the same emitBytecode call stack:

1
2
3
ModuleProgramNode::emitBytecode
└──emitProgramNodeBytecode
└──emitStatementsBytecode

EvalNode

1
2
3
4
5
6
7
void EvalNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
RefPtr<RegisterID> dstRegister = generator.newTemporary();
generator.emitLoad(dstRegister.get(), jsUndefined());
emitStatementsBytecode(generator, dstRegister.get());
generator.emitEnd(dstRegister.get());
}

Call stack:

1
2
EvalNode::emitBytecode
└──emitStatementsBytecode

FunctionNode

Bytecode generation for FunctionNode is more complicated. It distinguishes several parse modes:

1
2
3
4
5
6
7
8
9
10
11
12
enum class SourceParseMode : uint8_t {
NormalFunctionMode,
GeneratorBodyMode,
GeneratorWrapperFunctionMode,
GetterMode,
SetterMode,
MethodMode,
ArrowFunctionMode,
ProgramMode,
ModuleAnalyzeMode,
ModuleEvaluateMode
};

The first seven modes all fall under the function category. GeneratorWrapperFunctionMode and GeneratorBodyMode are handled separately, while the others take the default path.

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
92
93
94
95
96
97
98
99
void FunctionNode::emitBytecode(BytecodeGenerator& generator, RegisterID*)
{
...

switch (generator.parseMode())
{
case SourceParseMode::GeneratorWrapperFunctionMode:
{
StatementNode* singleStatement = this->singleStatement();
ExprStatementNode* exprStatement = static_cast<ExprStatementNode*>(singleStatement);
ExpressionNode* expr = exprStatement->expr();
FuncExprNode* funcExpr = static_cast<FuncExprNode*>(expr);

RefPtr<RegisterID> next = generator.newTemporary();
generator.emitNode(next.get(), funcExpr);

if (generator.superBinding() == SuperBinding::Needed) {
RefPtr<RegisterID> homeObject = emitHomeObjectForCallee(generator);
emitPutHomeObject(generator, next.get(), homeObject.get());
}

// FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
// But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
// https://bugs.webkit.org/show_bug.cgi?id=151545

generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorNextPrivateName, next.get(), PropertyNode::KnownDirect);

generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorThisPrivateName, generator.thisRegister(), PropertyNode::KnownDirect);

RegisterID* initialState = generator.emitLoad(nullptr, jsNumber(0));
generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorStatePrivateName, initialState, PropertyNode::KnownDirect);

generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorFramePrivateName, generator.emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);


generator.emitReturn(generator.generatorRegister());
break;
}

case SourceParseMode::GeneratorBodyMode:
{
RefPtr<Label> generatorBodyLabel = generator.newLabel();
{
RefPtr<RegisterID> condition = generator.newTemporary();
generator.emitEqualityOp(op_stricteq, condition.get(), generator.generatorResumeModeRegister(), generator.emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSGeneratorFunction::GeneratorResumeMode::NormalMode))));
generator.emitJumpIfTrue(condition.get(), generatorBodyLabel.get());

RefPtr<Label> throwLabel = generator.newLabel();
generator.emitEqualityOp(op_stricteq, condition.get(), generator.generatorResumeModeRegister(), generator.emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSGeneratorFunction::GeneratorResumeMode::ThrowMode))));
generator.emitJumpIfTrue(condition.get(), throwLabel.get());

generator.emitReturn(generator.generatorValueRegister());

generator.emitLabel(throwLabel.get());
generator.emitThrow(generator.generatorValueRegister());
}

generator.emitLabel(generatorBodyLabel.get());

emitStatementsBytecode(generator, generator.ignoredResult());

RefPtr<Label> done = generator.newLabel();
generator.emitLabel(done.get());
generator.emitReturn(generator.emitLoad(nullptr, jsUndefined()));
generator.endGenerator(done.get());
break;
}

default:
{
// Once again, it reaches emitStatementsBytecode.
emitStatementsBytecode(generator, generator.ignoredResult());

StatementNode* singleStatement = this->singleStatement();
ReturnNode* returnNode = 0;

// Check for a return statement at the end of a function composed of a single block.
if (singleStatement && singleStatement->isBlock()) {
StatementNode* lastStatementInBlock = static_cast<BlockNode*>(singleStatement)->lastStatement();
if (lastStatementInBlock && lastStatementInBlock->isReturnNode())
returnNode = static_cast<ReturnNode*>(lastStatementInBlock);
}

// If there is no return we must automatically insert one.
if (!returnNode)
{
if (generator.constructorKind() == ConstructorKind::Derived && generator.needsToUpdateArrowFunctionContext() && generator.isSuperCallUsedInInnerArrowFunction())
generator.emitLoadThisFromArrowFunctionLexicalEnvironment(); // Arrow function can invoke 'super' in constructor and before leave constructor we need load 'this' from lexical arrow function environment

RegisterID* r0 = generator.isConstructor() ? generator.thisRegister() : generator.emitLoad(0, jsUndefined());
generator.emitProfileType(r0, ProfileTypeBytecodeFunctionReturnStatement); // Do not emit expression info for this profile because it's not in the user's source code.

generator.emitReturn(r0);
return;
}
break;
}
}
}

Both GeneratorWrapperFunctionMode and GeneratorBodyMode contain Generator, so they are probably related to the ES6 Generator function. Briefly:

In form, a Generator function is still an ordinary function, but it has two characteristics. First, there is an asterisk between the function keyword and the function name. Second, the function body uses yield expressions to define different internal states.

GeneratorBodyMode looks like this:

1
2
3
4
5
6
7
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}

var hw = helloWorldGenerator();

GeneratorWrapperFunctionMode looks like this:

1
2
3
4
5
6
7
8
9
10
11
function *gen(a, b = hello())
{
return
{
@generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode)
{
arguments; // This `arguments` should reference to the gen's arguments.
...
}
}
}

This is only a brief introduction. I will not go deeper here, because the real focus is bytecode generation.

No matter which of the above nodes calls emitBytecode, the flow eventually reaches emitStatementsBytecode. After all, whether it is ProgramNode, EvalNode, or FunctionNode, it is composed of basic statements. Therefore, bytecode generation eventually becomes related to the various Node types discussed in the syntax-analysis article.

It is also reasonable to infer that emitStatementsBytecode is only a starting point, not the end. Inside it, many recursive and looping calls may still be waiting for us.

To Be Continued

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

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

Author:lingyun

Published:2018-08-10 00:34

Updated:2026-10-08 00:23

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

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