X-Git-Url: https://git.saurik.com/apple/javascriptcore.git/blobdiff_plain/93a3786624b2768d89bfa27e46598dc64e2fb70a..HEAD:/bytecompiler/BytecodeGenerator.cpp diff --git a/bytecompiler/BytecodeGenerator.cpp b/bytecompiler/BytecodeGenerator.cpp index e719380..8b2f8e6 100644 --- a/bytecompiler/BytecodeGenerator.cpp +++ b/bytecompiler/BytecodeGenerator.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008, 2009, 2012, 2013 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2009, 2012-2015 Apple Inc. All rights reserved. * Copyright (C) 2008 Cameron Zwarich * Copyright (C) 2012 Igalia, S.L. * @@ -12,7 +12,7 @@ * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * @@ -31,16 +31,20 @@ #include "config.h" #include "BytecodeGenerator.h" -#include "BatchedTransitionOptimizer.h" +#include "BuiltinExecutables.h" #include "Interpreter.h" -#include "JSActivation.h" #include "JSFunction.h" +#include "JSLexicalEnvironment.h" #include "JSNameScope.h" +#include "JSTemplateRegistryKey.h" #include "LowLevelInterpreter.h" -#include "Operations.h" +#include "JSCInlines.h" #include "Options.h" +#include "StackAlignment.h" #include "StrongInlines.h" #include "UnlinkedCodeBlock.h" +#include "UnlinkedInstructionStream.h" +#include #include using namespace std; @@ -53,37 +57,44 @@ void Label::setLocation(unsigned 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; + m_generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first; } -#ifndef NDEBUG -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 - ParserError BytecodeGenerator::generate() { SamplingRegion samplingRegion("Bytecode Generation"); - m_codeBlock->setThisRegister(m_thisRegister.index()); + m_codeBlock->setThisRegister(m_thisRegister.virtualRegister()); + + // If we have declared a variable named "arguments" and we are using arguments then we should + // perform that assignment now. + if (m_needToInitializeArguments) + initializeVariable(variable(propertyNames().arguments), m_argumentsRegister); + + for (size_t i = 0; i < m_destructuringParameters.size(); i++) { + auto& entry = m_destructuringParameters[i]; + entry.second->bindValue(*this, entry.first.get()); + } - m_scopeNode->emitBytecode(*this); + { + RefPtr temp = newTemporary(); + RefPtr globalScope = scopeRegister(); // FIXME: With lexical scoping, this won't always be the global object: https://bugs.webkit.org/show_bug.cgi?id=142944 + for (auto functionPair : m_functionsToInitialize) { + FunctionBodyNode* functionBody = functionPair.first; + FunctionVariableType functionType = functionPair.second; + emitNewFunction(temp.get(), functionBody); + if (functionType == NormalFunctionVariable) + initializeVariable(variable(functionBody->ident()) , temp.get()); + else if (functionType == GlobalFunctionVariable) + emitPutToScope(globalScope.get(), Variable(functionBody->ident()), temp.get(), ThrowIfNotFound); + else + RELEASE_ASSERT_NOT_REACHED(); + } + } + + bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor(); + if (!callingClassConstructor) + m_scopeNode->emitBytecode(*this); m_staticPropertyAnalyzer.kill(); @@ -118,324 +129,394 @@ ParserError BytecodeGenerator::generate() continue; ASSERT(range.tryData->targetScopeDepth != UINT_MAX); - UnlinkedHandlerInfo info = { - static_cast(start), static_cast(end), - static_cast(range.tryData->target->bind()), - range.tryData->targetScopeDepth - }; + ASSERT(range.tryData->handlerType != HandlerType::Illegal); + UnlinkedHandlerInfo info(static_cast(start), static_cast(end), + static_cast(range.tryData->target->bind()), range.tryData->targetScopeDepth, + range.tryData->handlerType); m_codeBlock->addExceptionHandler(info); } - m_codeBlock->instructions() = RefCountedArray(m_instructions); + m_codeBlock->setInstructions(std::make_unique(m_instructions)); m_codeBlock->shrinkToFit(); + if (m_codeBlock->symbolTable() && !m_codeBlock->vm()->typeProfiler()) + m_codeBlock->setSymbolTable(m_codeBlock->symbolTable()->cloneScopePart(*m_codeBlock->vm())); + if (m_expressionTooDeep) 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); - SymbolTable::AddResult result = symbolTable().add(ident.impl(), newEntry); - - if (!result.isNewEntry) { - r0 = ®isterFor(result.iterator->value.getIndex()); - return false; - } - - r0 = addVar(); - return true; -} - -void BytecodeGenerator::preserveLastVar() -{ - if ((m_firstConstantIndex = m_calleeRegisters.size()) != 0) - m_lastVar = &m_calleeRegisters.last(); -} - -BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope*, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode) - : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn) - , m_shouldEmitProfileHooks(profilerMode == ProfilerOn) - , m_symbolTable(0) +BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode) + : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn) + , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn) , m_scopeNode(programNode) , m_codeBlock(vm, codeBlock) , m_thisRegister(CallFrame::thisArgumentOffset()) - , m_emptyValueRegister(0) - , m_globalObjectRegister(0) - , m_finallyDepth(0) - , m_dynamicScopeDepth(0) , m_codeType(GlobalCode) - , m_nextConstantOffset(0) - , m_globalConstantIndex(0) - , m_hasCreatedActivation(true) - , m_firstLazyFunction(0) - , m_lastLazyFunction(0) - , m_staticPropertyAnalyzer(&m_instructions) , m_vm(&vm) - , m_lastOpcodeID(op_end) -#ifndef NDEBUG - , m_lastOpcodePosition(0) -#endif - , m_stack(wtfThreadData().stack()) - , m_usesExceptions(false) - , m_expressionTooDeep(false) { - if (m_shouldEmitDebugHooks) - m_codeBlock->setNeedsFullScopeChain(true); + for (auto& constantRegister : m_linkTimeConstantRegisters) + constantRegister = nullptr; m_codeBlock->setNumParameters(1); // Allocate space for "this" emitOpcode(op_enter); + allocateAndEmitScope(); + const VarStack& varStack = programNode->varStack(); const FunctionStack& functionStack = programNode->functionStack(); for (size_t i = 0; i < functionStack.size(); ++i) { FunctionBodyNode* function = functionStack[i]; - UnlinkedFunctionExecutable* unlinkedFunction = makeFunction(function); - codeBlock->addFunctionDeclaration(*m_vm, function->ident(), unlinkedFunction); + m_functionsToInitialize.append(std::make_pair(function, GlobalFunctionVariable)); } for (size_t i = 0; i < varStack.size(); ++i) - codeBlock->addVariableDeclaration(*varStack[i].first, !!(varStack[i].second & DeclarationStacks::IsConstant)); + codeBlock->addVariableDeclaration(varStack[i].first, !!(varStack[i].second & DeclarationStacks::IsConstant)); } -BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, FunctionBodyNode* functionBody, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode) - : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn) - , m_shouldEmitProfileHooks(profilerMode == ProfilerOn) +BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode) + : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn) + , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn) , m_symbolTable(codeBlock->symbolTable()) - , m_scopeNode(functionBody) - , m_scope(vm, scope) + , m_scopeNode(functionNode) , m_codeBlock(vm, codeBlock) - , m_activationRegister(0) - , m_emptyValueRegister(0) - , m_globalObjectRegister(0) - , m_finallyDepth(0) - , m_dynamicScopeDepth(0) , m_codeType(FunctionCode) - , m_nextConstantOffset(0) - , m_globalConstantIndex(0) - , m_hasCreatedActivation(false) - , m_firstLazyFunction(0) - , m_lastLazyFunction(0) - , m_staticPropertyAnalyzer(&m_instructions) , m_vm(&vm) - , m_lastOpcodeID(op_end) -#ifndef NDEBUG - , m_lastOpcodePosition(0) -#endif - , m_stack(wtfThreadData().stack()) - , m_usesExceptions(false) - , m_expressionTooDeep(false) + , m_isBuiltinFunction(codeBlock->isBuiltinFunction()) { - if (m_shouldEmitDebugHooks) - m_codeBlock->setNeedsFullScopeChain(true); + for (auto& constantRegister : m_linkTimeConstantRegisters) + constantRegister = nullptr; + if (m_isBuiltinFunction) + m_shouldEmitDebugHooks = false; + m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode()); - m_symbolTable->setParameterCountIncludingThis(functionBody->parameters()->size() + 1); - - emitOpcode(op_enter); - if (m_codeBlock->needsFullScopeChain()) { - m_activationRegister = addVar(); - emitInitLazyRegister(m_activationRegister); - m_codeBlock->setActivationRegister(m_activationRegister->index()); + Vector boundParameterProperties; + FunctionParameters& parameters = *functionNode->parameters(); + for (size_t i = 0; i < parameters.size(); i++) { + auto pattern = parameters.at(i); + if (pattern->isBindingNode()) + continue; + pattern->collectBoundIdentifiers(boundParameterProperties); + continue; } - 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'. - - // We can save a little space by hard-coding the knowledge that the two - // 'arguments' values are stored in consecutive registers, and storing - // only the index of the assignable one. - codeBlock->setArgumentsRegister(argumentsRegister->index()); - ASSERT_UNUSED(unmodifiedArgumentsRegister, unmodifiedArgumentsRegister->index() == JSC::unmodifiedArgumentsRegister(codeBlock->argumentsRegister())); - - emitInitLazyRegister(argumentsRegister); - emitInitLazyRegister(unmodifiedArgumentsRegister); - - if (m_codeBlock->isStrictMode()) { - emitOpcode(op_create_arguments); - instructions().append(argumentsRegister->index()); + bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || m_codeBlock->needsFullScopeChain(); + bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval(); + bool needsArguments = functionNode->usesArguments() || codeBlock->usesEval(); + + auto captures = [&] (UniquedStringImpl* uid) -> bool { + if (shouldCaptureAllOfTheThings) + return true; + if (!shouldCaptureSomeOfTheThings) + return false; + if (needsArguments && uid == propertyNames().arguments.impl()) { + // Actually, we only need to capture the arguments object when we "need full activation" + // because of name scopes. But historically we did it this way, so for now we just preserve + // the old behavior. + // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072 + return true; } + return functionNode->captures(uid); + }; + auto varKind = [&] (UniquedStringImpl* uid) -> VarKind { + return captures(uid) ? VarKind::Scope : VarKind::Stack; + }; - // The debugger currently retrieves the arguments object from an activation rather than pulling - // it from a call frame. In the long-term it should stop doing that (), - // but for now we force eager creation of the arguments object when debugging. - if (m_shouldEmitDebugHooks) { - emitOpcode(op_create_arguments); - instructions().append(argumentsRegister->index()); - } - } + emitOpcode(op_enter); - bool shouldCaptureAllTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval(); + allocateAndEmitScope(); + + m_calleeRegister.setIndex(JSStack::Callee); + + if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode()) + && functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode())) { + // When we do this, we should make our local scope stack know about the function name symbol + // table. Currently this works because bytecode linking creates a phony name scope. + // FIXME: https://bugs.webkit.org/show_bug.cgi?id=141885 + // Also, we could create the scope once per JSFunction instance that needs it. That wouldn't + // be any more correct, but it would be more performant. + // FIXME: https://bugs.webkit.org/show_bug.cgi?id=141887 + emitPushFunctionNameScope(m_scopeRegister, functionNode->ident(), &m_calleeRegister, ReadOnly | DontDelete); + } + if (shouldCaptureSomeOfTheThings) { + m_lexicalEnvironmentRegister = addVar(); + m_codeBlock->setActivationRegister(m_lexicalEnvironmentRegister->virtualRegister()); + emitOpcode(op_create_lexical_environment); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(scopeRegister()->index()); + emitOpcode(op_mov); + instructions().append(scopeRegister()->index()); + instructions().append(m_lexicalEnvironmentRegister->index()); + } + + // Make sure the code block knows about all of our parameters, and make sure that parameters + // needing destructuring are noted. + m_parameters.grow(parameters.size() + 1); // reserve space for "this" + m_thisRegister.setIndex(initializeNextParameter()->index()); // this + for (unsigned i = 0; i < parameters.size(); ++i) { + auto pattern = parameters.at(i); + RegisterID* reg = initializeNextParameter(); + if (!pattern->isBindingNode()) + m_destructuringParameters.append(std::make_pair(reg, pattern)); + } + + // Figure out some interesting facts about our arguments. bool capturesAnyArgumentByName = false; - Vector capturedArguments; - if (functionBody->hasCapturedVariables() || shouldCaptureAllTheThings) { - FunctionParameters& parameters = *functionBody->parameters(); - capturedArguments.resize(parameters.size()); + if (functionNode->hasCapturedVariables()) { + FunctionParameters& parameters = *functionNode->parameters(); for (size_t i = 0; i < parameters.size(); ++i) { - capturedArguments[i] = 0; - if (!functionBody->captures(parameters.at(i)) && !shouldCaptureAllTheThings) + auto pattern = parameters.at(i); + if (!pattern->isBindingNode()) continue; - capturesAnyArgumentByName = true; - capturedArguments[i] = addVar(); + const Identifier& ident = static_cast(pattern)->boundProperty(); + capturesAnyArgumentByName |= captures(ident.impl()); } } - if (capturesAnyArgumentByName && !codeBlock->isStrictMode()) { - size_t parameterCount = m_symbolTable->parameterCount(); - OwnArrayPtr 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(); - - // Captured variables and functions go first so that activations don't have - // to step over the non-captured locals to mark them. - m_hasCreatedActivation = false; - if (functionBody->hasCapturedVariables()) { - for (size_t i = 0; i < functionStack.size(); ++i) { - FunctionBodyNode* function = functionStack[i]; - const Identifier& ident = function->ident(); - if (functionBody->captures(ident)) { - if (!m_hasCreatedActivation) { - m_hasCreatedActivation = true; - emitOpcode(op_create_activation); - instructions().append(m_activationRegister->index()); + if (capturesAnyArgumentByName) + ASSERT(m_lexicalEnvironmentRegister); + + // Need to know what our functions are called. Parameters have some goofy behaviors when it + // comes to functions of the same name. + for (FunctionBodyNode* function : functionNode->functionStack()) + m_functions.add(function->ident().impl()); + + if (needsArguments) { + // Create the arguments object now. We may put the arguments object into the activation if + // it is captured. Either way, we create two arguments object variables: one is our + // private variable that is immutable, and another that is the user-visible variable. The + // immutable one is only used here, or during formal parameter resolutions if we opt for + // DirectArguments. + + m_argumentsRegister = addVar(); + m_argumentsRegister->ref(); + } + + if (needsArguments && !codeBlock->isStrictMode()) { + // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we + // use DirectArguments. With ScopedArguments, we lift all of our arguments into the + // activation. + + if (capturesAnyArgumentByName) { + m_symbolTable->setArgumentsLength(vm, parameters.size()); + + // For each parameter, we have two possibilities: + // Either it's a binding node with no function overlap, in which case it gets a name + // in the symbol table - or it just gets space reserved in the symbol table. Either + // way we lift the value into the scope. + for (unsigned i = 0; i < parameters.size(); ++i) { + ScopeOffset offset = m_symbolTable->takeNextScopeOffset(); + m_symbolTable->setArgumentOffset(vm, i, offset); + if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i))) { + VarOffset varOffset(offset); + SymbolTableEntry entry(varOffset); + // Stores to these variables via the ScopedArguments object will not do + // notifyWrite(), since that would be cumbersome. Also, watching formal + // parameters when "arguments" is in play is unlikely to be super profitable. + // So, we just disable it. + entry.disableWatching(); + m_symbolTable->set(name, entry); } - m_functions.add(ident.impl()); - emitNewFunction(addVar(ident, false), function); + emitOpcode(op_put_to_scope); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(UINT_MAX); + instructions().append(virtualRegisterForArgument(1 + i).offset()); + instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand()); + instructions().append(0); + instructions().append(offset.offset()); + } + + // This creates a scoped arguments object and copies the overflow arguments into the + // scope. It's the equivalent of calling ScopedArguments::createByCopying(). + emitOpcode(op_create_scoped_arguments); + instructions().append(m_argumentsRegister->index()); + instructions().append(m_lexicalEnvironmentRegister->index()); + } else { + // We're going to put all parameters into the DirectArguments object. First ensure + // that the symbol table knows that this is happening. + for (unsigned i = 0; i < parameters.size(); ++i) { + if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i))) + m_symbolTable->set(name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i)))); } + + emitOpcode(op_create_direct_arguments); + instructions().append(m_argumentsRegister->index()); } - for (size_t i = 0; i < varStack.size(); ++i) { - const Identifier& ident = *varStack[i].first; - if (functionBody->captures(ident)) - addVar(ident, varStack[i].second & DeclarationStacks::IsConstant); + } else { + // Create the formal parameters the normal way. Any of them could be captured, or not. If + // captured, lift them into the scope. + for (unsigned i = 0; i < parameters.size(); ++i) { + UniquedStringImpl* name = visibleNameForParameter(parameters.at(i)); + if (!name) + continue; + + if (!captures(name)) { + // This is the easy case - just tell the symbol table about the argument. It will + // be accessed directly. + m_symbolTable->set(name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i)))); + continue; + } + + ScopeOffset offset = m_symbolTable->takeNextScopeOffset(); + const Identifier& ident = + static_cast(parameters.at(i))->boundProperty(); + m_symbolTable->set(name, SymbolTableEntry(VarOffset(offset))); + + emitOpcode(op_put_to_scope); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(addConstant(ident)); + instructions().append(virtualRegisterForArgument(1 + i).offset()); + instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand()); + instructions().append(0); + instructions().append(offset.offset()); } } - bool canLazilyCreateFunctions = !functionBody->needsActivationForMoreThanVariables() && !m_shouldEmitDebugHooks; - if (!canLazilyCreateFunctions && !m_hasCreatedActivation) { - m_hasCreatedActivation = true; - emitOpcode(op_create_activation); - instructions().append(m_activationRegister->index()); + + if (needsArguments && codeBlock->isStrictMode()) { + // Allocate an out-of-bands arguments object. + emitOpcode(op_create_out_of_band_arguments); + instructions().append(m_argumentsRegister->index()); } - - m_symbolTable->setCaptureEnd(codeBlock->m_numVars); - - m_firstLazyFunction = codeBlock->m_numVars; - for (size_t i = 0; i < functionStack.size(); ++i) { - FunctionBodyNode* function = functionStack[i]; + + // Now declare all variables. + for (const Identifier& ident : boundParameterProperties) + createVariable(ident, varKind(ident.impl()), IsVariable); + for (FunctionBodyNode* function : functionNode->functionStack()) { const Identifier& ident = function->ident(); - if (!functionBody->captures(ident)) { - m_functions.add(ident.impl()); - RefPtr reg = addVar(ident, false); - // Don't lazily create functions that override the name 'arguments' - // as this would complicate lazy instantiation of actual arguments. - if (!canLazilyCreateFunctions || ident == propertyNames().arguments) - emitNewFunction(reg.get(), function); - else { - emitInitLazyRegister(reg.get()); - m_lazyFunctions.set(reg->index(), function); + createVariable(ident, varKind(ident.impl()), IsVariable); + m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable)); + } + for (auto& entry : functionNode->varStack()) { + ConstantMode constantMode = modeForIsConstant(entry.second & DeclarationStacks::IsConstant); + // Variables named "arguments" are never const. + if (entry.first == propertyNames().arguments) + constantMode = IsVariable; + createVariable(entry.first, varKind(entry.first.impl()), constantMode, IgnoreExisting); + } + + // There are some variables that need to be preinitialized to something other than Undefined: + // + // - "arguments": unless it's used as a function or parameter, this should refer to the + // arguments object. + // + // - callee: unless it's used as a var, function, or parameter, this should refer to the + // callee (i.e. our function). + // + // - functions: these always override everything else. + // + // The most logical way to do all of this is to initialize none of the variables until now, + // and then initialize them in BytecodeGenerator::generate() in such an order that the rules + // for how these things override each other end up holding. We would initialize the callee + // first, then "arguments", then all arguments, then the functions. + // + // But some arguments are already initialized by default, since if they aren't captured and we + // don't have "arguments" then we just point the symbol table at the stack slot of those + // arguments. We end up initializing the rest of the arguments that have an uncomplicated + // binding (i.e. don't involve destructuring) above when figuring out how to lay them out, + // because that's just the simplest thing. This means that when we initialize them, we have to + // watch out for the things that override arguments (namely, functions). + // + // We also initialize callee here as well, just because it's so weird. We know whether we want + // to do this because we can just check if it's in the symbol table. + if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode()) + && !functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode()) + && m_symbolTable->get(functionNode->ident().impl()).isNull()) { + if (captures(functionNode->ident().impl())) { + ScopeOffset offset; + { + ConcurrentJITLocker locker(m_symbolTable->m_lock); + offset = m_symbolTable->takeNextScopeOffset(locker); + m_symbolTable->add( + locker, functionNode->ident().impl(), + SymbolTableEntry(VarOffset(offset), ReadOnly)); } + + emitOpcode(op_put_to_scope); + instructions().append(m_lexicalEnvironmentRegister->index()); + instructions().append(addConstant(functionNode->ident())); + instructions().append(m_calleeRegister.index()); + instructions().append(ResolveModeAndType(ThrowIfNotFound, LocalClosureVar).operand()); + instructions().append(0); + instructions().append(offset.offset()); + } else { + m_symbolTable->add( + functionNode->ident().impl(), + SymbolTableEntry(VarOffset(m_calleeRegister.virtualRegister()), ReadOnly)); } } - m_lastLazyFunction = canLazilyCreateFunctions ? codeBlock->m_numVars : m_firstLazyFunction; - for (size_t i = 0; i < varStack.size(); ++i) { - const Identifier& ident = *varStack[i].first; - if (!functionBody->captures(ident)) - addVar(ident, varStack[i].second & DeclarationStacks::IsConstant); - } - - if (shouldCaptureAllTheThings) - m_symbolTable->setCaptureEnd(codeBlock->m_numVars); - - FunctionParameters& parameters = *functionBody->parameters(); - m_parameters.grow(parameters.size() + 1); // reserve space for "this" - - // Add "this" as a parameter - int nextParameterIndex = CallFrame::thisArgumentOffset(); - m_thisRegister.setIndex(nextParameterIndex--); - m_codeBlock->addParameter(); - 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); + // This is our final act of weirdness. "arguments" is overridden by everything except the + // callee. We add it to the symbol table if it's not already there and it's not an argument. + if (needsArguments) { + // If "arguments" is overridden by a function or destructuring parameter name, then it's + // OK for us to call createVariable() because it won't change anything. It's also OK for + // us to them tell BytecodeGenerator::generate() to write to it because it will do so + // before it initializes functions and destructuring parameters. But if "arguments" is + // overridden by a "simple" function parameter, then we have to bail: createVariable() + // would assert and BytecodeGenerator::generate() would write the "arguments" after the + // argument value had already been properly initialized. + + bool haveParameterNamedArguments = false; + for (unsigned i = 0; i < parameters.size(); ++i) { + UniquedStringImpl* name = visibleNameForParameter(parameters.at(i)); + if (name == propertyNames().arguments.impl()) { + haveParameterNamedArguments = true; + break; + } + } + + if (!haveParameterNamedArguments) { + createVariable( + propertyNames().arguments, varKind(propertyNames().arguments.impl()), IsVariable); + m_needToInitializeArguments = true; } - addParameter(parameters.at(i), index); } - preserveLastVar(); - - // We declare the callee's name last because it should lose to a var, function, and/or parameter declaration. - addCallee(functionBody, calleeRegister); - + if (isConstructor()) { - emitCreateThis(&m_thisRegister); - } else if (!codeBlock->isStrictMode() && (functionBody->usesThis() || codeBlock->usesEval() || m_shouldEmitDebugHooks)) { - UnlinkedValueProfile profile = emitProfiledOpcode(op_convert_this); + if (constructorKind() == ConstructorKind::Derived) { + m_newTargetRegister = addVar(); + emitMove(m_newTargetRegister, &m_thisRegister); + emitMoveEmptyValue(&m_thisRegister); + } else + emitCreateThis(&m_thisRegister); + } else if (constructorKind() != ConstructorKind::None) { + emitThrowTypeError("Cannot call a class constructor"); + } else if (functionNode->usesThis() || codeBlock->usesEval()) { + m_codeBlock->addPropertyAccessInstruction(instructions().size()); + emitOpcode(op_to_this); instructions().append(kill(&m_thisRegister)); - instructions().append(profile); + instructions().append(0); + instructions().append(0); } } -BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode) - : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn) - , m_shouldEmitProfileHooks(profilerMode == ProfilerOn) +BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode) + : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn) + , m_shouldEmitProfileHooks(Options::forceProfilerBytecodeGeneration() || profilerMode == ProfilerOn) , m_symbolTable(codeBlock->symbolTable()) , m_scopeNode(evalNode) - , 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_codeType(EvalCode) - , m_nextConstantOffset(0) - , m_globalConstantIndex(0) - , m_hasCreatedActivation(true) - , m_firstLazyFunction(0) - , m_lastLazyFunction(0) - , m_staticPropertyAnalyzer(&m_instructions) , m_vm(&vm) - , m_lastOpcodeID(op_end) -#ifndef NDEBUG - , m_lastOpcodePosition(0) -#endif - , m_stack(wtfThreadData().stack()) - , m_usesExceptions(false) - , m_expressionTooDeep(false) { - m_codeBlock->setNeedsFullScopeChain(true); + for (auto& constantRegister : m_linkTimeConstantRegisters) + constantRegister = nullptr; m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode()); m_codeBlock->setNumParameters(1); emitOpcode(op_enter); + allocateAndEmitScope(); + const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack(); for (size_t i = 0; i < functionStack.size(); ++i) m_codeBlock->addFunctionDecl(makeFunction(functionStack[i])); @@ -444,113 +525,42 @@ BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, EvalNode* evalNode, unsigned numVariables = varStack.size(); Vector variables; variables.reserveCapacity(numVariables); - for (size_t i = 0; i < numVariables; ++i) - variables.append(*varStack[i].first); + for (size_t i = 0; i < numVariables; ++i) { + ASSERT(varStack[i].first.impl()->isAtomic() || varStack[i].first.impl()->isSymbol()); + variables.append(varStack[i].first); + } codeBlock->adoptVariables(variables); - preserveLastVar(); } BytecodeGenerator::~BytecodeGenerator() { } -RegisterID* BytecodeGenerator::emitInitLazyRegister(RegisterID* reg) -{ - emitOpcode(op_init_lazy_reg); - instructions().append(reg->index()); - 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) +RegisterID* BytecodeGenerator::initializeNextParameter() { - // Parameters overwrite var declarations, but not function declarations. - StringImpl* rep = ident.impl(); - if (!m_functions.contains(rep)) { - symbolTable().set(rep, parameterIndex); - RegisterID& parameter = registerFor(parameterIndex); - parameter.setIndex(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. + VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters()); + RegisterID& parameter = registerFor(reg); + parameter.setIndex(reg.offset()); m_codeBlock->addParameter(); + return ¶meter; } -bool BytecodeGenerator::willResolveToArguments(const Identifier& ident) -{ - if (ident != propertyNames().arguments) - return false; - - if (!shouldOptimizeLocals()) - return false; - - SymbolTableEntry entry = symbolTable().get(ident.impl()); - if (entry.isNull()) - return false; - - if (m_codeBlock->usesArguments() && m_codeType == FunctionCode) - return true; - - return false; -} - -RegisterID* BytecodeGenerator::uncheckedRegisterForArguments() +UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern) { - ASSERT(willResolveToArguments(propertyNames().arguments)); - - SymbolTableEntry entry = symbolTable().get(propertyNames().arguments.impl()); - ASSERT(!entry.isNull()); - return ®isterFor(entry.getIndex()); -} - -RegisterID* BytecodeGenerator::createLazyRegisterIfNecessary(RegisterID* reg) -{ - if (m_lastLazyFunction <= reg->index() || reg->index() < m_firstLazyFunction) - return reg; - emitLazyNewFunction(reg, m_lazyFunctions.get(reg->index())); - return reg; + if (pattern->isBindingNode()) { + const Identifier& ident = static_cast(pattern)->boundProperty(); + if (!m_functions.contains(ident.impl())) + return ident.impl(); + } + return nullptr; } RegisterID* BytecodeGenerator::newRegister() { - m_calleeRegisters.append(m_calleeRegisters.size()); - m_codeBlock->m_numCalleeRegisters = max(m_codeBlock->m_numCalleeRegisters, m_calleeRegisters.size()); + m_calleeRegisters.append(virtualRegisterForLocal(m_calleeRegisters.size())); + int numCalleeRegisters = max(m_codeBlock->m_numCalleeRegisters, m_calleeRegisters.size()); + numCalleeRegisters = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeRegisters); + m_codeBlock->m_numCalleeRegisters = numCalleeRegisters; return &m_calleeRegisters.last(); } @@ -574,7 +584,7 @@ LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Iden // Allocate new label scope. LabelScope scope(type, name, scopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr