]> git.saurik.com Git - apple/javascriptcore.git/blobdiff - bytecompiler/BytecodeGenerator.cpp
JavaScriptCore-1218.tar.gz
[apple/javascriptcore.git] / bytecompiler / BytecodeGenerator.cpp
index c09a83766d6a9b406fb8aa6ee3491b9555e5aaaa..e7193807e54a5d13f13808078bd3855826d11bbc 100644 (file)
@@ -1,6 +1,7 @@
 /*
- * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009, 2012, 2013 Apple Inc. All rights reserved.
  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
+ * Copyright (C) 2012 Igalia, S.L.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "BytecodeGenerator.h"
 
 #include "BatchedTransitionOptimizer.h"
-#include "JSFunction.h"
 #include "Interpreter.h"
-#include "ScopeChain.h"
-#include "UString.h"
+#include "JSActivation.h"
+#include "JSFunction.h"
+#include "JSNameScope.h"
+#include "LowLevelInterpreter.h"
+#include "Operations.h"
+#include "Options.h"
+#include "StrongInlines.h"
+#include "UnlinkedCodeBlock.h"
+#include <wtf/text/WTFString.h>
 
 using namespace std;
 
 namespace JSC {
 
-/*
-    The layout of a register frame looks like this:
-
-    For
-
-    function f(x, y) {
-        var v1;
-        function g() { }
-        var v2;
-        return (x) * (y);
-    }
-
-    assuming (x) and (y) generated temporaries t1 and t2, you would have
-
-    ------------------------------------
-    |  x |  y |  g | v2 | v1 | t1 | t2 | <-- value held
-    ------------------------------------
-    | -5 | -4 | -3 | -2 | -1 | +0 | +1 | <-- register index
-    ------------------------------------
-    | params->|<-locals      | temps->
-
-    Because temporary registers are allocated in a stack-like fashion, we
-    can reclaim them with a simple popping algorithm. The same goes for labels.
-    (We never reclaim parameter or local registers, because parameters and
-    locals are DontDelete.)
-
-    The register layout before a function call looks like this:
-
-    For
-
-    function f(x, y)
-    {
-    }
-
-    f(1);
-
-    >                        <------------------------------
-    <                        >  reserved: call frame  |  1 | <-- value held
-    >         >snip<         <------------------------------
-    <                        > +0 | +1 | +2 | +3 | +4 | +5 | <-- register index
-    >                        <------------------------------
-    | params->|<-locals      | temps->
-
-    The call instruction fills in the "call frame" registers. It also pads
-    missing arguments at the end of the call:
-
-    >                        <-----------------------------------
-    <                        >  reserved: call frame  |  1 |  ? | <-- value held ("?" stands for "undefined")
-    >         >snip<         <-----------------------------------
-    <                        > +0 | +1 | +2 | +3 | +4 | +5 | +6 | <-- register index
-    >                        <-----------------------------------
-    | params->|<-locals      | temps->
-
-    After filling in missing arguments, the call instruction sets up the new
-    stack frame to overlap the end of the old stack frame:
-
-                             |---------------------------------->                        <
-                             |  reserved: call frame  |  1 |  ? <                        > <-- value held ("?" stands for "undefined")
-                             |---------------------------------->         >snip<         <
-                             | -7 | -6 | -5 | -4 | -3 | -2 | -1 <                        > <-- register index
-                             |---------------------------------->                        <
-                             |                        | params->|<-locals       | temps->
-
-    That way, arguments are "copied" into the callee's stack frame for free.
-
-    If the caller supplies too many arguments, this trick doesn't work. The
-    extra arguments protrude into space reserved for locals and temporaries.
-    In that case, the call instruction makes a real copy of the call frame header,
-    along with just the arguments expected by the callee, leaving the original
-    call frame header and arguments behind. (The call instruction can't just discard
-    extra arguments, because the "arguments" object may access them later.)
-    This copying strategy ensures that all named values will be at the indices
-    expected by the callee.
-*/
-
-#ifndef NDEBUG
-static bool s_dumpsGeneratedCode = false;
-#endif
-
-void BytecodeGenerator::setDumpsGeneratedCode(bool dumpsGeneratedCode)
+void Label::setLocation(unsigned location)
 {
-#ifndef NDEBUG
-    s_dumpsGeneratedCode = dumpsGeneratedCode;
-#else
-    UNUSED_PARAM(dumpsGeneratedCode);
-#endif
+    m_location = location;
+    
+    unsigned size = m_unresolvedJumps.size();
+    for (unsigned i = 0; i < size; ++i)
+        m_generator->m_instructions[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
 }
 
-bool BytecodeGenerator::dumpsGeneratedCode()
-{
 #ifndef NDEBUG
-    return s_dumpsGeneratedCode;
-#else
-    return false;
-#endif
+void ResolveResult::checkValidity()
+{
+    switch (m_type) {
+    case Register:
+    case ReadOnlyRegister:
+        ASSERT(m_local);
+        return;
+    case Dynamic:
+        ASSERT(!m_local);
+        return;
+    case Lexical:
+    case ReadOnlyLexical:
+        ASSERT(!m_local);
+        return;
+    default:
+        RELEASE_ASSERT_NOT_REACHED();
+    }
 }
+#endif
 
-JSObject* BytecodeGenerator::generate()
+ParserError BytecodeGenerator::generate()
 {
+    SamplingRegion samplingRegion("Bytecode Generation");
+    
     m_codeBlock->setThisRegister(m_thisRegister.index());
 
     m_scopeNode->emitBytecode(*this);
 
-#ifndef NDEBUG
-    m_codeBlock->setInstructionCount(m_codeBlock->instructions().size());
-
-    if (s_dumpsGeneratedCode)
-        m_codeBlock->dump(m_scopeChain->globalObject->globalExec());
-#endif
+    m_staticPropertyAnalyzer.kill();
 
-    if ((m_codeType == FunctionCode && !m_codeBlock->needsFullScopeChain() && !m_codeBlock->usesArguments()) || m_codeType == EvalCode)
-        symbolTable().clear();
+    for (unsigned i = 0; i < m_tryRanges.size(); ++i) {
+        TryRange& range = m_tryRanges[i];
+        int start = range.start->bind();
+        int end = range.end->bind();
+        
+        // This will happen for empty try blocks and for some cases of finally blocks:
+        //
+        // try {
+        //    try {
+        //    } finally {
+        //        return 42;
+        //        // *HERE*
+        //    }
+        // } finally {
+        //    print("things");
+        // }
+        //
+        // The return will pop scopes to execute the outer finally block. But this includes
+        // popping the try context for the inner try. The try context is live in the fall-through
+        // part of the finally block not because we will emit a handler that overlaps the finally,
+        // but because we haven't yet had a chance to plant the catch target. Then when we finish
+        // emitting code for the outer finally block, we repush the try contex, this time with a
+        // new start index. But that means that the start index for the try range corresponding
+        // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
+        // than the end index of the try block. This is harmless since end < start handlers will
+        // never get matched in our logic, but we do the runtime a favor and choose to not emit
+        // such handlers at all.
+        if (end <= start)
+            continue;
+        
+        ASSERT(range.tryData->targetScopeDepth != UINT_MAX);
+        UnlinkedHandlerInfo info = {
+            static_cast<uint32_t>(start), static_cast<uint32_t>(end),
+            static_cast<uint32_t>(range.tryData->target->bind()),
+            range.tryData->targetScopeDepth
+        };
+        m_codeBlock->addExceptionHandler(info);
+    }
+    
+    m_codeBlock->instructions() = RefCountedArray<UnlinkedInstruction>(m_instructions);
 
     m_codeBlock->shrinkToFit();
 
     if (m_expressionTooDeep)
-        return createOutOfMemoryError(m_scopeChain->globalObject.get());
-    return 0;
+        return ParserError(ParserError::OutOfMemory);
+    return ParserError(ParserError::ErrorNone);
 }
 
 bool BytecodeGenerator::addVar(const Identifier& ident, bool isConstant, RegisterID*& r0)
 {
     int index = m_calleeRegisters.size();
     SymbolTableEntry newEntry(index, isConstant ? ReadOnly : 0);
-    pair<SymbolTable::iterator, bool> result = symbolTable().add(ident.impl(), newEntry);
+    SymbolTable::AddResult result = symbolTable().add(ident.impl(), newEntry);
 
-    if (!result.second) {
-        r0 = &registerFor(result.first->second.getIndex());
+    if (!result.isNewEntry) {
+        r0 = &registerFor(result.iterator->value.getIndex());
         return false;
     }
 
@@ -175,183 +150,94 @@ bool BytecodeGenerator::addVar(const Identifier& ident, bool isConstant, Registe
     return true;
 }
 
-bool BytecodeGenerator::addGlobalVar(const Identifier& ident, bool isConstant, RegisterID*& r0)
-{
-    int index = m_nextGlobalIndex;
-    SymbolTableEntry newEntry(index, isConstant ? ReadOnly : 0);
-    pair<SymbolTable::iterator, bool> result = symbolTable().add(ident.impl(), newEntry);
-
-    if (!result.second)
-        index = result.first->second.getIndex();
-    else {
-        --m_nextGlobalIndex;
-        m_globals.append(index + m_globalVarStorageOffset);
-    }
-
-    r0 = &registerFor(index);
-    return result.second;
-}
-
 void BytecodeGenerator::preserveLastVar()
 {
     if ((m_firstConstantIndex = m_calleeRegisters.size()) != 0)
         m_lastVar = &m_calleeRegisters.last();
 }
 
-BytecodeGenerator::BytecodeGenerator(ProgramNode* programNode, ScopeChainNode* scopeChain, SymbolTable* symbolTable, ProgramCodeBlock* codeBlock)
-    : m_shouldEmitDebugHooks(scopeChain->globalObject->debugger())
-    , m_shouldEmitProfileHooks(scopeChain->globalObject->supportsProfiling())
-    , m_shouldEmitRichSourceInfo(scopeChain->globalObject->supportsRichSourceInfo())
-    , m_scopeChain(*scopeChain->globalData, scopeChain)
-    , m_symbolTable(symbolTable)
+BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope*, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
+    : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn)
+    , m_shouldEmitProfileHooks(profilerMode == ProfilerOn)
+    , m_symbolTable(0)
     , m_scopeNode(programNode)
-    , m_codeBlock(codeBlock)
-    , m_thisRegister(RegisterFile::ProgramCodeThisRegister)
+    , m_codeBlock(vm, codeBlock)
+    , m_thisRegister(CallFrame::thisArgumentOffset())
+    , m_emptyValueRegister(0)
+    , m_globalObjectRegister(0)
     , m_finallyDepth(0)
     , m_dynamicScopeDepth(0)
-    , m_baseScopeDepth(0)
     , m_codeType(GlobalCode)
-    , m_nextGlobalIndex(-1)
     , m_nextConstantOffset(0)
     , m_globalConstantIndex(0)
     , m_hasCreatedActivation(true)
     , m_firstLazyFunction(0)
     , m_lastLazyFunction(0)
-    , m_globalData(scopeChain->globalData)
+    , m_staticPropertyAnalyzer(&m_instructions)
+    , m_vm(&vm)
     , m_lastOpcodeID(op_end)
 #ifndef NDEBUG
     , m_lastOpcodePosition(0)
 #endif
-    , m_stack(m_globalData->stack())
+    , m_stack(wtfThreadData().stack())
     , m_usesExceptions(false)
     , m_expressionTooDeep(false)
 {
     if (m_shouldEmitDebugHooks)
         m_codeBlock->setNeedsFullScopeChain(true);
 
-    emitOpcode(op_enter);
-    codeBlock->setGlobalData(m_globalData);
-
-    // FIXME: Move code that modifies the global object to Interpreter::execute.
-    
-    m_codeBlock->m_numParameters = 1; // Allocate space for "this"
-
-    JSGlobalObject* globalObject = scopeChain->globalObject.get();
-    ExecState* exec = globalObject->globalExec();
-    RegisterFile* registerFile = &exec->globalData().interpreter->registerFile();
-    
-    // Shift register indexes in generated code to elide registers allocated by intermediate stack frames.
-    m_globalVarStorageOffset = -RegisterFile::CallFrameHeaderSize - m_codeBlock->m_numParameters - registerFile->size();
-
-    // Add previously defined symbols to bookkeeping.
-    m_globals.grow(symbolTable->size());
-    SymbolTable::iterator end = symbolTable->end();
-    for (SymbolTable::iterator it = symbolTable->begin(); it != end; ++it)
-        registerFor(it->second.getIndex()).setIndex(it->second.getIndex() + m_globalVarStorageOffset);
+    m_codeBlock->setNumParameters(1); // Allocate space for "this"
 
-    BatchedTransitionOptimizer optimizer(*m_globalData, globalObject);
+    emitOpcode(op_enter);
 
     const VarStack& varStack = programNode->varStack();
     const FunctionStack& functionStack = programNode->functionStack();
-    bool canOptimizeNewGlobals = symbolTable->size() + functionStack.size() + varStack.size() < registerFile->maxGlobals();
-    if (canOptimizeNewGlobals) {
-        // Shift new symbols so they get stored prior to existing symbols.
-        m_nextGlobalIndex -= symbolTable->size();
-
-        HashSet<StringImpl*, IdentifierRepHash> newGlobals;
-        Vector<std::pair<int, bool>, 16> functionInfo(functionStack.size());
-        for (size_t i = 0; i < functionStack.size(); ++i) {
-            FunctionBodyNode* function = functionStack[i];
-            globalObject->removeDirect(*m_globalData, function->ident()); // Make sure our new function is not shadowed by an old property.
-            SymbolTableEntry entry = symbolTable->inlineGet(function->ident().impl());
-            
-            if (entry.isNull())
-                newGlobals.add(function->ident().impl());
-            functionInfo[i] = make_pair(entry.getIndex(), entry.isReadOnly());
-        }
-        
-        Vector<bool, 16> shouldCreateVar(varStack.size());
-        for (size_t i = 0; i < varStack.size(); ++i) {
-            if (newGlobals.contains(varStack[i].first->impl()) || globalObject->hasProperty(exec, *varStack[i].first)) {
-                shouldCreateVar[i] = false;
-                continue;
-            }
-            shouldCreateVar[i] = true;
-            newGlobals.add(varStack[i].first->impl());
-        }
-
-        int expectedSize = symbolTable->size() + newGlobals.size();
-        globalObject->resizeRegisters(symbolTable->size(), expectedSize);
-    
-        for (size_t i = 0; i < functionStack.size(); ++i) {
-            FunctionBodyNode* function = functionStack[i];
-            if (functionInfo[i].second)
-                continue;
-            RegisterID* dst = addGlobalVar(function->ident(), false);
-            JSValue value = new (exec) JSFunction(exec, makeFunction(exec, function), scopeChain);
-            globalObject->registerAt(dst->index() - m_globalVarStorageOffset).set(*m_globalData, globalObject, value);
-        }
 
-        for (size_t i = 0; i < varStack.size(); ++i) {
-            if (!shouldCreateVar[i])
-                continue;
-            addGlobalVar(*varStack[i].first, varStack[i].second & DeclarationStacks::IsConstant);
-        }
-        if (symbolTable->size() != expectedSize)
-            CRASH();
+    for (size_t i = 0; i < functionStack.size(); ++i) {
+        FunctionBodyNode* function = functionStack[i];
+        UnlinkedFunctionExecutable* unlinkedFunction = makeFunction(function);
+        codeBlock->addFunctionDeclaration(*m_vm, function->ident(), unlinkedFunction);
+    }
 
-        preserveLastVar();
-    } else {
-        for (size_t i = 0; i < functionStack.size(); ++i) {
-            FunctionBodyNode* function = functionStack[i];
-            globalObject->putWithAttributes(exec, function->ident(), new (exec) JSFunction(exec, makeFunction(exec, function), scopeChain), DontDelete);
-        }
-        for (size_t i = 0; i < varStack.size(); ++i) {
-            if (globalObject->symbolTableHasProperty(*varStack[i].first) || globalObject->hasProperty(exec, *varStack[i].first))
-                continue;
-            int attributes = DontDelete;
-            if (varStack[i].second & DeclarationStacks::IsConstant)
-                attributes |= ReadOnly;
-            globalObject->putWithAttributes(exec, *varStack[i].first, jsUndefined(), attributes);
-        }
+    for (size_t i = 0; i < varStack.size(); ++i)
+        codeBlock->addVariableDeclaration(*varStack[i].first, !!(varStack[i].second & DeclarationStacks::IsConstant));
 
-        preserveLastVar();
-    }
-    codeBlock->m_numCapturedVars = codeBlock->m_numVars;
 }
 
-BytecodeGenerator::BytecodeGenerator(FunctionBodyNode* functionBody, ScopeChainNode* scopeChain, SymbolTable* symbolTable, CodeBlock* codeBlock)
-    : m_shouldEmitDebugHooks(scopeChain->globalObject->debugger())
-    , m_shouldEmitProfileHooks(scopeChain->globalObject->supportsProfiling())
-    , m_shouldEmitRichSourceInfo(scopeChain->globalObject->supportsRichSourceInfo())
-    , m_scopeChain(*scopeChain->globalData, scopeChain)
-    , m_symbolTable(symbolTable)
+BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, FunctionBodyNode* functionBody, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
+    : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn)
+    , m_shouldEmitProfileHooks(profilerMode == ProfilerOn)
+    , m_symbolTable(codeBlock->symbolTable())
     , m_scopeNode(functionBody)
-    , m_codeBlock(codeBlock)
+    , m_scope(vm, scope)
+    , m_codeBlock(vm, codeBlock)
     , m_activationRegister(0)
+    , m_emptyValueRegister(0)
+    , m_globalObjectRegister(0)
     , m_finallyDepth(0)
     , m_dynamicScopeDepth(0)
-    , m_baseScopeDepth(0)
     , m_codeType(FunctionCode)
     , m_nextConstantOffset(0)
     , m_globalConstantIndex(0)
     , m_hasCreatedActivation(false)
     , m_firstLazyFunction(0)
     , m_lastLazyFunction(0)
-    , m_globalData(scopeChain->globalData)
+    , m_staticPropertyAnalyzer(&m_instructions)
+    , m_vm(&vm)
     , m_lastOpcodeID(op_end)
 #ifndef NDEBUG
     , m_lastOpcodePosition(0)
 #endif
-    , m_stack(m_globalData->stack())
+    , m_stack(wtfThreadData().stack())
     , m_usesExceptions(false)
     , m_expressionTooDeep(false)
 {
     if (m_shouldEmitDebugHooks)
         m_codeBlock->setNeedsFullScopeChain(true);
 
-    codeBlock->setGlobalData(m_globalData);
-    
+    m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode());
+    m_symbolTable->setParameterCountIncludingThis(functionBody->parameters()->size() + 1);
+
     emitOpcode(op_enter);
     if (m_codeBlock->needsFullScopeChain()) {
         m_activationRegister = addVar();
@@ -359,9 +245,9 @@ BytecodeGenerator::BytecodeGenerator(FunctionBodyNode* functionBody, ScopeChainN
         m_codeBlock->setActivationRegister(m_activationRegister->index());
     }
 
-    // Both op_tear_off_activation and op_tear_off_arguments tear off the 'arguments'
-    // object, if created.
-    if (m_codeBlock->needsFullScopeChain() || functionBody->usesArguments()) {
+    m_symbolTable->setCaptureStart(m_codeBlock->m_numVars);
+
+    if (functionBody->usesArguments() || codeBlock->usesEval() || m_shouldEmitDebugHooks) { // May reify arguments object.
         RegisterID* unmodifiedArgumentsRegister = addVar(); // Anonymous, so it can't be modified by user code.
         RegisterID* argumentsRegister = addVar(propertyNames().arguments, false); // Can be changed by assigning to 'arguments'.
 
@@ -388,6 +274,39 @@ BytecodeGenerator::BytecodeGenerator(FunctionBodyNode* functionBody, ScopeChainN
         }
     }
 
+    bool shouldCaptureAllTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
+
+    bool capturesAnyArgumentByName = false;
+    Vector<RegisterID*, 0, UnsafeVectorOverflow> capturedArguments;
+    if (functionBody->hasCapturedVariables() || shouldCaptureAllTheThings) {
+        FunctionParameters& parameters = *functionBody->parameters();
+        capturedArguments.resize(parameters.size());
+        for (size_t i = 0; i < parameters.size(); ++i) {
+            capturedArguments[i] = 0;
+            if (!functionBody->captures(parameters.at(i)) && !shouldCaptureAllTheThings)
+                continue;
+            capturesAnyArgumentByName = true;
+            capturedArguments[i] = addVar();
+        }
+    }
+
+    if (capturesAnyArgumentByName && !codeBlock->isStrictMode()) {
+        size_t parameterCount = m_symbolTable->parameterCount();
+        OwnArrayPtr<SlowArgument> slowArguments = adoptArrayPtr(new SlowArgument[parameterCount]);
+        for (size_t i = 0; i < parameterCount; ++i) {
+            if (!capturedArguments[i]) {
+                ASSERT(slowArguments[i].status == SlowArgument::Normal);
+                slowArguments[i].index = CallFrame::argumentOffset(i);
+                continue;
+            }
+            slowArguments[i].status = SlowArgument::Captured;
+            slowArguments[i].index = capturedArguments[i]->index();
+        }
+        m_symbolTable->setSlowArguments(slowArguments.release());
+    }
+
+    RegisterID* calleeRegister = resolveCallee(functionBody); // May push to the scope chain and/or add a captured var.
+
     const DeclarationStacks::FunctionStack& functionStack = functionBody->functionStack();
     const DeclarationStacks::VarStack& varStack = functionBody->varStack();
 
@@ -421,7 +340,8 @@ BytecodeGenerator::BytecodeGenerator(FunctionBodyNode* functionBody, ScopeChainN
         instructions().append(m_activationRegister->index());
     }
 
-    codeBlock->m_numCapturedVars = codeBlock->m_numVars;
+    m_symbolTable->setCaptureEnd(codeBlock->m_numVars);
+
     m_firstLazyFunction = codeBlock->m_numVars;
     for (size_t i = 0; i < functionStack.size(); ++i) {
         FunctionBodyNode* function = functionStack[i];
@@ -445,94 +365,95 @@ BytecodeGenerator::BytecodeGenerator(FunctionBodyNode* functionBody, ScopeChainN
         if (!functionBody->captures(ident))
             addVar(ident, varStack[i].second & DeclarationStacks::IsConstant);
     }
-    
-    if (m_shouldEmitDebugHooks)
-        codeBlock->m_numCapturedVars = codeBlock->m_numVars;
+
+    if (shouldCaptureAllTheThings)
+        m_symbolTable->setCaptureEnd(codeBlock->m_numVars);
 
     FunctionParameters& parameters = *functionBody->parameters();
-    size_t parameterCount = parameters.size();
-    int nextParameterIndex = -RegisterFile::CallFrameHeaderSize - parameterCount - 1;
-    m_parameters.grow(1 + parameterCount); // reserve space for "this"
+    m_parameters.grow(parameters.size() + 1); // reserve space for "this"
 
     // Add "this" as a parameter
-    m_thisRegister.setIndex(nextParameterIndex);
-    ++m_codeBlock->m_numParameters;
+    int nextParameterIndex = CallFrame::thisArgumentOffset();
+    m_thisRegister.setIndex(nextParameterIndex--);
+    m_codeBlock->addParameter();
     
-    for (size_t i = 0; i < parameterCount; ++i)
-        addParameter(parameters[i], ++nextParameterIndex);
-
+    for (size_t i = 0; i < parameters.size(); ++i, --nextParameterIndex) {
+        int index = nextParameterIndex;
+        if (capturedArguments.size() && capturedArguments[i]) {
+            ASSERT((functionBody->hasCapturedVariables() && functionBody->captures(parameters.at(i))) || shouldCaptureAllTheThings);
+            index = capturedArguments[i]->index();
+            RegisterID original(nextParameterIndex);
+            emitMove(capturedArguments[i], &original);
+        }
+        addParameter(parameters.at(i), index);
+    }
     preserveLastVar();
 
-    if (isConstructor()) {
-        RefPtr<RegisterID> func = newTemporary();
-        RefPtr<RegisterID> funcProto = newTemporary();
+    // We declare the callee's name last because it should lose to a var, function, and/or parameter declaration.
+    addCallee(functionBody, calleeRegister);
 
-        emitOpcode(op_get_callee);
-        instructions().append(func->index());
-        // Load prototype.
-        emitGetById(funcProto.get(), func.get(), globalData()->propertyNames->prototype);
-
-        emitOpcode(op_create_this);
-        instructions().append(m_thisRegister.index());
-        instructions().append(funcProto->index());
-    } else if (functionBody->usesThis() || m_shouldEmitDebugHooks) {
-        if (codeBlock->isStrictMode())
-            emitOpcode(op_convert_this_strict);
-        else
-            emitOpcode(op_convert_this);
-        instructions().append(m_thisRegister.index());
+    if (isConstructor()) {
+        emitCreateThis(&m_thisRegister);
+    } else if (!codeBlock->isStrictMode() && (functionBody->usesThis() || codeBlock->usesEval() || m_shouldEmitDebugHooks)) {
+        UnlinkedValueProfile profile = emitProfiledOpcode(op_convert_this);
+        instructions().append(kill(&m_thisRegister));
+        instructions().append(profile);
     }
 }
 
-BytecodeGenerator::BytecodeGenerator(EvalNode* evalNode, ScopeChainNode* scopeChain, SymbolTable* symbolTable, EvalCodeBlock* codeBlock)
-    : m_shouldEmitDebugHooks(scopeChain->globalObject->debugger())
-    , m_shouldEmitProfileHooks(scopeChain->globalObject->supportsProfiling())
-    , m_shouldEmitRichSourceInfo(scopeChain->globalObject->supportsRichSourceInfo())
-    , m_scopeChain(*scopeChain->globalData, scopeChain)
-    , m_symbolTable(symbolTable)
+BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
+    : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn)
+    , m_shouldEmitProfileHooks(profilerMode == ProfilerOn)
+    , m_symbolTable(codeBlock->symbolTable())
     , m_scopeNode(evalNode)
-    , m_codeBlock(codeBlock)
-    , m_thisRegister(RegisterFile::ProgramCodeThisRegister)
+    , m_scope(vm, scope)
+    , m_codeBlock(vm, codeBlock)
+    , m_thisRegister(CallFrame::thisArgumentOffset())
+    , m_emptyValueRegister(0)
+    , m_globalObjectRegister(0)
     , m_finallyDepth(0)
     , m_dynamicScopeDepth(0)
-    , m_baseScopeDepth(codeBlock->baseScopeDepth())
     , m_codeType(EvalCode)
     , m_nextConstantOffset(0)
     , m_globalConstantIndex(0)
     , m_hasCreatedActivation(true)
     , m_firstLazyFunction(0)
     , m_lastLazyFunction(0)
-    , m_globalData(scopeChain->globalData)
+    , m_staticPropertyAnalyzer(&m_instructions)
+    , m_vm(&vm)
     , m_lastOpcodeID(op_end)
 #ifndef NDEBUG
     , m_lastOpcodePosition(0)
 #endif
-    , m_stack(m_globalData->stack())
+    , m_stack(wtfThreadData().stack())
     , m_usesExceptions(false)
     , m_expressionTooDeep(false)
 {
-    if (m_shouldEmitDebugHooks || m_baseScopeDepth)
-        m_codeBlock->setNeedsFullScopeChain(true);
+    m_codeBlock->setNeedsFullScopeChain(true);
+
+    m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode());
+    m_codeBlock->setNumParameters(1);
 
     emitOpcode(op_enter);
-    codeBlock->setGlobalData(m_globalData);
-    m_codeBlock->m_numParameters = 1; // Allocate space for "this"
 
     const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack();
     for (size_t i = 0; i < functionStack.size(); ++i)
-        m_codeBlock->addFunctionDecl(makeFunction(m_globalData, functionStack[i]));
+        m_codeBlock->addFunctionDecl(makeFunction(functionStack[i]));
 
     const DeclarationStacks::VarStack& varStack = evalNode->varStack();
     unsigned numVariables = varStack.size();
-    Vector<Identifier> variables;
+    Vector<Identifier, 0, UnsafeVectorOverflow> variables;
     variables.reserveCapacity(numVariables);
     for (size_t i = 0; i < numVariables; ++i)
         variables.append(*varStack[i].first);
     codeBlock->adoptVariables(variables);
-    codeBlock->m_numCapturedVars = codeBlock->m_numVars;
     preserveLastVar();
 }
 
+BytecodeGenerator::~BytecodeGenerator()
+{
+}
+
 RegisterID* BytecodeGenerator::emitInitLazyRegister(RegisterID* reg)
 {
     emitOpcode(op_init_lazy_reg);
@@ -540,6 +461,42 @@ RegisterID* BytecodeGenerator::emitInitLazyRegister(RegisterID* reg)
     return reg;
 }
 
+RegisterID* BytecodeGenerator::resolveCallee(FunctionBodyNode* functionBodyNode)
+{
+    if (functionBodyNode->ident().isNull() || !functionBodyNode->functionNameIsInScope())
+        return 0;
+
+    m_calleeRegister.setIndex(JSStack::Callee);
+
+    // If non-strict eval is in play, we use a separate object in the scope chain for the callee's name.
+    if ((m_codeBlock->usesEval() && !m_codeBlock->isStrictMode()) || m_shouldEmitDebugHooks) {
+        emitOpcode(op_push_name_scope);
+        instructions().append(addConstant(functionBodyNode->ident()));
+        instructions().append(m_calleeRegister.index());
+        instructions().append(ReadOnly | DontDelete);
+        return 0;
+    }
+
+    if (!functionBodyNode->captures(functionBodyNode->ident()))
+        return &m_calleeRegister;
+
+    // Move the callee into the captured section of the stack.
+    return emitMove(addVar(), &m_calleeRegister);
+}
+
+void BytecodeGenerator::addCallee(FunctionBodyNode* functionBodyNode, RegisterID* calleeRegister)
+{
+    if (functionBodyNode->ident().isNull() || !functionBodyNode->functionNameIsInScope())
+        return;
+
+    // If non-strict eval is in play, we use a separate object in the scope chain for the callee's name.
+    if ((m_codeBlock->usesEval() && !m_codeBlock->isStrictMode()) || m_shouldEmitDebugHooks)
+        return;
+
+    ASSERT(calleeRegister);
+    symbolTable().add(functionBodyNode->ident().impl(), SymbolTableEntry(calleeRegister->index(), ReadOnly));
+}
+
 void BytecodeGenerator::addParameter(const Identifier& ident, int parameterIndex)
 {
     // Parameters overwrite var declarations, but not function declarations.
@@ -552,25 +509,7 @@ void BytecodeGenerator::addParameter(const Identifier& ident, int parameterIndex
 
     // To maintain the calling convention, we have to allocate unique space for
     // each parameter, even if the parameter doesn't make it into the symbol table.
-    ++m_codeBlock->m_numParameters;
-}
-
-RegisterID* BytecodeGenerator::registerFor(const Identifier& ident)
-{
-    if (ident == propertyNames().thisIdentifier)
-        return &m_thisRegister;
-
-    if (!shouldOptimizeLocals())
-        return 0;
-
-    SymbolTableEntry entry = symbolTable().get(ident.impl());
-    if (entry.isNull())
-        return 0;
-
-    if (ident == propertyNames().arguments)
-        createArgumentsIfNecessary();
-
-    return createLazyRegisterIfNecessary(&registerFor(entry.getIndex()));
+    m_codeBlock->addParameter();
 }
 
 bool BytecodeGenerator::willResolveToArguments(const Identifier& ident)
@@ -584,7 +523,7 @@ bool BytecodeGenerator::willResolveToArguments(const Identifier& ident)
     SymbolTableEntry entry = symbolTable().get(ident.impl());
     if (entry.isNull())
         return false;
-    
+
     if (m_codeBlock->usesArguments() && m_codeType == FunctionCode)
         return true;
     
@@ -608,31 +547,6 @@ RegisterID* BytecodeGenerator::createLazyRegisterIfNecessary(RegisterID* reg)
     return reg;
 }
 
-RegisterID* BytecodeGenerator::constRegisterFor(const Identifier& ident)
-{
-    if (m_codeType == EvalCode)
-        return 0;
-
-    SymbolTableEntry entry = symbolTable().get(ident.impl());
-    if (entry.isNull())
-        return 0;
-
-    return createLazyRegisterIfNecessary(&registerFor(entry.getIndex()));
-}
-
-bool BytecodeGenerator::isLocal(const Identifier& ident)
-{
-    if (ident == propertyNames().thisIdentifier)
-        return true;
-    
-    return shouldOptimizeLocals() && symbolTable().contains(ident.impl());
-}
-
-bool BytecodeGenerator::isLocalConstant(const Identifier& ident)
-{
-    return symbolTable().get(ident.impl()).isReadOnly();
-}
-
 RegisterID* BytecodeGenerator::newRegister()
 {
     m_calleeRegisters.append(m_calleeRegisters.size());
@@ -651,15 +565,7 @@ RegisterID* BytecodeGenerator::newTemporary()
     return result;
 }
 
-RegisterID* BytecodeGenerator::highestUsedRegister()
-{
-    size_t count = m_codeBlock->m_numCalleeRegisters;
-    while (m_calleeRegisters.size() < count)
-        newRegister();
-    return &m_calleeRegisters.last();
-}
-
-PassRefPtr<LabelScope> BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
+LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
 {
     // Reclaim free label scopes.
     while (m_labelScopes.size() && !m_labelScopes.last().refCount())
@@ -668,7 +574,7 @@ PassRefPtr<LabelScope> BytecodeGenerator::newLabelScope(LabelScope::Type type, c
     // Allocate new label scope.
     LabelScope scope(type, name, scopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr<Label>()); // Only loops have continue targets.
     m_labelScopes.append(scope);
-    return &m_labelScopes.last();
+    return LabelScopePtr(&m_labelScopes, m_labelScopes.size() - 1);
 }
 
 PassRefPtr<Label> BytecodeGenerator::newLabel()
@@ -678,7 +584,7 @@ PassRefPtr<Label> BytecodeGenerator::newLabel()
         m_labels.removeLast();
 
     // Allocate new label ID.
-    m_labels.append(m_codeBlock);
+    m_labels.append(this);
     return &m_labels.last();
 }
 
@@ -710,10 +616,49 @@ void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
     ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
     m_lastOpcodePosition = opcodePosition;
 #endif
-    instructions().append(globalData()->interpreter->getOpcode(opcodeID));
+    instructions().append(opcodeID);
     m_lastOpcodeID = opcodeID;
 }
 
+UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
+{
+#if ENABLE(VALUE_PROFILER)
+    return m_codeBlock->addArrayProfile();
+#else
+    return 0;
+#endif
+}
+
+UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
+{
+#if ENABLE(VALUE_PROFILER)
+    return m_codeBlock->addArrayAllocationProfile();
+#else
+    return 0;
+#endif
+}
+
+UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
+{
+    return m_codeBlock->addObjectAllocationProfile();
+}
+
+UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
+{
+#if ENABLE(VALUE_PROFILER)
+    UnlinkedValueProfile result = m_codeBlock->addValueProfile();
+#else
+    UnlinkedValueProfile result = 0;
+#endif
+    emitOpcode(opcodeID);
+    return result;
+}
+
+void BytecodeGenerator::emitLoopHint()
+{
+    emitOpcode(op_loop_hint);
+}
+
 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
 {
     ASSERT(instructions().size() >= 4);
@@ -748,7 +693,7 @@ void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
 PassRefPtr<Label> BytecodeGenerator::emitJump(Label* target)
 {
     size_t begin = instructions().size();
-    emitOpcode(target->isForward() ? op_jmp : op_loop);
+    emitOpcode(op_jmp);
     instructions().append(target->bind(begin, instructions().size()));
     return target;
 }
@@ -766,7 +711,7 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* tar
             rewindBinaryOp();
 
             size_t begin = instructions().size();
-            emitOpcode(target->isForward() ? op_jless : op_loop_if_less);
+            emitOpcode(op_jless);
             instructions().append(src1Index);
             instructions().append(src2Index);
             instructions().append(target->bind(begin, instructions().size()));
@@ -783,7 +728,41 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* tar
             rewindBinaryOp();
 
             size_t begin = instructions().size();
-            emitOpcode(target->isForward() ? op_jlesseq : op_loop_if_lesseq);
+            emitOpcode(op_jlesseq);
+            instructions().append(src1Index);
+            instructions().append(src2Index);
+            instructions().append(target->bind(begin, instructions().size()));
+            return target;
+        }
+    } else if (m_lastOpcodeID == op_greater) {
+        int dstIndex;
+        int src1Index;
+        int src2Index;
+
+        retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
+
+        if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
+            rewindBinaryOp();
+
+            size_t begin = instructions().size();
+            emitOpcode(op_jgreater);
+            instructions().append(src1Index);
+            instructions().append(src2Index);
+            instructions().append(target->bind(begin, instructions().size()));
+            return target;
+        }
+    } else if (m_lastOpcodeID == op_greatereq) {
+        int dstIndex;
+        int src1Index;
+        int src2Index;
+
+        retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
+
+        if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
+            rewindBinaryOp();
+
+            size_t begin = instructions().size();
+            emitOpcode(op_jgreatereq);
             instructions().append(src1Index);
             instructions().append(src2Index);
             instructions().append(target->bind(begin, instructions().size()));
@@ -823,7 +802,7 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* tar
 
     size_t begin = instructions().size();
 
-    emitOpcode(target->isForward() ? op_jtrue : op_loop_if_true);
+    emitOpcode(op_jtrue);
     instructions().append(cond->index());
     instructions().append(target->bind(begin, instructions().size()));
     return target;
@@ -865,6 +844,40 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* ta
             instructions().append(target->bind(begin, instructions().size()));
             return target;
         }
