forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESTreeIRGen-func.cpp
More file actions
571 lines (477 loc) · 18.9 KB
/
ESTreeIRGen-func.cpp
File metadata and controls
571 lines (477 loc) · 18.9 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ESTreeIRGen.h"
#include "llvh/ADT/SmallString.h"
namespace hermes {
namespace irgen {
//===----------------------------------------------------------------------===//
// FunctionContext
FunctionContext::FunctionContext(
ESTreeIRGen *irGen,
Function *function,
sem::FunctionInfo *semInfo)
: irGen_(irGen),
semInfo_(semInfo),
oldContext_(irGen->functionContext_),
builderSaveState_(irGen->Builder),
function(function),
scope(irGen->nameTable_) {
irGen->functionContext_ = this;
// Initialize it to LiteraUndefined by default to avoid corner cases.
this->capturedNewTarget = irGen->Builder.getLiteralUndefined();
if (semInfo_) {
// Allocate the label table. Each label definition will be encountered in
// the AST before it is referenced (because of the nature of JavaScript), at
// which point we will initialize the GotoLabel structure with basic blocks
// targets.
labels_.resize(semInfo_->labelCount);
}
}
FunctionContext::~FunctionContext() {
irGen_->functionContext_ = oldContext_;
}
Identifier FunctionContext::genAnonymousLabelName(StringRef hint) {
llvh::SmallString<16> buf;
llvh::raw_svector_ostream nameBuilder{buf};
nameBuilder << "?anon_" << anonymousLabelCounter++ << "_" << hint;
return function->getContext().getIdentifier(nameBuilder.str());
}
//===----------------------------------------------------------------------===//
// ESTreeIRGen
void ESTreeIRGen::genFunctionDeclaration(
ESTree::FunctionDeclarationNode *func) {
if (func->_async) {
Builder.getModule()->getContext().getSourceErrorManager().error(
func->getSourceRange(), Twine("async functions are unsupported"));
return;
}
// Find the name of the function.
Identifier functionName = getNameFieldFromID(func->_id);
LLVM_DEBUG(dbgs() << "IRGen function \"" << functionName << "\".\n");
auto *funcStorage = nameTable_.lookup(functionName);
assert(
funcStorage && "function declaration variable should have been hoisted");
Function *newFunc = func->_generator
? genGeneratorFunction(functionName, nullptr, func)
: genES5Function(functionName, nullptr, func);
// Store the newly created closure into a frame variable with the same name.
auto *newClosure = Builder.createCreateFunctionInst(newFunc);
emitStore(Builder, newClosure, funcStorage, true);
}
Value *ESTreeIRGen::genFunctionExpression(
ESTree::FunctionExpressionNode *FE,
Identifier nameHint) {
if (FE->_async) {
Builder.getModule()->getContext().getSourceErrorManager().error(
FE->getSourceRange(), Twine("async functions are unsupported"));
return Builder.getLiteralUndefined();
}
LLVM_DEBUG(
dbgs() << "Creating anonymous closure. "
<< Builder.getInsertionBlock()->getParent()->getInternalName()
<< ".\n");
NameTableScopeTy newScope(nameTable_);
Variable *tempClosureVar = nullptr;
Identifier originalNameIden = nameHint;
if (FE->_id) {
auto closureName = genAnonymousLabelName("closure");
tempClosureVar = Builder.createVariable(
curFunction()->function->getFunctionScope(),
Variable::DeclKind::Var,
closureName);
// Insert the synthesized variable into the name table, so it can be
// looked up internally as well.
nameTable_.insertIntoScope(
&curFunction()->scope, tempClosureVar->getName(), tempClosureVar);
// Alias the lexical name to the synthesized variable.
originalNameIden = getNameFieldFromID(FE->_id);
nameTable_.insert(originalNameIden, tempClosureVar);
}
Function *newFunc = FE->_generator
? genGeneratorFunction(originalNameIden, tempClosureVar, FE)
: genES5Function(originalNameIden, tempClosureVar, FE);
Value *closure = Builder.createCreateFunctionInst(newFunc);
if (tempClosureVar)
emitStore(Builder, closure, tempClosureVar, true);
return closure;
}
Value *ESTreeIRGen::genArrowFunctionExpression(
ESTree::ArrowFunctionExpressionNode *AF,
Identifier nameHint) {
LLVM_DEBUG(
dbgs() << "Creating arrow function. "
<< Builder.getInsertionBlock()->getParent()->getInternalName()
<< ".\n");
if (AF->_async) {
Builder.getModule()->getContext().getSourceErrorManager().error(
AF->getSourceRange(), Twine("async functions are unsupported"));
return Builder.getLiteralUndefined();
}
auto *newFunc = Builder.createFunction(
nameHint,
Function::DefinitionKind::ES6Arrow,
ESTree::isStrict(AF->strictness),
AF->getSourceRange());
{
FunctionContext newFunctionContext{this, newFunc, AF->getSemInfo()};
// Propagate captured "this", "new.target" and "arguments" from parents.
auto *prev = curFunction()->getPreviousContext();
curFunction()->capturedThis = prev->capturedThis;
curFunction()->capturedNewTarget = prev->capturedNewTarget;
curFunction()->capturedArguments = prev->capturedArguments;
emitFunctionPrologue(
AF,
Builder.createBasicBlock(newFunc),
InitES5CaptureState::No,
DoEmitParameters::Yes);
genStatement(AF->_body);
emitFunctionEpilogue(Builder.getLiteralUndefined());
}
// Emit CreateFunctionInst after we have restored the builder state.
return Builder.createCreateFunctionInst(newFunc);
}
#ifndef HERMESVM_LEAN
namespace {
ESTree::NodeKind getLazyFunctionKind(ESTree::FunctionLikeNode *node) {
if (node->isMethodDefinition) {
// This is not a regular function expression but getter/setter.
// If we want to reparse it later, we have to start from an
// identifier and not from a 'function' keyword.
return ESTree::NodeKind::Property;
}
return node->getKind();
}
} // namespace
Function *ESTreeIRGen::genES5Function(
Identifier originalName,
Variable *lazyClosureAlias,
ESTree::FunctionLikeNode *functionNode,
bool isGeneratorInnerFunction) {
assert(functionNode && "Function AST cannot be null");
auto *body = ESTree::getBlockStatement(functionNode);
assert(body && "body of ES5 function cannot be null");
Function *newFunction = isGeneratorInnerFunction
? Builder.createGeneratorInnerFunction(
originalName,
Function::DefinitionKind::ES5Function,
ESTree::isStrict(functionNode->strictness),
functionNode->getSourceRange(),
/* insertBefore */ nullptr)
: Builder.createFunction(
originalName,
Function::DefinitionKind::ES5Function,
ESTree::isStrict(functionNode->strictness),
functionNode->getSourceRange(),
/* isGlobal */ false,
/* insertBefore */ nullptr);
newFunction->setLazyClosureAlias(lazyClosureAlias);
if (auto *bodyBlock = llvh::dyn_cast<ESTree::BlockStatementNode>(body)) {
if (bodyBlock->isLazyFunctionBody) {
// Set the AST position and variable context so we can continue later.
newFunction->setLazyScope(saveCurrentScope());
auto &lazySource = newFunction->getLazySource();
lazySource.bufferId = bodyBlock->bufferId;
lazySource.nodeKind = getLazyFunctionKind(functionNode);
lazySource.isGeneratorInnerFunction = isGeneratorInnerFunction;
lazySource.functionRange = functionNode->getSourceRange();
// Set the function's .length.
newFunction->setExpectedParamCountIncludingThis(
countExpectedArgumentsIncludingThis(functionNode));
return newFunction;
}
}
FunctionContext newFunctionContext{
this, newFunction, functionNode->getSemInfo()};
if (isGeneratorInnerFunction) {
// StartGeneratorInst
// ResumeGeneratorInst
// at the beginning of the function, to allow for the first .next() call.
auto *initGenBB = Builder.createBasicBlock(newFunction);
Builder.setInsertionBlock(initGenBB);
Builder.createStartGeneratorInst();
auto *prologueBB = Builder.createBasicBlock(newFunction);
auto *prologueResumeIsReturn = Builder.createAllocStackInst(
genAnonymousLabelName("isReturn_prologue"));
genResumeGenerator(nullptr, prologueResumeIsReturn, prologueBB);
if (hasSimpleParams(functionNode)) {
// If there are simple params, then we don't need an extra yield/resume.
// They can simply be initialized on the first call to `.next`.
Builder.setInsertionBlock(prologueBB);
emitFunctionPrologue(
functionNode,
prologueBB,
InitES5CaptureState::Yes,
DoEmitParameters::Yes);
} else {
// If there are non-simple params, then we must add a new yield/resume.
// The `.next()` call will occur once in the outer function, before
// the iterator is returned to the caller of the `function*`.
auto *entryPointBB = Builder.createBasicBlock(newFunction);
auto *entryPointResumeIsReturn =
Builder.createAllocStackInst(genAnonymousLabelName("isReturn_entry"));
// Initialize parameters.
Builder.setInsertionBlock(prologueBB);
emitFunctionPrologue(
functionNode,
prologueBB,
InitES5CaptureState::Yes,
DoEmitParameters::Yes);
Builder.createSaveAndYieldInst(
Builder.getLiteralUndefined(), entryPointBB);
// Actual entry point of function from the caller's perspective.
Builder.setInsertionBlock(entryPointBB);
genResumeGenerator(
nullptr,
entryPointResumeIsReturn,
Builder.createBasicBlock(newFunction));
}
} else {
emitFunctionPrologue(
functionNode,
Builder.createBasicBlock(newFunction),
InitES5CaptureState::Yes,
DoEmitParameters::Yes);
}
genStatement(body);
emitFunctionEpilogue(Builder.getLiteralUndefined());
return curFunction()->function;
}
#endif
Function *ESTreeIRGen::genGeneratorFunction(
Identifier originalName,
Variable *lazyClosureAlias,
ESTree::FunctionLikeNode *functionNode) {
assert(functionNode && "Function AST cannot be null");
if (!Builder.getModule()->getContext().isGeneratorEnabled()) {
Builder.getModule()->getContext().getSourceErrorManager().error(
functionNode->getSourceRange(), "generator compilation is disabled");
}
// Build the outer function which creates the generator.
// Does not have an associated source range.
auto *outerFn = Builder.createGeneratorFunction(
originalName,
Function::DefinitionKind::ES5Function,
ESTree::isStrict(functionNode->strictness),
/* insertBefore */ nullptr);
{
FunctionContext outerFnContext{this, outerFn, functionNode->getSemInfo()};
// Build the inner function. This must be done in the outerFnContext
// since it's lexically considered a child function.
auto *innerFn = genES5Function(
genAnonymousLabelName(originalName.isValid() ? originalName.str() : ""),
lazyClosureAlias,
functionNode,
true);
emitFunctionPrologue(
functionNode,
Builder.createBasicBlock(outerFn),
InitES5CaptureState::Yes,
DoEmitParameters::No);
// Create a generator function, which will store the arguments.
auto *gen = Builder.createCreateGeneratorInst(innerFn);
if (!hasSimpleParams(functionNode)) {
// If there are non-simple params, step the inner function once to
// initialize them.
Value *next = Builder.createLoadPropertyInst(gen, "next");
Builder.createCallInst(next, gen, {});
}
emitFunctionEpilogue(gen);
}
return outerFn;
}
void ESTreeIRGen::initCaptureStateInES5FunctionHelper() {
// Capture "this", "new.target" and "arguments" if there are inner arrows.
if (!curFunction()->getSemInfo()->containsArrowFunctions)
return;
auto *scope = curFunction()->function->getFunctionScope();
// "this".
curFunction()->capturedThis = Builder.createVariable(
scope, Variable::DeclKind::Var, genAnonymousLabelName("this"));
emitStore(
Builder,
Builder.getFunction()->getThisParameter(),
curFunction()->capturedThis,
true);
// "new.target".
curFunction()->capturedNewTarget = Builder.createVariable(
scope, Variable::DeclKind::Var, genAnonymousLabelName("new.target"));
emitStore(
Builder,
Builder.createGetNewTargetInst(),
curFunction()->capturedNewTarget,
true);
// "arguments".
if (curFunction()->getSemInfo()->containsArrowFunctionsUsingArguments) {
curFunction()->capturedArguments = Builder.createVariable(
scope, Variable::DeclKind::Var, genAnonymousLabelName("arguments"));
emitStore(
Builder,
curFunction()->createArgumentsInst,
curFunction()->capturedArguments,
true);
}
}
void ESTreeIRGen::emitFunctionPrologue(
ESTree::FunctionLikeNode *funcNode,
BasicBlock *entry,
InitES5CaptureState doInitES5CaptureState,
DoEmitParameters doEmitParameters) {
auto *newFunc = curFunction()->function;
auto *semInfo = curFunction()->getSemInfo();
LLVM_DEBUG(
dbgs() << "Hoisting "
<< (semInfo->varDecls.size() + semInfo->closures.size())
<< " variable decls.\n");
Builder.setLocation(newFunc->getSourceRange().Start);
// Start pumping instructions into the entry basic block.
Builder.setInsertionBlock(entry);
// Always insert a CreateArgumentsInst. We will delete it later if it is
// unused.
curFunction()->createArgumentsInst = Builder.createCreateArgumentsInst();
// Create variable declarations for each of the hoisted variables and
// functions. Initialize only the variables to undefined.
for (auto decl : semInfo->varDecls) {
auto res = declareVariableOrGlobalProperty(
newFunc, decl.kind, getNameFieldFromID(decl.identifier));
// If this is not a frame variable or it was already declared, skip.
auto *var = llvh::dyn_cast<Variable>(res.first);
if (!var || !res.second)
continue;
// Otherwise, initialize it to undefined.
Builder.createStoreFrameInst(Builder.getLiteralUndefined(), var);
if (var->getRelatedVariable()) {
Builder.createStoreFrameInst(
Builder.getLiteralUndefined(), var->getRelatedVariable());
}
}
for (auto *fd : semInfo->closures) {
declareVariableOrGlobalProperty(
newFunc, VarDecl::Kind::Var, getNameFieldFromID(fd->_id));
}
// Always create the "this" parameter. It needs to be created before we
// initialized the ES5 capture state.
Builder.createParameter(newFunc, "this");
if (doInitES5CaptureState != InitES5CaptureState::No)
initCaptureStateInES5FunctionHelper();
// Construct the parameter list. Create function parameters and register
// them in the scope.
if (doEmitParameters == DoEmitParameters::Yes) {
emitParameters(funcNode);
} else {
newFunc->setExpectedParamCountIncludingThis(
countExpectedArgumentsIncludingThis(funcNode));
}
// Generate the code for import declarations before generating the rest of the
// body.
for (auto importDecl : semInfo->imports) {
genImportDeclaration(importDecl);
}
// Generate and initialize the code for the hoisted function declarations
// before generating the rest of the body.
for (auto funcDecl : semInfo->closures) {
genFunctionDeclaration(funcDecl);
}
}
void ESTreeIRGen::emitParameters(ESTree::FunctionLikeNode *funcNode) {
auto *newFunc = curFunction()->function;
LLVM_DEBUG(dbgs() << "IRGen function parameters.\n");
// Create a variable for every parameter.
for (auto paramDecl : funcNode->getSemInfo()->paramNames) {
Identifier paramName = getNameFieldFromID(paramDecl.identifier);
LLVM_DEBUG(dbgs() << "Adding parameter: " << paramName << "\n");
auto *paramStorage = Builder.createVariable(
newFunc->getFunctionScope(), Variable::DeclKind::Var, paramName);
// Register the storage for the parameter.
nameTable_.insert(paramName, paramStorage);
}
// FIXME: T42569352 TDZ for parameters used in initializer expressions.
uint32_t paramIndex = uint32_t{0} - 1;
for (auto &elem : ESTree::getParams(funcNode)) {
ESTree::Node *param = &elem;
ESTree::Node *init = nullptr;
++paramIndex;
if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(param)) {
createLRef(rest->_argument, true)
.emitStore(genBuiltinCall(
BuiltinMethod::HermesBuiltin_copyRestArgs,
Builder.getLiteralNumber(paramIndex)));
break;
}
// Unpack the optional initialization.
if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(param)) {
param = assign->_left;
init = assign->_right;
}
Identifier formalParamName = llvh::isa<ESTree::IdentifierNode>(param)
? getNameFieldFromID(param)
: genAnonymousLabelName("param");
auto *formalParam = Builder.createParameter(newFunc, formalParamName);
createLRef(param, true)
.emitStore(
emitOptionalInitialization(formalParam, init, formalParamName));
}
newFunc->setExpectedParamCountIncludingThis(
countExpectedArgumentsIncludingThis(funcNode));
}
uint32_t ESTreeIRGen::countExpectedArgumentsIncludingThis(
ESTree::FunctionLikeNode *funcNode) {
// Start at 1 to account for "this".
uint32_t count = 1;
for (auto ¶m : ESTree::getParams(funcNode)) {
if (llvh::isa<ESTree::AssignmentPatternNode>(param)) {
// Found an initializer, stop counting expected arguments.
break;
}
++count;
}
return count;
}
void ESTreeIRGen::emitFunctionEpilogue(Value *returnValue) {
if (returnValue) {
Builder.setLocation(SourceErrorManager::convertEndToLocation(
Builder.getFunction()->getSourceRange()));
Builder.createReturnInst(returnValue);
}
// Delete CreateArgumentsInst if it is unused.
if (!curFunction()->createArgumentsInst->hasUsers())
curFunction()->createArgumentsInst->eraseFromParent();
curFunction()->function->clearStatementCount();
}
void ESTreeIRGen::genDummyFunction(Function *dummy) {
IRBuilder builder{dummy};
builder.createParameter(dummy, "this");
BasicBlock *firstBlock = builder.createBasicBlock(dummy);
builder.setInsertionBlock(firstBlock);
builder.createUnreachableInst();
builder.createReturnInst(builder.getLiteralUndefined());
}
/// Generate a function which immediately throws the specified SyntaxError
/// message.
Function *ESTreeIRGen::genSyntaxErrorFunction(
Module *M,
Identifier originalName,
SMRange sourceRange,
StringRef error) {
IRBuilder builder{M};
Function *function = builder.createFunction(
originalName,
Function::DefinitionKind::ES5Function,
true,
sourceRange,
false);
builder.createParameter(function, "this");
BasicBlock *firstBlock = builder.createBasicBlock(function);
builder.setInsertionBlock(firstBlock);
builder.createThrowInst(builder.createCallInst(
emitLoad(
builder, builder.createGlobalObjectProperty("SyntaxError", false)),
builder.getLiteralUndefined(),
builder.getLiteralString(error)));
return function;
}
} // namespace irgen
} // namespace hermes