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