+    } else if (m_lastOpcodeID == op_greater && target->isForward()) {
+        int dstIndex;
+        int src1Index;
+        int src2Index;
+
+        retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
+
+        if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
+            rewindBinaryOp();
+
+            size_t begin = instructions().size();
+            emitOpcode(op_jngreater);
+            instructions().append(src1Index);
+            instructions().append(src2Index);
+            instructions().append(target->bind(begin, instructions().size()));
+            return target;
+        }
+    } else if (m_lastOpcodeID == op_greatereq && target->isForward()) {
+        int dstIndex;
+        int src1Index;
+        int src2Index;
+
+        retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
+
+        if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
+            rewindBinaryOp();
+
+            size_t begin = instructions().size();
+            emitOpcode(op_jngreatereq);
+            instructions().append(src1Index);
+            instructions().append(src2Index);
+            instructions().append(target->bind(begin, instructions().size()));
+            return target;
+        }
     } else if (m_lastOpcodeID == op_not) {
         int dstIndex;
         int srcIndex;
@@ -875,7 +888,7 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* ta
             rewindUnaryOp();
 
             size_t begin = instructions().size();
-            emitOpcode(target->isForward() ? op_jtrue : op_loop_if_true);
+            emitOpcode(op_jtrue);
             instructions().append(srcIndex);
             instructions().append(target->bind(begin, instructions().size()));
             return target;
@@ -913,7 +926,7 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* ta
     }
 
     size_t begin = instructions().size();
