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