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