-    emitOpcode(target->isForward() ? op_jfalse : op_loop_if_false);
+    emitOpcode(op_jfalse);
     instructions().append(cond->index());
     instructions().append(target->bind(begin, instructions().size()));
     return target;
@@ -925,7 +938,7 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond,
 
     emitOpcode(op_jneq_ptr);
     instructions().append(cond->index());
-    instructions().append(Instruction(*m_globalData, m_codeBlock->ownerExecutable(), m_scopeChain->globalObject->callFunction()));
+    instructions().append(Special::CallFunction);
     instructions().append(target->bind(begin, instructions().size()));
     return target;
 }
@@ -936,7 +949,7 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond
 
     emitOpcode(op_jneq_ptr);
     instructions().append(cond->index());
-    instructions().append(Instruction(*m_globalData, m_codeBlock->ownerExecutable(), m_scopeChain->globalObject->applyFunction()));
+    instructions().append(Special::ApplyFunction);
     instructions().append(target->bind(begin, instructions().size()));
     return target;
 }
@@ -944,25 +957,40 @@ PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond
 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
 {
     StringImpl* rep = ident.impl();
-    pair<IdentifierMap::iterator, bool> result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
-    if (result.second) // new entry
-        m_codeBlock->addIdentifier(Identifier(m_globalData, rep));
+    IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
+    if (result.isNewEntry)
+        m_codeBlock->addIdentifier(Identifier(m_vm, rep));
+
+    return result.iterator->value;
+}
+
+// We can't hash JSValue(), so we use a dedicated data member to cache it.
+RegisterID* BytecodeGenerator::addConstantEmptyValue()
+{
+    if (!m_emptyValueRegister) {
+        int index = m_nextConstantOffset;
+        m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
+        ++m_nextConstantOffset;
+        m_codeBlock->addConstant(JSValue());
+        m_emptyValueRegister = &m_constantPoolRegisters[index];
+    }
 
-    return result.first->second;
+    return m_emptyValueRegister;
 }
 
 RegisterID* BytecodeGenerator::addConstantValue(JSValue v)
 {
-    int index = m_nextConstantOffset;
+    if (!v)
+        return addConstantEmptyValue();
 
-    pair<JSValueMap::iterator, bool> result = m_jsValueMap.add(JSValue::encode(v), m_nextConstantOffset);
-    if (result.second) {
+    int index = m_nextConstantOffset;
+    JSValueMap::AddResult result = m_jsValueMap.add(JSValue::encode(v), m_nextConstantOffset);
+    if (result.isNewEntry) {
         m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
         ++m_nextConstantOffset;
-        m_codeBlock->addConstant(JSValue(v));
+        m_codeBlock->addConstant(v);
     } else
-        index = result.first->second;
-
+        index = result.iterator->value;
     return &m_constantPoolRegisters[index];
 }
 
@@ -973,6 +1001,8 @@ unsigned BytecodeGenerator::addRegExp(RegExp* r)
 
 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
 {
+    m_staticPropertyAnalyzer.mov(dst->index(), src->index());
+
     emitOpcode(op_mov);
     instructions().append(dst->index());
     instructions().append(src->index());
@@ -987,36 +1017,20 @@ RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, R
     return dst;
 }
 
-RegisterID* BytecodeGenerator::emitPreInc(RegisterID* srcDst)
+RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
 {
-    emitOpcode(op_pre_inc);
+    emitOpcode(op_inc);
     instructions().append(srcDst->index());
     return srcDst;
 }
 
-RegisterID* BytecodeGenerator::emitPreDec(RegisterID* srcDst)
+RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
 {
-    emitOpcode(op_pre_dec);
+    emitOpcode(op_dec);
     instructions().append(srcDst->index());
     return srcDst;
 }
 
-RegisterID* BytecodeGenerator::emitPostInc(RegisterID* dst, RegisterID* srcDst)
-{
-    emitOpcode(op_post_inc);
-    instructions().append(dst->index());
-    instructions().append(srcDst->index());
-    return dst;
-}
-
-RegisterID* BytecodeGenerator::emitPostDec(RegisterID* dst, RegisterID* srcDst)
-{
-    emitOpcode(op_post_dec);
-    instructions().append(dst->index());
-    instructions().append(srcDst->index());
-    return dst;
-}
-
 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
 {
     emitOpcode(opcodeID);
@@ -1043,7 +1057,7 @@ RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst
             && src1->isTemporary()
             && m_codeBlock->isConstantRegisterIndex(src2->index())
             && m_codeBlock->constantRegister(src2->index()).get().isString()) {
-            const UString& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
+            const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
             if (value == "undefined") {
                 rewindUnaryOp();
                 emitOpcode(op_is_undefined);
@@ -1106,9 +1120,9 @@ RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, double number)
     // FIXME: Our hash tables won't hold infinity, so we make a new JSValue each time.
     // Later we can do the extra work to handle that like the other cases.  They also don't
     // work correctly with NaN as a key.
-    if (isnan(number) || number == HashTraits<double>::emptyValue() || HashTraits<double>::isDeletedValue(number))
+    if (std::isnan(number) || number == HashTraits<double>::emptyValue() || HashTraits<double>::isDeletedValue(number))
         return emitLoad(dst, jsNumber(number));
-    JSValue& valueInMap = m_numberMap.add(number, JSValue()).first->second;
+    JSValue& valueInMap = m_numberMap.add(number, JSValue()).iterator->value;
     if (!valueInMap)
         valueInMap = jsNumber(number);
     return emitLoad(dst, valueInMap);
@@ -1116,9 +1130,9 @@ RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, double number)
 
 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
 {
-    JSString*& stringInMap = m_stringMap.add(identifier.impl(), 0).first->second;
+    JSString*& stringInMap = m_stringMap.add(identifier.impl(), 0).iterator->value;
     if (!stringInMap)
-        stringInMap = jsOwnedString(globalData(), identifier.ustring());
+        stringInMap = jsOwnedString(vm(), identifier.string());
     return emitLoad(dst, JSValue(stringInMap));
 }
 
@@ -1126,299 +1140,272 @@ RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v)
 {
     RegisterID* constantID = addConstantValue(v);
     if (dst)
-        return emitMove(dst, constantID);
-    return constantID;
+        return emitMove(dst, constantID);
+    return constantID;
+}
+
+RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
+{
+    if (!m_globalObjectRegister) {
+        int index = m_nextConstantOffset;
+        m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
+        ++m_nextConstantOffset;
+        m_codeBlock->addConstant(JSValue());
+        m_globalObjectRegister = &m_constantPoolRegisters[index];
+        m_codeBlock->setGlobalObjectRegister(index);
+    }
+    if (dst)
+        emitMove(dst, m_globalObjectRegister);
+    return m_globalObjectRegister;
 }
 
