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