f7724b5f068b8e0cf157f53ca06498f5bffff46e
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.cpp
1 /*
2  * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  * Copyright (C) 2012 Igalia, S.L.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "BytecodeGenerator.h"
33
34 #include "ArithProfile.h"
35 #include "BuiltinExecutables.h"
36 #include "BytecodeGeneratorification.h"
37 #include "BytecodeLivenessAnalysis.h"
38 #include "DefinePropertyAttributes.h"
39 #include "Interpreter.h"
40 #include "JSCInlines.h"
41 #include "JSFunction.h"
42 #include "JSGeneratorFunction.h"
43 #include "JSLexicalEnvironment.h"
44 #include "JSTemplateRegistryKey.h"
45 #include "LowLevelInterpreter.h"
46 #include "Options.h"
47 #include "StackAlignment.h"
48 #include "StrongInlines.h"
49 #include "UnlinkedCodeBlock.h"
50 #include "UnlinkedEvalCodeBlock.h"
51 #include "UnlinkedFunctionCodeBlock.h"
52 #include "UnlinkedInstructionStream.h"
53 #include "UnlinkedModuleProgramCodeBlock.h"
54 #include "UnlinkedProgramCodeBlock.h"
55 #include <wtf/BitVector.h>
56 #include <wtf/CommaPrinter.h>
57 #include <wtf/SmallPtrSet.h>
58 #include <wtf/StdLibExtras.h>
59 #include <wtf/text/WTFString.h>
60
61 using namespace std;
62
63 namespace JSC {
64
65 void Label::setLocation(unsigned location)
66 {
67     m_location = location;
68     
69     unsigned size = m_unresolvedJumps.size();
70     for (unsigned i = 0; i < size; ++i)
71         m_generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
72 }
73
74 void Variable::dump(PrintStream& out) const
75 {
76     out.print(
77         "{ident = ", m_ident,
78         ", offset = ", m_offset,
79         ", local = ", RawPointer(m_local),
80         ", attributes = ", m_attributes,
81         ", kind = ", m_kind,
82         ", symbolTableConstantIndex = ", m_symbolTableConstantIndex,
83         ", isLexicallyScoped = ", m_isLexicallyScoped, "}");
84 }
85
86 ParserError BytecodeGenerator::generate()
87 {
88     m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());
89
90     emitLogShadowChickenPrologueIfNecessary();
91     
92     // If we have declared a variable named "arguments" and we are using arguments then we should
93     // perform that assignment now.
94     if (m_needToInitializeArguments)
95         initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
96
97     if (m_restParameter)
98         m_restParameter->emit(*this);
99
100     {
101         RefPtr<RegisterID> temp = newTemporary();
102         RefPtr<RegisterID> globalScope;
103         for (auto functionPair : m_functionsToInitialize) {
104             FunctionMetadataNode* metadata = functionPair.first;
105             FunctionVariableType functionType = functionPair.second;
106             emitNewFunction(temp.get(), metadata);
107             if (functionType == NormalFunctionVariable)
108                 initializeVariable(variable(metadata->ident()), temp.get());
109             else if (functionType == GlobalFunctionVariable) {
110                 if (!globalScope) {
111                     // We know this will resolve to the global object because our parser/global initialization code 
112                     // doesn't allow let/const/class variables to have the same names as functions.
113                     RefPtr<RegisterID> globalObjectScope = emitResolveScope(nullptr, Variable(metadata->ident())); 
114                     globalScope = newBlockScopeVariable(); 
115                     emitMove(globalScope.get(), globalObjectScope.get());
116                 }
117                 emitPutToScope(globalScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound, InitializationMode::NotInitialization);
118             } else
119                 RELEASE_ASSERT_NOT_REACHED();
120         }
121     }
122     
123     bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
124     if (!callingClassConstructor)
125         m_scopeNode->emitBytecode(*this);
126
127     m_staticPropertyAnalyzer.kill();
128
129     for (auto& range : m_tryRanges) {
130         int start = range.start->bind();
131         int end = range.end->bind();
132         
133         // This will happen for empty try blocks and for some cases of finally blocks:
134         //
135         // try {
136         //    try {
137         //    } finally {
138         //        return 42;
139         //        // *HERE*
140         //    }
141         // } finally {
142         //    print("things");
143         // }
144         //
145         // The return will pop scopes to execute the outer finally block. But this includes
146         // popping the try context for the inner try. The try context is live in the fall-through
147         // part of the finally block not because we will emit a handler that overlaps the finally,
148         // but because we haven't yet had a chance to plant the catch target. Then when we finish
149         // emitting code for the outer finally block, we repush the try contex, this time with a
150         // new start index. But that means that the start index for the try range corresponding
151         // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
152         // than the end index of the try block. This is harmless since end < start handlers will
153         // never get matched in our logic, but we do the runtime a favor and choose to not emit
154         // such handlers at all.
155         if (end <= start)
156             continue;
157         
158         UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end),
159             static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType);
160         m_codeBlock->addExceptionHandler(info);
161     }
162     
163
164     if (isGeneratorOrAsyncFunctionBodyParseMode(m_codeBlock->parseMode()))
165         performGeneratorification(m_codeBlock.get(), m_instructions, m_generatorFrameSymbolTable.get(), m_generatorFrameSymbolTableIndex);
166
167     m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
168
169     m_codeBlock->shrinkToFit();
170
171     if (m_expressionTooDeep)
172         return ParserError(ParserError::OutOfMemory);
173     return ParserError(ParserError::ErrorNone);
174 }
175
176 BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
177     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
178     , m_scopeNode(programNode)
179     , m_codeBlock(vm, codeBlock)
180     , m_thisRegister(CallFrame::thisArgumentOffset())
181     , m_codeType(GlobalCode)
182     , m_vm(&vm)
183     , m_needsToUpdateArrowFunctionContext(programNode->usesArrowFunction() || programNode->usesEval())
184 {
185     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
186
187     for (auto& constantRegister : m_linkTimeConstantRegisters)
188         constantRegister = nullptr;
189
190     allocateCalleeSaveSpace();
191
192     m_codeBlock->setNumParameters(1); // Allocate space for "this"
193
194     emitEnter();
195
196     allocateAndEmitScope();
197
198     emitCheckTraps();
199
200     const FunctionStack& functionStack = programNode->functionStack();
201
202     for (auto* function : functionStack)
203         m_functionsToInitialize.append(std::make_pair(function, GlobalFunctionVariable));
204
205     if (Options::validateBytecode()) {
206         for (auto& entry : programNode->varDeclarations())
207             RELEASE_ASSERT(entry.value.isVar());
208     }
209     codeBlock->setVariableDeclarations(programNode->varDeclarations());
210     codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
211     // Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
212     // operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
213     // additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
214     // to the TDZ stack.
215     
216     if (needsToUpdateArrowFunctionContext()) {
217         initializeArrowFunctionContextScopeIfNeeded();
218         emitPutThisToArrowFunctionContextScope();
219     }
220 }
221
222 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
223     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
224     , m_scopeNode(functionNode)
225     , m_codeBlock(vm, codeBlock)
226     , m_codeType(FunctionCode)
227     , m_vm(&vm)
228     , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
229     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
230     // FIXME: We should be able to have tail call elimination with the profiler
231     // enabled. This is currently not possible because the profiler expects
232     // op_will_call / op_did_call pairs before and after a call, which are not
233     // compatible with tail calls (we have no way of emitting op_did_call).
234     // https://bugs.webkit.org/show_bug.cgi?id=148819
235     , m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && isStrictMode())
236     , m_needsToUpdateArrowFunctionContext(functionNode->usesArrowFunction() || functionNode->usesEval())
237     , m_derivedContextType(codeBlock->derivedContextType())
238 {
239     for (auto& constantRegister : m_linkTimeConstantRegisters)
240         constantRegister = nullptr;
241
242     if (m_isBuiltinFunction)
243         m_shouldEmitDebugHooks = false;
244
245     allocateCalleeSaveSpace();
246     
247     SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm);
248     functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
249     int symbolTableConstantIndex = 0;
250
251     FunctionParameters& parameters = *functionNode->parameters(); 
252     // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
253     // This implements IsSimpleParameterList in the Ecma 2015 spec.
254     // If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
255     // IsSimpleParameterList is false if the argument list contains any default parameter values,
256     // a rest parameter, or any destructuring patterns.
257     // If we do have default parameters, destructuring parameters, or a rest parameter, our parameters will be allocated in a different scope.
258     bool isSimpleParameterList = parameters.isSimpleParameterList();
259
260     SourceParseMode parseMode = codeBlock->parseMode();
261
262     bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && !m_codeBlock->isArrowFunction();
263     bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
264
265     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
266     bool needsArguments = ((functionNode->usesArguments() && !codeBlock->isArrowFunction()) || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
267
268     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
269         // Generator and AsyncFunction never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
270         needsArguments = false;
271
272         // Generator and AsyncFunction uses the var scope to save and resume its variables. So the lexical scope is always instantiated.
273         shouldCaptureSomeOfTheThings = true;
274     }
275
276     if (isGeneratorOrAsyncFunctionWrapperParseMode(parseMode) && needsArguments) {
277         // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
278         // This is because arguments of a generator should be evaluated before starting it.
279         // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
280         //
281         //    function *gen(a, b = hello())
282         //    {
283         //        return {
284         //            @generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode, @generatorFrame)
285         //            {
286         //                arguments;  // This `arguments` should reference to the gen's arguments.
287         //                ...
288         //            }
289         //        }
290         //    }
291         shouldCaptureSomeOfTheThings = true;
292     }
293
294     if (shouldCaptureAllOfTheThings)
295         functionNode->varDeclarations().markAllVariablesAsCaptured();
296     
297     auto captures = [&] (UniquedStringImpl* uid) -> bool {
298         if (!shouldCaptureSomeOfTheThings)
299             return false;
300         if (needsArguments && uid == propertyNames().arguments.impl()) {
301             // Actually, we only need to capture the arguments object when we "need full activation"
302             // because of name scopes. But historically we did it this way, so for now we just preserve
303             // the old behavior.
304             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
305             return true;
306         }
307         return functionNode->captures(uid);
308     };
309     auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
310         return captures(uid) ? VarKind::Scope : VarKind::Stack;
311     };
312
313     m_calleeRegister.setIndex(CallFrameSlot::callee);
314
315     initializeParameters(parameters);
316     ASSERT(!(isSimpleParameterList && m_restParameter));
317
318     emitEnter();
319
320     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode))
321         m_generatorRegister = &m_parameters[1];
322
323     allocateAndEmitScope();
324
325     emitCheckTraps();
326     
327     if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
328         ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
329         ASSERT(!isAsyncFunctionBodyParseMode(parseMode));
330         bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
331         bool isFunctionNameCaptured = captures(functionNode->ident().impl());
332         bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
333         emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
334     }
335
336     if (shouldCaptureSomeOfTheThings)
337         m_lexicalEnvironmentRegister = addVar();
338
339     if (shouldCaptureSomeOfTheThings || vm.typeProfiler())
340         symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
341
342     // We can allocate the "var" environment if we don't have default parameter expressions. If we have
343     // default parameter expressions, we have to hold off on allocating the "var" environment because
344     // the parent scope of the "var" environment is the parameter environment.
345     if (isSimpleParameterList)
346         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, shouldCaptureSomeOfTheThings);
347
348     // Figure out some interesting facts about our arguments.
349     bool capturesAnyArgumentByName = false;
350     if (functionNode->hasCapturedVariables()) {
351         FunctionParameters& parameters = *functionNode->parameters();
352         for (size_t i = 0; i < parameters.size(); ++i) {
353             auto pattern = parameters.at(i).first;
354             if (!pattern->isBindingNode())
355                 continue;
356             const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
357             capturesAnyArgumentByName |= captures(ident.impl());
358         }
359     }
360     
361     if (capturesAnyArgumentByName)
362         ASSERT(m_lexicalEnvironmentRegister);
363
364     // Need to know what our functions are called. Parameters have some goofy behaviors when it
365     // comes to functions of the same name.
366     for (FunctionMetadataNode* function : functionNode->functionStack())
367         m_functions.add(function->ident().impl());
368     
369     if (needsArguments) {
370         // Create the arguments object now. We may put the arguments object into the activation if
371         // it is captured. Either way, we create two arguments object variables: one is our
372         // private variable that is immutable, and another that is the user-visible variable. The
373         // immutable one is only used here, or during formal parameter resolutions if we opt for
374         // DirectArguments.
375         
376         m_argumentsRegister = addVar();
377         m_argumentsRegister->ref();
378     }
379     
380     if (needsArguments && !codeBlock->isStrictMode() && isSimpleParameterList) {
381         // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
382         // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
383         // activation.
384         
385         if (capturesAnyArgumentByName) {
386             functionSymbolTable->setArgumentsLength(vm, parameters.size());
387             
388             // For each parameter, we have two possibilities:
389             // Either it's a binding node with no function overlap, in which case it gets a name
390             // in the symbol table - or it just gets space reserved in the symbol table. Either
391             // way we lift the value into the scope.
392             for (unsigned i = 0; i < parameters.size(); ++i) {
393                 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
394                 functionSymbolTable->setArgumentOffset(vm, i, offset);
395                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
396                     VarOffset varOffset(offset);
397                     SymbolTableEntry entry(varOffset);
398                     // Stores to these variables via the ScopedArguments object will not do
399                     // notifyWrite(), since that would be cumbersome. Also, watching formal
400                     // parameters when "arguments" is in play is unlikely to be super profitable.
401                     // So, we just disable it.
402                     entry.disableWatching(*m_vm);
403                     functionSymbolTable->set(NoLockingNecessary, name, entry);
404                 }
405                 emitOpcode(op_put_to_scope);
406                 instructions().append(m_lexicalEnvironmentRegister->index());
407                 instructions().append(UINT_MAX);
408                 instructions().append(virtualRegisterForArgument(1 + i).offset());
409                 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
410                 instructions().append(symbolTableConstantIndex);
411                 instructions().append(offset.offset());
412             }
413             
414             // This creates a scoped arguments object and copies the overflow arguments into the
415             // scope. It's the equivalent of calling ScopedArguments::createByCopying().
416             emitOpcode(op_create_scoped_arguments);
417             instructions().append(m_argumentsRegister->index());
418             instructions().append(m_lexicalEnvironmentRegister->index());
419         } else {
420             // We're going to put all parameters into the DirectArguments object. First ensure
421             // that the symbol table knows that this is happening.
422             for (unsigned i = 0; i < parameters.size(); ++i) {
423                 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
424                     functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
425             }
426             
427             emitOpcode(op_create_direct_arguments);
428             instructions().append(m_argumentsRegister->index());
429         }
430     } else if (isSimpleParameterList) {
431         // Create the formal parameters the normal way. Any of them could be captured, or not. If
432         // captured, lift them into the scope. We cannot do this if we have default parameter expressions
433         // because when default parameter expressions exist, they belong in their own lexical environment
434         // separate from the "var" lexical environment.
435         for (unsigned i = 0; i < parameters.size(); ++i) {
436             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
437             if (!name)
438                 continue;
439             
440             if (!captures(name)) {
441                 // This is the easy case - just tell the symbol table about the argument. It will
442                 // be accessed directly.
443                 functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
444                 continue;
445             }
446             
447             ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
448             const Identifier& ident =
449                 static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
450             functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(offset)));
451             
452             emitOpcode(op_put_to_scope);
453             instructions().append(m_lexicalEnvironmentRegister->index());
454             instructions().append(addConstant(ident));
455             instructions().append(virtualRegisterForArgument(1 + i).offset());
456             instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
457             instructions().append(symbolTableConstantIndex);
458             instructions().append(offset.offset());
459         }
460     }
461     
462     if (needsArguments && (codeBlock->isStrictMode() || !isSimpleParameterList)) {
463         // Allocate a cloned arguments object.
464         emitOpcode(op_create_cloned_arguments);
465         instructions().append(m_argumentsRegister->index());
466     }
467     
468     // There are some variables that need to be preinitialized to something other than Undefined:
469     //
470     // - "arguments": unless it's used as a function or parameter, this should refer to the
471     //   arguments object.
472     //
473     // - functions: these always override everything else.
474     //
475     // The most logical way to do all of this is to initialize none of the variables until now,
476     // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
477     // for how these things override each other end up holding. We would initialize "arguments" first, 
478     // then all arguments, then the functions.
479     //
480     // But some arguments are already initialized by default, since if they aren't captured and we
481     // don't have "arguments" then we just point the symbol table at the stack slot of those
482     // arguments. We end up initializing the rest of the arguments that have an uncomplicated
483     // binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
484     // because that's just the simplest thing. This means that when we initialize them, we have to
485     // watch out for the things that override arguments (namely, functions).
486     
487     // This is our final act of weirdness. "arguments" is overridden by everything except the
488     // callee. We add it to the symbol table if it's not already there and it's not an argument.
489     bool shouldCreateArgumentsVariableInParameterScope = false;
490     if (needsArguments) {
491         // If "arguments" is overridden by a function or destructuring parameter name, then it's
492         // OK for us to call createVariable() because it won't change anything. It's also OK for
493         // us to them tell BytecodeGenerator::generate() to write to it because it will do so
494         // before it initializes functions and destructuring parameters. But if "arguments" is
495         // overridden by a "simple" function parameter, then we have to bail: createVariable()
496         // would assert and BytecodeGenerator::generate() would write the "arguments" after the
497         // argument value had already been properly initialized.
498         
499         bool haveParameterNamedArguments = false;
500         for (unsigned i = 0; i < parameters.size(); ++i) {
501             UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
502             if (name == propertyNames().arguments.impl()) {
503                 haveParameterNamedArguments = true;
504                 break;
505             }
506         }
507
508         bool shouldCreateArgumensVariable = !haveParameterNamedArguments
509             && !SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(m_codeBlock->parseMode());
510         shouldCreateArgumentsVariableInParameterScope = shouldCreateArgumensVariable && !isSimpleParameterList;
511         // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
512         if (shouldCreateArgumensVariable && !shouldCreateArgumentsVariableInParameterScope) {
513             createVariable(
514                 propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
515
516             m_needToInitializeArguments = true;
517         }
518     }
519
520     for (FunctionMetadataNode* function : functionNode->functionStack()) {
521         const Identifier& ident = function->ident();
522         createVariable(ident, varKind(ident.impl()), functionSymbolTable);
523         m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
524     }
525     for (auto& entry : functionNode->varDeclarations()) {
526         ASSERT(!entry.value.isLet() && !entry.value.isConst());
527         if (!entry.value.isVar()) // This is either a parameter or callee.
528             continue;
529         if (shouldCreateArgumentsVariableInParameterScope && entry.key.get() == propertyNames().arguments.impl())
530             continue;
531         createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
532     }
533
534
535     m_newTargetRegister = addVar();
536     switch (parseMode) {
537     case SourceParseMode::GeneratorWrapperFunctionMode:
538     case SourceParseMode::GeneratorWrapperMethodMode: {
539         m_generatorRegister = addVar();
540
541         // FIXME: Emit to_this only when Generator uses it.
542         // https://bugs.webkit.org/show_bug.cgi?id=151586
543         m_codeBlock->addPropertyAccessInstruction(instructions().size());
544         emitOpcode(op_to_this);
545         instructions().append(kill(&m_thisRegister));
546         instructions().append(0);
547         instructions().append(0);
548
549         emitMove(m_generatorRegister, &m_calleeRegister);
550         emitCreateThis(m_generatorRegister);
551         break;
552     }
553
554     case SourceParseMode::AsyncArrowFunctionMode:
555     case SourceParseMode::AsyncMethodMode:
556     case SourceParseMode::AsyncFunctionMode: {
557         ASSERT(!isConstructor());
558         ASSERT(constructorKind() == ConstructorKind::None);
559         m_generatorRegister = addVar();
560         m_promiseCapabilityRegister = addVar();
561
562         if (parseMode != SourceParseMode::AsyncArrowFunctionMode) {
563             // FIXME: Emit to_this only when AsyncFunctionBody uses it.
564             // https://bugs.webkit.org/show_bug.cgi?id=151586
565             m_codeBlock->addPropertyAccessInstruction(instructions().size());
566             emitOpcode(op_to_this);
567             instructions().append(kill(&m_thisRegister));
568             instructions().append(0);
569             instructions().append(0);
570         }
571
572         emitNewObject(m_generatorRegister);
573
574         // let promiseCapability be @newPromiseCapability(@Promise)
575         auto varNewPromiseCapability = variable(propertyNames().builtinNames().newPromiseCapabilityPrivateName());
576         RefPtr<RegisterID> scope = newTemporary();
577         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varNewPromiseCapability));
578         RefPtr<RegisterID> newPromiseCapability = emitGetFromScope(newTemporary(), scope.get(), varNewPromiseCapability, ThrowIfNotFound);
579
580         CallArguments args(*this, nullptr, 1);
581         emitLoad(args.thisRegister(), jsUndefined());
582
583         auto varPromiseConstructor = variable(propertyNames().builtinNames().PromisePrivateName());
584         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varPromiseConstructor));
585         emitGetFromScope(args.argumentRegister(0), scope.get(), varPromiseConstructor, ThrowIfNotFound);
586
587         // JSTextPosition(int _line, int _offset, int _lineStartOffset)
588         JSTextPosition divot(m_scopeNode->firstLine(), m_scopeNode->startOffset(), m_scopeNode->lineStartOffset());
589         emitCall(promiseCapabilityRegister(), newPromiseCapability.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
590         break;
591     }
592
593     case SourceParseMode::AsyncFunctionBodyMode:
594     case SourceParseMode::AsyncArrowFunctionBodyMode:
595     case SourceParseMode::GeneratorBodyMode: {
596         // |this| is already filled correctly before here.
597         emitLoad(m_newTargetRegister, jsUndefined());
598         break;
599     }
600
601     default: {
602         if (SourceParseMode::ArrowFunctionMode != parseMode) {
603             if (isConstructor()) {
604                 emitMove(m_newTargetRegister, &m_thisRegister);
605                 if (constructorKind() == ConstructorKind::Extends) {
606                     Ref<Label> isDerived = newLabel();
607                     Ref<Label> done = newLabel();
608                     m_isDerivedConstuctor = addVar();
609                     emitGetById(m_isDerivedConstuctor, &m_calleeRegister, propertyNames().builtinNames().isDerivedConstructorPrivateName());
610                     emitJumpIfTrue(m_isDerivedConstuctor, isDerived.get());
611                     emitCreateThis(&m_thisRegister);
612                     emitJump(done.get());
613                     emitLabel(isDerived.get());
614                     emitMoveEmptyValue(&m_thisRegister);
615                     emitLabel(done.get());
616                 } else
617                     emitCreateThis(&m_thisRegister);
618             } else if (constructorKind() != ConstructorKind::None)
619                 emitThrowTypeError("Cannot call a class constructor without |new|");
620             else {
621                 bool shouldEmitToThis = false;
622                 if (functionNode->usesThis() || codeBlock->usesEval() || m_scopeNode->doAnyInnerArrowFunctionsUseThis() || m_scopeNode->doAnyInnerArrowFunctionsUseEval())
623                     shouldEmitToThis = true;
624                 else if ((functionNode->usesSuperProperty() || m_scopeNode->doAnyInnerArrowFunctionsUseSuperProperty()) && !codeBlock->isStrictMode()) {
625                     // We must emit to_this when we're not in strict mode because we
626                     // will convert |this| to an object, and that object may be passed
627                     // to a strict function as |this|. This is observable because that
628                     // strict function's to_this will just return the object.
629                     //
630                     // We don't need to emit this for strict-mode code because
631                     // strict-mode code may call another strict function, which will
632                     // to_this if it directly uses this; this is OK, because we defer
633                     // to_this until |this| is used directly. Strict-mode code might
634                     // also call a sloppy mode function, and that will to_this, which
635                     // will defer the conversion, again, until necessary.
636                     shouldEmitToThis = true;
637                 }
638
639                 if (shouldEmitToThis) {
640                     m_codeBlock->addPropertyAccessInstruction(instructions().size());
641                     emitOpcode(op_to_this);
642                     instructions().append(kill(&m_thisRegister));
643                     instructions().append(0);
644                     instructions().append(0);
645                 }
646             }
647         }
648         break;
649     }
650     }
651
652     // We need load |super| & |this| for arrow function before initializeDefaultParameterValuesAndSetupFunctionScopeStack
653     // if we have default parameter expression. Because |super| & |this| values can be used there
654     if ((SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && !isSimpleParameterList) || parseMode == SourceParseMode::AsyncArrowFunctionBodyMode) {
655         if (functionNode->usesThis() || functionNode->usesSuperProperty())
656             emitLoadThisFromArrowFunctionLexicalEnvironment();
657
658         if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
659             emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
660     }
661
662     if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
663         bool canReuseLexicalEnvironment = isSimpleParameterList;
664         initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable, canReuseLexicalEnvironment);
665         emitPutThisToArrowFunctionContextScope();
666         emitPutNewTargetToArrowFunctionContextScope();
667         emitPutDerivedConstructorToArrowFunctionContextScope();
668     }
669
670     // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
671     // because a function's default parameter ExpressionNodes will use temporary registers.
672     pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
673
674     Ref<Label> catchLabel = newLabel();
675     TryData* tryFormalParametersData = nullptr;
676     bool needTryCatch = isAsyncFunctionWrapperParseMode(parseMode) && !isSimpleParameterList;
677     if (needTryCatch) {
678         Ref<Label> tryFormalParametersStart = newEmittedLabel();
679         tryFormalParametersData = pushTry(tryFormalParametersStart.get(), catchLabel.get(), HandlerType::SynthesizedCatch);
680     }
681
682     initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures, shouldCreateArgumentsVariableInParameterScope);
683
684     if (needTryCatch) {
685         Ref<Label> didNotThrow = newLabel();
686         emitJump(didNotThrow.get());
687         emitLabel(catchLabel.get());
688         popTry(tryFormalParametersData, catchLabel.get());
689
690         RefPtr<RegisterID> thrownValue = newTemporary();
691         RegisterID* unused = newTemporary();
692         emitCatch(unused, thrownValue.get());
693
694         // return promiseCapability.@reject(thrownValue)
695         RefPtr<RegisterID> reject = emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().rejectPrivateName());
696
697         CallArguments args(*this, nullptr, 1);
698         emitLoad(args.thisRegister(), jsUndefined());
699         emitMove(args.argumentRegister(0), thrownValue.get());
700
701         JSTextPosition divot(functionNode->firstLine(), functionNode->startOffset(), functionNode->lineStartOffset());
702
703         RefPtr<RegisterID> result = emitCall(newTemporary(), reject.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
704         emitReturn(emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().promisePrivateName()));
705
706         emitLabel(didNotThrow.get());
707     }
708
709     // If we don't have  default parameter expression, then loading |this| inside an arrow function must be done
710     // after initializeDefaultParameterValuesAndSetupFunctionScopeStack() because that function sets up the
711     // SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment() consults the SymbolTable stack
712     if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && isSimpleParameterList) {
713         if (functionNode->usesThis() || functionNode->usesSuperProperty())
714             emitLoadThisFromArrowFunctionLexicalEnvironment();
715     
716         if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
717             emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
718     }
719     
720     // Set up the lexical environment scope as the generator frame. We store the saved and resumed generator registers into this scope with the symbol keys.
721     // Since they are symbol keyed, these variables cannot be reached from the usual code.
722     if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
723         ASSERT(m_lexicalEnvironmentRegister);
724         m_generatorFrameSymbolTable.set(*m_vm, functionSymbolTable);
725         m_generatorFrameSymbolTableIndex = symbolTableConstantIndex;
726         emitMove(generatorFrameRegister(), m_lexicalEnvironmentRegister);
727         emitPutById(generatorRegister(), propertyNames().builtinNames().generatorFramePrivateName(), generatorFrameRegister());
728     }
729
730     bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
731     pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
732 }
733
734 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
735     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
736     , m_scopeNode(evalNode)
737     , m_codeBlock(vm, codeBlock)
738     , m_thisRegister(CallFrame::thisArgumentOffset())
739     , m_codeType(EvalCode)
740     , m_vm(&vm)
741     , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
742     , m_needsToUpdateArrowFunctionContext(evalNode->usesArrowFunction() || evalNode->usesEval())
743     , m_derivedContextType(codeBlock->derivedContextType())
744 {
745     for (auto& constantRegister : m_linkTimeConstantRegisters)
746         constantRegister = nullptr;
747
748     allocateCalleeSaveSpace();
749
750     m_codeBlock->setNumParameters(1);
751
752     pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
753
754     emitEnter();
755
756     allocateAndEmitScope();
757
758     emitCheckTraps();
759     
760     for (FunctionMetadataNode* function : evalNode->functionStack())
761         m_codeBlock->addFunctionDecl(makeFunction(function));
762
763     const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
764     Vector<Identifier, 0, UnsafeVectorOverflow> variables;
765     Vector<Identifier, 0, UnsafeVectorOverflow> hoistedFunctions;
766     for (auto& entry : varDeclarations) {
767         ASSERT(entry.value.isVar());
768         ASSERT(entry.key->isAtomic() || entry.key->isSymbol());
769         if (entry.value.isSloppyModeHoistingCandidate())
770             hoistedFunctions.append(Identifier::fromUid(m_vm, entry.key.get()));
771         else
772             variables.append(Identifier::fromUid(m_vm, entry.key.get()));
773     }
774     codeBlock->adoptVariables(variables);
775     codeBlock->adoptFunctionHoistingCandidates(WTFMove(hoistedFunctions));
776     
777     if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
778         m_newTargetRegister = addVar();
779
780     if (codeBlock->isArrowFunctionContext() && (evalNode->usesThis() || evalNode->usesSuperProperty()))
781         emitLoadThisFromArrowFunctionLexicalEnvironment();
782
783     if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
784         emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
785
786     if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunctionContext() && !isDerivedConstructorContext()) {
787         initializeArrowFunctionContextScopeIfNeeded();
788         emitPutThisToArrowFunctionContextScope();
789     }
790     
791     bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
792     pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
793 }
794
795 BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
796     : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
797     , m_scopeNode(moduleProgramNode)
798     , m_codeBlock(vm, codeBlock)
799     , m_thisRegister(CallFrame::thisArgumentOffset())
800     , m_codeType(ModuleCode)
801     , m_vm(&vm)
802     , m_usesNonStrictEval(false)
803     , m_needsToUpdateArrowFunctionContext(moduleProgramNode->usesArrowFunction() || moduleProgramNode->usesEval())
804 {
805     ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
806
807     for (auto& constantRegister : m_linkTimeConstantRegisters)
808         constantRegister = nullptr;
809
810     if (m_isBuiltinFunction)
811         m_shouldEmitDebugHooks = false;
812
813     allocateCalleeSaveSpace();
814
815     SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(*m_vm);
816     moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
817     moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
818
819     bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
820     if (shouldCaptureAllOfTheThings)
821         moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
822
823     auto captures = [&] (UniquedStringImpl* uid) -> bool {
824         return moduleProgramNode->captures(uid);
825     };
826     auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
827         // Allocate the exported variables in the module environment.
828         if (entry.isExported())
829             return VarKind::Scope;
830
831         // Allocate the namespace variables in the module environment to instantiate
832         // it from the outside of the module code.
833         if (entry.isImportedNamespace())
834             return VarKind::Scope;
835
836         if (entry.isCaptured())
837             return VarKind::Scope;
838         return captures(uid) ? VarKind::Scope : VarKind::Stack;
839     };
840
841     emitEnter();
842
843     allocateAndEmitScope();
844
845     emitCheckTraps();
846     
847     m_calleeRegister.setIndex(CallFrameSlot::callee);
848
849     m_codeBlock->setNumParameters(1); // Allocate space for "this"
850
851     // Now declare all variables.
852
853     for (auto& entry : moduleProgramNode->varDeclarations()) {
854         ASSERT(!entry.value.isLet() && !entry.value.isConst());
855         if (!entry.value.isVar()) // This is either a parameter or callee.
856             continue;
857         // Imported bindings are not allocated in the module environment as usual variables' way.
858         // These references remain the "Dynamic" in the unlinked code block. Later, when linking
859         // the code block, we resolve the reference to the "ModuleVar".
860         if (entry.value.isImported() && !entry.value.isImportedNamespace())
861             continue;
862         createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
863     }
864
865     VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
866     instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
867
868     // We keep the symbol table in the constant pool.
869     RegisterID* constantSymbolTable = nullptr;
870     if (vm.typeProfiler())
871         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
872     else
873         constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
874
875     pushTDZVariables(lexicalVariables, TDZCheckOptimization::Optimize, TDZRequirement::UnderTDZ);
876     bool isWithScope = false;
877     m_lexicalScopeStack.append({ moduleEnvironmentSymbolTable, m_topMostScope, isWithScope, constantSymbolTable->index() });
878     emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
879
880     // makeFunction assumes that there's correct TDZ stack entries.
881     // So it should be called after putting our lexical environment to the TDZ stack correctly.
882
883     for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
884         const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
885         RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
886         RELEASE_ASSERT(!iterator->value.isImported());
887
888         VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
889         if (varKind == VarKind::Scope) {
890             // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
891             // Section 15.2.1.16.4, step 16-a-iv-1.
892             // All heap allocated function declarations should be instantiated when the module environment
893             // is created. They include the exported function declarations and not-exported-but-heap-allocated
894             // function declarations. This is required because exported function should be instantiated before
895             // executing the any module in the dependency graph. This enables the modules to link the imported
896             // bindings before executing the any module code.
897             //
898             // And since function declarations are instantiated before executing the module body code, the spec
899             // allows the functions inside the module to be executed before its module body is executed under
900             // the circular dependencies. The following is the example.
901             //
902             // Module A (executed first):
903             //    import { b } from "B";
904             //    // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
905             //    // So we can call the function exported from "B".
906             //    b();
907             //
908             //    export function a() {
909             //    }
910             //
911             // Module B (executed second):
912             //    import { a } from "A";
913             //
914             //    export function b() {
915             //        c();
916             //    }
917             //
918             //    // c is not exported, but since it is referenced from the b, we should instantiate it before
919             //    // executing the "B" module code.
920             //    function c() {
921             //        a();
922             //    }
923             //
924             // Module EntryPoint (executed last):
925             //    import "B";
926             //    import "A";
927             //
928             m_codeBlock->addFunctionDecl(makeFunction(function));
929         } else {
930             // Stack allocated functions can be allocated when executing the module's body.
931             m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
932         }
933     }
934
935     // Remember the constant register offset to the top-most symbol table. This symbol table will be
936     // cloned in the code block linking. After that, to create the module environment, we retrieve
937     // the cloned symbol table from the linked code block by using this offset.
938     codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
939 }
940
941 BytecodeGenerator::~BytecodeGenerator()
942 {
943 }
944
945 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
946     FunctionParameters& parameters, bool isSimpleParameterList, FunctionNode* functionNode, SymbolTable* functionSymbolTable, 
947     int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope)
948 {
949     Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
950     ASSERT(!(isSimpleParameterList && shouldCreateArgumentsVariableInParameterScope));
951     if (!isSimpleParameterList) {
952         // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
953         // This implements step 21.
954         VariableEnvironment environment;
955         Vector<Identifier> allParameterNames; 
956         for (unsigned i = 0; i < parameters.size(); i++)
957             parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
958         if (shouldCreateArgumentsVariableInParameterScope)
959             allParameterNames.append(propertyNames().arguments);
960         IdentifierSet parameterSet;
961         for (auto& ident : allParameterNames) {
962             parameterSet.add(ident.impl());
963             auto addResult = environment.add(ident);
964             addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
965             if (captures(ident.impl()))
966                 addResult.iterator->value.setIsCaptured();
967         }
968         // This implements step 25 of section 9.2.12.
969         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
970
971         if (shouldCreateArgumentsVariableInParameterScope) {
972             Variable argumentsVariable = variable(propertyNames().arguments); 
973             initializeVariable(argumentsVariable, m_argumentsRegister);
974             liftTDZCheckIfPossible(argumentsVariable);
975         }
976
977         RefPtr<RegisterID> temp = newTemporary();
978         for (unsigned i = 0; i < parameters.size(); i++) {
979             std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
980             if (parameter.first->isRestParameter())
981                 continue;
982             if ((i + 1) < m_parameters.size())
983                 emitMove(temp.get(), &m_parameters[i + 1]);
984             else
985                 emitGetArgument(temp.get(), i);
986             if (parameter.second) {
987                 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), temp.get());
988                 Ref<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
989                 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
990                 emitNode(temp.get(), parameter.second);
991                 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
992             }
993
994             parameter.first->bindValue(*this, temp.get());
995         }
996
997         // Final act of weirdness for default parameters. If a "var" also
998         // has the same name as a parameter, it should start out as the
999         // value of that parameter. Note, though, that they will be distinct
1000         // bindings.
1001         // This is step 28 of section 9.2.12. 
1002         for (auto& entry : functionNode->varDeclarations()) {
1003             if (!entry.value.isVar()) // This is either a parameter or callee.
1004                 continue;
1005
1006             if (parameterSet.contains(entry.key)) {
1007                 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
1008                 Variable var = variable(ident);
1009                 RegisterID* scope = emitResolveScope(nullptr, var);
1010                 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
1011                 valuesToMoveIntoVars.append(std::make_pair(ident, value));
1012             }
1013         }
1014
1015         // Functions with default parameter expressions must have a separate environment
1016         // record for parameters and "var"s. The "var" environment record must have the
1017         // parameter environment record as its parent.
1018         // See step 28 of section 9.2.12.
1019         bool hasCapturedVariables = !!m_lexicalEnvironmentRegister; 
1020         initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, hasCapturedVariables);
1021     }
1022
1023     // This completes step 28 of section 9.2.12.
1024     for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
1025         ASSERT(!isSimpleParameterList);
1026         Variable var = variable(valuesToMoveIntoVars[i].first);
1027         RegisterID* scope = emitResolveScope(nullptr, var);
1028         emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
1029     }
1030 }
1031
1032 bool BytecodeGenerator::needsDerivedConstructorInArrowFunctionLexicalEnvironment()
1033 {
1034     ASSERT(m_codeBlock->isClassContext() || !(isConstructor() && constructorKind() == ConstructorKind::Extends));
1035     return m_codeBlock->isClassContext() && isSuperUsedInInnerArrowFunction();
1036 }
1037
1038 void BytecodeGenerator::initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable, bool canReuseLexicalEnvironment)
1039 {
1040     ASSERT(!m_arrowFunctionContextLexicalEnvironmentRegister);
1041
1042     if (canReuseLexicalEnvironment && m_lexicalEnvironmentRegister) {
1043         RELEASE_ASSERT(!m_codeBlock->isArrowFunction());
1044         RELEASE_ASSERT(functionSymbolTable);
1045
1046         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalEnvironmentRegister;
1047         
1048         ScopeOffset offset;
1049         
1050         if (isThisUsedInInnerArrowFunction()) {
1051             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1052             functionSymbolTable->set(NoLockingNecessary, propertyNames().thisIdentifier.impl(), SymbolTableEntry(VarOffset(offset)));
1053         }
1054
1055         if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1056             offset = functionSymbolTable->takeNextScopeOffset();
1057             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().newTargetLocalPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1058         }
1059         
1060         if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1061             offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1062             functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().derivedConstructorPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1063         }
1064
1065         return;
1066     }
1067
1068     VariableEnvironment environment;
1069
1070     if (isThisUsedInInnerArrowFunction()) {
1071         auto addResult = environment.add(propertyNames().thisIdentifier);
1072         addResult.iterator->value.setIsCaptured();
1073         addResult.iterator->value.setIsLet();
1074     }
1075     
1076     if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1077         auto addTarget = environment.add(propertyNames().builtinNames().newTargetLocalPrivateName());
1078         addTarget.iterator->value.setIsCaptured();
1079         addTarget.iterator->value.setIsLet();
1080     }
1081
1082     if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1083         auto derivedConstructor = environment.add(propertyNames().builtinNames().derivedConstructorPrivateName());
1084         derivedConstructor.iterator->value.setIsCaptured();
1085         derivedConstructor.iterator->value.setIsLet();
1086     }
1087
1088     if (environment.size() > 0) {
1089         size_t size = m_lexicalScopeStack.size();
1090         pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1091
1092         ASSERT_UNUSED(size, m_lexicalScopeStack.size() == size + 1);
1093
1094         m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalScopeStack.last().m_scope;
1095     }
1096 }
1097
1098 RegisterID* BytecodeGenerator::initializeNextParameter()
1099 {
1100     VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
1101     m_parameters.grow(m_parameters.size() + 1);
1102     auto& parameter = registerFor(reg);
1103     parameter.setIndex(reg.offset());
1104     m_codeBlock->addParameter();
1105     return &parameter;
1106 }
1107
1108 void BytecodeGenerator::initializeParameters(FunctionParameters& parameters)
1109 {
1110     // Make sure the code block knows about all of our parameters, and make sure that parameters
1111     // needing destructuring are noted.
1112     m_thisRegister.setIndex(initializeNextParameter()->index()); // this
1113
1114     bool nonSimpleArguments = false;
1115     for (unsigned i = 0; i < parameters.size(); ++i) {
1116         auto parameter = parameters.at(i);
1117         auto pattern = parameter.first;
1118         if (pattern->isRestParameter()) {
1119             RELEASE_ASSERT(!m_restParameter);
1120             m_restParameter = static_cast<RestParameterNode*>(pattern);
1121             nonSimpleArguments = true;
1122             continue;
1123         }
1124         if (parameter.second) {
1125             nonSimpleArguments = true;
1126             continue;
1127         }
1128         if (!nonSimpleArguments)
1129             initializeNextParameter();
1130     }
1131 }
1132
1133 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables)
1134 {
1135     if (hasCapturedVariables) {
1136         RELEASE_ASSERT(m_lexicalEnvironmentRegister);
1137         emitOpcode(op_create_lexical_environment);
1138         instructions().append(m_lexicalEnvironmentRegister->index());
1139         instructions().append(scopeRegister()->index());
1140         instructions().append(symbolTableConstantIndex);
1141         instructions().append(addConstantValue(jsUndefined())->index());
1142
1143         emitOpcode(op_mov);
1144         instructions().append(scopeRegister()->index());
1145         instructions().append(m_lexicalEnvironmentRegister->index());
1146
1147         pushLocalControlFlowScope();
1148     }
1149     bool isWithScope = false;
1150     m_lexicalScopeStack.append({ functionSymbolTable, m_lexicalEnvironmentRegister, isWithScope, symbolTableConstantIndex });
1151     m_varScopeLexicalScopeStackIndex = m_lexicalScopeStack.size() - 1;
1152 }
1153
1154 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
1155 {
1156     if (pattern->isBindingNode()) {
1157         const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
1158         if (!m_functions.contains(ident.impl()))
1159             return ident.impl();
1160     }
1161     return nullptr;
1162 }
1163
1164 RegisterID* BytecodeGenerator::newRegister()
1165 {
1166     m_calleeLocals.append(virtualRegisterForLocal(m_calleeLocals.size()));
1167     int numCalleeLocals = max<int>(m_codeBlock->m_numCalleeLocals, m_calleeLocals.size());
1168     numCalleeLocals = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeLocals);
1169     m_codeBlock->m_numCalleeLocals = numCalleeLocals;
1170     return &m_calleeLocals.last();
1171 }
1172
1173 void BytecodeGenerator::reclaimFreeRegisters()
1174 {
1175     while (m_calleeLocals.size() && !m_calleeLocals.last().refCount())
1176         m_calleeLocals.removeLast();
1177 }
1178
1179 RegisterID* BytecodeGenerator::newBlockScopeVariable()
1180 {
1181     reclaimFreeRegisters();
1182
1183     return newRegister();
1184 }
1185
1186 RegisterID* BytecodeGenerator::newTemporary()
1187 {
1188     reclaimFreeRegisters();
1189
1190     RegisterID* result = newRegister();
1191     result->setTemporary();
1192     return result;
1193 }
1194
1195 LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
1196 {
1197     // Reclaim free label scopes.
1198     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
1199         m_labelScopes.removeLast();
1200
1201     // Allocate new label scope.
1202     LabelScope scope(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? RefPtr<Label>(newLabel()) : RefPtr<Label>()); // Only loops have continue targets.
1203     m_labelScopes.append(WTFMove(scope));
1204     return LabelScopePtr(m_labelScopes, m_labelScopes.size() - 1);
1205 }
1206
1207 Ref<Label> BytecodeGenerator::newLabel()
1208 {
1209     // Reclaim free label IDs.
1210     while (m_labels.size() && !m_labels.last().refCount())
1211         m_labels.removeLast();
1212
1213     // Allocate new label ID.
1214     m_labels.append(*this);
1215     return m_labels.last();
1216 }
1217
1218 Ref<Label> BytecodeGenerator::newEmittedLabel()
1219 {
1220     Ref<Label> label = newLabel();
1221     emitLabel(label.get());
1222     return label;
1223 }
1224
1225 void BytecodeGenerator::emitLabel(Label& l0)
1226 {
1227     unsigned newLabelIndex = instructions().size();
1228     l0.setLocation(newLabelIndex);
1229
1230     if (m_codeBlock->numberOfJumpTargets()) {
1231         unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
1232         ASSERT(lastLabelIndex <= newLabelIndex);
1233         if (newLabelIndex == lastLabelIndex) {
1234             // Peephole optimizations have already been disabled by emitting the last label
1235             return;
1236         }
1237     }
1238
1239     m_codeBlock->addJumpTarget(newLabelIndex);
1240
1241     // This disables peephole optimizations when an instruction is a jump target
1242     m_lastOpcodeID = op_end;
1243 }
1244
1245 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
1246 {
1247 #ifndef NDEBUG
1248     size_t opcodePosition = instructions().size();
1249     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
1250     m_lastOpcodePosition = opcodePosition;
1251 #endif
1252     instructions().append(opcodeID);
1253     m_lastOpcodeID = opcodeID;
1254 }
1255
1256 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
1257 {
1258     return m_codeBlock->addArrayProfile();
1259 }
1260
1261 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
1262 {
1263     return m_codeBlock->addArrayAllocationProfile();
1264 }
1265
1266 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
1267 {
1268     return m_codeBlock->addObjectAllocationProfile();
1269 }
1270
1271 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
1272 {
1273     UnlinkedValueProfile result = m_codeBlock->addValueProfile();
1274     emitOpcode(opcodeID);
1275     return result;
1276 }
1277
1278 void BytecodeGenerator::emitEnter()
1279 {
1280     emitOpcode(op_enter);
1281 }
1282
1283 void BytecodeGenerator::emitLoopHint()
1284 {
1285     emitOpcode(op_loop_hint);
1286     emitCheckTraps();
1287 }
1288
1289 void BytecodeGenerator::emitCheckTraps()
1290 {
1291     emitOpcode(op_check_traps);
1292 }
1293
1294 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
1295 {
1296     ASSERT(instructions().size() >= 4);
1297     size_t size = instructions().size();
1298     dstIndex = instructions().at(size - 3).u.operand;
1299     src1Index = instructions().at(size - 2).u.operand;
1300     src2Index = instructions().at(size - 1).u.operand;
1301 }
1302
1303 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
1304 {
1305     ASSERT(instructions().size() >= 3);
1306     size_t size = instructions().size();
1307     dstIndex = instructions().at(size - 2).u.operand;
1308     srcIndex = instructions().at(size - 1).u.operand;
1309 }
1310
1311 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
1312 {
1313     ASSERT(instructions().size() >= 4);
1314     instructions().shrink(instructions().size() - 4);
1315     m_lastOpcodeID = op_end;
1316 }
1317
1318 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
1319 {
1320     ASSERT(instructions().size() >= 3);
1321     instructions().shrink(instructions().size() - 3);
1322     m_lastOpcodeID = op_end;
1323 }
1324
1325 void BytecodeGenerator::emitJump(Label& target)
1326 {
1327     size_t begin = instructions().size();
1328     emitOpcode(op_jmp);
1329     instructions().append(target.bind(begin, instructions().size()));
1330 }
1331
1332 void BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label& target)
1333 {
1334     if (m_lastOpcodeID == op_less) {
1335         int dstIndex;
1336         int src1Index;
1337         int src2Index;
1338
1339         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1340
1341         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1342             rewindBinaryOp();
1343
1344             size_t begin = instructions().size();
1345             emitOpcode(op_jless);
1346             instructions().append(src1Index);
1347             instructions().append(src2Index);
1348             instructions().append(target.bind(begin, instructions().size()));
1349             return;
1350         }
1351     } else if (m_lastOpcodeID == op_lesseq) {
1352         int dstIndex;
1353         int src1Index;
1354         int src2Index;
1355
1356         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1357
1358         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1359             rewindBinaryOp();
1360
1361             size_t begin = instructions().size();
1362             emitOpcode(op_jlesseq);
1363             instructions().append(src1Index);
1364             instructions().append(src2Index);
1365             instructions().append(target.bind(begin, instructions().size()));
1366             return;
1367         }
1368     } else if (m_lastOpcodeID == op_greater) {
1369         int dstIndex;
1370         int src1Index;
1371         int src2Index;
1372
1373         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1374
1375         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1376             rewindBinaryOp();
1377
1378             size_t begin = instructions().size();
1379             emitOpcode(op_jgreater);
1380             instructions().append(src1Index);
1381             instructions().append(src2Index);
1382             instructions().append(target.bind(begin, instructions().size()));
1383             return;
1384         }
1385     } else if (m_lastOpcodeID == op_greatereq) {
1386         int dstIndex;
1387         int src1Index;
1388         int src2Index;
1389
1390         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1391
1392         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1393             rewindBinaryOp();
1394
1395             size_t begin = instructions().size();
1396             emitOpcode(op_jgreatereq);
1397             instructions().append(src1Index);
1398             instructions().append(src2Index);
1399             instructions().append(target.bind(begin, instructions().size()));
1400             return;
1401         }
1402     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1403         int dstIndex;
1404         int srcIndex;
1405
1406         retrieveLastUnaryOp(dstIndex, srcIndex);
1407
1408         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1409             rewindUnaryOp();
1410
1411             size_t begin = instructions().size();
1412             emitOpcode(op_jeq_null);
1413             instructions().append(srcIndex);
1414             instructions().append(target.bind(begin, instructions().size()));
1415             return;
1416         }
1417     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1418         int dstIndex;
1419         int srcIndex;
1420
1421         retrieveLastUnaryOp(dstIndex, srcIndex);
1422
1423         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1424             rewindUnaryOp();
1425
1426             size_t begin = instructions().size();
1427             emitOpcode(op_jneq_null);
1428             instructions().append(srcIndex);
1429             instructions().append(target.bind(begin, instructions().size()));
1430             return;
1431         }
1432     }
1433
1434     size_t begin = instructions().size();
1435
1436     emitOpcode(op_jtrue);
1437     instructions().append(cond->index());
1438     instructions().append(target.bind(begin, instructions().size()));
1439 }
1440
1441 void BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label& target)
1442 {
1443     if (m_lastOpcodeID == op_less && target.isForward()) {
1444         int dstIndex;
1445         int src1Index;
1446         int src2Index;
1447
1448         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1449
1450         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1451             rewindBinaryOp();
1452
1453             size_t begin = instructions().size();
1454             emitOpcode(op_jnless);
1455             instructions().append(src1Index);
1456             instructions().append(src2Index);
1457             instructions().append(target.bind(begin, instructions().size()));
1458             return;
1459         }
1460     } else if (m_lastOpcodeID == op_lesseq && target.isForward()) {
1461         int dstIndex;
1462         int src1Index;
1463         int src2Index;
1464
1465         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1466
1467         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1468             rewindBinaryOp();
1469
1470             size_t begin = instructions().size();
1471             emitOpcode(op_jnlesseq);
1472             instructions().append(src1Index);
1473             instructions().append(src2Index);
1474             instructions().append(target.bind(begin, instructions().size()));
1475             return;
1476         }
1477     } else if (m_lastOpcodeID == op_greater && target.isForward()) {
1478         int dstIndex;
1479         int src1Index;
1480         int src2Index;
1481
1482         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1483
1484         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1485             rewindBinaryOp();
1486
1487             size_t begin = instructions().size();
1488             emitOpcode(op_jngreater);
1489             instructions().append(src1Index);
1490             instructions().append(src2Index);
1491             instructions().append(target.bind(begin, instructions().size()));
1492             return;
1493         }
1494     } else if (m_lastOpcodeID == op_greatereq && target.isForward()) {
1495         int dstIndex;
1496         int src1Index;
1497         int src2Index;
1498
1499         retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1500
1501         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1502             rewindBinaryOp();
1503
1504             size_t begin = instructions().size();
1505             emitOpcode(op_jngreatereq);
1506             instructions().append(src1Index);
1507             instructions().append(src2Index);
1508             instructions().append(target.bind(begin, instructions().size()));
1509             return;
1510         }
1511     } else if (m_lastOpcodeID == op_not) {
1512         int dstIndex;
1513         int srcIndex;
1514
1515         retrieveLastUnaryOp(dstIndex, srcIndex);
1516
1517         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1518             rewindUnaryOp();
1519
1520             size_t begin = instructions().size();
1521             emitOpcode(op_jtrue);
1522             instructions().append(srcIndex);
1523             instructions().append(target.bind(begin, instructions().size()));
1524             return;
1525         }
1526     } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1527         int dstIndex;
1528         int srcIndex;
1529
1530         retrieveLastUnaryOp(dstIndex, srcIndex);
1531
1532         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1533             rewindUnaryOp();
1534
1535             size_t begin = instructions().size();
1536             emitOpcode(op_jneq_null);
1537             instructions().append(srcIndex);
1538             instructions().append(target.bind(begin, instructions().size()));
1539             return;
1540         }
1541     } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1542         int dstIndex;
1543         int srcIndex;
1544
1545         retrieveLastUnaryOp(dstIndex, srcIndex);
1546
1547         if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1548             rewindUnaryOp();
1549
1550             size_t begin = instructions().size();
1551             emitOpcode(op_jeq_null);
1552             instructions().append(srcIndex);
1553             instructions().append(target.bind(begin, instructions().size()));
1554             return;
1555         }
1556     }
1557
1558     size_t begin = instructions().size();
1559     emitOpcode(op_jfalse);
1560     instructions().append(cond->index());
1561     instructions().append(target.bind(begin, instructions().size()));
1562 }
1563
1564 void BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label& target)
1565 {
1566     size_t begin = instructions().size();
1567
1568     emitOpcode(op_jneq_ptr);
1569     instructions().append(cond->index());
1570     instructions().append(Special::CallFunction);
1571     instructions().append(target.bind(begin, instructions().size()));
1572     instructions().append(0);
1573 }
1574
1575 void BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label& target)
1576 {
1577     size_t begin = instructions().size();
1578
1579     emitOpcode(op_jneq_ptr);
1580     instructions().append(cond->index());
1581     instructions().append(Special::ApplyFunction);
1582     instructions().append(target.bind(begin, instructions().size()));
1583     instructions().append(0);
1584 }
1585
1586 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1587 {
1588     UniquedStringImpl* rep = ident.impl();
1589     return m_identifierMap.contains(rep);
1590 }
1591
1592 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1593 {
1594     UniquedStringImpl* rep = ident.impl();
1595     IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1596     if (result.isNewEntry)
1597         m_codeBlock->addIdentifier(ident);
1598
1599     return result.iterator->value;
1600 }
1601
1602 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1603 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1604 {
1605     if (!m_emptyValueRegister) {
1606         int index = m_nextConstantOffset;
1607         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1608         ++m_nextConstantOffset;
1609         m_codeBlock->addConstant(JSValue());
1610         m_emptyValueRegister = &m_constantPoolRegisters[index];
1611     }
1612
1613     return m_emptyValueRegister;
1614 }
1615
1616 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1617 {
1618     if (!v)
1619         return addConstantEmptyValue();
1620
1621     int index = m_nextConstantOffset;
1622
1623     if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1624         v = jsDoubleNumber(v.asNumber());
1625     EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1626     JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1627     if (result.isNewEntry) {
1628         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1629         ++m_nextConstantOffset;
1630         m_codeBlock->addConstant(v, sourceCodeRepresentation);
1631     } else
1632         index = result.iterator->value;
1633     return &m_constantPoolRegisters[index];
1634 }
1635
1636 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1637 {
1638     unsigned constantIndex = static_cast<unsigned>(type);
1639     if (!m_linkTimeConstantRegisters[constantIndex]) {
1640         int index = m_nextConstantOffset;
1641         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1642         ++m_nextConstantOffset;
1643         m_codeBlock->addConstant(type);
1644         m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1645     }
1646
1647     if (!dst)
1648         return m_linkTimeConstantRegisters[constantIndex];
1649
1650     emitOpcode(op_mov);
1651     instructions().append(dst->index());
1652     instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1653
1654     return dst;
1655 }
1656
1657 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1658 {
1659     return m_codeBlock->addRegExp(r);
1660 }
1661
1662 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1663 {
1664     RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1665
1666     emitOpcode(op_mov);
1667     instructions().append(dst->index());
1668     instructions().append(emptyValue->index());
1669     return dst;
1670 }
1671
1672 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1673 {
1674     ASSERT(src != m_emptyValueRegister);
1675
1676     m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1677     emitOpcode(op_mov);
1678     instructions().append(dst->index());
1679     instructions().append(src->index());
1680
1681     return dst;
1682 }
1683
1684 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1685 {
1686     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1687     ASSERT_WITH_MESSAGE(op_negate != opcodeID, "op_negate has an Arith Profile.");
1688     emitOpcode(opcodeID);
1689     instructions().append(dst->index());
1690     instructions().append(src->index());
1691
1692     return dst;
1693 }
1694
1695 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src, OperandTypes types)
1696 {
1697     ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1698     emitOpcode(opcodeID);
1699     instructions().append(dst->index());
1700     instructions().append(src->index());
1701
1702     if (opcodeID == op_negate)
1703         instructions().append(ArithProfile(types.first()).bits());
1704     return dst;
1705 }
1706
1707 RegisterID* BytecodeGenerator::emitUnaryOpProfiled(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1708 {
1709     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1710     instructions().append(dst->index());
1711     instructions().append(src->index());
1712     instructions().append(profile);
1713     return dst;
1714 }
1715
1716 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1717 {
1718     emitOpcode(op_inc);
1719     instructions().append(srcDst->index());
1720     return srcDst;
1721 }
1722
1723 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1724 {
1725     emitOpcode(op_dec);
1726     instructions().append(srcDst->index());
1727     return srcDst;
1728 }
1729
1730 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1731 {
1732     emitOpcode(opcodeID);
1733     instructions().append(dst->index());
1734     instructions().append(src1->index());
1735     instructions().append(src2->index());
1736
1737     if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1738         opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1739         instructions().append(ArithProfile(types.first(), types.second()).bits());
1740
1741     return dst;
1742 }
1743
1744 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1745 {
1746     if (m_lastOpcodeID == op_typeof) {
1747         int dstIndex;
1748         int srcIndex;
1749
1750         retrieveLastUnaryOp(dstIndex, srcIndex);
1751
1752         if (src1->index() == dstIndex
1753             && src1->isTemporary()
1754             && m_codeBlock->isConstantRegisterIndex(src2->index())
1755             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1756             const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1757             if (value == "undefined") {
1758                 rewindUnaryOp();
1759                 emitOpcode(op_is_undefined);
1760                 instructions().append(dst->index());
1761                 instructions().append(srcIndex);
1762                 return dst;
1763             }
1764             if (value == "boolean") {
1765                 rewindUnaryOp();
1766                 emitOpcode(op_is_boolean);
1767                 instructions().append(dst->index());
1768                 instructions().append(srcIndex);
1769                 return dst;
1770             }
1771             if (value == "number") {
1772                 rewindUnaryOp();
1773                 emitOpcode(op_is_number);
1774                 instructions().append(dst->index());
1775                 instructions().append(srcIndex);
1776                 return dst;
1777             }
1778             if (value == "string") {
1779                 rewindUnaryOp();
1780                 emitOpcode(op_is_cell_with_type);
1781                 instructions().append(dst->index());
1782                 instructions().append(srcIndex);
1783                 instructions().append(StringType);
1784                 return dst;
1785             }
1786             if (value == "symbol") {
1787                 rewindUnaryOp();
1788                 emitOpcode(op_is_cell_with_type);
1789                 instructions().append(dst->index());
1790                 instructions().append(srcIndex);
1791                 instructions().append(SymbolType);
1792                 return dst;
1793             }
1794             if (value == "object") {
1795                 rewindUnaryOp();
1796                 emitOpcode(op_is_object_or_null);
1797                 instructions().append(dst->index());
1798                 instructions().append(srcIndex);
1799                 return dst;
1800             }
1801             if (value == "function") {
1802                 rewindUnaryOp();
1803                 emitOpcode(op_is_function);
1804                 instructions().append(dst->index());
1805                 instructions().append(srcIndex);
1806                 return dst;
1807             }
1808         }
1809     }
1810
1811     emitOpcode(opcodeID);
1812     instructions().append(dst->index());
1813     instructions().append(src1->index());
1814     instructions().append(src2->index());
1815     return dst;
1816 }
1817
1818 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1819 {
1820     ASSERT(vm()->typeProfiler());
1821
1822     unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1823     unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1824     unsigned instructionOffset = instructions().size() - 1;
1825     m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1826 }
1827
1828 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1829 {
1830     if (!vm()->typeProfiler())
1831         return;
1832
1833     if (!registerToProfile)
1834         return;
1835
1836     emitOpcode(op_profile_type);
1837     instructions().append(registerToProfile->index());
1838     instructions().append(0);
1839     instructions().append(flag);
1840     instructions().append(0);
1841     instructions().append(resolveType());
1842
1843     // Don't emit expression info for this version of profile type. This generally means
1844     // we're profiling information for something that isn't in the actual text of a JavaScript
1845     // program. For example, implicit return undefined from a function call.
1846 }
1847
1848 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1849 {
1850     emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1851 }
1852
1853 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1854 {
1855     if (!vm()->typeProfiler())
1856         return;
1857
1858     if (!registerToProfile)
1859         return;
1860
1861     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1862     emitOpcode(op_profile_type);
1863     instructions().append(registerToProfile->index());
1864     instructions().append(0);
1865     instructions().append(flag);
1866     instructions().append(0);
1867     instructions().append(resolveType());
1868
1869     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1870 }
1871
1872 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1873 {
1874     if (!vm()->typeProfiler())
1875         return;
1876
1877     if (!registerToProfile)
1878         return;
1879
1880     ProfileTypeBytecodeFlag flag;
1881     int symbolTableOrScopeDepth;
1882     if (var.local() || var.offset().isScope()) {
1883         flag = ProfileTypeBytecodeLocallyResolved;
1884         ASSERT(var.symbolTableConstantIndex());
1885         symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1886     } else {
1887         flag = ProfileTypeBytecodeClosureVar;
1888         symbolTableOrScopeDepth = localScopeDepth();
1889     }
1890
1891     // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1892     emitOpcode(op_profile_type);
1893     instructions().append(registerToProfile->index());
1894     instructions().append(symbolTableOrScopeDepth);
1895     instructions().append(flag);
1896     instructions().append(addConstant(var.ident()));
1897     instructions().append(resolveType());
1898
1899     emitTypeProfilerExpressionInfo(startDivot, endDivot);
1900 }
1901
1902 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1903 {
1904     if (vm()->controlFlowProfiler()) {
1905         RELEASE_ASSERT(textOffset >= 0);
1906         size_t bytecodeOffset = instructions().size();
1907         m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1908
1909         emitOpcode(op_profile_control_flow);
1910         instructions().append(textOffset);
1911     }
1912 }
1913
1914 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1915 {
1916     return emitLoad(dst, jsBoolean(b));
1917 }
1918
1919 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1920 {
1921     ASSERT(!identifier.isSymbol());
1922     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1923     if (!stringInMap)
1924         stringInMap = jsOwnedString(vm(), identifier.string());
1925
1926     return emitLoad(dst, JSValue(stringInMap));
1927 }
1928
1929 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1930 {
1931     RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1932     if (dst)
1933         return emitMove(dst, constantID);
1934     return constantID;
1935 }
1936
1937 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, IdentifierSet& set)
1938 {
1939     for (const auto& entry : m_codeBlock->constantIdentifierSets()) {
1940         if (entry.first != set)
1941             continue;
1942         
1943         return &m_constantPoolRegisters[entry.second];
1944     }
1945     
1946     unsigned index = m_nextConstantOffset;
1947     m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1948     ++m_nextConstantOffset;
1949     m_codeBlock->addSetConstant(set);
1950     RegisterID* m_setRegister = &m_constantPoolRegisters[index];
1951     
1952     if (dst)
1953         return emitMove(dst, m_setRegister);
1954     
1955     return m_setRegister;
1956 }
1957
1958 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1959 {
1960     if (!m_globalObjectRegister) {
1961         int index = m_nextConstantOffset;
1962         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1963         ++m_nextConstantOffset;
1964         m_codeBlock->addConstant(JSValue());
1965         m_globalObjectRegister = &m_constantPoolRegisters[index];
1966         m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1967     }
1968     if (dst)
1969         emitMove(dst, m_globalObjectRegister);
1970     return m_globalObjectRegister;
1971 }
1972
1973 template<typename LookUpVarKindFunctor>
1974 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
1975 {
1976     bool hasCapturedVariables = false;
1977     {
1978         for (auto& entry : lexicalVariables) {
1979             ASSERT(entry.value.isLet() || entry.value.isConst() || entry.value.isFunction());
1980             ASSERT(!entry.value.isVar());
1981             SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
1982             ASSERT(symbolTableEntry.isNull());
1983
1984             // Imported bindings which are not the namespace bindings are not allocated
1985             // in the module environment as usual variables' way.
1986             // And since these types of the variables only seen in the module environment,
1987             // other lexical environment need not to take care this.
1988             if (entry.value.isImported() && !entry.value.isImportedNamespace())
1989                 continue;
1990
1991             VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
1992             VarOffset varOffset;
1993             if (varKind == VarKind::Scope) {
1994                 varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
1995                 hasCapturedVariables = true;
1996             } else {
1997                 ASSERT(varKind == VarKind::Stack);
1998                 RegisterID* local;
1999                 if (scopeRegisterType == ScopeRegisterType::Block) {
2000                     local = newBlockScopeVariable();
2001                     local->ref();
2002                 } else
2003                     local = addVar();
2004                 varOffset = VarOffset(local->virtualRegister());
2005             }
2006
2007             SymbolTableEntry newEntry(varOffset, entry.value.isConst() ? ReadOnly : 0);
2008             symbolTable->add(NoLockingNecessary, entry.key.get(), newEntry);
2009         }
2010     }
2011     return hasCapturedVariables;
2012 }
2013
2014 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
2015 {
2016     // Prefill stack variables with the TDZ empty value.
2017     // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
2018     for (auto& entry : lexicalVariables) {
2019         // Imported bindings which are not the namespace bindings are not allocated
2020         // in the module environment as usual variables' way.
2021         // And since these types of the variables only seen in the module environment,
2022         // other lexical environment need not to take care this.
2023         if (entry.value.isImported() && !entry.value.isImportedNamespace())
2024             continue;
2025
2026         if (entry.value.isFunction())
2027             continue;
2028
2029         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2030         ASSERT(!symbolTableEntry.isNull());
2031         VarOffset offset = symbolTableEntry.varOffset();
2032         if (offset.isScope())
2033             continue;
2034
2035         ASSERT(offset.isStack());
2036         emitMoveEmptyValue(&registerFor(offset.stackOffset()));
2037     }
2038 }
2039
2040 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType, RegisterID** constantSymbolTableResult, bool shouldInitializeBlockScopedFunctions)
2041 {
2042     VariableEnvironment& environment = node->lexicalVariables();
2043     RegisterID* constantSymbolTableResultTemp = nullptr;
2044     pushLexicalScopeInternal(environment, tdzCheckOptimization, nestedScopeType, &constantSymbolTableResultTemp, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
2045
2046     if (shouldInitializeBlockScopedFunctions)
2047         initializeBlockScopedFunctions(environment, node->functionStack(), constantSymbolTableResultTemp);
2048
2049     if (constantSymbolTableResult && constantSymbolTableResultTemp)
2050         *constantSymbolTableResult = constantSymbolTableResultTemp;
2051 }
2052
2053 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType,
2054     RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
2055 {
2056     if (!environment.size())
2057         return;
2058
2059     if (m_shouldEmitDebugHooks)
2060         environment.markAllVariablesAsCaptured();
2061
2062     SymbolTable* symbolTable = SymbolTable::create(*m_vm);
2063     switch (scopeType) {
2064     case ScopeType::CatchScope:
2065         symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
2066         break;
2067     case ScopeType::LetConstScope:
2068         symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
2069         break;
2070     case ScopeType::FunctionNameScope:
2071         symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
2072         break;
2073     }
2074
2075     if (nestedScopeType == NestedScopeType::IsNested)
2076         symbolTable->markIsNestedLexicalScope();
2077
2078     auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
2079         return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
2080     };
2081
2082     bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable, scopeRegisterType, lookUpVarKind);
2083
2084     RegisterID* newScope = nullptr;
2085     RegisterID* constantSymbolTable = nullptr;
2086     int symbolTableConstantIndex = 0;
2087     if (vm()->typeProfiler()) {
2088         constantSymbolTable = addConstantValue(symbolTable);
2089         symbolTableConstantIndex = constantSymbolTable->index();
2090     }
2091     if (hasCapturedVariables) {
2092         if (scopeRegisterType == ScopeRegisterType::Block) {
2093             newScope = newBlockScopeVariable();
2094             newScope->ref();
2095         } else
2096             newScope = addVar();
2097         if (!constantSymbolTable) {
2098             ASSERT(!vm()->typeProfiler());
2099             constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
2100             symbolTableConstantIndex = constantSymbolTable->index();
2101         }
2102         if (constantSymbolTableResult)
2103             *constantSymbolTableResult = constantSymbolTable;
2104
2105         emitOpcode(op_create_lexical_environment);
2106         instructions().append(newScope->index());
2107         instructions().append(scopeRegister()->index());
2108         instructions().append(constantSymbolTable->index());
2109         instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
2110
2111         emitMove(scopeRegister(), newScope);
2112
2113         pushLocalControlFlowScope();
2114     }
2115
2116     bool isWithScope = false;
2117     m_lexicalScopeStack.append({ symbolTable, newScope, isWithScope, symbolTableConstantIndex });
2118     pushTDZVariables(environment, tdzCheckOptimization, tdzRequirement);
2119
2120     if (tdzRequirement == TDZRequirement::UnderTDZ)
2121         emitPrefillStackTDZVariables(environment, symbolTable);
2122 }
2123
2124 void BytecodeGenerator::initializeBlockScopedFunctions(VariableEnvironment& environment, FunctionStack& functionStack, RegisterID* constantSymbolTable)
2125 {
2126     /*
2127      * We must transform block scoped function declarations in strict mode like so:
2128      *
2129      * function foo() {
2130      *     if (c) {
2131      *           function foo() { ... }
2132      *           if (bar) { ... }
2133      *           else { ... }
2134      *           function baz() { ... }
2135      *     }
2136      * }
2137      *
2138      * to:
2139      *
2140      * function foo() {
2141      *     if (c) {
2142      *         let foo = function foo() { ... }
2143      *         let baz = function baz() { ... }
2144      *         if (bar) { ... }
2145      *         else { ... }
2146      *     }
2147      * }
2148      * 
2149      * But without the TDZ checks.
2150     */
2151
2152     if (!environment.size()) {
2153         RELEASE_ASSERT(!functionStack.size());
2154         return;
2155     }
2156
2157     if (!functionStack.size())
2158         return;
2159
2160     SymbolTable* symbolTable = m_lexicalScopeStack.last().m_symbolTable;
2161     RegisterID* scope = m_lexicalScopeStack.last().m_scope;
2162     RefPtr<RegisterID> temp = newTemporary();
2163     int symbolTableIndex = constantSymbolTable ? constantSymbolTable->index() : 0;
2164     for (FunctionMetadataNode* function : functionStack) {
2165         const Identifier& name = function->ident();
2166         auto iter = environment.find(name.impl());
2167         RELEASE_ASSERT(iter != environment.end());
2168         RELEASE_ASSERT(iter->value.isFunction());
2169         // We purposefully don't hold the symbol table lock around this loop because emitNewFunctionExpressionCommon may GC.
2170         SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, name.impl()); 
2171         RELEASE_ASSERT(!entry.isNull());
2172         emitNewFunctionExpressionCommon(temp.get(), function);
2173         bool isLexicallyScoped = true;
2174         emitPutToScope(scope, variableForLocalEntry(name, entry, symbolTableIndex, isLexicallyScoped), temp.get(), DoNotThrowIfNotFound, InitializationMode::Initialization);
2175     }
2176 }
2177
2178 void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
2179 {
2180     if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl())) {
2181         if (codeType() != EvalCode) {
2182             Variable currentFunctionVariable = variable(functionName);
2183             RefPtr<RegisterID> currentValue;
2184             if (RegisterID* local = currentFunctionVariable.local())
2185                 currentValue = local;
2186             else {
2187                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2188                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2189             }
2190
2191             ASSERT(m_varScopeLexicalScopeStackIndex);
2192             ASSERT(*m_varScopeLexicalScopeStackIndex < m_lexicalScopeStack.size());
2193             LexicalScopeStackEntry varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex];
2194             SymbolTable* varSymbolTable = varScope.m_symbolTable;
2195             ASSERT(varSymbolTable->scopeType() == SymbolTable::ScopeType::VarScope);
2196             SymbolTableEntry entry = varSymbolTable->get(NoLockingNecessary, functionName.impl());
2197             if (functionName == propertyNames().arguments && entry.isNull()) {
2198                 // "arguments" might be put in the parameter scope when we have a non-simple
2199                 // parameter list since "arguments" is visible to expressions inside the
2200                 // parameter evaluation list.
2201                 // e.g:
2202                 // function foo(x = arguments) { { function arguments() { } } }
2203                 RELEASE_ASSERT(*m_varScopeLexicalScopeStackIndex > 0);
2204                 varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex - 1];
2205                 SymbolTable* parameterSymbolTable = varScope.m_symbolTable;
2206                 entry = parameterSymbolTable->get(NoLockingNecessary, functionName.impl());
2207             }
2208             RELEASE_ASSERT(!entry.isNull());
2209             bool isLexicallyScoped = false;
2210             emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2211         } else {
2212             Variable currentFunctionVariable = variable(functionName);
2213             RefPtr<RegisterID> currentValue;
2214             if (RegisterID* local = currentFunctionVariable.local())
2215                 currentValue = local;
2216             else {
2217                 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2218                 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2219             }
2220
2221             RefPtr<RegisterID> scopeId = emitResolveScopeForHoistingFuncDeclInEval(nullptr, functionName);
2222             RefPtr<RegisterID> checkResult = emitIsUndefined(newTemporary(), scopeId.get());
2223             
2224             Ref<Label> isNotVarScopeLabel = newLabel();
2225             emitJumpIfTrue(checkResult.get(), isNotVarScopeLabel.get());
2226
2227             // Put to outer scope
2228             emitPutToScope(scopeId.get(), functionName, currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2229             emitLabel(isNotVarScopeLabel.get());
2230
2231         }
2232     }
2233 }
2234
2235 RegisterID* BytecodeGenerator::emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier& property)
2236 {
2237     ASSERT(m_codeType == EvalCode);
2238
2239     dst = finalDestination(dst);
2240     emitOpcode(op_resolve_scope_for_hoisting_func_decl_in_eval);
2241     instructions().append(kill(dst));
2242     instructions().append(m_topMostScope->index());
2243     instructions().append(addConstant(property));
2244     return dst;
2245 }
2246
2247 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
2248 {
2249     VariableEnvironment& environment = node->lexicalVariables();
2250     popLexicalScopeInternal(environment);
2251 }
2252
2253 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment)
2254 {
2255     // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
2256     // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
2257     if (!environment.size())
2258         return;
2259
2260     if (m_shouldEmitDebugHooks)
2261         environment.markAllVariablesAsCaptured();
2262
2263     auto stackEntry = m_lexicalScopeStack.takeLast();
2264     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2265     bool hasCapturedVariables = false;
2266     for (auto& entry : environment) {
2267         if (entry.value.isCaptured()) {
2268             hasCapturedVariables = true;
2269             continue;
2270         }
2271         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2272         ASSERT(!symbolTableEntry.isNull());
2273         VarOffset offset = symbolTableEntry.varOffset();
2274         ASSERT(offset.isStack());
2275         RegisterID* local = &registerFor(offset.stackOffset());
2276         local->deref();
2277     }
2278
2279     if (hasCapturedVariables) {
2280         RELEASE_ASSERT(stackEntry.m_scope);
2281         emitPopScope(scopeRegister(), stackEntry.m_scope);
2282         popLocalControlFlowScope();
2283         stackEntry.m_scope->deref();
2284     }
2285
2286     m_TDZStack.removeLast();
2287 }
2288
2289 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
2290 {
2291     VariableEnvironment& environment = node->lexicalVariables();
2292     if (!environment.size())
2293         return;
2294     if (m_shouldEmitDebugHooks)
2295         environment.markAllVariablesAsCaptured();
2296     if (!environment.hasCapturedVariables())
2297         return;
2298
2299     RELEASE_ASSERT(loopSymbolTable);
2300
2301     // This function needs to do setup for a for loop's activation if any of
2302     // the for loop's lexically declared variables are captured (that is, variables
2303     // declared in the loop header, not the loop body). This function needs to
2304     // make a copy of the current activation and copy the values from the previous
2305     // activation into the new activation because each iteration of a for loop
2306     // gets a new activation.
2307
2308     auto stackEntry = m_lexicalScopeStack.last();
2309     SymbolTable* symbolTable = stackEntry.m_symbolTable;
2310     RegisterID* loopScope = stackEntry.m_scope;
2311     ASSERT(symbolTable->scopeSize());
2312     ASSERT(loopScope);
2313     Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
2314
2315     {
2316         activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
2317
2318         for (auto end = symbolTable->end(NoLockingNecessary), ptr = symbolTable->begin(NoLockingNecessary); ptr != end; ++ptr) {
2319             if (!ptr->value.varOffset().isScope())
2320                 continue;
2321
2322             RefPtr<UniquedStringImpl> ident = ptr->key;
2323             Identifier identifier = Identifier::fromUid(m_vm, ident.get());
2324
2325             RegisterID* transitionValue = newBlockScopeVariable();
2326             transitionValue->ref();
2327             emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
2328             activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
2329         }
2330     }
2331
2332     // We need this dynamic behavior of the executing code to ensure
2333     // each loop iteration has a new activation object. (It's pretty ugly).
2334     // Also, this new activation needs to be assigned to the same register
2335     // as the previous scope because the loop body is compiled under
2336     // the assumption that the scope's register index is constant even
2337     // though the value in that register will change on each loop iteration.
2338     RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
2339     emitMove(scopeRegister(), parentScope.get());
2340
2341     emitOpcode(op_create_lexical_environment);
2342     instructions().append(loopScope->index());
2343     instructions().append(scopeRegister()->index());
2344     instructions().append(loopSymbolTable->index());
2345     instructions().append(addConstantValue(jsTDZValue())->index());
2346
2347     emitMove(scopeRegister(), loopScope);
2348
2349     {
2350         for (auto pair : activationValuesToCopyOver) {
2351             const Identifier& identifier = pair.second;
2352             SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, identifier.impl());
2353             RELEASE_ASSERT(!entry.isNull());
2354             RegisterID* transitionValue = pair.first;
2355             emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2356             transitionValue->deref();
2357         }
2358     }
2359 }
2360
2361 Variable BytecodeGenerator::variable(const Identifier& property, ThisResolutionType thisResolutionType)
2362 {
2363     if (property == propertyNames().thisIdentifier && thisResolutionType == ThisResolutionType::Local) {
2364         return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(),
2365             ReadOnly, Variable::SpecialVariable, 0, false);
2366     }
2367     
2368     // We can optimize lookups if the lexical variable is found before a "with" or "catch"
2369     // scope because we're guaranteed static resolution. If we have to pass through
2370     // a "with" or "catch" scope we loose this guarantee.
2371     // We can't optimize cases like this:
2372     // {
2373     //     let x = ...;
2374     //     with (o) {
2375     //         doSomethingWith(x);
2376     //     }
2377     // }
2378     // Because we can't gaurantee static resolution on x.
2379     // But, in this case, we are guaranteed static resolution:
2380     // {
2381     //     let x = ...;
2382     //     with (o) {
2383     //         let x = ...;
2384     //         doSomethingWith(x);
2385     //     }
2386     // }
2387     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2388         auto& stackEntry = m_lexicalScopeStack[i];
2389         if (stackEntry.m_isWithScope)
2390             return Variable(property);
2391         SymbolTable* symbolTable = stackEntry.m_symbolTable;
2392         SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, property.impl());
2393         if (symbolTableEntry.isNull())
2394             continue;
2395         bool resultIsCallee = false;
2396         if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2397             if (m_usesNonStrictEval) {
2398                 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
2399                 // We resort to dynamic lookup to answer this question.
2400                 Variable result = Variable(property);
2401                 return result;
2402             }
2403             resultIsCallee = true;
2404         }
2405         Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
2406         if (resultIsCallee)
2407             result.setIsReadOnly();
2408         return result;
2409     }
2410     
2411     return Variable(property);
2412 }
2413
2414 Variable BytecodeGenerator::variableForLocalEntry(
2415     const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
2416 {
2417     VarOffset offset = entry.varOffset();
2418     
2419     RegisterID* local;
2420     if (offset.isStack())
2421         local = &registerFor(offset.stackOffset());
2422     else
2423         local = nullptr;
2424     
2425     return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
2426 }
2427
2428 void BytecodeGenerator::createVariable(
2429     const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
2430 {
2431     ASSERT(property != propertyNames().thisIdentifier);
2432     SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, property.impl());
2433     
2434     if (!entry.isNull()) {
2435         if (existingVariableMode == IgnoreExisting)
2436             return;
2437         
2438         // Do some checks to ensure that the variable we're being asked to create is sufficiently
2439         // compatible with the one we have already created.
2440
2441         VarOffset offset = entry.varOffset();
2442         
2443         // We can't change our minds about whether it's captured.
2444         if (offset.kind() != varKind) {
2445             dataLog(
2446                 "Trying to add variable called ", property, " as ", varKind,
2447                 " but it was already added as ", offset, ".\n");
2448             RELEASE_ASSERT_NOT_REACHED();
2449         }
2450
2451         return;
2452     }
2453     
2454     VarOffset varOffset;
2455     if (varKind == VarKind::Scope)
2456         varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
2457     else {
2458         ASSERT(varKind == VarKind::Stack);
2459         varOffset = VarOffset(virtualRegisterForLocal(m_calleeLocals.size()));
2460     }
2461     SymbolTableEntry newEntry(varOffset, 0);
2462     symbolTable->add(NoLockingNecessary, property.impl(), newEntry);
2463     
2464     if (varKind == VarKind::Stack) {
2465         RegisterID* local = addVar();
2466         RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
2467     }
2468 }
2469
2470 RegisterID* BytecodeGenerator::emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue)
2471 {
2472     emitOpcode(op_overrides_has_instance);
2473     instructions().append(dst->index());
2474     instructions().append(constructor->index());
2475     instructions().append(hasInstanceValue->index());
2476     return dst;
2477 }
2478
2479 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
2480 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
2481 ResolveType BytecodeGenerator::resolveType()
2482 {
2483     for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2484         if (m_lexicalScopeStack[i].m_isWithScope)
2485             return Dynamic;
2486         if (m_usesNonStrictEval && m_lexicalScopeStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2487             // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
2488             // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
2489             // a put_to_scope with the destination being the function name scope variable.
2490             return Dynamic;
2491         }
2492     }
2493
2494     if (m_usesNonStrictEval)
2495         return GlobalPropertyWithVarInjectionChecks;
2496     return GlobalProperty;
2497 }
2498
2499 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
2500 {
2501     switch (variable.offset().kind()) {
2502     case VarKind::Stack:
2503         return nullptr;
2504         
2505     case VarKind::DirectArgument:
2506         return argumentsRegister();
2507         
2508     case VarKind::Scope: {
2509         // This always refers to the activation that *we* allocated, and not the current scope that code
2510         // lives in. Note that this will change once we have proper support for block scoping. Once that
2511         // changes, it will be correct for this code to return scopeRegister(). The only reason why we
2512         // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
2513         // requires weird things because it is a shameful pile of nonsense, but block scoping would make
2514         // that code sensible and obviate the need for us to do bad things.
2515         for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2516             auto& stackEntry = m_lexicalScopeStack[i];
2517             // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
2518             // scope and the resolved scope.
2519             RELEASE_ASSERT(!stackEntry.m_isWithScope);
2520
2521             if (stackEntry.m_symbolTable->get(NoLockingNecessary, variable.ident().impl()).isNull())
2522                 continue;
2523             
2524             RegisterID* scope = stackEntry.m_scope;
2525             RELEASE_ASSERT(scope);
2526             return scope;
2527         }
2528
2529         RELEASE_ASSERT_NOT_REACHED();
2530         return nullptr;
2531         
2532     }
2533     case VarKind::Invalid:
2534         // Indicates non-local resolution.
2535         
2536         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2537         
2538         // resolve_scope dst, id, ResolveType, depth
2539         dst = tempDestination(dst);
2540         emitOpcode(op_resolve_scope);
2541         instructions().append(kill(dst));
2542         instructions().append(scopeRegister()->index());
2543         instructions().append(addConstant(variable.ident()));
2544         instructions().append(resolveType());
2545         instructions().append(localScopeDepth());
2546         instructions().append(0);
2547         return dst;
2548     }
2549     
2550     RELEASE_ASSERT_NOT_REACHED();
2551     return nullptr;
2552 }
2553
2554 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2555 {
2556     switch (variable.offset().kind()) {
2557     case VarKind::Stack:
2558         return emitMove(dst, variable.local());
2559         
2560     case VarKind::DirectArgument: {
2561         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2562         instructions().append(kill(dst));
2563         instructions().append(scope->index());
2564         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2565         instructions().append(profile);
2566         return dst;
2567     }
2568         
2569     case VarKind::Scope:
2570     case VarKind::Invalid: {
2571         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2572         
2573         // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2574         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2575         instructions().append(kill(dst));
2576         instructions().append(scope->index());
2577         instructions().append(addConstant(variable.ident()));
2578         instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), InitializationMode::NotInitialization).operand());
2579         instructions().append(localScopeDepth());
2580         instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2581         instructions().append(profile);
2582         return dst;
2583     } }
2584     
2585     RELEASE_ASSERT_NOT_REACHED();
2586 }
2587
2588 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2589 {
2590     switch (variable.offset().kind()) {
2591     case VarKind::Stack:
2592         emitMove(variable.local(), value);
2593         return value;
2594         
2595     case VarKind::DirectArgument:
2596         emitOpcode(op_put_to_arguments);
2597         instructions().append(scope->index());
2598         instructions().append(variable.offset().capturedArgumentsOffset().offset());
2599         instructions().append(value->index());
2600         return value;
2601         
2602     case VarKind::Scope:
2603     case VarKind::Invalid: {
2604         m_codeBlock->addPropertyAccessInstruction(instructions().size());
2605         
2606         // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2607         emitOpcode(op_put_to_scope);
2608         instructions().append(scope->index());
2609         instructions().append(addConstant(variable.ident()));
2610         instructions().append(value->index());
2611         ScopeOffset offset;
2612         if (variable.offset().isScope()) {
2613             offset = variable.offset().scopeOffset();
2614             instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2615             instructions().append(variable.symbolTableConstantIndex());
2616         } else {
2617             ASSERT(resolveType() != LocalClosureVar);
2618             instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2619             instructions().append(localScopeDepth());
2620         }
2621         instructions().append(!!offset ? offset.offset() : 0);
2622         return value;
2623     } }
2624     
2625     RELEASE_ASSERT_NOT_REACHED();
2626 }
2627
2628 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2629 {
2630     RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2631     RegisterID* scope = emitResolveScope(nullptr, variable);
2632     return emitPutToScope(scope, variable, value, ThrowIfNotFound, InitializationMode::NotInitialization);
2633 }
2634
2635 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2636 {
2637     emitOpcode(op_instanceof);
2638     instructions().append(dst->index());
2639     instructions().append(value->index());
2640     instructions().append(basePrototype->index());
2641     return dst;
2642 }
2643
2644 RegisterID* BytecodeGenerator::emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue)
2645 {
2646     emitOpcode(op_instanceof_custom);
2647     instructions().append(dst->index());
2648     instructions().append(value->index());
2649     instructions().append(constructor->index());
2650     instructions().append(hasInstanceValue->index());
2651     return dst;
2652 }
2653
2654 RegisterID* BytecodeGenerator::emitIn(RegisterID* dst, RegisterID* property, RegisterID* base)
2655 {
2656     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2657     emitOpcode(op_in);
2658     instructions().append(dst->index());
2659     instructions().append(base->index());
2660     instructions().append(property->index());
2661     instructions().append(arrayProfile);
2662     return dst;
2663 }
2664
2665 RegisterID* BytecodeGenerator::emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2666 {
2667     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties are not supported with tryGetById.");
2668
2669     UnlinkedValueProfile profile = emitProfiledOpcode(op_try_get_by_id);
2670     instructions().append(kill(dst));
2671     instructions().append(base->index());
2672     instructions().append(addConstant(property));
2673     instructions().append(profile);
2674     return dst;
2675 }
2676
2677 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2678 {
2679     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2680
2681     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2682
2683     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2684     instructions().append(kill(dst));
2685     instructions().append(base->index());
2686     instructions().append(addConstant(property));
2687     instructions().append(0);
2688     instructions().append(0);
2689     instructions().append(0);
2690     instructions().append(Options::prototypeHitCountForLLIntCaching());
2691     instructions().append(profile);
2692     return dst;
2693 }
2694
2695 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
2696 {
2697     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2698
2699     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id_with_this);
2700     instructions().append(kill(dst));
2701     instructions().append(base->index());
2702     instructions().append(thisVal->index());
2703     instructions().append(addConstant(property));
2704     instructions().append(profile);
2705     return dst;
2706 }
2707
2708 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2709 {
2710     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2711
2712     unsigned propertyIndex = addConstant(property);
2713
2714     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2715
2716     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2717
2718     emitOpcode(op_put_by_id);
2719     instructions().append(base->index());
2720     instructions().append(propertyIndex);
2721     instructions().append(value->index());
2722     instructions().append(0); // old structure
2723     instructions().append(0); // offset
2724     instructions().append(0); // new structure
2725     instructions().append(0); // structure chain
2726     instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2727
2728     return value;
2729 }
2730
2731 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value)
2732 {
2733     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2734
2735     unsigned propertyIndex = addConstant(property);
2736
2737     emitOpcode(op_put_by_id_with_this);
2738     instructions().append(base->index());
2739     instructions().append(thisValue->index());
2740     instructions().append(propertyIndex);
2741     instructions().append(value->index());
2742
2743     return value;
2744 }
2745
2746 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2747 {
2748     ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val(direct).");
2749
2750     unsigned propertyIndex = addConstant(property);
2751
2752     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2753
2754     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2755     
2756     emitOpcode(op_put_by_id);
2757     instructions().append(base->index());
2758     instructions().append(propertyIndex);
2759     instructions().append(value->index());
2760     instructions().append(0); // old structure
2761     instructions().append(0); // offset
2762     instructions().append(0); // new structure
2763     instructions().append(0); // structure chain (unused if direct)
2764     instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2765     return value;
2766 }
2767
2768 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2769 {
2770     unsigned propertyIndex = addConstant(property);
2771     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2772
2773     emitOpcode(op_put_getter_by_id);
2774     instructions().append(base->index());
2775     instructions().append(propertyIndex);
2776     instructions().append(attributes);
2777     instructions().append(getter->index());
2778 }
2779
2780 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2781 {
2782     unsigned propertyIndex = addConstant(property);
2783     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2784
2785     emitOpcode(op_put_setter_by_id);
2786     instructions().append(base->index());
2787     instructions().append(propertyIndex);
2788     instructions().append(attributes);
2789     instructions().append(setter->index());
2790 }
2791
2792 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2793 {
2794     unsigned propertyIndex = addConstant(property);
2795
2796     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2797
2798     emitOpcode(op_put_getter_setter_by_id);
2799     instructions().append(base->index());
2800     instructions().append(propertyIndex);
2801     instructions().append(attributes);
2802     instructions().append(getter->index());
2803     instructions().append(setter->index());
2804 }
2805
2806 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2807 {
2808     emitOpcode(op_put_getter_by_val);
2809     instructions().append(base->index());
2810     instructions().append(property->index());
2811     instructions().append(attributes);
2812     instructions().append(getter->index());
2813 }
2814
2815 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2816 {
2817     emitOpcode(op_put_setter_by_val);
2818     instructions().append(base->index());
2819     instructions().append(property->index());
2820     instructions().append(attributes);
2821     instructions().append(setter->index());
2822 }
2823
2824 void BytecodeGenerator::emitPutGeneratorFields(RegisterID* nextFunction)
2825 {
2826     // FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
2827     // But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
2828     // https://bugs.webkit.org/show_bug.cgi?id=151545
2829
2830     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2831
2832     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2833
2834     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(0)), PropertyNode::KnownDirect);
2835
2836     emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2837 }
2838
2839 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2840 {
2841     emitOpcode(op_del_by_id);
2842     instructions().append(dst->index());
2843     instructions().append(base->index());
2844     instructions().append(addConstant(property));
2845     return dst;
2846 }
2847
2848 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2849 {
2850     for (size_t i = m_forInContextStack.size(); i > 0; i--) {
2851         ForInContext& context = m_forInContextStack[i - 1].get();
2852         if (context.local() != property)
2853             continue;
2854
2855         if (!context.isValid())
2856             break;
2857
2858         if (context.type() == ForInContext::IndexedForInContextType) {
2859             property = static_cast<IndexedForInContext&>(context).index();
2860             break;
2861         }
2862
2863         ASSERT(context.type() == ForInContext::StructureForInContextType);
2864         StructureForInContext& structureContext = static_cast<StructureForInContext&>(context);
2865         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2866         instructions().append(kill(dst));
2867         instructions().append(base->index());
2868         instructions().append(property->index());
2869         instructions().append(structureContext.index()->index());
2870         instructions().append(structureContext.enumerator()->index());
2871         instructions().append(profile);
2872         return dst;
2873     }
2874
2875     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2876     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2877     instructions().append(kill(dst));
2878     instructions().append(base->index());
2879     instructions().append(property->index());
2880     instructions().append(arrayProfile);
2881     instructions().append(profile);
2882     return dst;
2883 }
2884
2885 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
2886 {
2887     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val_with_this);
2888     instructions().append(kill(dst));
2889     instructions().append(base->index());
2890     instructions().append(thisValue->index());
2891     instructions().append(property->index());
2892     instructions().append(profile);
2893     return dst;
2894 }
2895
2896 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2897 {
2898     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2899     emitOpcode(op_put_by_val);
2900     instructions().append(base->index());
2901     instructions().append(property->index());
2902     instructions().append(value->index());
2903     instructions().append(arrayProfile);
2904
2905     return value;
2906 }
2907
2908 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value)
2909 {
2910     emitOpcode(op_put_by_val_with_this);
2911     instructions().append(base->index());
2912     instructions().append(thisValue->index());
2913     instructions().append(property->index());
2914     instructions().append(value->index());
2915
2916     return value;
2917 }
2918
2919 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2920 {
2921     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2922     emitOpcode(op_put_by_val_direct);
2923     instructions().append(base->index());
2924     instructions().append(property->index());
2925     instructions().append(value->index());
2926     instructions().append(arrayProfile);
2927     return value;
2928 }
2929
2930 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2931 {
2932     emitOpcode(op_del_by_val);
2933     instructions().append(dst->index());
2934     instructions().append(base->index());
2935     instructions().append(property->index());
2936     return dst;
2937 }
2938
2939 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
2940 {
2941     emitOpcode(op_put_by_index);
2942     instructions().append(base->index());
2943     instructions().append(index);
2944     instructions().append(value->index());
2945     return value;
2946 }
2947
2948 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
2949 {
2950     emitOpcode(op_assert);
2951     instructions().append(condition->index());
2952     instructions().append(line);
2953     return condition;
2954 }
2955
2956 RegisterID* BytecodeGenerator::emitGetArgument(RegisterID* dst, int32_t index)
2957 {
2958     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument);
2959     instructions().append(dst->index());
2960     instructions().append(index + 1); // Including |this|.
2961     instructions().append(profile);
2962     return dst;
2963 }
2964
2965 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
2966 {
2967     size_t begin = instructions().size();
2968     m_staticPropertyAnalyzer.createThis(dst->index(), begin + 3);
2969
2970     m_codeBlock->addPropertyAccessInstruction(instructions().size());
2971     emitOpcode(op_create_this); 
2972     instructions().append(dst->index());
2973     instructions().append(dst->index());
2974     instructions().append(0);
2975     instructions().append(0);
2976     return dst;
2977 }
2978
2979 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
2980 {
2981     emitOpcode(op_check_tdz);
2982     instructions().append(target->index());
2983 }
2984
2985 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
2986 {
2987     for (unsigned i = m_TDZStack.size(); i--;) {
2988         auto iter = m_TDZStack[i].find(variable.ident().impl());
2989         if (iter == m_TDZStack[i].end())
2990             continue;
2991         return iter->value != TDZNecessityLevel::NotNeeded;
2992     }
2993
2994     return false;
2995 }
2996
2997 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
2998 {
2999     if (needsTDZCheck(variable)) {
3000         if (target)
3001             emitTDZCheck(target);
3002         else {
3003             RELEASE_ASSERT(!variable.isLocal() && scope);
3004             RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
3005             emitTDZCheck(result.get());
3006         }
3007     }
3008 }
3009
3010 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
3011 {
3012     RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
3013     for (unsigned i = m_TDZStack.size(); i--;) {
3014         auto iter = m_TDZStack[i].find(identifier);
3015         if (iter != m_TDZStack[i].end()) {
3016             if (iter->value == TDZNecessityLevel::Optimize)
3017                 iter->value = TDZNecessityLevel::NotNeeded;
3018             break;
3019         }
3020     }
3021 }
3022
3023 void BytecodeGenerator::pushTDZVariables(const VariableEnvironment& environment, TDZCheckOptimization optimization, TDZRequirement requirement)
3024 {
3025     if (!environment.size())
3026         return;
3027     
3028     TDZNecessityLevel level;
3029     if (requirement == TDZRequirement::UnderTDZ) {
3030         if (optimization == TDZCheckOptimization::Optimize)
3031             level = TDZNecessityLevel::Optimize;
3032         else
3033             level = TDZNecessityLevel::DoNotOptimize;
3034     } else
3035         level = TDZNecessityLevel::NotNeeded;
3036     
3037     TDZMap map;
3038     for (const auto& entry : environment)
3039         map.add(entry.key, entry.value.isFunction() ? TDZNecessityLevel::NotNeeded : level);
3040
3041     m_TDZStack.append(WTFMove(map));
3042 }
3043
3044 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
3045 {
3046     // We keep track of variablesThatDontNeedTDZ in this algorithm to prevent
3047     // reporting that "x" is under TDZ if this function is called at "...".
3048     //
3049     //     {
3050     //         {
3051     //             let x;
3052     //             ...
3053     //         }
3054     //         let x;
3055     //     }
3056     //
3057     SmallPtrSet<UniquedStringImpl*, 16> variablesThatDontNeedTDZ;
3058     for (unsigned i = m_TDZStack.size(); i--; ) {
3059         auto& map = m_TDZStack[i];
3060         for (auto& entry : map)  {
3061             if (entry.value != TDZNecessityLevel::NotNeeded) {
3062                 if (!variablesThatDontNeedTDZ.contains(entry.key.get()))
3063                     result.add(entry.key.get());
3064             } else
3065                 variablesThatDontNeedTDZ.add(entry.key.get());
3066         }
3067     }
3068 }
3069
3070 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
3071 {
3072     size_t begin = instructions().size();
3073     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
3074
3075     emitOpcode(op_new_object);
3076     instructions().append(dst->index());
3077     instructions().append(0);
3078     instructions().append(newObjectAllocationProfile());
3079     return dst;
3080 }
3081
3082 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
3083 {
3084     return m_codeBlock->addConstantBuffer(length);
3085 }
3086
3087 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
3088 {
3089     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
3090     if (!stringInMap) {
3091         stringInMap = jsString(vm(), identifier.string());
3092         addConstantValue(stringInMap);
3093     }
3094     return stringInMap;
3095 }
3096
3097 RegisterID* BytecodeGenerator::addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&& templateRegistryKey)
3098 {
3099     return m_templateRegistryKeyMap.ensure(templateRegistryKey.copyRef(), [&] {
3100         auto* result = JSTemplateRegistryKey::create(*vm(), WTFMove(templateRegistryKey));
3101         unsigned index = m_nextConstantOffset;
3102         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
3103         ++m_nextConstantOffset;
3104         m_codeBlock->addConstant(result);
3105         return &m_constantPoolRegisters[index];
3106     }).iterator->value;
3107 }
3108
3109 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
3110 {
3111 #if !ASSERT_DISABLED
3112     unsigned checkLength = 0;
3113 #endif
3114     bool hadVariableExpression = false;
3115     if (length) {
3116         for (ElementNode* n = elements; n; n = n->next()) {
3117             if (!n->value()->isConstant()) {
3118                 hadVariableExpression = true;
3119                 break;
3120             }
3121             if (n->elision())
3122                 break;
3123 #if !ASSERT_DISABLED
3124             checkLength++;
3125 #endif
3126         }
3127         if (!hadVariableExpression) {
3128             ASSERT(length == checkLength);
3129             unsigned constantBufferIndex = addConstantBuffer(length);
3130             JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
3131             unsigned index = 0;
3132             for (ElementNode* n = elements; index < length; n = n->next()) {
3133                 ASSERT(n->value()->isConstant());
3134                 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
3135             }
3136             emitOpcode(op_new_array_buffer);
3137             instructions().append(dst->index());
3138             instructions().append(constantBufferIndex);
3139             instructions().append(length);
3140             instructions().append(newArrayAllocationProfile());
3141             return dst;
3142         }
3143     }
3144
3145     Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
3146     for (ElementNode* n = elements; n; n = n->next()) {
3147         if (!length)
3148             break;
3149         length--;
3150         ASSERT(!n->value()->isSpreadExpression());
3151         argv.append(newTemporary());
3152         // op_new_array requires the initial values to be a sequential range of registers
3153         ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
3154         emitNode(argv.last().get(), n->value());
3155     }
3156     ASSERT(!length);
3157     emitOpcode(op_new_array);
3158     instructions().append(dst->index());
3159     instructions().append(argv.size() ? argv[0]->index() : 0); // argv
3160     instructions().append(argv.size()); // argc
3161     instructions().append(newArrayAllocationProfile());
3162     return dst;
3163 }
3164
3165 RegisterID* BytecodeGenerator::emitNewArrayWithSpread(RegisterID* dst, ElementNode* elements)
3166 {
3167     BitVector bitVector;
3168     Vector<RefPtr<RegisterID>, 16> argv;
3169     for (ElementNode* node = elements; node; node = node->next()) {
3170         bitVector.set(argv.size(), node->value()->isSpreadExpression());
3171
3172         argv.append(newTemporary());
3173         // op_new_array_with_spread requires the initial values to be a sequential range of registers.
3174         RELEASE_ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
3175     }
3176
3177     RELEASE_ASSERT(argv.size());
3178
3179     {
3180         unsigned i = 0;
3181         for (ElementNode* node = elements; node; node = node->next()) {
3182             if (node->value()->isSpreadExpression()) {
3183                 ExpressionNode* expression = static_cast<SpreadExpressionNode*>(node->value())->expression();
3184                 RefPtr<RegisterID> tmp = newTemporary();
3185                 emitNode(tmp.get(), expression);
3186
3187                 emitOpcode(op_spread);
3188                 instructions().append(argv[i].get()->index());
3189                 instructions().append(tmp.get()->index());
3190             } else {
3191                 ExpressionNode* expression = node->value();
3192                 emitNode(argv[i].get(), expression);
3193             }
3194             i++;
3195         }
3196     }
3197
3198     unsigned bitVectorIndex = m_codeBlock->addBitVector(WTFMove(bitVector));
3199     emitOpcode(op_new_array_with_spread);
3200     instructions().append(dst->index());
3201     instructions().append(argv[0]->index()); // argv
3202     instructions().append(argv.size()); // argc
3203     instructions().append(bitVectorIndex);
3204
3205     return dst;
3206 }
3207
3208 RegisterID* BytecodeGenerator::emitNewArrayWithSize(RegisterID* dst, RegisterID* length)
3209 {
3210     emitOpcode(op_new_array_with_size);
3211     instructions().append(dst->index());
3212     instructions().append(length->index());
3213     instructions().append(newArrayAllocationProfile());
3214
3215     return dst;
3216 }
3217
3218 RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
3219 {
3220     emitOpcode(op_new_regexp);
3221     instructions().append(dst->index());
3222     instructions().append(addRegExp(regExp));
3223     return dst;
3224 }
3225
3226 void BytecodeGenerator::emitNewFunctionExpressionCommon(RegisterID* dst, FunctionMetadataNode* function)
3227 {
3228     unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
3229
3230     OpcodeID opcodeID = op_new_func_exp;
3231     switch (function->parseMode()) {
3232     case SourceParseMode::GeneratorWrapperFunctionMode:
3233     case SourceParseMode::GeneratorWrapperMethodMode:
3234         opcodeID = op_new_generator_func_exp;
3235         break;
3236     case SourceParseMode::AsyncFunctionMode:
3237     case SourceParseMode::AsyncMethodMode:
3238     case SourceParseMode::AsyncArrowFunctionMode:
3239         opcodeID = op_new_async_func_exp;
3240         break;
3241     default:
3242         break;
3243     }
3244     
3245     emitOpcode(opcodeID);
3246     instructions().append(dst->index());
3247     instructions().append(scopeRegister()->index());
3248     instructions().append(index);
3249 }
3250
3251 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func)
3252 {
3253     emitNewFunctionExpressionCommon(dst, func->metadata());
3254     return dst;
3255 }
3256
3257 RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
3258 {
3259     ASSERT(SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(func->metadata()->parseMode()));
3260     emitNewFunctionExpressionCommon(dst, func->metadata());
3261     return dst;
3262 }
3263
3264 RegisterID* BytecodeGenerator::emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode* func)
3265 {
3266     ASSERT(isMethodParseMode(func->metadata()->parseMode()));
3267     emitNewFunctionExpressionCommon(dst, func->metadata());
3268     return dst;
3269 }
3270
3271 RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name,
3272     const Identifier& ecmaName, const SourceCode& classSource)
3273 {
3274     UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name);
3275     executable->setInvalidTypeProfilingOffsets();
3276     executable->setEcmaName(ecmaName);
3277     executable->setClassSource(classSource);
3278
3279     unsigned index = m_codeBlock->addFunctionExpr(executable);
3280
3281     emitOpcode(op_new_func_exp);
3282     instructions().append(dst->index());
3283     instructions().append(scopeRegister()->index());
3284     instructions().append(index);
3285     return dst;
3286 }
3287
3288 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionMetadataNode* function)
3289 {
3290     unsigned index = m_codeBlock->addFunctionDecl(makeFunction(function));
3291     if (isGeneratorWrapperParseMode(function->parseMode()))
3292         emitOpcode(op_new_generator_func);
3293     else if (function->parseMode() == SourceParseMode::AsyncFunctionMode)
3294         emitOpcode(op_new_async_func);
3295     else
3296         emitOpcode(op_new_func);
3297     instructions().append(dst->index());
3298     instructions().append(scopeRegister()->index());
3299     instructions().append(index);
3300     return dst;
3301 }
3302
3303 void BytecodeGenerator::emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name)
3304 {
3305     if (valueNode->isBaseFuncExprNode()) {
3306         FunctionMetadataNode* metadata = static_cast<BaseFuncExprNode*>(valueNode)->metadata();
3307         if (!metadata->ecmaName().isNull())
3308             return;
3309     } else if (valueNode->isClassExprNode()) {
3310         ClassExprNode* classExprNode = static_cast<ClassExprNode*>(valueNode);
3311         if (!classExprNode->ecmaName().isNull())
3312             return;
3313         if (classExprNode->hasStaticProperty(m_vm->propertyNames->name))
3314             return;
3315     } else
3316         return;
3317
3318     // FIXME: We should use an op_call to an internal function here instead.
3319     // https://bugs.webkit.org/show_bug.cgi?id=155547
3320     emitOpcode(op_set_function_name);
3321     instructions().append(value->index());
3322     instructions().append(name->index());
3323 }
3324
3325 RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3326 {
3327     return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3328 }
3329
3330 RegisterID* BytecodeGenerator::emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3331 {
3332     return emitCall(m_inTailPosition ? op_tail_call : op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3333 }
3334
3335 RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3336 {
3337     return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd, debuggableCall);
3338 }
3339
3340 ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
3341 {
3342     if (identifier == propertyNames().Object || identifier == propertyNames().builtinNames().ObjectPrivateName())
3343         return ExpectObjectConstructor;
3344     if (identifier == propertyNames().Array || identifier == propertyNames().builtinNames().ArrayPrivateName())
3345         return ExpectArrayConstructor;
3346     return NoExpectedFunction;
3347 }
3348
3349 ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label& done)
3350 {
3351     Ref<Label> realCall = newLabel();
3352     switch (expectedFunction) {
3353     case ExpectObjectConstructor: {
3354         // If the number of arguments is non-zero, then we can't do anything interesting.
3355         if (callArguments.argumentCountIncludingThis() >= 2)
3356             return NoExpectedFunction;
3357         
3358         size_t begin = instructions().size();
3359         emitOpcode(op_jneq_ptr);
3360         instructions().append(func->index());
3361         instructions().append(Special::ObjectConstructor);
3362         instructions().append(realCall->bind(begin, instructions().size()));
3363         instructions().append(0);
3364         
3365         if (dst != ignoredResult())
3366             emitNewObject(dst);
3367         break;
3368     }
3369         
3370     case ExpectArrayConstructor: {
3371         // If you're doing anything other than "new Array()" or "new Array(foo)" then we
3372         // don't do inline it, for now. The only reason is that call arguments are in
3373         // the opposite order of what op_new_array expects, so we'd either need to change
3374         // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
3375         // things sounds like it's worth it.
3376         if (callArguments.argumentCountIncludingThis() > 2)
3377             return NoExpectedFunction;
3378         
3379         size_t begin = instructions().size();
3380         emitOpcode(op_jneq_ptr);
3381         instructions().append(func->index());
3382         instructions().append(Special::ArrayConstructor);
3383         instructions().append(realCall->bind(begin, instructions().size()));
3384         instructions().append(0);
3385         
3386         if (dst != ignoredResult()) {
3387             if (callArguments.argumentCountIncludingThis() == 2)
3388                 emitNewArrayWithSize(dst, callArguments.argumentRegister(0));
3389             else {
3390                 ASSERT(callArguments.argumentCountIncludingThis() == 1);
3391                 emitOpcode(op_new_array);
3392                 instructions().append(dst->index());
3393                 instructions().append(0);
3394                 instructions().append(0);
3395                 instructions().append(newArrayAllocationProfile());
3396             }
3397         }
3398         break;
3399     }
3400         
3401     default:
3402         ASSERT(expectedFunction == NoExpectedFunction);
3403         return NoExpectedFunction;
3404     }
3405     
3406     size_t begin = instructions().size();
3407     emitOpcode(op_jmp);
3408     instructions().append(done.bind(begin, instructions().size()));
3409     emitLabel(realCall.get());
3410     
3411     return expectedFunction;
3412 }
3413
3414 RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3415 {
3416     ASSERT(opcodeID == op_call || opcodeID == op_call_eval || opcodeID == op_tail_call);
3417     ASSERT(func->refCount());
3418     
3419     // Generate code for arguments.
3420     unsigned argument = 0;
3421     if (callArguments.argumentsNode()) {
3422         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
3423         if (n && n->m_expr->isSpreadExpression()) {
3424             RELEASE_ASSERT(!n->m_next);
3425             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
3426             if (expression->isArrayLiteral()) {
3427                 auto* elements = static_cast<ArrayNode*>(expression)->elements();
3428                 if (elements && !elements->next() && elements->value()->isSpreadExpression()) {
3429                     ExpressionNode* expression = static_cast<SpreadExpressionNode*>(elements->value())->expression();
3430                     RefPtr<RegisterID> argumentRegister = emitNode(callArguments.argumentRegister(0), expression);
3431                     emitOpcode(op_spread);
3432                     instructions().append(argumentRegister.get()->index());
3433                     instructions().append(argumentRegister.get()->index());
3434
3435                     RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
3436                     return emitCallVarargs(opcodeID == op_tail_call ? op_tail_call_varargs : op_call_varargs, dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, divot, divotStart, divotEnd, debuggableCall);
3437                 }
3438             }
3439             RefPtr<RegisterID> argumentRegister;
3440             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
3441             RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
3442             return emitCallVarargs(opcodeID == op_tail_call ? op_tail_call_varargs : op_call_varargs, dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, divot, divotStart, divotEnd, debuggableCall);
3443         }
3444         for (; n; n = n->m_next)
3445             emitNode(callArguments.argumentRegister(argument++), n);
3446     }
3447     
3448     // Reserve space for call frame.
3449     Vector<RefPtr<RegisterID>, CallFrame::headerSizeInRegisters, UnsafeVectorOverflow> callFrame;
3450     for (int i = 0; i < CallFrame::headerSizeInRegisters; ++i)
3451         callFrame.append(newTemporary());
3452
3453     if (m_shouldEmitDebugHooks && debuggableCall == DebuggableCall::Yes)
3454         emitDebugHook(WillExecuteExpression, divotStart);
3455
3456     emitExpressionInfo(divot, divotStart, divotEnd);
3457
3458     Ref<Label> done = newLabel();
3459     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
3460     
3461     if (opcodeID == op_tail_call)
3462         emitLogShadowChickenTailIfNecessary();
3463     
3464     // Emit call.
3465     UnlinkedArrayProfile arrayProfile = newArrayProfile();
3466     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
3467     ASSERT(dst);
3468     ASSERT(dst != ignoredResult());
3469     instructions().append(dst->index());
3470     instructions().append(func->index());
3471     instructions().append(callArguments.argumentCountIncludingThis());
3472     instructions().append(callArguments.stackOffset());
3473     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
3474     instructions().append(0);
3475     instructions().append(arrayProfile);
3476     instructions().append(profile);
3477     
3478     if (expectedFunction != NoExpectedFunction)
3479         emitLabel(done.get());
3480
3481     return dst;
3482 }
3483
3484 RegisterID* BytecodeGenerator::emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3485 {
3486     return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3487 }
3488
3489 RegisterID* BytecodeGenerator::emitCallVarargsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3490 {
3491     return emitCallVarargs(m_inTailPosition ? op_tail_call_varargs : op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3492 }
3493
3494 RegisterID* BytecodeGenerator::emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3495 {
3496     return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3497 }
3498
3499 RegisterID* BytecodeGenerator::emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3500 {
3501     ASSERT(m_inTailPosition);
3502     return emitCallVarargs(op_tail_call_forward_arguments, dst, func, thisRegister, nullptr, firstFreeRegister, firstVarArgOffset, divot, divotStart, divotEnd, debuggableCall);
3503 }
3504     
3505 RegisterID* BytecodeGenerator::emitCallVarargs(OpcodeID opcode, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall debuggableCall)
3506 {
3507     if (m_shouldEmitDebugHooks && debuggableCall == DebuggableCall::Yes)
3508         emitDebugHook(WillExecuteExpression, divotStart);
3509
3510     emitExpressionInfo(divot, divotStart, divotEnd);
3511
3512     if (opcode == op_tail_call_varargs)
3513         emitLogShadowChickenTailIfNecessary();
3514     
3515     // Emit call.
3516     UnlinkedArrayProfile arrayProfile = newArrayProfile();
3517     UnlinkedValueProfile profile = emitProfiledOpcode(opcode);
3518     ASSERT(dst != ignoredResult());
3519     instructions().append(dst->index());
3520     instructions().append(func->index());
3521     instructions().append(thisRegister ? thisRegister->index() : 0);
3522     instructions().append(arguments ? arguments->index() : 0);
3523     instructions().append(firstFreeRegister->index());
3524     instructions().append(firstVarArgOffset);
3525     instructions().append(arrayProfile);
3526     instructions().append(profile);
3527     return dst;
3528 }
3529
3530 void BytecodeGenerator::emitLogShadowChickenPrologueIfNecessary()
3531 {
3532     if (!m_shouldEmitDebugHooks && !Options::alwaysUseShadowChicken())
3533         return;
3534     emitOpcode(op_log_shadow_chicken_prologue);
3535     instructions().append(scopeRegister()->index());
3536 }
3537
3538 void BytecodeGenerator::emitLogShadowChickenTailIfNecessary()
3539 {
3540     if (!m_shouldEmitDebugHooks && !Options::alwaysUseShadowChicken())
3541         return;
3542     emitOpcode(op_log_shadow_chicken_tail);
3543     instructions().append(thisRegister()->index());
3544     instructions().append(scopeRegister()->index());
3545 }
3546
3547 void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
3548     RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position)
3549 {
3550     DefinePropertyAttributes attributes;
3551     if (options & PropertyConfigurable)
3552         attributes.setConfigurable(true);
3553
3554     if (options & PropertyWritable)
3555         attributes.setWritable(true);
3556     else if (valueRegister)
3557         attributes.setWritable(false);
3558
3559     if (options & PropertyEnumerable)
3560         attributes.setEnumerable(true);
3561
3562     if (valueRegister)
3563         attributes.setValue();
3564     if (getterRegister)
3565         attributes.setGet();
3566     if (setterRegister)
3567         attributes.setSet();
3568
3569     ASSERT(!valueRegister || (!getterRegister && !setterRegister));
3570
3571     emitExpressionInfo(position, position, position);
3572
3573     if (attributes.hasGet() || attributes.hasSet()) {
3574         RefPtr<RegisterID> throwTypeErrorFunction;
3575         if (!attributes.hasGet() || !attributes.hasSet())
3576             throwTypeErrorFunction = emitMoveLinkTimeConstant(nullptr, LinkTimeConstant::ThrowTypeErrorFunction);
3577
3578         RefPtr<RegisterID> getter;
3579         if (attributes.hasGet())
3580             getter = getterRegister;
3581         else
3582             getter = throwTypeErrorFunction;
3583
3584         RefPtr<RegisterID> setter;
3585         if (attributes.hasSet())
3586             setter = setterRegister;
3587         else
3588             setter = throwTypeErrorFunction;
3589
3590         emitOpcode(op_define_accessor_property);
3591         instructions().append(newObj->index());
3592         instructions().append(propertyNameRegister->index());
3593         instructions().append(getter->index());
3594         instructions().append(setter->index());
3595         instructions().append(emitLoad(nullptr, jsNumber(attributes.rawRepresentation()))->index());
3596     } else {
3597         emitOpcode(op_define_data_property);
3598         instructions().append(newObj->index());
3599         instructions().append(propertyNameRegister->index());
3600         instructions().append(valueRegister->index());
3601         instructions().append(emitLoad(nullptr, jsNumber(attributes.rawRepresentation()))->index());
3602     }
3603 }
3604
3605 RegisterID* BytecodeGenerator::emitReturn(RegisterID* src, ReturnFrom from)
3606 {
3607     if (isConstructor()) {
3608         bool mightBeDerived = constructorKind() == ConstructorKind::Extends;
3609         bool srcIsThis = src->index() == m_thisRegister.index();
3610
3611         if (mightBeDerived && (srcIsThis || from == ReturnFrom::Finally))
3612             emitTDZCheck(src);
3613
3614         if (!srcIsThis || from == ReturnFrom::Finally) {
3615             Ref<Label> isObjectLabel = newLabel();
3616             emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get());
3617
3618             if (mightBeDerived) {
3619                 ASSERT(m_isDerivedConstuctor);
3620                 Ref<Label> returnThis = newLabel();
3621                 emitJumpIfFalse(m_isDerivedConstuctor, returnThis.get());
3622                 // Else, we're a derived constructor here.
3623                 Ref<Label> isUndefinedLabel = newLabel();
3624                 emitJumpIfTrue(emitIsUndefined(newTemporary(), src), isUndefinedLabel.get());
3625                 emitThrowTypeError("Cannot return a non-object type in the constructor of a derived class.");
3626                 emitLabel(isUndefinedLabel.get());
3627                 emitTDZCheck(&m_thisRegister);
3628                 emitLabel(returnThis.get());
3629             }
3630             emitUnaryNoDstOp(op_ret, &m_thisRegister);
3631             emitLabel(isObjectLabel.get());
3632         }
3633     }
3634
3635     return emitUnaryNoDstOp(op_ret, src);
3636 }
3637
3638 RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
3639 {
3640     emitOpcode(opcodeID);
3641     instructions().append(src->index());
3642     return src;
3643 }
3644
3645 RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
3646 {
3647     ASSERT(func->refCount());
3648
3649     // Generate code for arguments.
3650     unsigned argument = 0;
3651     if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
3652