-bool BytecodeGenerator::findScopedProperty(const Identifier& property, int& index, size_t& stackDepth, bool forWriting, bool& requiresDynamicChecks, JSObject*& globalObject)
+ResolveResult BytecodeGenerator::resolve(const Identifier& property)
 {
-    // Cases where we cannot statically optimize the lookup.
-    if (property == propertyNames().arguments || !canOptimizeNonLocals()) {
-        stackDepth = 0;
-        index = missingSymbolMarker();
-
-        if (shouldOptimizeLocals() && m_codeType == GlobalCode) {
-            ScopeChainIterator iter = m_scopeChain->begin();
-            globalObject = iter->get();
-            ASSERT((++iter) == m_scopeChain->end());
+    if (property == propertyNames().thisIdentifier)
+        return ResolveResult::registerResolve(thisRegister(), ResolveResult::ReadOnlyFlag);
+
+    // Check if the property should be allocated in a register.
+    if (m_codeType != GlobalCode && shouldOptimizeLocals() && m_symbolTable) {
+        SymbolTableEntry entry = symbolTable().get(property.impl());
+        if (!entry.isNull()) {
+            if (property == propertyNames().arguments)
+                createArgumentsIfNecessary();
+            unsigned flags = entry.isReadOnly() ? ResolveResult::ReadOnlyFlag : 0;
+            RegisterID* local = createLazyRegisterIfNecessary(&registerFor(entry.getIndex()));
+            return ResolveResult::registerResolve(local, flags);
         }
-        return false;
     }
+    // Cases where we cannot statically optimize the lookup.
+    if (property == propertyNames().arguments || !canOptimizeNonLocals())
+        return ResolveResult::dynamicResolve();
 
-    size_t depth = 0;
-    requiresDynamicChecks = false;
-    ScopeChainIterator iter = m_scopeChain->begin();
-    ScopeChainIterator end = m_scopeChain->end();
+    if (!m_scope || m_codeType != FunctionCode || m_shouldEmitDebugHooks)
+        return ResolveResult::dynamicResolve();
+
+    ScopeChainIterator iter = m_scope->begin();
+    ScopeChainIterator end = m_scope->end();
+    size_t depth = m_codeBlock->needsFullScopeChain();
+    unsigned flags = 0;
     for (; iter != end; ++iter, ++depth) {
-        JSObject* currentScope = iter->get();
-        if (!currentScope->isVariableObject())
-            break;
-        JSVariableObject* currentVariableObject = static_cast<JSVariableObject*>(currentScope);
-        SymbolTableEntry entry = currentVariableObject->symbolTable().get(property.impl());
+        JSObject* currentScope = iter.get();
+        if (!currentScope->isStaticScopeObject())
+            return ResolveResult::dynamicResolve();
+
+        JSSymbolTableObject* currentVariableObject = jsCast<JSSymbolTableObject*>(currentScope);
+        SymbolTableEntry entry = currentVariableObject->symbolTable()->get(property.impl());
 
         // Found the property
         if (!entry.isNull()) {
-            if (entry.isReadOnly() && forWriting) {
-                stackDepth = 0;
-                index = missingSymbolMarker();
-                if (++iter == end)
-                    globalObject = currentVariableObject;
-                return false;
-            }
-            stackDepth = depth + m_codeBlock->needsFullScopeChain();
-            index = entry.getIndex();
+            if (entry.isReadOnly())
+                flags |= ResolveResult::ReadOnlyFlag;
             if (++iter == end)
-                globalObject = currentVariableObject;
-            return true;
+                return ResolveResult::dynamicResolve();
+#if !ASSERT_DISABLED
+            if (JSActivation* activation = jsDynamicCast<JSActivation*>(currentVariableObject))
+                ASSERT(activation->isValid(entry));
+#endif
+            return ResolveResult::lexicalResolve(entry.getIndex(), depth, flags);
         }
         bool scopeRequiresDynamicChecks = false;
         if (currentVariableObject->isDynamicScope(scopeRequiresDynamicChecks))
             break;
-        requiresDynamicChecks |= scopeRequiresDynamicChecks;
+        if (scopeRequiresDynamicChecks)
+            flags |= ResolveResult::DynamicFlag;
     }
-    // Can't locate the property but we're able to avoid a few lookups.
-    stackDepth = depth + m_codeBlock->needsFullScopeChain();
-    index = missingSymbolMarker();
-    JSObject* scope = iter->get();
-    if (++iter == end)
-        globalObject = scope;
-    return true;
+
+    return ResolveResult::dynamicResolve();
 }
 
-void BytecodeGenerator::emitCheckHasInstance(RegisterID* base)
-{ 
+ResolveResult BytecodeGenerator::resolveConstDecl(const Identifier& property)
+{
+    // Register-allocated const declarations.
+    if (m_codeType == FunctionCode && m_symbolTable) {
+        SymbolTableEntry entry = symbolTable().get(property.impl());
+        if (!entry.isNull()) {
+            unsigned flags = entry.isReadOnly() ? ResolveResult::ReadOnlyFlag : 0;
+            RegisterID* local = createLazyRegisterIfNecessary(&registerFor(entry.getIndex()));
+            return ResolveResult::registerResolve(local, flags);
+        }
+    }
+
+    return ResolveResult::dynamicResolve();
+}
+
+void BytecodeGenerator::emitCheckHasInstance(RegisterID* dst, RegisterID* value, RegisterID* base, Label* target)
+{
+    size_t begin = instructions().size();
     emitOpcode(op_check_has_instance);
+    instructions().append(dst->index());
+    instructions().append(value->index());
     instructions().append(base->index());
+    instructions().append(target->bind(begin, instructions().size()));
 }
 
-RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* base, RegisterID* basePrototype)
+RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
 { 
     emitOpcode(op_instanceof);
     instructions().append(dst->index());
     instructions().append(value->index());
-    instructions().append(base->index());
     instructions().append(basePrototype->index());
     return dst;
 }
 
-static const unsigned maxGlobalResolves = 128;
-
 bool BytecodeGenerator::shouldAvoidResolveGlobal()
 {
-    return m_codeBlock->globalResolveInfoCount() > maxGlobalResolves && !m_labelScopes.size();
+    return !m_labelScopes.size();
 }
 
-RegisterID* BytecodeGenerator::emitResolve(RegisterID* dst, const Identifier& property)
+RegisterID* BytecodeGenerator::emitResolve(RegisterID* dst, const ResolveResult& resolveResult, const Identifier& property)
 {
-    size_t depth = 0;
-    int index = 0;
-    JSObject* globalObject = 0;
-    bool requiresDynamicChecks = false;
-    if (!findScopedProperty(property, index, depth, false, requiresDynamicChecks, globalObject) && !globalObject) {
-        // We can't optimise at all :-(
-        emitOpcode(op_resolve);
-        instructions().append(dst->index());
-        instructions().append(addConstant(property));
-        return dst;
-    }
-    if (shouldAvoidResolveGlobal()) {
-        globalObject = 0;
-        requiresDynamicChecks = true;
-    }
-        
-    if (globalObject) {
-        bool forceGlobalResolve = false;
-
-        if (index != missingSymbolMarker() && !forceGlobalResolve && !requiresDynamicChecks) {
-            // Directly index the property lookup across multiple scopes.
-            return emitGetScopedVar(dst, depth, index, globalObject);
-        }
 
-#if ENABLE(JIT)
-        m_codeBlock->addGlobalResolveInfo(instructions().size());
-#endif
-#if ENABLE(INTERPRETER)
-        m_codeBlock->addGlobalResolveInstruction(instructions().size());
-#endif
-        emitOpcode(requiresDynamicChecks ? op_resolve_global_dynamic : op_resolve_global);
-        instructions().append(dst->index());
-        instructions().append(addConstant(property));
-        instructions().append(0);
-        instructions().append(0);
-        if (requiresDynamicChecks)
-            instructions().append(depth);
-        return dst;
-    }
+    if (resolveResult.isStatic())
+        return emitGetStaticVar(dst, resolveResult, property);
 
-    if (requiresDynamicChecks) {
-        // If we get here we have eval nested inside a |with| just give up
-        emitOpcode(op_resolve);
-        instructions().append(dst->index());
-        instructions().append(addConstant(property));
-        return dst;
-    }
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve);
+    instructions().append(kill(dst));
+    instructions().append(addConstant(property));
+    instructions().append(getResolveOperations(property));
+    instructions().append(profile);
+    return dst;
+}
 
-    if (index != missingSymbolMarker()) {
-        // Directly index the property lookup across multiple scopes.
-        return emitGetScopedVar(dst, depth, index, globalObject);
+RegisterID* BytecodeGenerator::emitResolveBase(RegisterID* dst, const ResolveResult& resolveResult, const Identifier& property)
+{
+    if (!resolveResult.isDynamic()) {
+        // Global object is the base
+        return emitLoadGlobalObject(dst);
     }
 
-    // In this case we are at least able to drop a few scope chains from the
-    // lookup chain, although we still need to hash from then on.
-    emitOpcode(op_resolve_skip);
-    instructions().append(dst->index());
+    // We can't optimise at all :-(
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_base);
+    instructions().append(kill(dst));
     instructions().append(addConstant(property));
-    instructions().append(depth);
+    instructions().append(false);
+    instructions().append(getResolveBaseOperations(property));
+    instructions().append(0);
+    instructions().append(profile);
     return dst;
 }
 
-RegisterID* BytecodeGenerator::emitGetScopedVar(RegisterID* dst, size_t depth, int index, JSValue globalObject)
+RegisterID* BytecodeGenerator::emitResolveBaseForPut(RegisterID* dst, const ResolveResult&, const Identifier& property, NonlocalResolveInfo& verifier)
 {
-    if (globalObject) {
-        emitOpcode(op_get_global_var);
-        instructions().append(dst->index());
-        instructions().append(index);
-        return dst;
-    }
-
-    emitOpcode(op_get_scoped_var);
-    instructions().append(dst->index());
-    instructions().append(index);
-    instructions().append(depth);
+    // We can't optimise at all :-(
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_base);
+    instructions().append(kill(dst));
+    instructions().append(addConstant(property));
+    instructions().append(m_codeBlock->isStrictMode());
+    uint32_t putToBaseIndex = 0;
+    instructions().append(getResolveBaseForPutOperations(property, putToBaseIndex));
+    verifier.resolved(putToBaseIndex);
+    instructions().append(putToBaseIndex);
+    instructions().append(profile);
     return dst;
 }
 
