forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathBytecodeGeneratorification.cpp
More file actions
380 lines (324 loc) · 15.6 KB
/
Copy pathBytecodeGeneratorification.cpp
File metadata and controls
380 lines (324 loc) · 15.6 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
* Copyright (C) 2016 Yusuke Suzuki <utatane.tea@gmail.com>
* Copyright (C) 2016-2021 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BytecodeGeneratorification.h"
#include "BytecodeDumper.h"
#include "BytecodeGeneratorBaseInlines.h"
#include "BytecodeLivenessAnalysisInlines.h"
#include "BytecodeRewriter.h"
#include "BytecodeStructs.h"
#include "BytecodeUseDef.h"
#include "JSGenerator.h"
#include "Label.h"
#include "StrongInlines.h"
#include "UnlinkedCodeBlockGenerator.h"
#include "UnlinkedMetadataTableInlines.h"
#include <wtf/HashMap.h>
namespace JSC {
struct YieldData {
JSInstructionStream::Offset point { 0 };
VirtualRegister argument { 0 };
FastBitVector liveness;
};
class BytecodeGeneratorification {
public:
typedef Vector<YieldData> Yields;
struct GeneratorFrameData {
JSInstructionStream::Offset m_point;
VirtualRegister m_dst;
VirtualRegister m_scope;
VirtualRegister m_symbolTable;
VirtualRegister m_initialValue;
};
BytecodeGeneratorification(BytecodeGenerator& bytecodeGenerator, UnlinkedCodeBlockGenerator* codeBlock, JSInstructionStreamWriter& instructions, SymbolTable* generatorFrameSymbolTable, int generatorFrameSymbolTableIndex)
: m_bytecodeGenerator(bytecodeGenerator)
, m_codeBlock(codeBlock)
, m_instructions(instructions)
, m_graph(m_codeBlock, m_instructions)
, m_generatorFrameSymbolTable(codeBlock->vm(), generatorFrameSymbolTable)
, m_generatorFrameSymbolTableIndex(generatorFrameSymbolTableIndex)
{
for (const auto& instruction : m_instructions) {
switch (instruction->opcodeID()) {
case op_enter: {
m_enterPoint = instruction.offset();
break;
}
case op_yield: {
auto bytecode = instruction->as<OpYield>();
unsigned liveCalleeLocalsIndex = bytecode.m_yieldPoint;
if (liveCalleeLocalsIndex >= m_yields.size())
m_yields.grow(liveCalleeLocalsIndex + 1);
YieldData& data = m_yields[liveCalleeLocalsIndex];
data.point = instruction.offset();
data.argument = bytecode.m_argument;
break;
}
case op_create_generator_frame_environment: {
auto bytecode = instruction->as<OpCreateGeneratorFrameEnvironment>();
GeneratorFrameData data;
data.m_point = instruction.offset();
data.m_dst = bytecode.m_dst;
data.m_scope = bytecode.m_scope;
data.m_symbolTable = bytecode.m_symbolTable;
data.m_initialValue = bytecode.m_initialValue;
m_generatorFrameData = WTF::move(data);
break;
}
default:
break;
}
}
}
struct Storage {
Identifier identifier;
unsigned identifierIndex;
ScopeOffset scopeOffset;
};
void run();
BytecodeGraph& NODELETE graph() { return m_graph; }
const Yields& NODELETE yields() const
{
return m_yields;
}
Yields& NODELETE yields()
{
return m_yields;
}
JSInstructionStream::Ref NODELETE enterPoint() const
{
return m_instructions.at(m_enterPoint);
}
std::optional<GeneratorFrameData> NODELETE generatorFrameData() const
{
return m_generatorFrameData;
}
const JSInstructionStream& NODELETE instructions() const
{
return m_instructions;
}
private:
Storage storageForGeneratorLocal(VM& vm, unsigned index)
{
// We assign a symbol to a register. There is one-on-one corresponding between a register and a symbol.
// By doing so, we allocate the specific storage to save the given register.
// This allow us not to save all the live registers even if the registers are not overwritten from the previous resuming time.
// It means that, the register can be retrieved even if the immediate previous op_save does not save it.
if (m_storages.size() <= index)
m_storages.grow(index + 1);
if (std::optional<Storage> storage = m_storages[index])
return *storage;
Identifier identifier = Identifier::from(vm, index);
unsigned identifierIndex = m_codeBlock->numberOfIdentifiers();
m_codeBlock->addIdentifier(identifier);
ScopeOffset scopeOffset = m_generatorFrameSymbolTable->takeNextScopeOffset(NoLockingNecessary);
m_generatorFrameSymbolTable->add(NoLockingNecessary, identifier.impl(), SymbolTableEntry(VarOffset(scopeOffset)));
Storage storage = {
identifier,
identifierIndex,
scopeOffset
};
m_storages[index] = storage;
return storage;
}
void emitBulkSaveAndRestore(BytecodeRewriter&);
void emitPerLocalSaveAndRestore(BytecodeRewriter&);
BytecodeGenerator& m_bytecodeGenerator;
JSInstructionStream::Offset m_enterPoint;
std::optional<GeneratorFrameData> m_generatorFrameData;
UnlinkedCodeBlockGenerator* m_codeBlock;
JSInstructionStreamWriter& m_instructions;
BytecodeGraph m_graph;
Vector<std::optional<Storage>> m_storages;
Yields m_yields;
Strong<SymbolTable> m_generatorFrameSymbolTable;
int m_generatorFrameSymbolTableIndex;
};
class GeneratorLivenessAnalysis : public BytecodeLivenessPropagation {
public:
GeneratorLivenessAnalysis(BytecodeGeneratorification& generatorification)
: m_generatorification(generatorification)
{
}
void run(UnlinkedCodeBlockGenerator* codeBlock, JSInstructionStreamWriter& instructions)
{
// Perform modified liveness analysis to determine which locals are live at the merge points.
// This produces the conservative results for the question, "which variables should be saved and resumed?".
runLivenessFixpoint(codeBlock, instructions, m_generatorification.graph());
for (YieldData& data : m_generatorification.yields())
data.liveness = getLivenessInfoAtInstruction(codeBlock, instructions, m_generatorification.graph(), BytecodeIndex(m_generatorification.instructions().at(data.point).next().offset()));
}
private:
BytecodeGeneratorification& m_generatorification;
};
void BytecodeGeneratorification::run()
{
// We calculate the liveness at each merge point. This gives us the information which registers should be saved and resumed conservatively.
{
GeneratorLivenessAnalysis pass(*this);
pass.run(m_codeBlock, m_instructions);
}
BytecodeRewriter rewriter(m_bytecodeGenerator, m_graph, m_codeBlock, m_instructions);
// Setup the global switch for the generator.
{
auto nextToEnterPoint = enterPoint().next();
unsigned switchTableIndex = m_codeBlock->numberOfUnlinkedSwitchJumpTables();
VirtualRegister state = virtualRegisterForArgumentIncludingThis(static_cast<int32_t>(JSGenerator::Argument::State));
auto& jumpTable = m_codeBlock->addUnlinkedSwitchJumpTable();
jumpTable.m_min = 0;
jumpTable.m_branchOffsets = FixedVector<int32_t>(m_yields.size() + 1);
std::ranges::fill(jumpTable.m_branchOffsets, 0);
jumpTable.add(0, nextToEnterPoint.offset());
for (unsigned i = 0; i < m_yields.size(); ++i)
jumpTable.add(i + 1, m_yields[i].point);
jumpTable.m_defaultOffset = nextToEnterPoint.offset();
rewriter.insertFragmentBefore(nextToEnterPoint, [&] (BytecodeRewriter::Fragment& fragment) {
fragment.appendInstruction<OpSwitchImm>(switchTableIndex, state);
});
}
if (Options::useGeneratorBulkSaveRestore())
emitBulkSaveAndRestore(rewriter);
else
emitPerLocalSaveAndRestore(rewriter);
if (m_generatorFrameData) {
auto instruction = m_instructions.at(m_generatorFrameData->m_point);
rewriter.replaceBytecodeWithFragment(instruction, [&] (BytecodeRewriter::Fragment& fragment) {
if (!m_generatorFrameSymbolTable->scopeSize()) {
// This will cause us to put jsUndefined() into the generator frame's scope value.
fragment.appendInstruction<OpMov>(m_generatorFrameData->m_dst, m_generatorFrameData->m_initialValue);
} else
fragment.appendInstruction<OpCreateLexicalEnvironment>(m_generatorFrameData->m_dst, m_generatorFrameData->m_scope, m_generatorFrameData->m_symbolTable, m_generatorFrameData->m_initialValue);
});
}
rewriter.execute();
}
void BytecodeGeneratorification::emitBulkSaveAndRestore(BytecodeRewriter& rewriter)
{
BitVector savedLocals;
for (const YieldData& data : m_yields) {
data.liveness.forEachSetBit([&](size_t index) {
savedLocals.set(index);
});
}
unsigned firstScopeOffset = m_generatorFrameSymbolTable->scopeSize();
for (unsigned i = 0, count = savedLocals.bitCount(); i < count; ++i) {
ScopeOffset scopeOffset = m_generatorFrameSymbolTable->takeNextScopeOffset(NoLockingNecessary);
ASSERT_UNUSED(scopeOffset, scopeOffset.offset() == firstScopeOffset + i);
}
unsigned numberOfLocalBits = savedLocals.size();
UncheckedKeyHashMap<BitVector, unsigned> bitVectorIndices;
auto addBitVectorConstant = [&](const BitVector& bitVector) {
return bitVectorIndices.ensure(bitVector, [&] {
return m_codeBlock->addBitVector(BitVector(bitVector));
}).iterator->value;
};
unsigned savedLocalsIndex = savedLocals.isEmpty() ? 0 : addBitVectorConstant(savedLocals);
for (const YieldData& data : m_yields) {
VirtualRegister scope = virtualRegisterForArgumentIncludingThis(static_cast<int32_t>(JSGenerator::Argument::Frame));
auto instruction = m_instructions.at(data.point);
if (data.liveness.isEmpty()) {
rewriter.insertFragmentBefore(instruction, [&] (BytecodeRewriter::Fragment& fragment) {
fragment.appendInstruction<OpRet>(data.argument);
});
rewriter.replaceBytecodeWithFragment(instruction, [&] (BytecodeRewriter::Fragment&) { });
continue;
}
BitVector liveLocals;
liveLocals.ensureSize(numberOfLocalBits);
data.liveness.forEachSetBit([&](size_t index) {
liveLocals.quickSet(index);
});
unsigned liveLocalsIndex = addBitVectorConstant(liveLocals);
unsigned firstValueProfile = m_bytecodeGenerator.nextValueProfileIndex();
for (unsigned i = 1, count = data.liveness.bitCount(); i < count; ++i)
m_bytecodeGenerator.nextValueProfileIndex();
// Emit save sequence.
rewriter.insertFragmentBefore(instruction, [&] (BytecodeRewriter::Fragment& fragment) {
fragment.appendInstruction<OpSaveGeneratorLocals>(scope, liveLocalsIndex, savedLocalsIndex, firstScopeOffset);
// Insert op_ret just after save sequence.
fragment.appendInstruction<OpRet>(data.argument);
});
// Emit resume sequence.
rewriter.replaceBytecodeWithFragment(instruction, [&] (BytecodeRewriter::Fragment& fragment) {
fragment.appendInstruction<OpRestoreGeneratorLocals>(scope, liveLocalsIndex, savedLocalsIndex, firstScopeOffset, firstValueProfile);
});
}
}
void BytecodeGeneratorification::emitPerLocalSaveAndRestore(BytecodeRewriter& rewriter)
{
VM& vm = m_bytecodeGenerator.vm();
for (const YieldData& data : m_yields) {
VirtualRegister scope = virtualRegisterForArgumentIncludingThis(static_cast<int32_t>(JSGenerator::Argument::Frame));
auto instruction = m_instructions.at(data.point);
// Emit save sequence.
rewriter.insertFragmentBefore(instruction, [&] (BytecodeRewriter::Fragment& fragment) {
data.liveness.forEachSetBit([&](size_t index) {
VirtualRegister operand = virtualRegisterForLocal(index);
Storage storage = storageForGeneratorLocal(vm, index);
fragment.appendInstruction<OpPutToScope>(
scope, // scope
storage.identifierIndex, // identifier
operand, // value
GetPutInfo(DoNotThrowIfNotFound, ResolvedClosureVar, InitializationMode::NotInitialization, m_bytecodeGenerator.ecmaMode()), // info
SymbolTableOrScopeDepth::symbolTable(VirtualRegister { m_generatorFrameSymbolTableIndex }), // symbol table constant index
storage.scopeOffset.offset() // scope offset
);
});
// Insert op_ret just after save sequence.
fragment.appendInstruction<OpRet>(data.argument);
});
// Emit resume sequence.
rewriter.replaceBytecodeWithFragment(instruction, [&] (BytecodeRewriter::Fragment& fragment) {
data.liveness.forEachSetBit([&](size_t index) {
VirtualRegister operand = virtualRegisterForLocal(index);
Storage storage = storageForGeneratorLocal(vm, index);
fragment.appendInstruction<OpGetFromScope>(
operand, // dst
scope, // scope
storage.identifierIndex, // identifier
GetPutInfo(DoNotThrowIfNotFound, ResolvedClosureVar, InitializationMode::NotInitialization, m_bytecodeGenerator.ecmaMode()), // info
0, // local scope depth
storage.scopeOffset.offset(), // scope offset
m_bytecodeGenerator.nextValueProfileIndex()
);
});
});
}
}
void performGeneratorification(BytecodeGenerator& bytecodeGenerator, UnlinkedCodeBlockGenerator* codeBlock, JSInstructionStreamWriter& instructions, SymbolTable* generatorFrameSymbolTable, int generatorFrameSymbolTableIndex)
{
if (Options::dumpBytecodesBeforeGeneratorification()) [[unlikely]] {
dataLogLn("Bytecodes before generatorification");
CodeBlockBytecodeDumper<UnlinkedCodeBlockGenerator>::dumpBlock(codeBlock, instructions, WTF::dataFile());
}
BytecodeGeneratorification pass(bytecodeGenerator, codeBlock, instructions, generatorFrameSymbolTable, generatorFrameSymbolTableIndex);
pass.run();
if (Options::dumpBytecodesBeforeGeneratorification()) [[unlikely]] {
dataLogLn("Bytecodes after generatorification");
CodeBlockBytecodeDumper<UnlinkedCodeBlockGenerator>::dumpBlock(codeBlock, instructions, WTF::dataFile());
}
}
} // namespace JSC