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