-RegisterID* BytecodeGenerator::emitPutScopedVar(size_t depth, int index, RegisterID* value, JSValue globalObject)
+RegisterID* BytecodeGenerator::emitResolveWithBaseForPut(RegisterID* baseDst, RegisterID* propDst, const ResolveResult& resolveResult, const Identifier& property, NonlocalResolveInfo& verifier)
 {
-    if (globalObject) {
-        emitOpcode(op_put_global_var);
-        instructions().append(index);
-        instructions().append(value->index());
-        return value;
-    }
-    emitOpcode(op_put_scoped_var);
-    instructions().append(index);
-    instructions().append(depth);
-    instructions().append(value->index());
-    return value;
+    ASSERT_UNUSED(resolveResult, !resolveResult.isStatic());
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_with_base);
+    instructions().append(kill(baseDst));
+    instructions().append(propDst->index());
+    instructions().append(addConstant(property));
+    uint32_t putToBaseIndex = 0;
+    instructions().append(getResolveWithBaseForPutOperations(property, putToBaseIndex));
+    verifier.resolved(putToBaseIndex);
+    instructions().append(putToBaseIndex);
+    instructions().append(profile);
+    return baseDst;
 }
 
-RegisterID* BytecodeGenerator::emitResolveBase(RegisterID* dst, const Identifier& property)
+RegisterID* BytecodeGenerator::emitResolveWithThis(RegisterID* baseDst, RegisterID* propDst, const ResolveResult& resolveResult, const Identifier& property)
 {
-    size_t depth = 0;
-    int index = 0;
-    JSObject* globalObject = 0;
-    bool requiresDynamicChecks = false;
-    findScopedProperty(property, index, depth, false, requiresDynamicChecks, globalObject);
-    if (!globalObject || requiresDynamicChecks) {
-        // We can't optimise at all :-(
-        emitOpcode(op_resolve_base);
-        instructions().append(dst->index());
-        instructions().append(addConstant(property));
-        instructions().append(false);
-        return dst;
+    if (resolveResult.isStatic()) {
+        emitLoad(baseDst, jsUndefined());
+        emitGetStaticVar(propDst, resolveResult, property);
+        return baseDst;
     }
 
-    // Global object is the base
-    return emitLoad(dst, JSValue(globalObject));
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_with_this);
+    instructions().append(kill(baseDst));
+    instructions().append(propDst->index());
+    instructions().append(addConstant(property));
+    instructions().append(getResolveWithThisOperations(property));
+    instructions().append(profile);
+    return baseDst;
 }
 
-RegisterID* BytecodeGenerator::emitResolveBaseForPut(RegisterID* dst, const Identifier& property)
+RegisterID* BytecodeGenerator::emitGetStaticVar(RegisterID* dst, const ResolveResult& resolveResult, const Identifier&)
 {
-    if (!m_codeBlock->isStrictMode())
-        return emitResolveBase(dst, property);
-    size_t depth = 0;
-    int index = 0;
-    JSObject* globalObject = 0;
-    bool requiresDynamicChecks = false;
-    findScopedProperty(property, index, depth, false, requiresDynamicChecks, globalObject);
-    if (!globalObject || requiresDynamicChecks) {
-        // We can't optimise at all :-(
-        emitOpcode(op_resolve_base);
+    ASSERT(m_codeType == FunctionCode);
+    switch (resolveResult.type()) {
+    case ResolveResult::Register:
+    case ResolveResult::ReadOnlyRegister:
+        if (dst == ignoredResult())
+            return 0;
+        return moveToDestinationIfNeeded(dst, resolveResult.local());
+
+    case ResolveResult::Lexical:
+    case ResolveResult::ReadOnlyLexical: {
+        UnlinkedValueProfile profile = emitProfiledOpcode(op_get_scoped_var);
         instructions().append(dst->index());
-        instructions().append(addConstant(property));
-        instructions().append(true);
+        instructions().append(resolveResult.index());
+        instructions().append(resolveResult.depth());
+        instructions().append(profile);
         return dst;
     }
-    
-    // Global object is the base
-    RefPtr<RegisterID> result = emitLoad(dst, JSValue(globalObject));
-    emitOpcode(op_ensure_property_exists);
-    instructions().append(dst->index());
-    instructions().append(addConstant(property));
-    return result.get();
-}
 
-RegisterID* BytecodeGenerator::emitResolveWithBase(RegisterID* baseDst, RegisterID* propDst, const Identifier& property)
-{
-    size_t depth = 0;
-    int index = 0;
-    JSObject* globalObject = 0;
-    bool requiresDynamicChecks = false;
-    if (!findScopedProperty(property, index, depth, false, requiresDynamicChecks, globalObject) || !globalObject || requiresDynamicChecks) {
-        // We can't optimise at all :-(
-        emitOpcode(op_resolve_with_base);
-        instructions().append(baseDst->index());
-        instructions().append(propDst->index());
-        instructions().append(addConstant(property));
-        return baseDst;
+    default:
+        RELEASE_ASSERT_NOT_REACHED();
+        return 0;
     }
+}
 
-    bool forceGlobalResolve = false;
-
-    // Global object is the base
-    emitLoad(baseDst, JSValue(globalObject));
-
-    if (index != missingSymbolMarker() && !forceGlobalResolve) {
-        // Directly index the property lookup across multiple scopes.
-        emitGetScopedVar(propDst, depth, index, globalObject);
-        return baseDst;
-    }
-    if (shouldAvoidResolveGlobal()) {
-        emitOpcode(op_resolve);
-        instructions().append(propDst->index());
-        instructions().append(addConstant(property));
-        return baseDst;
-    }
-#if ENABLE(JIT)
-    m_codeBlock->addGlobalResolveInfo(instructions().size());
-#endif
-#if ENABLE(INTERPRETER)
-    m_codeBlock->addGlobalResolveInstruction(instructions().size());
-#endif
-    emitOpcode(requiresDynamicChecks ? op_resolve_global_dynamic : op_resolve_global);
-    instructions().append(propDst->index());
-    instructions().append(addConstant(property));
+RegisterID* BytecodeGenerator::emitInitGlobalConst(const Identifier& identifier, RegisterID* value)
+{
+    ASSERT(m_codeType == GlobalCode);
+    emitOpcode(op_init_global_const_nop);
     instructions().append(0);
+    instructions().append(value->index());
     instructions().append(0);
-    if (requiresDynamicChecks)
-        instructions().append(depth);
-    return baseDst;
+    instructions().append(addConstant(identifier));
+    return value;
 }
 
-void BytecodeGenerator::emitMethodCheck()
+RegisterID* BytecodeGenerator::emitPutStaticVar(const ResolveResult& resolveResult, const Identifier&, RegisterID* value)
 {
-    emitOpcode(op_method_check);
+    ASSERT(m_codeType == FunctionCode);
+    switch (resolveResult.type()) {
+    case ResolveResult::Register:
+    case ResolveResult::ReadOnlyRegister:
+        return moveToDestinationIfNeeded(resolveResult.local(), value);
+
+    case ResolveResult::Lexical:
+    case ResolveResult::ReadOnlyLexical:
+        emitOpcode(op_put_scoped_var);
+        instructions().append(resolveResult.index());
+        instructions().append(resolveResult.depth());
+        instructions().append(value->index());
+        return value;
+
+    default:
+        RELEASE_ASSERT_NOT_REACHED();
+        return 0;
+    }
 }
 
 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
 {
-#if ENABLE(JIT)
-    m_codeBlock->addStructureStubInfo(StructureStubInfo(access_get_by_id));
-#endif
-    
-#if ENABLE(INTERPRETER)
     m_codeBlock->addPropertyAccessInstruction(instructions().size());
-#endif
 
-    emitOpcode(op_get_by_id);
-    instructions().append(dst->index());
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
+    instructions().append(kill(dst));
     instructions().append(base->index());
     instructions().append(addConstant(property));
     instructions().append(0);
     instructions().append(0);
     instructions().append(0);
     instructions().append(0);
+    instructions().append(profile);
     return dst;
 }
 
@@ -1434,16 +1421,15 @@ RegisterID* BytecodeGenerator::emitGetArgumentsLength(RegisterID* dst, RegisterI
 
 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
 {
-#if ENABLE(JIT)
-    m_codeBlock->addStructureStubInfo(StructureStubInfo(access_put_by_id));
-#endif
-#if ENABLE(INTERPRETER)
+    unsigned propertyIndex = addConstant(property);
+
+    m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
+
     m_codeBlock->addPropertyAccessInstruction(instructions().size());
-#endif
 
     emitOpcode(op_put_by_id);
     instructions().append(base->index());
-    instructions().append(addConstant(property));
+    instructions().append(propertyIndex);
     instructions().append(value->index());
     instructions().append(0);
     instructions().append(0);
@@ -1453,43 +1439,49 @@ RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& p
     return value;
 }
 
+RegisterID* BytecodeGenerator::emitPutToBase(RegisterID* base, const Identifier& property, RegisterID* value, NonlocalResolveInfo& resolveInfo)
+{
+    emitOpcode(op_put_to_base);
+    instructions().append(base->index());
+    instructions().append(addConstant(property));
+    instructions().append(value->index());
+    instructions().append(resolveInfo.put());
+    return value;
+}
+
 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value)
 {
-#if ENABLE(JIT)
-    m_codeBlock->addStructureStubInfo(StructureStubInfo(access_put_by_id));
-#endif
-#if ENABLE(INTERPRETER)
+    unsigned propertyIndex = addConstant(property);
+
+    m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
+
     m_codeBlock->addPropertyAccessInstruction(instructions().size());
-#endif
     
     emitOpcode(op_put_by_id);
     instructions().append(base->index());
-    instructions().append(addConstant(property));
+    instructions().append(propertyIndex);
     instructions().append(value->index());
     instructions().append(0);
     instructions().append(0);
     instructions().append(0);
     instructions().append(0);
-    instructions().append(property != m_globalData->propertyNames->underscoreProto);
+    instructions().append(
+        property != m_vm->propertyNames->underscoreProto
+        && PropertyName(property).asIndex() == PropertyName::NotAnIndex);
     return value;
 }
 
-RegisterID* BytecodeGenerator::emitPutGetter(RegisterID* base, const Identifier& property, RegisterID* value)
+void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, RegisterID* getter, RegisterID* setter)
 {
-    emitOpcode(op_put_getter);
-    instructions().append(base->index());
-    instructions().append(addConstant(property));
-    instructions().append(value->index());
-    return value;
-}
+    unsigned propertyIndex = addConstant(property);
 
-RegisterID* BytecodeGenerator::emitPutSetter(RegisterID* base, const Identifier& property, RegisterID* value)
-{
-    emitOpcode(op_put_setter);
+    m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
+
+    emitOpcode(op_put_getter_setter);
     instructions().append(base->index());
-    instructions().append(addConstant(property));
-    instructions().append(value->index());
-    return value;
+    instructions().append(propertyIndex);
+    instructions().append(getter->index());
+    instructions().append(setter->index());
 }
 
 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
@@ -1503,11 +1495,14 @@ RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base,
 
 RegisterID* BytecodeGenerator::emitGetArgumentByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
 {
-    emitOpcode(op_get_argument_by_val);
-    instructions().append(dst->index());
+    UnlinkedArrayProfile arrayProfile = newArrayProfile();
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument_by_val);
+    instructions().append(kill(dst));
     ASSERT(base->index() == m_codeBlock->argumentsRegister());
     instructions().append(base->index());
     instructions().append(property->index());
+    instructions().append(arrayProfile);
+    instructions().append(profile);
     return dst;
 }
 
