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