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