@@ -1526,19 +1521,24 @@ RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, R
             return dst;
         }
     }
-    emitOpcode(op_get_by_val);
-    instructions().append(dst->index());
+    UnlinkedArrayProfile arrayProfile = newArrayProfile();
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
+    instructions().append(kill(dst));
     instructions().append(base->index());
     instructions().append(property->index());
+    instructions().append(arrayProfile);
+    instructions().append(profile);
     return dst;
 }
 
 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
 {
+    UnlinkedArrayProfile arrayProfile = newArrayProfile();
     emitOpcode(op_put_by_val);
     instructions().append(base->index());
     instructions().append(property->index());
     instructions().append(value->index());
+    instructions().append(arrayProfile);
     return value;
 }
 
@@ -1560,10 +1560,33 @@ RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index,
     return value;
 }
 
+RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
+{
+    RefPtr<RegisterID> func = newTemporary(); 
+
+    UnlinkedValueProfile profile = emitProfiledOpcode(op_get_callee);
+    instructions().append(func->index());
+    instructions().append(profile);
+
+    size_t begin = instructions().size();
+    m_staticPropertyAnalyzer.createThis(m_thisRegister.index(), begin + 3);
+
+    emitOpcode(op_create_this); 
+    instructions().append(m_thisRegister.index()); 
+    instructions().append(func->index()); 
+    instructions().append(0);
+    return dst;
+}
+
 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
 {
+    size_t begin = instructions().size();
+    m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
+
     emitOpcode(op_new_object);
     instructions().append(dst->index());
+    instructions().append(0);
+    instructions().append(newObjectAllocationProfile());
     return dst;
 }
 
@@ -1574,9 +1597,9 @@ unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
 
 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
 {
-    JSString*& stringInMap = m_stringMap.add(identifier.impl(), 0).first->second;
+    JSString*& stringInMap = m_stringMap.add(identifier.impl(), 0).iterator->value;
     if (!stringInMap) {
-        stringInMap = jsString(globalData(), identifier.ustring());
+        stringInMap = jsString(vm(), identifier.string());
         addConstantValue(stringInMap);
     }
     return stringInMap;
@@ -1590,7 +1613,7 @@ RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elemen
     bool hadVariableExpression = false;
     if (length) {
         for (ElementNode* n = elements; n; n = n->next()) {
-            if (!n->value()->isNumber() && !n->value()->isString()) {
+            if (!n->value()->isConstant()) {
                 hadVariableExpression = true;
                 break;
             }
@@ -1603,25 +1626,22 @@ RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elemen
         if (!hadVariableExpression) {
             ASSERT(length == checkLength);
             unsigned constantBufferIndex = addConstantBuffer(length);
-            JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex);
+            JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
             unsigned index = 0;
             for (ElementNode* n = elements; index < length; n = n->next()) {
-                if (n->value()->isNumber())
-                    constantBuffer[index++] = jsNumber(static_cast<NumberNode*>(n->value())->value());
-                else {
-                    ASSERT(n->value()->isString());
-                    constantBuffer[index++] = addStringConstant(static_cast<StringNode*>(n->value())->value());
-                }
+                ASSERT(n->value()->isConstant());
+                constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
             }
             emitOpcode(op_new_array_buffer);
             instructions().append(dst->index());
             instructions().append(constantBufferIndex);
             instructions().append(length);
+            instructions().append(newArrayAllocationProfile());
             return dst;
         }
     }
 
-    Vector<RefPtr<RegisterID>, 16> argv;
+    Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
     for (ElementNode* n = elements; n; n = n->next()) {
         if (n->elision())
             break;
@@ -1634,20 +1654,21 @@ RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elemen
     instructions().append(dst->index());
     instructions().append(argv.size() ? argv[0]->index() : 0); // argv
     instructions().append(argv.size()); // argc
+    instructions().append(newArrayAllocationProfile());
     return dst;
 }
 
 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionBodyNode* function)
 {
-    return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(m_globalData, function)), false);
+    return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(function)), false);
 }
 
 RegisterID* BytecodeGenerator::emitLazyNewFunction(RegisterID* dst, FunctionBodyNode* function)
 {
-    std::pair<FunctionOffsetMap::iterator, bool> ptr = m_functionOffsets.add(function, 0);
-    if (ptr.second)
-        ptr.first->second = m_codeBlock->addFunctionDecl(makeFunction(m_globalData, function));
-    return emitNewFunctionInternal(dst, ptr.first->second, true);
+    FunctionOffsetMap::AddResult ptr = m_functionOffsets.add(function, 0);
+    if (ptr.isNewEntry)
+        ptr.iterator->value = m_codeBlock->addFunctionDecl(makeFunction(function));
+    return emitNewFunctionInternal(dst, ptr.iterator->value, true);
 }
 
 RegisterID* BytecodeGenerator::emitNewFunctionInternal(RegisterID* dst, unsigned index, bool doNullCheck)
@@ -1671,7 +1692,7 @@ RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* r0, FuncExprNode* n)
 {
     FunctionBodyNode* function = n->body();
-    unsigned index = m_codeBlock->addFunctionExpr(makeFunction(m_globalData, function));
+    unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
     
     createActivationIfNecessary();
     emitOpcode(op_new_func_exp);
@@ -1680,9 +1701,9 @@ RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* r0, FuncExp
     return r0;
 }
 
-RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset)
+RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
 {
-    return emitCall(op_call, dst, func, callArguments, divot, startOffset, endOffset);
+    return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, startOffset, endOffset, line, lineStart);
 }
 
 void BytecodeGenerator::createArgumentsIfNecessary()
@@ -1713,12 +1734,87 @@ void BytecodeGenerator::createActivationIfNecessary()
     instructions().append(m_activationRegister->index());
 }
 
-RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset)
+RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
+{
+    return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, startOffset, endOffset, line, lineStart);
+}
+
+ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
+{
+    if (identifier == m_vm->propertyNames->Object)
+        return ExpectObjectConstructor;
+    if (identifier == m_vm->propertyNames->Array)
+        return ExpectArrayConstructor;
+    return NoExpectedFunction;
+}
+
+ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done)
 {
-    return emitCall(op_call_eval, dst, func, callArguments, divot, startOffset, endOffset);
+    RefPtr<Label> realCall = newLabel();
+    switch (expectedFunction) {
+    case ExpectObjectConstructor: {
+        // If the number of arguments is non-zero, then we can't do anything interesting.
+        if (callArguments.argumentCountIncludingThis() >= 2)
+            return NoExpectedFunction;
+        
+        size_t begin = instructions().size();
+        emitOpcode(op_jneq_ptr);
+        instructions().append(func->index());
+        instructions().append(Special::ObjectConstructor);
+        instructions().append(realCall->bind(begin, instructions().size()));
+        
+        if (dst != ignoredResult())
+            emitNewObject(dst);
+        break;
+    }
+        
+    case ExpectArrayConstructor: {
+        // If you're doing anything other than "new Array()" or "new Array(foo)" then we
+        // don't do inline it, for now. The only reason is that call arguments are in
+        // the opposite order of what op_new_array expects, so we'd either need to change
+        // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
+        // things sounds like it's worth it.
+        if (callArguments.argumentCountIncludingThis() > 2)
+            return NoExpectedFunction;
+        
+        size_t begin = instructions().size();
+        emitOpcode(op_jneq_ptr);
+        instructions().append(func->index());
+        instructions().append(Special::ArrayConstructor);
+        instructions().append(realCall->bind(begin, instructions().size()));
+        
+        if (dst != ignoredResult()) {
+            if (callArguments.argumentCountIncludingThis() == 2) {
+                emitOpcode(op_new_array_with_size);
+                instructions().append(dst->index());
+                instructions().append(callArguments.argumentRegister(0)->index());
+                instructions().append(newArrayAllocationProfile());
+            } else {
+                ASSERT(callArguments.argumentCountIncludingThis() == 1);
+                emitOpcode(op_new_array);
+                instructions().append(dst->index());
+                instructions().append(0);
+                instructions().append(0);
+                instructions().append(newArrayAllocationProfile());
+            }
+        }
+        break;
+    }
+        
+    default:
+        ASSERT(expectedFunction == NoExpectedFunction);
+        return NoExpectedFunction;
+    }
+    
+    size_t begin = instructions().size();
+    emitOpcode(op_jmp);
+    instructions().append(done->bind(begin, instructions().size()));
+    emitLabel(realCall.get());
+    
+    return expectedFunction;
 }
 
-RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset)
+RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
 {
     ASSERT(opcodeID == op_call || opcodeID == op_call_eval);
     ASSERT(func->refCount());
@@ -1727,13 +1823,13 @@ RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, Regi
         emitMove(callArguments.profileHookRegister(), func);
 
     // Generate code for arguments.
-    unsigned argumentIndex = 0;
+    unsigned argument = 0;
     for (ArgumentListNode* n = callArguments.argumentsNode()->m_listNode; n; n = n->m_next)
-        emitNode(callArguments.argumentRegister(argumentIndex++), n);
+        emitNode(callArguments.argumentRegister(argument++), n);
 
     // Reserve space for call frame.
-    Vector<RefPtr<RegisterID>, RegisterFile::CallFrameHeaderSize> callFrame;
-    for (int i = 0; i < RegisterFile::CallFrameHeaderSize; ++i)
+    Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
+    for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
         callFrame.append(newTemporary());
 
     if (m_shouldEmitProfileHooks) {
@@ -1741,21 +1837,31 @@ RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, Regi
         instructions().append(callArguments.profileHookRegister()->index());
     }
 
-    emitExpressionInfo(divot, startOffset, endOffset);
-
-#if ENABLE(JIT)
-    m_codeBlock->addCallLinkInfo();
-#endif
+    emitExpressionInfo(divot, startOffset, endOffset, line, lineStart);
 
+    RefPtr<Label> done = newLabel();
+    expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
+    
     // Emit call.
+    UnlinkedArrayProfile arrayProfile = newArrayProfile();
     emitOpcode(opcodeID);
     instructions().append(func->index()); // func
-    instructions().append(callArguments.count()); // argCount
-    instructions().append(callArguments.callFrame()); // registerOffset
+    instructions().append(callArguments.argumentCountIncludingThis()); // argCount
+    instructions().append(callArguments.registerOffset()); // registerOffset
+#if ENABLE(LLINT)
+    instructions().append(m_codeBlock->addLLIntCallLinkInfo());
+#else
+    instructions().append(0);
+#endif
+    instructions().append(arrayProfile);
     if (dst != ignoredResult()) {
-        emitOpcode(op_call_put_result);
-        instructions().append(dst->index()); // dst
+        UnlinkedValueProfile profile = emitProfiledOpcode(op_call_put_result);
+        instructions().append(kill(dst));
+        instructions().append(profile);
     }
+    
+    if (expectedFunction != NoExpectedFunction)
+        emitLabel(done.get());
 
     if (m_shouldEmitProfileHooks) {
         emitOpcode(op_profile_did_call);
@@ -1765,40 +1871,30 @@ RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, Regi
     return dst;
 }
 
-RegisterID* BytecodeGenerator::emitLoadVarargs(RegisterID* argCountDst, RegisterID* thisRegister, RegisterID* arguments)
-{
-    ASSERT(argCountDst->index() < arguments->index());
-    emitOpcode(op_load_varargs);
-    instructions().append(argCountDst->index());
-    instructions().append(arguments->index());
-    instructions().append(thisRegister->index() + RegisterFile::CallFrameHeaderSize); // initial registerOffset
-    return argCountDst;
-}
-
-RegisterID* BytecodeGenerator::emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* argCountRegister, unsigned divot, unsigned startOffset, unsigned endOffset)
+RegisterID* BytecodeGenerator::emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, RegisterID* profileHookRegister, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
 {
-    ASSERT(func->refCount());
-    ASSERT(thisRegister->refCount());
-    ASSERT(dst != func);
     if (m_shouldEmitProfileHooks) {
+        emitMove(profileHookRegister, func);
         emitOpcode(op_profile_will_call);
-        instructions().append(func->index());
+        instructions().append(profileHookRegister->index());
     }
     
-    emitExpressionInfo(divot, startOffset, endOffset);
-    
+    emitExpressionInfo(divot, startOffset, endOffset, line, lineStart);
+
     // Emit call.
     emitOpcode(op_call_varargs);
-    instructions().append(func->index()); // func
-    instructions().append(argCountRegister->index()); // arg count
-    instructions().append(thisRegister->index() + RegisterFile::CallFrameHeaderSize); // initial registerOffset
+    instructions().append(func->index());
+    instructions().append(thisRegister->index());
+    instructions().append(arguments->index());
+    instructions().append(firstFreeRegister->index());
     if (dst != ignoredResult()) {
-        emitOpcode(op_call_put_result);
-        instructions().append(dst->index()); // dst
+        UnlinkedValueProfile profile = emitProfiledOpcode(op_call_put_result);
+        instructions().append(kill(dst));
+        instructions().append(profile);
     }
     if (m_shouldEmitProfileHooks) {
         emitOpcode(op_profile_did_call);
-        instructions().append(func->index());
+        instructions().append(profileHookRegister->index());
     }
     return dst;
 }
@@ -1808,11 +1904,12 @@ RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
     if (m_codeBlock->needsFullScopeChain()) {
         emitOpcode(op_tear_off_activation);
         instructions().append(m_activationRegister->index());
-        instructions().append(m_codeBlock->argumentsRegister());
-    } else if (m_codeBlock->usesArguments() && m_codeBlock->m_numParameters > 1
-               && !m_codeBlock->isStrictMode()) { // If there are no named parameters, there's nothing to tear off, since extra / unnamed parameters get copied to the arguments object at construct time.
+    }
+
+    if (m_codeBlock->usesArguments() && m_codeBlock->numParameters() != 1 && !m_codeBlock->isStrictMode()) {
         emitOpcode(op_tear_off_arguments);
         instructions().append(m_codeBlock->argumentsRegister());
+        instructions().append(m_activationRegister ? m_activationRegister->index() : emitLoad(0, JSValue())->index());
     }
 
     // Constructors use op_ret_object_or_this to check the result is an
@@ -1834,7 +1931,7 @@ RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* s
     return src;
 }
 
-RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset)
+RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
 {
     ASSERT(func->refCount());
 
@@ -1842,10 +1939,10 @@ RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func,
         emitMove(callArguments.profileHookRegister(), func);
 
     // Generate code for arguments.
-    unsigned argumentIndex = 0;
+    unsigned argument = 0;
     if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
         for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next)
-            emitNode(callArguments.argumentRegister(argumentIndex++), n);
+            emitNode(callArguments.argumentRegister(argument++), n);
     }
 
     if (m_shouldEmitProfileHooks) {
@@ -1854,25 +1951,34 @@ RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func,
     }
 
     // Reserve space for call frame.
-    Vector<RefPtr<RegisterID>, RegisterFile::CallFrameHeaderSize> callFrame;
-    for (int i = 0; i < RegisterFile::CallFrameHeaderSize; ++i)
+    Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
+    for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
         callFrame.append(newTemporary());
 
-    emitExpressionInfo(divot, startOffset, endOffset);
-
-#if ENABLE(JIT)
-    m_codeBlock->addCallLinkInfo();
-#endif
+    emitExpressionInfo(divot, startOffset, endOffset, line, lineStart);
+    
+    RefPtr<Label> done = newLabel();
+    expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
 
     emitOpcode(op_construct);
     instructions().append(func->index()); // func
-    instructions().append(callArguments.count()); // argCount
-    instructions().append(callArguments.callFrame()); // registerOffset
+    instructions().append(callArguments.argumentCountIncludingThis()); // argCount
+    instructions().append(callArguments.registerOffset()); // registerOffset
+#if ENABLE(LLINT)
+    instructions().append(m_codeBlock->addLLIntCallLinkInfo());
+#else
+    instructions().append(0);
+#endif
+    instructions().append(0);
     if (dst != ignoredResult()) {
-        emitOpcode(op_call_put_result);
-        instructions().append(dst->index()); // dst
+        UnlinkedValueProfile profile = emitProfiledOpcode(op_call_put_result);
+        instructions().append(kill(dst));
+        instructions().append(profile);
     }
 
+    if (expectedFunction != NoExpectedFunction)
+        emitLabel(done.get());
+
     if (m_shouldEmitProfileHooks) {
         emitOpcode(op_profile_did_call);
         instructions().append(callArguments.profileHookRegister()->index());
@@ -1898,15 +2004,14 @@ void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src)
     instructions().append(src->index());
 }
 
-RegisterID* BytecodeGenerator::emitPushScope(RegisterID* scope)
+RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* scope)
 {
-    ASSERT(scope->isTemporary());
     ControlFlowContext context;
     context.isFinallyBlock = false;
     m_scopeContextStack.append(context);
     m_dynamicScopeDepth++;
 
-    return emitUnaryNoDstOp(op_push_scope, scope);
+    return emitUnaryNoDstOp(op_push_with_scope, scope);
 }
 
 void BytecodeGenerator::emitPopScope()
@@ -1920,7 +2025,7 @@ void BytecodeGenerator::emitPopScope()
     m_dynamicScopeDepth--;
 }
 
-void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, int firstLine, int lastLine)
+void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned firstLine, unsigned lastLine, unsigned charOffset, unsigned lineStart)
 {
 #if ENABLE(DEBUG_WITH_BREAKPOINT)
     if (debugHookID != DidReachBreakpoint)
@@ -1929,17 +2034,29 @@ void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, int firstLine, in
     if (!m_shouldEmitDebugHooks)
         return;
 #endif
+    emitExpressionInfo(charOffset, 0, 0, firstLine, lineStart);
+    unsigned charPosition = charOffset - m_scopeNode->source().startOffset();
     emitOpcode(op_debug);
     instructions().append(debugHookID);
     instructions().append(firstLine);
     instructions().append(lastLine);
+    instructions().append(charPosition);
 }
 
-void BytecodeGenerator::pushFinallyContext(Label* target, RegisterID* retAddrDst)
+void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock)
 {
     ControlFlowContext scope;
     scope.isFinallyBlock = true;
-    FinallyContext context = { target, retAddrDst };
+    FinallyContext context = {
+        finallyBlock,
+        static_cast<unsigned>(m_scopeContextStack.size()),
+        static_cast<unsigned>(m_switchContextStack.size()),
+        static_cast<unsigned>(m_forInContextStack.size()),
+        static_cast<unsigned>(m_tryContextStack.size()),
+        static_cast<unsigned>(m_labelScopes.size()),
+        m_finallyDepth,
+        m_dynamicScopeDepth
+    };
     scope.finallyContext = context;
     m_scopeContextStack.append(scope);
     m_finallyDepth++;
@@ -2031,7 +2148,7 @@ LabelScope* BytecodeGenerator::continueTarget(const Identifier& name)
     return 0;
 }
 
