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