ca487999341822ee2844f5bde837d1d5107b506c
[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     ASSERT(!parseIndex(property));
1535     unsigned propertyIndex = addConstant(property);
1536
1537     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1538
1539     m_codeBlock->addPropertyAccessInstruction(instructions().size());
1540     
1541     emitOpcode(op_put_by_id);
1542     instructions().append(base->index());
1543     instructions().append(propertyIndex);
1544     instructions().append(value->index());
1545     instructions().append(0);
1546     instructions().append(0);
1547     instructions().append(0);
1548     instructions().append(0);
1549     instructions().append(putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto);
1550     return value;
1551 }
1552
1553 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, RegisterID* getter)
1554 {
1555     unsigned propertyIndex = addConstant(property);
1556     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1557
1558     emitOpcode(op_put_getter_by_id);
1559     instructions().append(base->index());
1560     instructions().append(propertyIndex);
1561     instructions().append(getter->index());
1562 }
1563
1564 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, RegisterID* setter)
1565 {
1566     unsigned propertyIndex = addConstant(property);
1567     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1568
1569     emitOpcode(op_put_setter_by_id);
1570     instructions().append(base->index());
1571     instructions().append(propertyIndex);
1572     instructions().append(setter->index());
1573 }
1574
1575 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, RegisterID* getter, RegisterID* setter)
1576 {
1577     unsigned propertyIndex = addConstant(property);
1578
1579     m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
1580
1581     emitOpcode(op_put_getter_setter);
1582     instructions().append(base->index());
1583     instructions().append(propertyIndex);
1584     instructions().append(getter->index());
1585     instructions().append(setter->index());
1586 }
1587
1588 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
1589 {
1590     emitOpcode(op_del_by_id);
1591     instructions().append(dst->index());
1592     instructions().append(base->index());
1593     instructions().append(addConstant(property));
1594     return dst;
1595 }
1596
1597 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
1598 {
1599     for (size_t i = m_forInContextStack.size(); i > 0; i--) {
1600         ForInContext* context = m_forInContextStack[i - 1].get();
1601         if (context->local() != property)
1602             continue;
1603
1604         if (!context->isValid())
1605             break;
1606
1607         if (context->type() == ForInContext::IndexedForInContextType) {
1608             property = static_cast<IndexedForInContext*>(context)->index();
1609             break;
1610         }
1611
1612         ASSERT(context->type() == ForInContext::StructureForInContextType);
1613         StructureForInContext* structureContext = static_cast<StructureForInContext*>(context);
1614         UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
1615         instructions().append(kill(dst));
1616         instructions().append(base->index());
1617         instructions().append(property->index());
1618         instructions().append(structureContext->index()->index());
1619         instructions().append(structureContext->enumerator()->index());
1620         instructions().append(profile);
1621         return dst;
1622     }
1623
1624     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1625     UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
1626     instructions().append(kill(dst));
1627     instructions().append(base->index());
1628     instructions().append(property->index());
1629     instructions().append(arrayProfile);
1630     instructions().append(profile);
1631     return dst;
1632 }
1633
1634 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
1635 {
1636     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1637     emitOpcode(op_put_by_val);
1638     instructions().append(base->index());
1639     instructions().append(property->index());
1640     instructions().append(value->index());
1641     instructions().append(arrayProfile);
1642
1643     return value;
1644 }
1645
1646 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
1647 {
1648     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1649     emitOpcode(op_put_by_val_direct);
1650     instructions().append(base->index());
1651     instructions().append(property->index());
1652     instructions().append(value->index());
1653     instructions().append(arrayProfile);
1654     return value;
1655 }
1656
1657 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
1658 {
1659     emitOpcode(op_del_by_val);
1660     instructions().append(dst->index());
1661     instructions().append(base->index());
1662     instructions().append(property->index());
1663     return dst;
1664 }
1665
1666 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
1667 {
1668     emitOpcode(op_put_by_index);
1669     instructions().append(base->index());
1670     instructions().append(index);
1671     instructions().append(value->index());
1672     return value;
1673 }
1674
1675 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
1676 {
1677     size_t begin = instructions().size();
1678     m_staticPropertyAnalyzer.createThis(m_thisRegister.index(), begin + 3);
1679
1680     m_codeBlock->addPropertyAccessInstruction(instructions().size());
1681     emitOpcode(op_create_this); 
1682     instructions().append(m_thisRegister.index()); 
1683     instructions().append(m_thisRegister.index()); 
1684     instructions().append(0);
1685     instructions().append(0);
1686     return dst;
1687 }
1688
1689 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
1690 {
1691     emitOpcode(op_check_tdz);
1692     instructions().append(target->index());
1693 }
1694
1695 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
1696 {
1697     size_t begin = instructions().size();
1698     m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
1699
1700     emitOpcode(op_new_object);
1701     instructions().append(dst->index());
1702     instructions().append(0);
1703     instructions().append(newObjectAllocationProfile());
1704     return dst;
1705 }
1706
1707 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
1708 {
1709     return m_codeBlock->addConstantBuffer(length);
1710 }
1711
1712 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
1713 {
1714     JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1715     if (!stringInMap) {
1716         stringInMap = jsString(vm(), identifier.string());
1717         addConstantValue(stringInMap);
1718     }
1719     return stringInMap;
1720 }
1721
1722 JSTemplateRegistryKey* BytecodeGenerator::addTemplateRegistryKeyConstant(const TemplateRegistryKey& templateRegistryKey)
1723 {
1724     JSTemplateRegistryKey*& templateRegistryKeyInMap = m_templateRegistryKeyMap.add(templateRegistryKey, nullptr).iterator->value;
1725     if (!templateRegistryKeyInMap) {
1726         templateRegistryKeyInMap = JSTemplateRegistryKey::create(*vm(), templateRegistryKey);
1727         addConstantValue(templateRegistryKeyInMap);
1728     }
1729     return templateRegistryKeyInMap;
1730 }
1731
1732 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
1733 {
1734 #if !ASSERT_DISABLED
1735     unsigned checkLength = 0;
1736 #endif
1737     bool hadVariableExpression = false;
1738     if (length) {
1739         for (ElementNode* n = elements; n; n = n->next()) {
1740             if (!n->value()->isConstant()) {
1741                 hadVariableExpression = true;
1742                 break;
1743             }
1744             if (n->elision())
1745                 break;
1746 #if !ASSERT_DISABLED
1747             checkLength++;
1748 #endif
1749         }
1750         if (!hadVariableExpression) {
1751             ASSERT(length == checkLength);
1752             unsigned constantBufferIndex = addConstantBuffer(length);
1753             JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
1754             unsigned index = 0;
1755             for (ElementNode* n = elements; index < length; n = n->next()) {
1756                 ASSERT(n->value()->isConstant());
1757                 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
1758             }
1759             emitOpcode(op_new_array_buffer);
1760             instructions().append(dst->index());
1761             instructions().append(constantBufferIndex);
1762             instructions().append(length);
1763             instructions().append(newArrayAllocationProfile());
1764             return dst;
1765         }
1766     }
1767
1768     Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
1769     for (ElementNode* n = elements; n; n = n->next()) {
1770         if (!length)
1771             break;
1772         length--;
1773         ASSERT(!n->value()->isSpreadExpression());
1774         argv.append(newTemporary());
1775         // op_new_array requires the initial values to be a sequential range of registers
1776         ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() - 1);
1777         emitNode(argv.last().get(), n->value());
1778     }
1779     ASSERT(!length);
1780     emitOpcode(op_new_array);
1781     instructions().append(dst->index());
1782     instructions().append(argv.size() ? argv[0]->index() : 0); // argv
1783     instructions().append(argv.size()); // argc
1784     instructions().append(newArrayAllocationProfile());
1785     return dst;
1786 }
1787
1788 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionBodyNode* function)
1789 {
1790     return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(function)));
1791 }
1792
1793 RegisterID* BytecodeGenerator::emitNewFunctionInternal(RegisterID* dst, unsigned index)
1794 {
1795     emitOpcode(op_new_func);
1796     instructions().append(dst->index());
1797     instructions().append(scopeRegister()->index());
1798     instructions().append(index);
1799     return dst;
1800 }
1801
1802 RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
1803 {
1804     emitOpcode(op_new_regexp);
1805     instructions().append(dst->index());
1806     instructions().append(addRegExp(regExp));
1807     return dst;
1808 }
1809
1810 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* r0, FuncExprNode* n)
1811 {
1812     FunctionBodyNode* function = n->body();
1813     unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
1814
1815     emitOpcode(op_new_func_exp);
1816     instructions().append(r0->index());
1817     instructions().append(scopeRegister()->index());
1818     instructions().append(index);
1819     return r0;
1820 }
1821
1822 RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, ConstructorKind constructorKind, const Identifier& name)
1823 {
1824     UnlinkedFunctionExecutable* executable = m_vm->builtinExecutables()->createDefaultConstructor(constructorKind, name);
1825
1826     unsigned index = m_codeBlock->addFunctionExpr(executable);
1827
1828     emitOpcode(op_new_func_exp);
1829     instructions().append(dst->index());
1830     instructions().append(scopeRegister()->index());
1831     instructions().append(index);
1832     return dst;
1833 }
1834
1835 RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
1836 {
1837     return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, divotStart, divotEnd);
1838 }
1839
1840 RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
1841 {
1842     return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, divotStart, divotEnd);
1843 }
1844
1845 ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
1846 {
1847     if (identifier == m_vm->propertyNames->Object)
1848         return ExpectObjectConstructor;
1849     if (identifier == m_vm->propertyNames->Array)
1850         return ExpectArrayConstructor;
1851     return NoExpectedFunction;
1852 }
1853
1854 ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done)
1855 {
1856     RefPtr<Label> realCall = newLabel();
1857     switch (expectedFunction) {
1858     case ExpectObjectConstructor: {
1859         // If the number of arguments is non-zero, then we can't do anything interesting.
1860         if (callArguments.argumentCountIncludingThis() >= 2)
1861             return NoExpectedFunction;
1862         
1863         size_t begin = instructions().size();
1864         emitOpcode(op_jneq_ptr);
1865         instructions().append(func->index());
1866         instructions().append(Special::ObjectConstructor);
1867         instructions().append(realCall->bind(begin, instructions().size()));
1868         
1869         if (dst != ignoredResult())
1870             emitNewObject(dst);
1871         break;
1872     }
1873         
1874     case ExpectArrayConstructor: {
1875         // If you're doing anything other than "new Array()" or "new Array(foo)" then we
1876         // don't do inline it, for now. The only reason is that call arguments are in
1877         // the opposite order of what op_new_array expects, so we'd either need to change
1878         // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
1879         // things sounds like it's worth it.
1880         if (callArguments.argumentCountIncludingThis() > 2)
1881             return NoExpectedFunction;
1882         
1883         size_t begin = instructions().size();
1884         emitOpcode(op_jneq_ptr);
1885         instructions().append(func->index());
1886         instructions().append(Special::ArrayConstructor);
1887         instructions().append(realCall->bind(begin, instructions().size()));
1888         
1889         if (dst != ignoredResult()) {
1890             if (callArguments.argumentCountIncludingThis() == 2) {
1891                 emitOpcode(op_new_array_with_size);
1892                 instructions().append(dst->index());
1893                 instructions().append(callArguments.argumentRegister(0)->index());
1894                 instructions().append(newArrayAllocationProfile());
1895             } else {
1896                 ASSERT(callArguments.argumentCountIncludingThis() == 1);
1897                 emitOpcode(op_new_array);
1898                 instructions().append(dst->index());
1899                 instructions().append(0);
1900                 instructions().append(0);
1901                 instructions().append(newArrayAllocationProfile());
1902             }
1903         }
1904         break;
1905     }
1906         
1907     default:
1908         ASSERT(expectedFunction == NoExpectedFunction);
1909         return NoExpectedFunction;
1910     }
1911     
1912     size_t begin = instructions().size();
1913     emitOpcode(op_jmp);
1914     instructions().append(done->bind(begin, instructions().size()));
1915     emitLabel(realCall.get());
1916     
1917     return expectedFunction;
1918 }
1919
1920 RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
1921 {
1922     ASSERT(opcodeID == op_call || opcodeID == op_call_eval);
1923     ASSERT(func->refCount());
1924
1925     if (m_shouldEmitProfileHooks)
1926         emitMove(callArguments.profileHookRegister(), func);
1927
1928     // Generate code for arguments.
1929     unsigned argument = 0;
1930     if (callArguments.argumentsNode()) {
1931         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
1932         if (n && n->m_expr->isSpreadExpression()) {
1933             RELEASE_ASSERT(!n->m_next);
1934             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
1935             RefPtr<RegisterID> argumentRegister;
1936             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
1937             RefPtr<RegisterID> thisRegister = emitMove(newTemporary(), callArguments.thisRegister());
1938             return emitCallVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd);
1939         }
1940         for (; n; n = n->m_next)
1941             emitNode(callArguments.argumentRegister(argument++), n);
1942     }
1943     
1944     // Reserve space for call frame.
1945     Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
1946     for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
1947         callFrame.append(newTemporary());
1948
1949     if (m_shouldEmitProfileHooks) {
1950         emitOpcode(op_profile_will_call);
1951         instructions().append(callArguments.profileHookRegister()->index());
1952     }
1953
1954     emitExpressionInfo(divot, divotStart, divotEnd);
1955
1956     RefPtr<Label> done = newLabel();
1957     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
1958     
1959     // Emit call.
1960     UnlinkedArrayProfile arrayProfile = newArrayProfile();
1961     UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1962     ASSERT(dst);
1963     ASSERT(dst != ignoredResult());
1964     instructions().append(dst->index());
1965     instructions().append(func->index());
1966     instructions().append(callArguments.argumentCountIncludingThis());
1967     instructions().append(callArguments.stackOffset());
1968     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
1969     instructions().append(0);
1970     instructions().append(arrayProfile);
1971     instructions().append(profile);
1972     
1973     if (expectedFunction != NoExpectedFunction)
1974         emitLabel(done.get());
1975
1976     if (m_shouldEmitProfileHooks) {
1977         emitOpcode(op_profile_did_call);
1978         instructions().append(callArguments.profileHookRegister()->index());
1979     }
1980
1981     return dst;
1982 }
1983
1984 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)
1985 {
1986     return emitCallVarargs(op_call_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
1987 }
1988
1989 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)
1990 {
1991     return emitCallVarargs(op_construct_varargs, dst, func, thisRegister, arguments, firstFreeRegister, firstVarArgOffset, profileHookRegister, divot, divotStart, divotEnd);
1992 }
1993     
1994 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)
1995 {
1996     if (m_shouldEmitProfileHooks) {
1997         emitMove(profileHookRegister, func);
1998         emitOpcode(op_profile_will_call);
1999         instructions().append(profileHookRegister->index());
2000     }
2001     
2002     emitExpressionInfo(divot, divotStart, divotEnd);
2003
2004     // Emit call.
2005     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2006     UnlinkedValueProfile profile = emitProfiledOpcode(opcode);
2007     ASSERT(dst != ignoredResult());
2008     instructions().append(dst->index());
2009     instructions().append(func->index());
2010     instructions().append(thisRegister ? thisRegister->index() : 0);
2011     instructions().append(arguments->index());
2012     instructions().append(firstFreeRegister->index());
2013     instructions().append(firstVarArgOffset);
2014     instructions().append(arrayProfile);
2015     instructions().append(profile);
2016     if (m_shouldEmitProfileHooks) {
2017         emitOpcode(op_profile_did_call);
2018         instructions().append(profileHookRegister->index());
2019     }
2020     return dst;
2021 }
2022
2023 void BytecodeGenerator::emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
2024     RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition& position)
2025 {
2026     RefPtr<RegisterID> descriptorRegister = emitNewObject(newTemporary());
2027
2028     RefPtr<RegisterID> trueRegister = emitLoad(newTemporary(), true);
2029     if (options & PropertyConfigurable)
2030         emitDirectPutById(descriptorRegister.get(), propertyNames().configurable, trueRegister.get(), PropertyNode::Unknown);
2031     if (options & PropertyWritable)
2032         emitDirectPutById(descriptorRegister.get(), propertyNames().writable, trueRegister.get(), PropertyNode::Unknown);
2033     else if (valueRegister) {
2034         RefPtr<RegisterID> falseRegister = emitLoad(newTemporary(), false);
2035         emitDirectPutById(descriptorRegister.get(), propertyNames().writable, falseRegister.get(), PropertyNode::Unknown);
2036     }
2037     if (options & PropertyEnumerable)
2038         emitDirectPutById(descriptorRegister.get(), propertyNames().enumerable, trueRegister.get(), PropertyNode::Unknown);
2039
2040     if (valueRegister)
2041         emitDirectPutById(descriptorRegister.get(), propertyNames().value, valueRegister, PropertyNode::Unknown);
2042     if (getterRegister)
2043         emitDirectPutById(descriptorRegister.get(), propertyNames().get, getterRegister, PropertyNode::Unknown);
2044     if (setterRegister)
2045         emitDirectPutById(descriptorRegister.get(), propertyNames().set, setterRegister, PropertyNode::Unknown);
2046
2047     RefPtr<RegisterID> definePropertyRegister = emitMoveLinkTimeConstant(newTemporary(), LinkTimeConstant::DefinePropertyFunction);
2048
2049     CallArguments callArguments(*this, nullptr, 3);
2050     emitLoad(callArguments.thisRegister(), jsUndefined());
2051     emitMove(callArguments.argumentRegister(0), newObj);
2052     emitMove(callArguments.argumentRegister(1), propertyNameRegister);
2053     emitMove(callArguments.argumentRegister(2), descriptorRegister.get());
2054
2055     emitCall(newTemporary(), definePropertyRegister.get(), NoExpectedFunction, callArguments, position, position, position);
2056 }
2057
2058 RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
2059 {
2060     if (isConstructor()) {
2061         bool derived = constructorKind() == ConstructorKind::Derived;
2062         if (derived && src->index() == m_thisRegister.index())
2063             emitTDZCheck(src);
2064
2065         RefPtr<Label> isObjectLabel = newLabel();
2066         emitJumpIfTrue(emitIsObject(newTemporary(), src), isObjectLabel.get());
2067
2068         if (derived) {
2069             RefPtr<Label> isUndefinedLabel = newLabel();
2070             emitJumpIfTrue(emitIsUndefined(newTemporary(), src), isUndefinedLabel.get());
2071             emitThrowTypeError("Cannot return a non-object type in the constructor of a derived class.");
2072             emitLabel(isUndefinedLabel.get());
2073             if (constructorKind() == ConstructorKind::Derived)
2074                 emitTDZCheck(&m_thisRegister);
2075         }
2076
2077         emitUnaryNoDstOp(op_ret, &m_thisRegister);
2078
2079         emitLabel(isObjectLabel.get());
2080     }
2081
2082     return emitUnaryNoDstOp(op_ret, src);
2083 }
2084
2085 RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
2086 {
2087     emitOpcode(opcodeID);
2088     instructions().append(src->index());
2089     return src;
2090 }
2091
2092 RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
2093 {
2094     ASSERT(func->refCount());
2095
2096     if (m_shouldEmitProfileHooks)
2097         emitMove(callArguments.profileHookRegister(), func);
2098
2099     // Generate code for arguments.
2100     unsigned argument = 0;
2101     if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
2102         
2103         ArgumentListNode* n = callArguments.argumentsNode()->m_listNode;
2104         if (n && n->m_expr->isSpreadExpression()) {
2105             RELEASE_ASSERT(!n->m_next);
2106             auto expression = static_cast<SpreadExpressionNode*>(n->m_expr)->expression();
2107             RefPtr<RegisterID> argumentRegister;
2108             argumentRegister = expression->emitBytecode(*this, callArguments.argumentRegister(0));
2109             return emitConstructVarargs(dst, func, callArguments.thisRegister(), argumentRegister.get(), newTemporary(), 0, callArguments.profileHookRegister(), divot, divotStart, divotEnd);
2110         }
2111         
2112         for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next)
2113             emitNode(callArguments.argumentRegister(argument++), n);
2114     }
2115
2116     if (m_shouldEmitProfileHooks) {
2117         emitOpcode(op_profile_will_call);
2118         instructions().append(callArguments.profileHookRegister()->index());
2119     }
2120
2121     // Reserve space for call frame.
2122     Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
2123     for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
2124         callFrame.append(newTemporary());
2125
2126     emitExpressionInfo(divot, divotStart, divotEnd);
2127     
2128     RefPtr<Label> done = newLabel();
2129     expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
2130
2131     UnlinkedValueProfile profile = emitProfiledOpcode(op_construct);
2132     ASSERT(dst != ignoredResult());
2133     instructions().append(dst->index());
2134     instructions().append(func->index());
2135     instructions().append(callArguments.argumentCountIncludingThis());
2136     instructions().append(callArguments.stackOffset());
2137     instructions().append(m_codeBlock->addLLIntCallLinkInfo());
2138     instructions().append(0);
2139     instructions().append(0);
2140     instructions().append(profile);
2141
2142     if (expectedFunction != NoExpectedFunction)
2143         emitLabel(done.get());
2144
2145     if (m_shouldEmitProfileHooks) {
2146         emitOpcode(op_profile_did_call);
2147         instructions().append(callArguments.profileHookRegister()->index());
2148     }
2149
2150     return dst;
2151 }
2152
2153 RegisterID* BytecodeGenerator::emitStrcat(RegisterID* dst, RegisterID* src, int count)
2154 {
2155     emitOpcode(op_strcat);
2156     instructions().append(dst->index());
2157     instructions().append(src->index());
2158     instructions().append(count);
2159
2160     return dst;
2161 }
2162
2163 void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src)
2164 {
2165     emitOpcode(op_to_primitive);
2166     instructions().append(dst->index());
2167     instructions().append(src->index());
2168 }
2169
2170 void BytecodeGenerator::emitGetScope()
2171 {
2172     emitOpcode(op_get_scope);
2173     instructions().append(scopeRegister()->index());
2174 }
2175
2176 RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* dst, RegisterID* scope)
2177 {
2178     ControlFlowContext context;
2179     context.isFinallyBlock = false;
2180     m_scopeContextStack.append(context);
2181     m_localScopeDepth++;
2182
2183     return emitUnaryOp(op_push_with_scope, dst, scope);
2184 }
2185
2186 void BytecodeGenerator::emitPopScope(RegisterID* srcDst)
2187 {
2188     ASSERT(m_scopeContextStack.size());
2189     ASSERT(!m_scopeContextStack.last().isFinallyBlock);
2190
2191     emitOpcode(op_pop_scope);
2192     instructions().append(srcDst->index());
2193
2194     m_scopeContextStack.removeLast();
2195     m_localScopeDepth--;
2196 }
2197
2198 void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned line, unsigned charOffset, unsigned lineStart)
2199 {
2200 #if ENABLE(DEBUG_WITH_BREAKPOINT)
2201     if (debugHookID != DidReachBreakpoint)
2202         return;
2203 #else
2204     if (!m_shouldEmitDebugHooks)
2205         return;
2206 #endif
2207     JSTextPosition divot(line, charOffset, lineStart);
2208     emitExpressionInfo(divot, divot, divot);
2209     emitOpcode(op_debug);
2210     instructions().append(debugHookID);
2211     instructions().append(false);
2212 }
2213
2214 void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock)
2215 {
2216     // Reclaim free label scopes.
2217     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2218         m_labelScopes.removeLast();
2219
2220     ControlFlowContext scope;
2221     scope.isFinallyBlock = true;
2222     FinallyContext context = {
2223         finallyBlock,
2224         nullptr,
2225         nullptr,
2226         static_cast<unsigned>(m_scopeContextStack.size()),
2227         static_cast<unsigned>(m_switchContextStack.size()),
2228         static_cast<unsigned>(m_forInContextStack.size()),
2229         static_cast<unsigned>(m_tryContextStack.size()),
2230         static_cast<unsigned>(m_labelScopes.size()),
2231         m_finallyDepth,
2232         m_localScopeDepth
2233     };
2234     scope.finallyContext = context;
2235     m_scopeContextStack.append(scope);
2236     m_finallyDepth++;
2237 }
2238
2239 void BytecodeGenerator::pushIteratorCloseContext(RegisterID* iterator, ThrowableExpressionData* node)
2240 {
2241     // Reclaim free label scopes.
2242     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2243         m_labelScopes.removeLast();
2244
2245     ControlFlowContext scope;
2246     scope.isFinallyBlock = true;
2247     FinallyContext context = {
2248         nullptr,
2249         iterator,
2250         node,
2251         static_cast<unsigned>(m_scopeContextStack.size()),
2252         static_cast<unsigned>(m_switchContextStack.size()),
2253         static_cast<unsigned>(m_forInContextStack.size()),
2254         static_cast<unsigned>(m_tryContextStack.size()),
2255         static_cast<unsigned>(m_labelScopes.size()),
2256         m_finallyDepth,
2257         m_localScopeDepth
2258     };
2259     scope.finallyContext = context;
2260     m_scopeContextStack.append(scope);
2261     m_finallyDepth++;
2262 }
2263
2264 void BytecodeGenerator::popFinallyContext()
2265 {
2266     ASSERT(m_scopeContextStack.size());
2267     ASSERT(m_scopeContextStack.last().isFinallyBlock);
2268     ASSERT(m_scopeContextStack.last().finallyContext.finallyBlock);
2269     ASSERT(!m_scopeContextStack.last().finallyContext.iterator);
2270     ASSERT(!m_scopeContextStack.last().finallyContext.enumerationNode);
2271     ASSERT(m_finallyDepth > 0);
2272     m_scopeContextStack.removeLast();
2273     m_finallyDepth--;
2274 }
2275
2276 void BytecodeGenerator::popIteratorCloseContext()
2277 {
2278     ASSERT(m_scopeContextStack.size());
2279     ASSERT(m_scopeContextStack.last().isFinallyBlock);
2280     ASSERT(!m_scopeContextStack.last().finallyContext.finallyBlock);
2281     ASSERT(m_scopeContextStack.last().finallyContext.iterator);
2282     ASSERT(m_scopeContextStack.last().finallyContext.enumerationNode);
2283     ASSERT(m_finallyDepth > 0);
2284     m_scopeContextStack.removeLast();
2285     m_finallyDepth--;
2286 }
2287
2288 LabelScopePtr BytecodeGenerator::breakTarget(const Identifier& name)
2289 {
2290     // Reclaim free label scopes.
2291     //
2292     // The condition was previously coded as 'm_labelScopes.size() && !m_labelScopes.last().refCount()',
2293     // however sometimes this appears to lead to GCC going a little haywire and entering the loop with
2294     // size 0, leading to segfaulty badness.  We are yet to identify a valid cause within our code to
2295     // cause the GCC codegen to misbehave in this fashion, and as such the following refactoring of the
2296     // loop condition is a workaround.
2297     while (m_labelScopes.size()) {
2298         if  (m_labelScopes.last().refCount())
2299             break;
2300         m_labelScopes.removeLast();
2301     }
2302
2303     if (!m_labelScopes.size())
2304         return LabelScopePtr::null();
2305
2306     // We special-case the following, which is a syntax error in Firefox:
2307     // label:
2308     //     break;
2309     if (name.isEmpty()) {
2310         for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2311             LabelScope* scope = &m_labelScopes[i];
2312             if (scope->type() != LabelScope::NamedLabel) {
2313                 ASSERT(scope->breakTarget());
2314                 return LabelScopePtr(m_labelScopes, i);
2315             }
2316         }
2317         return LabelScopePtr::null();
2318     }
2319
2320     for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2321         LabelScope* scope = &m_labelScopes[i];
2322         if (scope->name() && *scope->name() == name) {
2323             ASSERT(scope->breakTarget());
2324             return LabelScopePtr(m_labelScopes, i);
2325         }
2326     }
2327     return LabelScopePtr::null();
2328 }
2329
2330 LabelScopePtr BytecodeGenerator::continueTarget(const Identifier& name)
2331 {
2332     // Reclaim free label scopes.
2333     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
2334         m_labelScopes.removeLast();
2335
2336     if (!m_labelScopes.size())
2337         return LabelScopePtr::null();
2338
2339     if (name.isEmpty()) {
2340         for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2341             LabelScope* scope = &m_labelScopes[i];
2342             if (scope->type() == LabelScope::Loop) {
2343                 ASSERT(scope->continueTarget());
2344                 return LabelScopePtr(m_labelScopes, i);
2345             }
2346         }
2347         return LabelScopePtr::null();
2348     }
2349
2350     // Continue to the loop nested nearest to the label scope that matches
2351     // 'name'.
2352     LabelScopePtr result = LabelScopePtr::null();
2353     for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
2354         LabelScope* scope = &m_labelScopes[i];
2355         if (scope->type() == LabelScope::Loop) {
2356             ASSERT(scope->continueTarget());
2357             result = LabelScopePtr(m_labelScopes, i);
2358         }
2359         if (scope->name() && *scope->name() == name)
2360             return result; // may be null.
2361     }
2362     return LabelScopePtr::null();
2363 }
2364
2365 void BytecodeGenerator::allocateAndEmitScope()
2366 {
2367     m_scopeRegister = addVar();
2368     m_scopeRegister->ref();
2369     m_codeBlock->setScopeRegister(scopeRegister()->virtualRegister());
2370     emitGetScope();
2371 }
2372
2373 void BytecodeGenerator::emitComplexPopScopes(RegisterID* scope, ControlFlowContext* topScope, ControlFlowContext* bottomScope)
2374 {
2375     while (topScope > bottomScope) {
2376         // First we count the number of dynamic scopes we need to remove to get
2377         // to a finally block.
2378         int nNormalScopes = 0;
2379         while (topScope > bottomScope) {
2380             if (topScope->isFinallyBlock)
2381                 break;
2382             ++nNormalScopes;
2383             --topScope;
2384         }
2385
2386         if (nNormalScopes) {
2387             // We need to remove a number of dynamic scopes to get to the next
2388             // finally block
2389             while (nNormalScopes--) {
2390                 emitOpcode(op_pop_scope);
2391                 instructions().append(scope->index());
2392             }
2393
2394             // If topScope == bottomScope then there isn't a finally block left to emit.
2395             if (topScope == bottomScope)
2396                 return;
2397         }
2398         
2399         Vector<ControlFlowContext> savedScopeContextStack;
2400         Vector<SwitchInfo> savedSwitchContextStack;
2401         Vector<std::unique_ptr<ForInContext>> savedForInContextStack;
2402         Vector<TryContext> poppedTryContexts;
2403         LabelScopeStore savedLabelScopes;
2404         while (topScope > bottomScope && topScope->isFinallyBlock) {
2405             RefPtr<Label> beforeFinally = emitLabel(newLabel().get());
2406             
2407             // Save the current state of the world while instating the state of the world
2408             // for the finally block.
2409             FinallyContext finallyContext = topScope->finallyContext;
2410             bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size();
2411             bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size();
2412             bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size();
2413             bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size();
2414             bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size();
2415             int topScopeIndex = -1;
2416             int bottomScopeIndex = -1;
2417             if (flipScopes) {
2418                 topScopeIndex = topScope - m_scopeContextStack.begin();
2419                 bottomScopeIndex = bottomScope - m_scopeContextStack.begin();
2420                 savedScopeContextStack = m_scopeContextStack;
2421                 m_scopeContextStack.shrink(finallyContext.scopeContextStackSize);
2422             }
2423             if (flipSwitches) {
2424                 savedSwitchContextStack = m_switchContextStack;
2425                 m_switchContextStack.shrink(finallyContext.switchContextStackSize);
2426             }
2427             if (flipForIns) {
2428                 savedForInContextStack.swap(m_forInContextStack);
2429                 m_forInContextStack.shrink(finallyContext.forInContextStackSize);
2430             }
2431             if (flipTries) {
2432                 while (m_tryContextStack.size() != finallyContext.tryContextStackSize) {
2433                     ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize);
2434                     TryContext context = m_tryContextStack.last();
2435                     m_tryContextStack.removeLast();
2436                     TryRange range;
2437                     range.start = context.start;
2438                     range.end = beforeFinally;
2439                     range.tryData = context.tryData;
2440                     m_tryRanges.append(range);
2441                     poppedTryContexts.append(context);
2442                 }
2443             }
2444             if (flipLabelScopes) {
2445                 savedLabelScopes = m_labelScopes;
2446                 while (m_labelScopes.size() > finallyContext.labelScopesSize)
2447                     m_labelScopes.removeLast();
2448             }
2449             int savedFinallyDepth = m_finallyDepth;
2450             m_finallyDepth = finallyContext.finallyDepth;
2451             int savedDynamicScopeDepth = m_localScopeDepth;
2452             m_localScopeDepth = finallyContext.dynamicScopeDepth;
2453             
2454             if (finallyContext.finallyBlock) {
2455                 // Emit the finally block.
2456                 emitNode(finallyContext.finallyBlock);
2457             } else {
2458                 // Emit the IteratorClose block.
2459                 ASSERT(finallyContext.iterator);
2460                 emitIteratorClose(finallyContext.iterator, finallyContext.enumerationNode);
2461             }
2462
2463             RefPtr<Label> afterFinally = emitLabel(newLabel().get());
2464             
2465             // Restore the state of the world.
2466             if (flipScopes) {
2467                 m_scopeContextStack = savedScopeContextStack;
2468                 topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds
2469                 bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1.
2470             }
2471             if (flipSwitches)
2472                 m_switchContextStack = savedSwitchContextStack;
2473             if (flipForIns)
2474                 m_forInContextStack.swap(savedForInContextStack);
2475             if (flipTries) {
2476                 ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize);
2477                 for (unsigned i = poppedTryContexts.size(); i--;) {
2478                     TryContext context = poppedTryContexts[i];
2479                     context.start = afterFinally;
2480                     m_tryContextStack.append(context);
2481                 }
2482                 poppedTryContexts.clear();
2483             }
2484             if (flipLabelScopes)
2485                 m_labelScopes = savedLabelScopes;
2486             m_finallyDepth = savedFinallyDepth;
2487             m_localScopeDepth = savedDynamicScopeDepth;
2488             
2489             --topScope;
2490         }
2491     }
2492 }
2493
2494 void BytecodeGenerator::emitPopScopes(RegisterID* scope, int targetScopeDepth)
2495 {
2496     ASSERT(scopeDepth() - targetScopeDepth >= 0);
2497
2498     size_t scopeDelta = scopeDepth() - targetScopeDepth;
2499     ASSERT(scopeDelta <= m_scopeContextStack.size());
2500     if (!scopeDelta)
2501         return;
2502
2503     if (!m_finallyDepth) {
2504         while (scopeDelta--) {
2505             emitOpcode(op_pop_scope);
2506             instructions().append(scope->index());
2507         }
2508         return;
2509     }
2510
2511     emitComplexPopScopes(scope, &m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta);
2512 }
2513
2514 TryData* BytecodeGenerator::pushTry(Label* start)
2515 {
2516     TryData tryData;
2517     tryData.target = newLabel();
2518     tryData.targetScopeDepth = UINT_MAX;
2519     m_tryData.append(tryData);
2520     TryData* result = &m_tryData.last();
2521     
2522     TryContext tryContext;
2523     tryContext.start = start;
2524     tryContext.tryData = result;
2525     
2526     m_tryContextStack.append(tryContext);
2527     
2528     return result;
2529 }
2530
2531 RegisterID* BytecodeGenerator::popTryAndEmitCatch(TryData* tryData, RegisterID* targetRegister, Label* end)
2532 {
2533     m_usesExceptions = true;
2534     
2535     ASSERT_UNUSED(tryData, m_tryContextStack.last().tryData == tryData);
2536     
2537     TryRange tryRange;
2538     tryRange.start = m_tryContextStack.last().start;
2539     tryRange.end = end;
2540     tryRange.tryData = m_tryContextStack.last().tryData;
2541     m_tryRanges.append(tryRange);
2542     m_tryContextStack.removeLast();
2543     
2544     emitLabel(tryRange.tryData->target.get());
2545     tryRange.tryData->targetScopeDepth = m_localScopeDepth;
2546
2547     emitOpcode(op_catch);
2548     instructions().append(targetRegister->index());
2549     return targetRegister;
2550 }
2551
2552 void BytecodeGenerator::emitThrowReferenceError(const String& message)
2553 {
2554     emitOpcode(op_throw_static_error);
2555     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index());
2556     instructions().append(true);
2557 }
2558
2559 void BytecodeGenerator::emitThrowTypeError(const String& message)
2560 {
2561     emitOpcode(op_throw_static_error);
2562     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, message)))->index());
2563     instructions().append(false);
2564 }
2565
2566 void BytecodeGenerator::emitPushFunctionNameScope(RegisterID* dst, const Identifier& property, RegisterID* value, unsigned attributes)
2567 {
2568     emitOpcode(op_push_name_scope);
2569     instructions().append(dst->index());
2570     instructions().append(value->index());
2571     instructions().append(addConstantValue(SymbolTable::createNameScopeTable(*vm(), property, attributes))->index());
2572     instructions().append(JSNameScope::FunctionNameScope);
2573 }
2574
2575 void BytecodeGenerator::emitPushCatchScope(RegisterID* dst, const Identifier& property, RegisterID* value, unsigned attributes)
2576 {
2577     ControlFlowContext context;
2578     context.isFinallyBlock = false;
2579     m_scopeContextStack.append(context);
2580     m_localScopeDepth++;
2581
2582     emitOpcode(op_push_name_scope);
2583     instructions().append(dst->index());
2584     instructions().append(value->index());
2585     instructions().append(addConstantValue(SymbolTable::createNameScopeTable(*vm(), property, attributes))->index());
2586     instructions().append(JSNameScope::CatchScope);
2587 }
2588
2589 void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::SwitchType type)
2590 {
2591     SwitchInfo info = { static_cast<uint32_t>(instructions().size()), type };
2592     switch (type) {
2593         case SwitchInfo::SwitchImmediate:
2594             emitOpcode(op_switch_imm);
2595             break;
2596         case SwitchInfo::SwitchCharacter:
2597             emitOpcode(op_switch_char);
2598             break;
2599         case SwitchInfo::SwitchString:
2600             emitOpcode(op_switch_string);
2601             break;
2602         default:
2603             RELEASE_ASSERT_NOT_REACHED();
2604     }
2605
2606     instructions().append(0); // place holder for table index
2607     instructions().append(0); // place holder for default target    
2608     instructions().append(scrutineeRegister->index());
2609     m_switchContextStack.append(info);
2610 }
2611
2612 static int32_t keyForImmediateSwitch(ExpressionNode* node, int32_t min, int32_t max)
2613 {
2614     UNUSED_PARAM(max);
2615     ASSERT(node->isNumber());
2616     double value = static_cast<NumberNode*>(node)->value();
2617     int32_t key = static_cast<int32_t>(value);
2618     ASSERT(key == value);
2619     ASSERT(key >= min);
2620     ASSERT(key <= max);
2621     return key - min;
2622 }
2623
2624 static int32_t keyForCharacterSwitch(ExpressionNode* node, int32_t min, int32_t max)
2625 {
2626     UNUSED_PARAM(max);
2627     ASSERT(node->isString());
2628     StringImpl* clause = static_cast<StringNode*>(node)->value().impl();
2629     ASSERT(clause->length() == 1);
2630     
2631     int32_t key = (*clause)[0];
2632     ASSERT(key >= min);
2633     ASSERT(key <= max);
2634     return key - min;
2635 }
2636
2637 static void prepareJumpTableForSwitch(
2638     UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount,
2639     RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max,
2640     int32_t (*keyGetter)(ExpressionNode*, int32_t min, int32_t max))
2641 {
2642     jumpTable.min = min;
2643     jumpTable.branchOffsets.resize(max - min + 1);
2644     jumpTable.branchOffsets.fill(0);
2645     for (uint32_t i = 0; i < clauseCount; ++i) {
2646         // We're emitting this after the clause labels should have been fixed, so 
2647         // the labels should not be "forward" references
2648         ASSERT(!labels[i]->isForward());
2649         jumpTable.add(keyGetter(nodes[i], min, max), labels[i]->bind(switchAddress, switchAddress + 3)); 
2650     }
2651 }
2652
2653 static void prepareJumpTableForStringSwitch(UnlinkedStringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes)
2654 {
2655     for (uint32_t i = 0; i < clauseCount; ++i) {
2656         // We're emitting this after the clause labels should have been fixed, so 
2657         // the labels should not be "forward" references
2658         ASSERT(!labels[i]->isForward());
2659         
2660         ASSERT(nodes[i]->isString());
2661         StringImpl* clause = static_cast<StringNode*>(nodes[i])->value().impl();
2662         jumpTable.offsetTable.add(clause, labels[i]->bind(switchAddress, switchAddress + 3));
2663     }
2664 }
2665
2666 void BytecodeGenerator::endSwitch(uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, Label* defaultLabel, int32_t min, int32_t max)
2667 {
2668     SwitchInfo switchInfo = m_switchContextStack.last();
2669     m_switchContextStack.removeLast();
2670     
2671     switch (switchInfo.switchType) {
2672     case SwitchInfo::SwitchImmediate:
2673     case SwitchInfo::SwitchCharacter: {
2674         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfSwitchJumpTables();
2675         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
2676
2677         UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addSwitchJumpTable();
2678         prepareJumpTableForSwitch(
2679             jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max,
2680             switchInfo.switchType == SwitchInfo::SwitchImmediate
2681                 ? keyForImmediateSwitch
2682                 : keyForCharacterSwitch); 
2683         break;
2684     }
2685         
2686     case SwitchInfo::SwitchString: {
2687         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfStringSwitchJumpTables();
2688         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
2689
2690         UnlinkedStringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable();
2691         prepareJumpTableForStringSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes);
2692         break;
2693     }
2694         
2695     default:
2696         RELEASE_ASSERT_NOT_REACHED();
2697         break;
2698     }
2699 }
2700
2701 RegisterID* BytecodeGenerator::emitThrowExpressionTooDeepException()
2702 {
2703     // It would be nice to do an even better job of identifying exactly where the expression is.
2704     // And we could make the caller pass the node pointer in, if there was some way of getting
2705     // that from an arbitrary node. However, calling emitExpressionInfo without any useful data
2706     // is still good enough to get us an accurate line number.
2707     m_expressionTooDeep = true;
2708     return newTemporary();
2709 }
2710
2711 bool BytecodeGenerator::isArgumentNumber(const Identifier& ident, int argumentNumber)
2712 {
2713     RegisterID* registerID = variable(ident).local();
2714     if (!registerID)
2715         return false;
2716     return registerID->index() == CallFrame::argumentOffset(argumentNumber);
2717 }
2718
2719 void BytecodeGenerator::emitReadOnlyExceptionIfNeeded()
2720 {
2721     if (!isStrictMode())
2722         return;
2723     emitOpcode(op_throw_static_error);
2724     instructions().append(addConstantValue(addStringConstant(Identifier::fromString(m_vm, StrictModeReadonlyPropertyWriteError)))->index());
2725     instructions().append(false);
2726 }
2727     
2728 void BytecodeGenerator::emitEnumeration(ThrowableExpressionData* node, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack)
2729 {
2730     RefPtr<RegisterID> subject = newTemporary();
2731     emitNode(subject.get(), subjectNode);
2732     RefPtr<RegisterID> iterator = emitGetById(newTemporary(), subject.get(), propertyNames().iteratorSymbol);
2733     {
2734         CallArguments args(*this, nullptr);
2735         emitMove(args.thisRegister(), subject.get());
2736         emitCall(iterator.get(), iterator.get(), NoExpectedFunction, args, node->divot(), node->divotStart(), node->divotEnd());
2737     }
2738
2739     RefPtr<Label> loopDone = newLabel();
2740     // RefPtr<Register> iterator's lifetime must be longer than IteratorCloseContext.
2741     pushIteratorCloseContext(iterator.get(), node);
2742     {
2743         LabelScopePtr scope = newLabelScope(LabelScope::Loop);
2744         RefPtr<RegisterID> value = newTemporary();
2745         emitLoad(value.get(), jsUndefined());
2746
2747         emitJump(scope->continueTarget());
2748
2749         RefPtr<Label> loopStart = newLabel();
2750         emitLabel(loopStart.get());
2751         emitLoopHint();
2752
2753         RefPtr<Label> tryStartLabel = newLabel();
2754         emitLabel(tryStartLabel.get());
2755         TryData* tryData = pushTry(tryStartLabel.get());
2756         callBack(*this, value.get());
2757         emitJump(scope->continueTarget());
2758
2759         // IteratorClose sequence for throw-ed control flow.
2760         {
2761             RefPtr<Label> catchHere = emitLabel(newLabel().get());
2762             RefPtr<RegisterID> exceptionRegister = popTryAndEmitCatch(tryData, newTemporary(), catchHere.get());
2763             RefPtr<Label> catchDone = newLabel();
2764
2765             RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator.get(), propertyNames().returnKeyword);
2766             emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), catchDone.get());
2767
2768             RefPtr<Label> returnCallTryStart = newLabel();
2769             emitLabel(returnCallTryStart.get());
2770             TryData* returnCallTryData = pushTry(returnCallTryStart.get());
2771
2772             CallArguments returnArguments(*this, nullptr);
2773             emitMove(returnArguments.thisRegister(), iterator.get());
2774             emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd());
2775
2776             emitLabel(catchDone.get());
2777             emitThrow(exceptionRegister.get());
2778
2779             // Absorb exception.
2780             popTryAndEmitCatch(returnCallTryData, newTemporary(), catchDone.get());
2781             emitThrow(exceptionRegister.get());
2782         }
2783
2784         emitLabel(scope->continueTarget());
2785         {
2786             {
2787                 RefPtr<RegisterID> next = emitGetById(newTemporary(), iterator.get(), propertyNames().next);
2788                 CallArguments nextArguments(*this, nullptr);
2789                 emitMove(nextArguments.thisRegister(), iterator.get());
2790                 emitCall(value.get(), next.get(), NoExpectedFunction, nextArguments, node->divot(), node->divotStart(), node->divotEnd());
2791             }
2792             {
2793                 RefPtr<Label> typeIsObject = newLabel();
2794                 emitJumpIfTrue(emitIsObject(newTemporary(), value.get()), typeIsObject.get());
2795                 emitThrowTypeError(ASCIILiteral("Iterator result interface is not an object."));
2796                 emitLabel(typeIsObject.get());
2797             }
2798             emitJumpIfTrue(emitGetById(newTemporary(), value.get(), propertyNames().done), loopDone.get());
2799             emitGetById(value.get(), value.get(), propertyNames().value);
2800             emitJump(loopStart.get());
2801         }
2802
2803         emitLabel(scope->breakTarget());
2804     }
2805
2806     // IteratorClose sequence for break-ed control flow.
2807     popIteratorCloseContext();
2808     emitIteratorClose(iterator.get(), node);
2809     emitLabel(loopDone.get());
2810 }
2811
2812 #if ENABLE(ES6_TEMPLATE_LITERAL_SYNTAX)
2813 RegisterID* BytecodeGenerator::emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode* taggedTemplate)
2814 {
2815     TemplateRegistryKey::StringVector rawStrings;
2816     TemplateRegistryKey::StringVector cookedStrings;
2817
2818     TemplateStringListNode* templateString = taggedTemplate->templateLiteral()->templateStrings();
2819     for (; templateString; templateString = templateString->next()) {
2820         rawStrings.append(templateString->value()->raw().impl());
2821         cookedStrings.append(templateString->value()->cooked().impl());
2822     }
2823
2824     RefPtr<RegisterID> getTemplateObject = nullptr;
2825     Variable var = variable(propertyNames().getTemplateObjectPrivateName);
2826     if (RegisterID* local = var.local())
2827         getTemplateObject = emitMove(newTemporary(), local);
2828     else {
2829         getTemplateObject = newTemporary();
2830         RefPtr<RegisterID> scope = newTemporary();
2831         moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), var));
2832         emitGetFromScope(getTemplateObject.get(), scope.get(), var, ThrowIfNotFound);
2833     }
2834
2835     CallArguments arguments(*this, nullptr);
2836     emitLoad(arguments.thisRegister(), JSValue(addTemplateRegistryKeyConstant(TemplateRegistryKey(rawStrings, cookedStrings))));
2837     return emitCall(dst, getTemplateObject.get(), NoExpectedFunction, arguments, taggedTemplate->divot(), taggedTemplate->divotStart(), taggedTemplate->divotEnd());
2838 }
2839 #endif
2840
2841 RegisterID* BytecodeGenerator::emitGetEnumerableLength(RegisterID* dst, RegisterID* base)
2842 {
2843     emitOpcode(op_get_enumerable_length);
2844     instructions().append(dst->index());
2845     instructions().append(base->index());
2846     return dst;
2847 }
2848
2849 RegisterID* BytecodeGenerator::emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName)
2850 {
2851     emitOpcode(op_has_generic_property);
2852     instructions().append(dst->index());
2853     instructions().append(base->index());
2854     instructions().append(propertyName->index());
2855     return dst;
2856 }
2857
2858 RegisterID* BytecodeGenerator::emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName)
2859 {
2860     UnlinkedArrayProfile arrayProfile = newArrayProfile();
2861     emitOpcode(op_has_indexed_property);
2862     instructions().append(dst->index());
2863     instructions().append(base->index());
2864     instructions().append(propertyName->index());
2865     instructions().append(arrayProfile);
2866     return dst;
2867 }
2868
2869 RegisterID* BytecodeGenerator::emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator)
2870 {
2871     emitOpcode(op_has_structure_property);
2872     instructions().append(dst->index());
2873     instructions().append(base->index());
2874     instructions().append(propertyName->index());
2875     instructions().append(enumerator->index());
2876     return dst;
2877 }
2878
2879 RegisterID* BytecodeGenerator::emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base)
2880 {
2881     emitOpcode(op_get_property_enumerator);
2882     instructions().append(dst->index());
2883     instructions().append(base->index());
2884     return dst;
2885 }
2886
2887 RegisterID* BytecodeGenerator::emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index)
2888 {
2889     emitOpcode(op_enumerator_structure_pname);
2890     instructions().append(dst->index());
2891     instructions().append(enumerator->index());
2892     instructions().append(index->index());
2893     return dst;
2894 }
2895
2896 RegisterID* BytecodeGenerator::emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index)
2897 {
2898     emitOpcode(op_enumerator_generic_pname);
2899     instructions().append(dst->index());
2900     instructions().append(enumerator->index());
2901     instructions().append(index->index());
2902     return dst;
2903 }
2904
2905 RegisterID* BytecodeGenerator::emitToIndexString(RegisterID* dst, RegisterID* index)
2906 {
2907     emitOpcode(op_to_index_string);
2908     instructions().append(dst->index());
2909     instructions().append(index->index());
2910     return dst;
2911 }
2912
2913
2914 RegisterID* BytecodeGenerator::emitIsObject(RegisterID* dst, RegisterID* src)
2915 {
2916     emitOpcode(op_is_object);
2917     instructions().append(dst->index());
2918     instructions().append(src->index());
2919     return dst;
2920 }
2921
2922 RegisterID* BytecodeGenerator::emitIsUndefined(RegisterID* dst, RegisterID* src)
2923 {
2924     emitOpcode(op_is_undefined);
2925     instructions().append(dst->index());
2926     instructions().append(src->index());
2927     return dst;
2928 }
2929
2930 void BytecodeGenerator::emitIteratorClose(RegisterID* iterator, ThrowableExpressionData* node)
2931 {
2932     RefPtr<Label> done = newLabel();
2933     RefPtr<RegisterID> returnMethod = emitGetById(newTemporary(), iterator, propertyNames().returnKeyword);
2934     emitJumpIfTrue(emitIsUndefined(newTemporary(), returnMethod.get()), done.get());
2935
2936     RefPtr<RegisterID> value = newTemporary();
2937     CallArguments returnArguments(*this, nullptr);
2938     emitMove(returnArguments.thisRegister(), iterator);
2939     emitCall(value.get(), returnMethod.get(), NoExpectedFunction, returnArguments, node->divot(), node->divotStart(), node->divotEnd());
2940     emitJumpIfTrue(emitIsObject(newTemporary(), value.get()), done.get());
2941     emitThrowTypeError(ASCIILiteral("Iterator result interface is not an object."));
2942     emitLabel(done.get());
2943 }
2944
2945 void BytecodeGenerator::pushIndexedForInScope(RegisterID* localRegister, RegisterID* indexRegister)
2946 {
2947     if (!localRegister)
2948         return;
2949     m_forInContextStack.append(std::make_unique<IndexedForInContext>(localRegister, indexRegister));
2950 }
2951
2952 void BytecodeGenerator::popIndexedForInScope(RegisterID* localRegister)
2953 {
2954     if (!localRegister)
2955         return;
2956     m_forInContextStack.removeLast();
2957 }
2958
2959 void BytecodeGenerator::pushStructureForInScope(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister)
2960 {
2961     if (!localRegister)
2962         return;
2963     m_forInContextStack.append(std::make_unique<StructureForInContext>(localRegister, indexRegister, propertyRegister, enumeratorRegister));
2964 }
2965
2966 void BytecodeGenerator::popStructureForInScope(RegisterID* localRegister)
2967 {
2968     if (!localRegister)
2969         return;
2970     m_forInContextStack.removeLast();
2971 }
2972
2973 void BytecodeGenerator::invalidateForInContextForLocal(RegisterID* localRegister)
2974 {
2975     // Lexically invalidating ForInContexts is kind of weak sauce, but it only occurs if 
2976     // either of the following conditions is true:
2977     // 
2978     // (1) The loop iteration variable is re-assigned within the body of the loop.
2979     // (2) The loop iteration variable is captured in the lexical scope of the function.
2980     //
2981     // These two situations occur sufficiently rarely that it's okay to use this style of 
2982     // "analysis" to make iteration faster. If we didn't want to do this, we would either have 
2983     // to perform some flow-sensitive analysis to see if/when the loop iteration variable was 
2984     // reassigned, or we'd have to resort to runtime checks to see if the variable had been 
2985     // reassigned from its original value.
2986     for (size_t i = m_forInContextStack.size(); i > 0; i--) {
2987         ForInContext* context = m_forInContextStack[i - 1].get();
2988         if (context->local() != localRegister)
2989             continue;
2990         context->invalidate();
2991         break;
2992     }
2993 }
2994
2995 } // namespace JSC