-PassRefPtr<Label> BytecodeGenerator::emitComplexJumpScopes(Label* target, ControlFlowContext* topScope, ControlFlowContext* bottomScope)
+void BytecodeGenerator::emitComplexPopScopes(ControlFlowContext* topScope, ControlFlowContext* bottomScope)
 {
     while (topScope > bottomScope) {
         // First we count the number of dynamic scopes we need to remove to get
@@ -2045,54 +2162,121 @@ PassRefPtr<Label> BytecodeGenerator::emitComplexJumpScopes(Label* target, Contro
         }
 
         if (nNormalScopes) {
-            size_t begin = instructions().size();
-
             // We need to remove a number of dynamic scopes to get to the next
             // finally block
-            emitOpcode(op_jmp_scopes);
-            instructions().append(nNormalScopes);
-
-            // If topScope == bottomScope then there isn't actually a finally block
-            // left to emit, so make the jmp_scopes jump directly to the target label
-            if (topScope == bottomScope) {
-                instructions().append(target->bind(begin, instructions().size()));
-                return target;
-            }
+            while (nNormalScopes--)
+                emitOpcode(op_pop_scope);
 
-            // Otherwise we just use jmp_scopes to pop a group of scopes and go
-            // to the next instruction
-            RefPtr<Label> nextInsn = newLabel();
-            instructions().append(nextInsn->bind(begin, instructions().size()));
-            emitLabel(nextInsn.get());
+            // If topScope == bottomScope then there isn't a finally block left to emit.
+            if (topScope == bottomScope)
+                return;
         }
-
+        
+        Vector<ControlFlowContext> savedScopeContextStack;
+        Vector<SwitchInfo> savedSwitchContextStack;
+        Vector<ForInContext> savedForInContextStack;
+        Vector<TryContext> poppedTryContexts;
+        LabelScopeStore savedLabelScopes;
         while (topScope > bottomScope && topScope->isFinallyBlock) {
-            emitJumpSubroutine(topScope->finallyContext.retAddrDst, topScope->finallyContext.finallyAddr);
+            RefPtr<Label> beforeFinally = emitLabel(newLabel().get());
+            
+            // Save the current state of the world while instating the state of the world
+            // for the finally block.
+            FinallyContext finallyContext = topScope->finallyContext;
+            bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size();
+            bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size();
+            bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size();
+            bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size();
+            bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size();
+            int topScopeIndex = -1;
+            int bottomScopeIndex = -1;
+            if (flipScopes) {
+                topScopeIndex = topScope - m_scopeContextStack.begin();
+                bottomScopeIndex = bottomScope - m_scopeContextStack.begin();
+                savedScopeContextStack = m_scopeContextStack;
+                m_scopeContextStack.shrink(finallyContext.scopeContextStackSize);
+            }
+            if (flipSwitches) {
+                savedSwitchContextStack = m_switchContextStack;
+                m_switchContextStack.shrink(finallyContext.switchContextStackSize);
+            }
+            if (flipForIns) {
+                savedForInContextStack = m_forInContextStack;
+                m_forInContextStack.shrink(finallyContext.forInContextStackSize);
+            }
+            if (flipTries) {
+                while (m_tryContextStack.size() != finallyContext.tryContextStackSize) {
+                    ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize);
+                    TryContext context = m_tryContextStack.last();
+                    m_tryContextStack.removeLast();
+                    TryRange range;
+                    range.start = context.start;
+                    range.end = beforeFinally;
+                    range.tryData = context.tryData;
+                    m_tryRanges.append(range);
+                    poppedTryContexts.append(context);
+                }
+            }
+            if (flipLabelScopes) {
+                savedLabelScopes = m_labelScopes;
+                while (m_labelScopes.size() > finallyContext.labelScopesSize)
+                    m_labelScopes.removeLast();
+            }
+            int savedFinallyDepth = m_finallyDepth;
+            m_finallyDepth = finallyContext.finallyDepth;
+            int savedDynamicScopeDepth = m_dynamicScopeDepth;
+            m_dynamicScopeDepth = finallyContext.dynamicScopeDepth;
+            
+            // Emit the finally block.
+            emitNode(finallyContext.finallyBlock);
+            
+            RefPtr<Label> afterFinally = emitLabel(newLabel().get());
+            
+            // Restore the state of the world.
+            if (flipScopes) {
+                m_scopeContextStack = savedScopeContextStack;
+                topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds
+                bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1.
+            }
+            if (flipSwitches)
+                m_switchContextStack = savedSwitchContextStack;
+            if (flipForIns)
+                m_forInContextStack = savedForInContextStack;
+            if (flipTries) {
+                ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize);
+                for (unsigned i = poppedTryContexts.size(); i--;) {
+                    TryContext context = poppedTryContexts[i];
+                    context.start = afterFinally;
+                    m_tryContextStack.append(context);
+                }
+                poppedTryContexts.clear();
+            }
+            if (flipLabelScopes)
+                m_labelScopes = savedLabelScopes;
+            m_finallyDepth = savedFinallyDepth;
+            m_dynamicScopeDepth = savedDynamicScopeDepth;
+            
             --topScope;
         }
     }
-    return emitJump(target);
 }
 
-PassRefPtr<Label> BytecodeGenerator::emitJumpScopes(Label* target, int targetScopeDepth)
+void BytecodeGenerator::emitPopScopes(int targetScopeDepth)
 {
     ASSERT(scopeDepth() - targetScopeDepth >= 0);
-    ASSERT(target->isForward());
 
     size_t scopeDelta = scopeDepth() - targetScopeDepth;
     ASSERT(scopeDelta <= m_scopeContextStack.size());
     if (!scopeDelta)
-        return emitJump(target);
-
-    if (m_finallyDepth)
-        return emitComplexJumpScopes(target, &m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta);
+        return;
 
-    size_t begin = instructions().size();
+    if (!m_finallyDepth) {
+        while (scopeDelta--)
+            emitOpcode(op_pop_scope);
+        return;
+    }
 
-    emitOpcode(op_jmp_scopes);
-    instructions().append(scopeDelta);
-    instructions().append(target->bind(begin, instructions().size()));
-    return target;
+    emitComplexPopScopes(&m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta);
 }
 
 RegisterID* BytecodeGenerator::emitGetPropertyNames(RegisterID* dst, RegisterID* base, RegisterID* i, RegisterID* size, Label* breakTarget)
@@ -2122,60 +2306,67 @@ RegisterID* BytecodeGenerator::emitNextPropertyName(RegisterID* dst, RegisterID*
     return dst;
 }
 
-RegisterID* BytecodeGenerator::emitCatch(RegisterID* targetRegister, Label* start, Label* end)
+TryData* BytecodeGenerator::pushTry(Label* start)
+{
+    TryData tryData;
+    tryData.target = newLabel();
+    tryData.targetScopeDepth = UINT_MAX;
+    m_tryData.append(tryData);
+    TryData* result = &m_tryData.last();
+    
+    TryContext tryContext;
+    tryContext.start = start;
+    tryContext.tryData = result;
+    
+    m_tryContextStack.append(tryContext);
+    
+    return result;
+}
+
+RegisterID* BytecodeGenerator::popTryAndEmitCatch(TryData* tryData, RegisterID* targetRegister, Label* end)
 {
     m_usesExceptions = true;
-#if ENABLE(JIT)
-    HandlerInfo info = { start->bind(0, 0), end->bind(0, 0), instructions().size(), m_dynamicScopeDepth + m_baseScopeDepth, CodeLocationLabel() };
-#else
-    HandlerInfo info = { start->bind(0, 0), end->bind(0, 0), instructions().size(), m_dynamicScopeDepth + m_baseScopeDepth };
-#endif
+    
+    ASSERT_UNUSED(tryData, m_tryContextStack.last().tryData == tryData);
+    
+    TryRange tryRange;
+    tryRange.start = m_tryContextStack.last().start;
+    tryRange.end = end;
+    tryRange.tryData = m_tryContextStack.last().tryData;
+    m_tryRanges.append(tryRange);
+    m_tryContextStack.removeLast();
+    
+    emitLabel(tryRange.tryData->target.get());
+    tryRange.tryData->targetScopeDepth = m_dynamicScopeDepth;
 
-    m_codeBlock->addExceptionHandler(info);
     emitOpcode(op_catch);
     instructions().append(targetRegister->index());
     return targetRegister;
 }
 
-void BytecodeGenerator::emitThrowReferenceError(const UString& message)
-{
-    emitOpcode(op_throw_reference_error);
-    instructions().append(addConstantValue(jsString(globalData(), message))->index());
-}
-
-PassRefPtr<Label> BytecodeGenerator::emitJumpSubroutine(RegisterID* retAddrDst, Label* finally)
-{
-    size_t begin = instructions().size();
-
-    emitOpcode(op_jsr);
-    instructions().append(retAddrDst->index());
-    instructions().append(finally->bind(begin, instructions().size()));
-    emitLabel(newLabel().get()); // Record the fact that the next instruction is implicitly labeled, because op_sret will return to it.
-    return finally;
-}
-
-void BytecodeGenerator::emitSubroutineReturn(RegisterID* retAddrSrc)
+void BytecodeGenerator::emitThrowReferenceError(const String& message)
 {
-    emitOpcode(op_sret);
-    instructions().append(retAddrSrc->index());
+    emitOpcode(op_throw_static_error);
+    instructions().append(addConstantValue(addStringConstant(Identifier(m_vm, message)))->index());
+    instructions().append(true);
 }
 
-void BytecodeGenerator::emitPushNewScope(RegisterID* dst, const Identifier& property, RegisterID* value)
+void BytecodeGenerator::emitPushNameScope(const Identifier& property, RegisterID* value, unsigned attributes)
 {
     ControlFlowContext context;
     context.isFinallyBlock = false;
     m_scopeContextStack.append(context);
     m_dynamicScopeDepth++;
 
-    emitOpcode(op_push_new_scope);
-    instructions().append(dst->index());
+    emitOpcode(op_push_name_scope);
     instructions().append(addConstant(property));
     instructions().append(value->index());
+    instructions().append(attributes);
 }
 
 void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::SwitchType type)
 {
-    SwitchInfo info = { instructions().size(), type };
+    SwitchInfo info = { static_cast<uint32_t>(instructions().size()), type };
     switch (type) {
         case SwitchInfo::SwitchImmediate:
             emitOpcode(op_switch_imm);
@@ -2187,7 +2378,7 @@ void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::S
             emitOpcode(op_switch_string);
             break;
         default:
-            ASSERT_NOT_REACHED();
+            RELEASE_ASSERT_NOT_REACHED();
     }
 
     instructions().append(0); // place holder for table index
@@ -2208,7 +2399,7 @@ static int32_t keyForImmediateSwitch(ExpressionNode* node, int32_t min, int32_t
     return key - min;
 }
 
-static void prepareJumpTableForImmediateSwitch(SimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max)
+static void prepareJumpTableForImmediateSwitch(UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max)
 {
     jumpTable.min = min;
     jumpTable.branchOffsets.resize(max - min + 1);
@@ -2228,13 +2419,13 @@ static int32_t keyForCharacterSwitch(ExpressionNode* node, int32_t min, int32_t
     StringImpl* clause = static_cast<StringNode*>(node)->value().impl();
     ASSERT(clause->length() == 1);
     
-    int32_t key = clause->characters()[0];
+    int32_t key = (*clause)[0];
     ASSERT(key >= min);
     ASSERT(key <= max);
     return key - min;
 }
 
-static void prepareJumpTableForCharacterSwitch(SimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max)
+static void prepareJumpTableForCharacterSwitch(UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max)
 {
     jumpTable.min = min;
     jumpTable.branchOffsets.resize(max - min + 1);
@@ -2247,7 +2438,7 @@ static void prepareJumpTableForCharacterSwitch(SimpleJumpTable& jumpTable, int32
     }
 }
 
-static void prepareJumpTableForStringSwitch(StringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes)
+static void prepareJumpTableForStringSwitch(UnlinkedStringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes)
 {
     for (uint32_t i = 0; i < clauseCount; ++i) {
         // We're emitting this after the clause labels should have been fixed, so 
@@ -2256,9 +2447,7 @@ static void prepareJumpTableForStringSwitch(StringJumpTable& jumpTable, int32_t
         
         ASSERT(nodes[i]->isString());
         StringImpl* clause = static_cast<StringNode*>(nodes[i])->value().impl();
-        OffsetLocation location;
-        location.branchOffset = labels[i]->bind(switchAddress, switchAddress + 3);
-        jumpTable.offsetTable.add(clause, location);
+        jumpTable.offsetTable.add(clause, labels[i]->bind(switchAddress, switchAddress + 3));
     }
 }
 
@@ -2270,20 +2459,20 @@ void BytecodeGenerator::endSwitch(uint32_t clauseCount, RefPtr<Label>* labels, E
         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfImmediateSwitchJumpTables();
         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
 
-        SimpleJumpTable& jumpTable = m_codeBlock->addImmediateSwitchJumpTable();
+        UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addImmediateSwitchJumpTable();
         prepareJumpTableForImmediateSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max);
     } else if (switchInfo.switchType == SwitchInfo::SwitchCharacter) {
         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfCharacterSwitchJumpTables();
         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
         
-        SimpleJumpTable& jumpTable = m_codeBlock->addCharacterSwitchJumpTable();
+        UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addCharacterSwitchJumpTable();
         prepareJumpTableForCharacterSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max);
     } else {
         ASSERT(switchInfo.switchType == SwitchInfo::SwitchString);
         instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfStringSwitchJumpTables();
         instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
 
-        StringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable();
+        UnlinkedStringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable();
         prepareJumpTableForStringSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes);
     }
 }
@@ -2303,14 +2492,21 @@ void BytecodeGenerator::setIsNumericCompareFunction(bool isNumericCompareFunctio
     m_codeBlock->setIsNumericCompareFunction(isNumericCompareFunction);
 }
 
-int BytecodeGenerator::argumentNumberFor(const Identifier& ident)
+bool BytecodeGenerator::isArgumentNumber(const Identifier& ident, int argumentNumber)
 {
-    int parameterCount = m_parameters.size(); // includes 'this'
-    RegisterID* registerID = registerFor(ident);
-    if (!registerID)
-        return 0;
-    int index = registerID->index() + RegisterFile::CallFrameHeaderSize + parameterCount;
-    return (index > 0 && index < parameterCount) ? index : 0;
+    RegisterID* registerID = resolve(ident).local();
+    if (!registerID || registerID->index() >= 0)
+         return 0;
+    return registerID->index() == CallFrame::argumentOffset(argumentNumber);
+}
+
+void BytecodeGenerator::emitReadOnlyExceptionIfNeeded()
+{
+    if (!isStrictMode())
+        return;
+    emitOpcode(op_throw_static_error);
+    instructions().append(addConstantValue(addStringConstant(Identifier(m_vm, StrictModeReadonlyPropertyWriteError)))->index());
+    instructions().append(false);
 }
 
 } // namespace JSC