Commit 493a7d64 authored by Ross McIlroy's avatar Ross McIlroy Committed by Commit Bot

[TurboFan] Delete AstGraphBuilder.

Deletes AstGraphBuilder and associated classes now that it is
unreachable. The following classes are also removed:
 - ControlBuilders
 - JSFrameSpecialization
 - AstLoopAssignmentAnalysis

Also removes flags from compilation-info which are no longer used, and removes
the no-deoptimization paths from TypedOptimization, JsTypedLowering,
JSIntrinsicLowering and JSBuiltinLowering.

BUG=v8:6409

Change-Id: I63986e8e3497bf63c4a27ea8ae827b8a633d4a26
Reviewed-on: https://chromium-review.googlesource.com/583652
Commit-Queue: Ross McIlroy <rmcilroy@chromium.org>
Reviewed-by: 's avatarBenedikt Meurer <bmeurer@chromium.org>
Reviewed-by: 's avatarMichael Starzinger <mstarzinger@chromium.org>
Cr-Commit-Position: refs/heads/master@{#47284}
parent dadbde03
......@@ -1289,10 +1289,6 @@ v8_source_set("v8_base") {
"src/compiler/access-info.h",
"src/compiler/all-nodes.cc",
"src/compiler/all-nodes.h",
"src/compiler/ast-graph-builder.cc",
"src/compiler/ast-graph-builder.h",
"src/compiler/ast-loop-assignment-analyzer.cc",
"src/compiler/ast-loop-assignment-analyzer.h",
"src/compiler/basic-block-instrumentor.cc",
"src/compiler/basic-block-instrumentor.h",
"src/compiler/branch-elimination.cc",
......@@ -1319,8 +1315,6 @@ v8_source_set("v8_base") {
"src/compiler/common-operator.h",
"src/compiler/compiler-source-position-table.cc",
"src/compiler/compiler-source-position-table.h",
"src/compiler/control-builders.cc",
"src/compiler/control-builders.h",
"src/compiler/control-equivalence.cc",
"src/compiler/control-equivalence.h",
"src/compiler/control-flow-optimizer.cc",
......@@ -1370,8 +1364,6 @@ v8_source_set("v8_base") {
"src/compiler/js-context-specialization.h",
"src/compiler/js-create-lowering.cc",
"src/compiler/js-create-lowering.h",
"src/compiler/js-frame-specialization.cc",
"src/compiler/js-frame-specialization.h",
"src/compiler/js-generic-lowering.cc",
"src/compiler/js-generic-lowering.h",
"src/compiler/js-graph.cc",
......
......@@ -41,18 +41,14 @@ class V8_EXPORT_PRIVATE CompilationInfo final {
kIsNative = 1 << 2,
kSerializing = 1 << 3,
kBlockCoverageEnabled = 1 << 4,
kRequiresFrame = 1 << 5,
kAccessorInliningEnabled = 1 << 6,
kFunctionContextSpecializing = 1 << 7,
kFrameSpecializing = 1 << 8,
kInliningEnabled = 1 << 9,
kDisableFutureOptimization = 1 << 10,
kSplittingEnabled = 1 << 11,
kDeoptimizationEnabled = 1 << 12,
kSourcePositionsEnabled = 1 << 13,
kBailoutOnUninitialized = 1 << 14,
kOptimizeFromBytecode = 1 << 15,
kLoopPeelingEnabled = 1 << 16,
kAccessorInliningEnabled = 1 << 5,
kFunctionContextSpecializing = 1 << 6,
kInliningEnabled = 1 << 7,
kDisableFutureOptimization = 1 << 8,
kSplittingEnabled = 1 << 9,
kSourcePositionsEnabled = 1 << 10,
kBailoutOnUninitialized = 1 << 11,
kLoopPeelingEnabled = 1 << 12,
};
// Construct a compilation info for unoptimized compilation.
......@@ -133,9 +129,6 @@ class V8_EXPORT_PRIVATE CompilationInfo final {
// Flags used by optimized compilation.
void MarkAsRequiresFrame() { SetFlag(kRequiresFrame); }
bool requires_frame() const { return GetFlag(kRequiresFrame); }
void MarkAsFunctionContextSpecializing() {
SetFlag(kFunctionContextSpecializing);
}
......@@ -143,14 +136,6 @@ class V8_EXPORT_PRIVATE CompilationInfo final {
return GetFlag(kFunctionContextSpecializing);
}
void MarkAsFrameSpecializing() { SetFlag(kFrameSpecializing); }
bool is_frame_specializing() const { return GetFlag(kFrameSpecializing); }
void MarkAsDeoptimizationEnabled() { SetFlag(kDeoptimizationEnabled); }
bool is_deoptimization_enabled() const {
return GetFlag(kDeoptimizationEnabled);
}
void MarkAsAccessorInliningEnabled() { SetFlag(kAccessorInliningEnabled); }
bool is_accessor_inlining_enabled() const {
return GetFlag(kAccessorInliningEnabled);
......@@ -172,11 +157,6 @@ class V8_EXPORT_PRIVATE CompilationInfo final {
return GetFlag(kBailoutOnUninitialized);
}
void MarkAsOptimizeFromBytecode() { SetFlag(kOptimizeFromBytecode); }
bool is_optimizing_from_bytecode() const {
return GetFlag(kOptimizeFromBytecode);
}
void MarkAsLoopPeelingEnabled() { SetFlag(kLoopPeelingEnabled); }
bool is_loop_peeling_enabled() const { return GetFlag(kLoopPeelingEnabled); }
......
......@@ -563,8 +563,6 @@ void InsertCodeIntoOptimizedCodeCache(CompilationInfo* compilation_info) {
ClearOptimizedCodeCache(compilation_info);
return;
}
// Frame specialization implies function context specialization.
DCHECK(!compilation_info->is_frame_specializing());
// Cache optimized context-specific code.
Handle<JSFunction> function = compilation_info->closure();
......@@ -715,9 +713,6 @@ MaybeHandle<Code> GetOptimizedCode(Handle<JSFunction> function,
RuntimeCallTimerScope runtimeTimer(isolate, &RuntimeCallStats::OptimizeCode);
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.OptimizeCode");
// TODO(rmcilroy): Remove OptimizeFromBytecode flag.
compilation_info->MarkAsOptimizeFromBytecode();
// In case of concurrent recompilation, all handles below this point will be
// allocated in a deferred handle scope that is detached and handed off to
// the background thread when we return.
......
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/ast-graph-builder.h"
#include "src/ast/compile-time-value.h"
#include "src/ast/scopes.h"
#include "src/compilation-info.h"
#include "src/compiler.h"
#include "src/compiler/ast-loop-assignment-analyzer.h"
#include "src/compiler/control-builders.h"
#include "src/compiler/linkage.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/operator-properties.h"
#include "src/compiler/state-values-utils.h"
#include "src/feedback-vector.h"
#include "src/objects-inl.h"
#include "src/objects/literal-objects.h"
namespace v8 {
namespace internal {
namespace compiler {
// Each expression in the AST is evaluated in a specific context. This context
// decides how the evaluation result is passed up the visitor.
class AstGraphBuilder::AstContext BASE_EMBEDDED {
public:
bool IsEffect() const { return kind_ == Expression::kEffect; }
bool IsValue() const { return kind_ == Expression::kValue; }
bool IsTest() const { return kind_ == Expression::kTest; }
// Plug a node into this expression context. Call this function in tail
// position in the Visit functions for expressions.
virtual void ProduceValue(Expression* expr, Node* value) = 0;
// Unplugs a node from this expression context. Call this to retrieve the
// result of another Visit function that already plugged the context.
virtual Node* ConsumeValue() = 0;
// Shortcut for "context->ProduceValue(context->ConsumeValue())".
void ReplaceValue(Expression* expr) { ProduceValue(expr, ConsumeValue()); }
protected:
AstContext(AstGraphBuilder* owner, Expression::Context kind);
virtual ~AstContext();
AstGraphBuilder* owner() const { return owner_; }
Environment* environment() const { return owner_->environment(); }
// We want to be able to assert, in a context-specific way, that the stack
// height makes sense when the context is filled.
#ifdef DEBUG
int original_height_;
#endif
private:
Expression::Context kind_;
AstGraphBuilder* owner_;
AstContext* outer_;
};
// Context to evaluate expression for its side effects only.
class AstGraphBuilder::AstEffectContext final : public AstContext {
public:
explicit AstEffectContext(AstGraphBuilder* owner)
: AstContext(owner, Expression::kEffect) {}
~AstEffectContext() final;
void ProduceValue(Expression* expr, Node* value) final;
Node* ConsumeValue() final;
};
// Context to evaluate expression for its value (and side effects).
class AstGraphBuilder::AstValueContext final : public AstContext {
public:
explicit AstValueContext(AstGraphBuilder* owner)
: AstContext(owner, Expression::kValue) {}
~AstValueContext() final;
void ProduceValue(Expression* expr, Node* value) final;
Node* ConsumeValue() final;
};
// Context to evaluate expression for a condition value (and side effects).
class AstGraphBuilder::AstTestContext final : public AstContext {
public:
explicit AstTestContext(AstGraphBuilder* owner)
: AstContext(owner, Expression::kTest) {}
~AstTestContext() final;
void ProduceValue(Expression* expr, Node* value) final;
Node* ConsumeValue() final;
};
// Scoped class tracking context objects created by the visitor. Represents
// mutations of the context chain within the function body and allows to
// change the current {scope} and {context} during visitation.
class AstGraphBuilder::ContextScope BASE_EMBEDDED {
public:
ContextScope(AstGraphBuilder* builder, Scope* scope, Node* context)
: builder_(builder),
outer_(builder->execution_context()),
scope_(scope),
depth_(builder_->environment()->context_chain_length()) {
builder_->environment()->PushContext(context); // Push.
builder_->set_execution_context(this);
}
~ContextScope() {
builder_->set_execution_context(outer_); // Pop.
builder_->environment()->PopContext();
CHECK_EQ(depth_, builder_->environment()->context_chain_length());
}
// Current scope during visitation.
Scope* scope() const { return scope_; }
private:
AstGraphBuilder* builder_;
ContextScope* outer_;
Scope* scope_;
int depth_;
};
// Scoped class tracking control statements entered by the visitor. There are
// different types of statements participating in this stack to properly track
// local as well as non-local control flow:
// - IterationStatement : Allows proper 'break' and 'continue' behavior.
// - BreakableStatement : Allows 'break' from block and switch statements.
// - TryCatchStatement : Intercepts 'throw' and implicit exceptional edges.
// - TryFinallyStatement: Intercepts 'break', 'continue', 'throw' and 'return'.
class AstGraphBuilder::ControlScope BASE_EMBEDDED {
public:
explicit ControlScope(AstGraphBuilder* builder)
: builder_(builder),
outer_(builder->execution_control()),
context_length_(builder->environment()->context_chain_length()),
stack_height_(builder->environment()->stack_height()) {
builder_->set_execution_control(this); // Push.
}
virtual ~ControlScope() {
builder_->set_execution_control(outer_); // Pop.
}
// Either 'break' or 'continue' to the target statement.
void BreakTo(BreakableStatement* target);
void ContinueTo(BreakableStatement* target);
// Either 'return' or 'throw' the given value.
void ReturnValue(Node* return_value);
void ThrowValue(Node* exception_value);
protected:
enum Command { CMD_BREAK, CMD_CONTINUE, CMD_RETURN, CMD_THROW };
// Performs one of the above commands on this stack of control scopes. This
// walks through the stack giving each scope a chance to execute or defer the
// given command by overriding the {Execute} method appropriately. Note that
// this also drops extra operands from the environment for each skipped scope.
void PerformCommand(Command cmd, Statement* target, Node* value);
// Interface to execute a given command in this scope. Returning {true} here
// indicates successful execution whereas {false} requests to skip scope.
virtual bool Execute(Command cmd, Statement* target, Node** value) {
// For function-level control.
switch (cmd) {
case CMD_THROW:
builder()->BuildThrow(*value);
return true;
case CMD_RETURN:
builder()->BuildReturn(*value);
return true;
case CMD_BREAK:
case CMD_CONTINUE:
break;
}
return false;
}
Environment* environment() { return builder_->environment(); }
AstGraphBuilder* builder() const { return builder_; }
int context_length() const { return context_length_; }
int stack_height() const { return stack_height_; }
private:
AstGraphBuilder* builder_;
ControlScope* outer_;
int context_length_;
int stack_height_;
};
// Control scope implementation for a BreakableStatement.
class AstGraphBuilder::ControlScopeForBreakable : public ControlScope {
public:
ControlScopeForBreakable(AstGraphBuilder* owner, BreakableStatement* target,
ControlBuilder* control)
: ControlScope(owner), target_(target), control_(control) {}
protected:
bool Execute(Command cmd, Statement* target, Node** value) override {
if (target != target_) return false; // We are not the command target.
switch (cmd) {
case CMD_BREAK:
control_->Break();
return true;
case CMD_CONTINUE:
case CMD_THROW:
case CMD_RETURN:
break;
}
return false;
}
private:
BreakableStatement* target_;
ControlBuilder* control_;
};
// Control scope implementation for an IterationStatement.
class AstGraphBuilder::ControlScopeForIteration : public ControlScope {
public:
ControlScopeForIteration(AstGraphBuilder* owner, IterationStatement* target,
LoopBuilder* control)
: ControlScope(owner), target_(target), control_(control) {}
protected:
bool Execute(Command cmd, Statement* target, Node** value) override {
if (target != target_) {
control_->ExitLoop(value);
return false;
}
switch (cmd) {
case CMD_BREAK:
control_->Break();
return true;
case CMD_CONTINUE:
control_->Continue();
return true;
case CMD_THROW:
case CMD_RETURN:
break;
}
return false;
}
private:
BreakableStatement* target_;
LoopBuilder* control_;
};
AstGraphBuilder::AstGraphBuilder(Zone* local_zone, CompilationInfo* info,
JSGraph* jsgraph,
CallFrequency invocation_frequency,
LoopAssignmentAnalysis* loop)
: isolate_(info->isolate()),
local_zone_(local_zone),
info_(info),
jsgraph_(jsgraph),
invocation_frequency_(invocation_frequency),
environment_(nullptr),
ast_context_(nullptr),
globals_(0, local_zone),
execution_control_(nullptr),
execution_context_(nullptr),
input_buffer_size_(0),
input_buffer_(nullptr),
exit_controls_(local_zone),
loop_assignment_analysis_(loop),
state_values_cache_(jsgraph) {
// TODO(6409, rmcilroy): Remove ast graph builder in followup CL.
UNREACHABLE();
InitializeAstVisitor(info->isolate());
}
Node* AstGraphBuilder::GetFunctionClosureForContext() {
DeclarationScope* closure_scope = current_scope()->GetClosureScope();
if (closure_scope->is_script_scope() ||
closure_scope->is_module_scope()) {
// Contexts nested in the native context have a canonical empty function as
// their closure, not the anonymous closure containing the global code.
return BuildLoadNativeContextField(Context::CLOSURE_INDEX);
} else if (closure_scope->is_eval_scope()) {
// Contexts nested inside eval code have the same closure as the context
// calling eval, not the anonymous closure containing the eval code.
const Operator* op =
javascript()->LoadContext(0, Context::CLOSURE_INDEX, false);
return NewNode(op);
} else {
DCHECK(closure_scope->is_function_scope());
return GetFunctionClosure();
}
}
Node* AstGraphBuilder::GetFunctionClosure() {
if (!function_closure_.is_set()) {
int index = Linkage::kJSCallClosureParamIndex;
const Operator* op = common()->Parameter(index, "%closure");
Node* node = NewNode(op, graph()->start());
function_closure_.set(node);
}
return function_closure_.get();
}
Node* AstGraphBuilder::GetFunctionContext() {
if (!function_context_.is_set()) {
int params = info()->num_parameters_including_this();
int index = Linkage::GetJSCallContextParamIndex(params);
const Operator* op = common()->Parameter(index, "%context");
Node* node = NewNode(op, graph()->start());
function_context_.set(node);
}
return function_context_.get();
}
Node* AstGraphBuilder::GetEmptyFrameState() {
if (!empty_frame_state_.is_set()) {
const Operator* op = common()->FrameState(
BailoutId::None(), OutputFrameStateCombine::Ignore(), nullptr);
Node* node = graph()->NewNode(
op, jsgraph()->EmptyStateValues(), jsgraph()->EmptyStateValues(),
jsgraph()->EmptyStateValues(), jsgraph()->NoContextConstant(),
jsgraph()->UndefinedConstant(), graph()->start());
empty_frame_state_.set(node);
}
return empty_frame_state_.get();
}
bool AstGraphBuilder::CreateGraph(bool stack_check) {
DeclarationScope* scope = info()->scope();
DCHECK_NOT_NULL(graph());
// Set up the basic structure of the graph. Outputs for {Start} are the formal
// parameters (including the receiver) plus new target, number of arguments,
// context and closure.
int actual_parameter_count = info()->num_parameters_including_this() + 4;
graph()->SetStart(graph()->NewNode(common()->Start(actual_parameter_count)));
// Initialize the top-level environment.
Environment env(this, scope, graph()->start());
set_environment(&env);
if (info()->is_osr()) {
// Use OSR normal entry as the start of the top-level environment.
// It will be replaced with {Dead} after typing and optimizations.
NewNode(common()->OsrNormalEntry());
}
// Initialize the incoming context.
ContextScope incoming(this, scope, GetFunctionContext());
// Initialize control scope.
ControlScope control(this);
// TODO(mstarzinger): For now we cannot assume that the {this} parameter is
// not {the_hole}, because for derived classes {this} has a TDZ and the
// JSConstructStubForDerived magically passes {the_hole} as a receiver.
if (scope->has_this_declaration() && scope->receiver()->mode() == CONST) {
env.RawParameterBind(0, jsgraph()->TheHoleConstant());
}
if (scope->NeedsContext()) {
// Push a new inner context scope for the current activation.
Node* inner_context = BuildLocalActivationContext(GetFunctionContext());
ContextScope top_context(this, scope, inner_context);
CreateGraphBody(stack_check);
} else {
// Simply use the outer function context in building the graph.
CreateGraphBody(stack_check);
}
// Finish the basic structure of the graph.
DCHECK_NE(0u, exit_controls_.size());
int const input_count = static_cast<int>(exit_controls_.size());
Node** const inputs = &exit_controls_.front();
Node* end = graph()->NewNode(common()->End(input_count), input_count, inputs);
graph()->SetEnd(end);
// Failures indicated by stack overflow.
return !HasStackOverflow();
}
void AstGraphBuilder::CreateGraphBody(bool stack_check) {
DeclarationScope* scope = info()->scope();
// Build the arguments object if it is used.
BuildArgumentsObject(scope->arguments());
// We don't support new.target and rest parameters here.
DCHECK_NULL(scope->new_target_var());
DCHECK_NULL(scope->rest_parameter());
DCHECK_NULL(scope->this_function_var());
// Emit tracing call if requested to do so.
if (FLAG_trace) {
NewNode(javascript()->CallRuntime(Runtime::kTraceEnter));
}
// Visit declarations within the function scope.
VisitDeclarations(scope->declarations());
// Build a stack-check before the body.
if (stack_check) {
NewNode(javascript()->StackCheck());
}
// Visit statements in the function body.
VisitStatements(info()->literal()->body());
// Return 'undefined' in case we can fall off the end.
BuildReturn(jsgraph()->UndefinedConstant());
}
static const char* GetDebugParameterName(Zone* zone, DeclarationScope* scope,
int index) {
#if DEBUG
const AstRawString* name = scope->parameter(index)->raw_name();
if (name && name->length() > 0) {
char* data = zone->NewArray<char>(name->length() + 1);
data[name->length()] = 0;
memcpy(data, name->raw_data(), name->length());
return data;
}
#endif
return nullptr;
}
AstGraphBuilder::Environment::Environment(AstGraphBuilder* builder,
DeclarationScope* scope,
Node* control_dependency)
: builder_(builder),
parameters_count_(scope->num_parameters() + 1),
locals_count_(scope->num_stack_slots()),
values_(builder_->local_zone()),
contexts_(builder_->local_zone()),
control_dependency_(control_dependency),
effect_dependency_(control_dependency),
parameters_node_(nullptr),
locals_node_(nullptr),
stack_node_(nullptr) {
DCHECK_EQ(scope->num_parameters() + 1, parameters_count());
// Bind the receiver variable.
int param_num = 0;
if (builder->info()->is_this_defined()) {
const Operator* op = common()->Parameter(param_num++, "%this");
Node* receiver = builder->graph()->NewNode(op, builder->graph()->start());
values()->push_back(receiver);
} else {
values()->push_back(builder->jsgraph()->UndefinedConstant());
}
// Bind all parameter variables. The parameter indices are shifted by 1
// (receiver is variable index -1 but {Parameter} node index 0 and located at
// index 0 in the environment).
for (int i = 0; i < scope->num_parameters(); ++i) {
const char* debug_name = GetDebugParameterName(graph()->zone(), scope, i);
const Operator* op = common()->Parameter(param_num++, debug_name);
Node* parameter = builder->graph()->NewNode(op, builder->graph()->start());
values()->push_back(parameter);
}
// Bind all local variables to undefined.
Node* undefined_constant = builder->jsgraph()->UndefinedConstant();
values()->insert(values()->end(), locals_count(), undefined_constant);
}
AstGraphBuilder::Environment::Environment(AstGraphBuilder::Environment* copy)
: builder_(copy->builder_),
parameters_count_(copy->parameters_count_),
locals_count_(copy->locals_count_),
values_(copy->zone()),
contexts_(copy->zone()),
control_dependency_(copy->control_dependency_),
effect_dependency_(copy->effect_dependency_),
parameters_node_(copy->parameters_node_),
locals_node_(copy->locals_node_),
stack_node_(copy->stack_node_) {
const size_t kStackEstimate = 7; // optimum from experimentation!
values_.reserve(copy->values_.size() + kStackEstimate);
values_.insert(values_.begin(), copy->values_.begin(), copy->values_.end());
contexts_.reserve(copy->contexts_.size());
contexts_.insert(contexts_.begin(), copy->contexts_.begin(),
copy->contexts_.end());
}
void AstGraphBuilder::Environment::Bind(Variable* variable, Node* node) {
DCHECK(variable->IsStackAllocated());
if (variable->IsParameter()) {
// The parameter indices are shifted by 1 (receiver is variable
// index -1 but located at index 0 in the environment).
values()->at(variable->index() + 1) = node;
} else {
DCHECK(variable->IsStackLocal());
values()->at(variable->index() + parameters_count_) = node;
}
}
Node* AstGraphBuilder::Environment::Lookup(Variable* variable) {
DCHECK(variable->IsStackAllocated());
if (variable->IsParameter()) {
// The parameter indices are shifted by 1 (receiver is variable
// index -1 but located at index 0 in the environment).
return values()->at(variable->index() + 1);
} else {
DCHECK(variable->IsStackLocal());
return values()->at(variable->index() + parameters_count_);
}
}
void AstGraphBuilder::Environment::RawParameterBind(int index, Node* node) {
DCHECK_LT(index, parameters_count());
values()->at(index) = node;
}
Node* AstGraphBuilder::Environment::RawParameterLookup(int index) {
DCHECK_LT(index, parameters_count());
return values()->at(index);
}
AstGraphBuilder::Environment*
AstGraphBuilder::Environment::CopyForConditional() {
return new (zone()) Environment(this);
}
AstGraphBuilder::Environment*
AstGraphBuilder::Environment::CopyAsUnreachable() {
Environment* env = new (zone()) Environment(this);
env->MarkAsUnreachable();
return env;
}
AstGraphBuilder::Environment* AstGraphBuilder::Environment::CopyForOsrEntry() {
return new (zone()) Environment(this);
}
AstGraphBuilder::Environment*
AstGraphBuilder::Environment::CopyAndShareLiveness() {
Environment* env = new (zone()) Environment(this);
return env;
}
AstGraphBuilder::Environment* AstGraphBuilder::Environment::CopyForLoop(
BitVector* assigned, bool is_osr) {
PrepareForLoop(assigned);
Environment* loop = CopyAndShareLiveness();
if (is_osr) {
// Create and merge the OSR entry if necessary.
Environment* osr_env = CopyForOsrEntry();
osr_env->PrepareForOsrEntry();
loop->Merge(osr_env);
}
return loop;
}
void AstGraphBuilder::Environment::PrepareForLoopExit(
Node* loop, BitVector* assigned_variables) {
if (IsMarkedAsUnreachable()) return;
DCHECK_EQ(loop->opcode(), IrOpcode::kLoop);
Node* control = GetControlDependency();
// Create the loop exit node.
Node* loop_exit = graph()->NewNode(common()->LoopExit(), control, loop);
UpdateControlDependency(loop_exit);
// Rename the environmnent values.
for (size_t i = 0; i < values()->size(); i++) {
if (assigned_variables == nullptr ||
static_cast<int>(i) >= assigned_variables->length() ||
assigned_variables->Contains(static_cast<int>(i))) {
Node* rename = graph()->NewNode(common()->LoopExitValue(), (*values())[i],
loop_exit);
(*values())[i] = rename;
}
}
// Rename the effect.
Node* effect_rename = graph()->NewNode(common()->LoopExitEffect(),
GetEffectDependency(), loop_exit);
UpdateEffectDependency(effect_rename);
}
AstGraphBuilder::AstContext::AstContext(AstGraphBuilder* own,
Expression::Context kind)
: kind_(kind), owner_(own), outer_(own->ast_context()) {
owner()->set_ast_context(this); // Push.
#ifdef DEBUG
original_height_ = environment()->stack_height();
#endif
}
AstGraphBuilder::AstContext::~AstContext() {
owner()->set_ast_context(outer_); // Pop.
}
AstGraphBuilder::AstEffectContext::~AstEffectContext() {
DCHECK(environment()->stack_height() == original_height_);
}
AstGraphBuilder::AstValueContext::~AstValueContext() {
DCHECK(environment()->stack_height() == original_height_ + 1);
}
AstGraphBuilder::AstTestContext::~AstTestContext() {
DCHECK(environment()->stack_height() == original_height_ + 1);
}
void AstGraphBuilder::AstEffectContext::ProduceValue(Expression* expr,
Node* value) {
// The value is ignored.
}
void AstGraphBuilder::AstValueContext::ProduceValue(Expression* expr,
Node* value) {
environment()->Push(value);
}
void AstGraphBuilder::AstTestContext::ProduceValue(Expression* expr,
Node* value) {
environment()->Push(owner()->BuildToBoolean(value));
}
Node* AstGraphBuilder::AstEffectContext::ConsumeValue() { return nullptr; }
Node* AstGraphBuilder::AstValueContext::ConsumeValue() {
return environment()->Pop();
}
Node* AstGraphBuilder::AstTestContext::ConsumeValue() {
return environment()->Pop();
}
Scope* AstGraphBuilder::current_scope() const {
return execution_context_->scope();
}
Node* AstGraphBuilder::current_context() const {
return environment()->Context();
}
void AstGraphBuilder::ControlScope::PerformCommand(Command command,
Statement* target,
Node* value) {
Environment* env = environment()->CopyAsUnreachable();
ControlScope* current = this;
while (current != nullptr) {
environment()->TrimStack(current->stack_height());
environment()->TrimContextChain(current->context_length());
if (current->Execute(command, target, &value)) break;
current = current->outer_;
}
builder()->set_environment(env);
DCHECK_NOT_NULL(current); // Always handled (unless stack is malformed).
}
void AstGraphBuilder::ControlScope::BreakTo(BreakableStatement* stmt) {
PerformCommand(CMD_BREAK, stmt, builder()->jsgraph()->TheHoleConstant());
}
void AstGraphBuilder::ControlScope::ContinueTo(BreakableStatement* stmt) {
PerformCommand(CMD_CONTINUE, stmt, builder()->jsgraph()->TheHoleConstant());
}
void AstGraphBuilder::ControlScope::ReturnValue(Node* return_value) {
PerformCommand(CMD_RETURN, nullptr, return_value);
}
void AstGraphBuilder::ControlScope::ThrowValue(Node* exception_value) {
PerformCommand(CMD_THROW, nullptr, exception_value);
}
void AstGraphBuilder::VisitForValueOrNull(Expression* expr) {
if (expr == nullptr) {
return environment()->Push(jsgraph()->NullConstant());
}
VisitForValue(expr);
}
void AstGraphBuilder::VisitForValueOrTheHole(Expression* expr) {
if (expr == nullptr) {
return environment()->Push(jsgraph()->TheHoleConstant());
}
VisitForValue(expr);
}
void AstGraphBuilder::VisitForValues(ZoneList<Expression*>* exprs) {
for (int i = 0; i < exprs->length(); ++i) {
VisitForValue(exprs->at(i));
}
}
void AstGraphBuilder::VisitForValue(Expression* expr) {
AstValueContext for_value(this);
if (!CheckStackOverflow()) {
VisitNoStackOverflowCheck(expr);
} else {
ast_context()->ProduceValue(expr, jsgraph()->UndefinedConstant());
}
}
void AstGraphBuilder::VisitForEffect(Expression* expr) {
AstEffectContext for_effect(this);
if (!CheckStackOverflow()) {
VisitNoStackOverflowCheck(expr);
} else {
ast_context()->ProduceValue(expr, jsgraph()->UndefinedConstant());
}
}
void AstGraphBuilder::VisitForTest(Expression* expr) {
AstTestContext for_condition(this);
if (!CheckStackOverflow()) {
VisitNoStackOverflowCheck(expr);
} else {
ast_context()->ProduceValue(expr, jsgraph()->UndefinedConstant());
}
}
void AstGraphBuilder::Visit(Expression* expr) {
// Reuses enclosing AstContext.
if (!CheckStackOverflow()) {
VisitNoStackOverflowCheck(expr);
} else {
ast_context()->ProduceValue(expr, jsgraph()->UndefinedConstant());
}
}
void AstGraphBuilder::VisitVariableDeclaration(VariableDeclaration* decl) {
Variable* variable = decl->proxy()->var();
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
DCHECK(!variable->binding_needs_init());
globals()->push_back(variable->name());
FeedbackSlot slot = decl->proxy()->VariableFeedbackSlot();
DCHECK(!slot.IsInvalid());
globals()->push_back(handle(Smi::FromInt(slot.ToInt()), isolate()));
globals()->push_back(isolate()->factory()->undefined_value());
globals()->push_back(isolate()->factory()->undefined_value());
break;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL:
if (variable->binding_needs_init()) {
Node* value = jsgraph()->TheHoleConstant();
environment()->Bind(variable, value);
}
break;
case VariableLocation::CONTEXT:
if (variable->binding_needs_init()) {
Node* value = jsgraph()->TheHoleConstant();
const Operator* op = javascript()->StoreContext(0, variable->index());
NewNode(op, value);
}
break;
case VariableLocation::LOOKUP:
case VariableLocation::MODULE:
UNREACHABLE();
}
}
void AstGraphBuilder::VisitFunctionDeclaration(FunctionDeclaration* decl) {
Variable* variable = decl->proxy()->var();
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
Handle<SharedFunctionInfo> function = Compiler::GetSharedFunctionInfo(
decl->fun(), info()->script(), info()->isolate());
// Check for stack-overflow exception.
if (function.is_null()) return SetStackOverflow();
globals()->push_back(variable->name());
FeedbackSlot slot = decl->proxy()->VariableFeedbackSlot();
DCHECK(!slot.IsInvalid());
globals()->push_back(handle(Smi::FromInt(slot.ToInt()), isolate()));
// We need the slot where the literals array lives, too.
slot = decl->fun()->LiteralFeedbackSlot();
DCHECK(!slot.IsInvalid());
globals()->push_back(handle(Smi::FromInt(slot.ToInt()), isolate()));
globals()->push_back(function);
break;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL: {
VisitForValue(decl->fun());
Node* value = environment()->Pop();
environment()->Bind(variable, value);
break;
}
case VariableLocation::CONTEXT: {
VisitForValue(decl->fun());
Node* value = environment()->Pop();
const Operator* op = javascript()->StoreContext(0, variable->index());
NewNode(op, value);
break;
}
case VariableLocation::LOOKUP:
case VariableLocation::MODULE:
UNREACHABLE();
}
}
void AstGraphBuilder::VisitBlock(Block* stmt) {
BlockBuilder block(this);
ControlScopeForBreakable scope(this, stmt, &block);
if (stmt->labels() != nullptr) block.BeginBlock();
if (stmt->scope() == nullptr) {
// Visit statements in the same scope, no declarations.
VisitStatements(stmt->statements());
} else {
// Visit declarations and statements in a block scope.
if (stmt->scope()->NeedsContext()) {
Node* context = BuildLocalBlockContext(stmt->scope());
ContextScope scope(this, stmt->scope(), context);
VisitDeclarations(stmt->scope()->declarations());
VisitStatements(stmt->statements());
} else {
VisitDeclarations(stmt->scope()->declarations());
VisitStatements(stmt->statements());
}
}
if (stmt->labels() != nullptr) block.EndBlock();
}
void AstGraphBuilder::VisitExpressionStatement(ExpressionStatement* stmt) {
VisitForEffect(stmt->expression());
}
void AstGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
// Do nothing.
}
void AstGraphBuilder::VisitSloppyBlockFunctionStatement(
SloppyBlockFunctionStatement* stmt) {
Visit(stmt->statement());
}
void AstGraphBuilder::VisitIfStatement(IfStatement* stmt) {
IfBuilder compare_if(this);
VisitForTest(stmt->condition());
Node* condition = environment()->Pop();
compare_if.If(condition);
compare_if.Then();
Visit(stmt->then_statement());
compare_if.Else();
Visit(stmt->else_statement());
compare_if.End();
}
void AstGraphBuilder::VisitContinueStatement(ContinueStatement* stmt) {
execution_control()->ContinueTo(stmt->target());
}
void AstGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
execution_control()->BreakTo(stmt->target());
}
void AstGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
VisitForValue(stmt->expression());
Node* result = environment()->Pop();
execution_control()->ReturnValue(result);
}
void AstGraphBuilder::VisitWithStatement(WithStatement* stmt) {
// Dynamic scoping is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
ZoneList<CaseClause*>* clauses = stmt->cases();
SwitchBuilder compare_switch(this, clauses->length());
ControlScopeForBreakable scope(this, stmt, &compare_switch);
compare_switch.BeginSwitch();
int default_index = -1;
// Keep the switch value on the stack until a case matches.
VisitForValue(stmt->tag());
// Iterate over all cases and create nodes for label comparison.
for (int i = 0; i < clauses->length(); i++) {
CaseClause* clause = clauses->at(i);
// The default is not a test, remember index.
if (clause->is_default()) {
default_index = i;
continue;
}
// Create nodes to perform label comparison as if via '==='. The switch
// value is still on the operand stack while the label is evaluated.
VisitForValue(clause->label());
Node* label = environment()->Pop();
Node* tag = environment()->Top();
CompareOperationHint hint = CompareOperationHint::kAny;
const Operator* op = javascript()->StrictEqual(hint);
Node* condition = NewNode(op, tag, label);
compare_switch.BeginLabel(i, condition);
// Discard the switch value at label match.
environment()->Pop();
compare_switch.EndLabel();
}
// Discard the switch value and mark the default case.
environment()->Pop();
if (default_index >= 0) {
compare_switch.DefaultAt(default_index);
}
// Iterate over all cases and create nodes for case bodies.
for (int i = 0; i < clauses->length(); i++) {
CaseClause* clause = clauses->at(i);
compare_switch.BeginCase(i);
VisitStatements(clause->statements());
compare_switch.EndCase();
}
compare_switch.EndSwitch();
}
void AstGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
LoopBuilder while_loop(this);
while_loop.BeginLoop(GetVariablesAssignedInLoop(stmt), CheckOsrEntry(stmt));
VisitIterationBody(stmt, &while_loop);
while_loop.EndBody();
VisitForTest(stmt->cond());
Node* condition = environment()->Pop();
while_loop.BreakUnless(condition);
while_loop.EndLoop();
}
void AstGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
LoopBuilder while_loop(this);
while_loop.BeginLoop(GetVariablesAssignedInLoop(stmt), CheckOsrEntry(stmt));
VisitForTest(stmt->cond());
Node* condition = environment()->Pop();
while_loop.BreakUnless(condition);
VisitIterationBody(stmt, &while_loop);
while_loop.EndBody();
while_loop.EndLoop();
}
void AstGraphBuilder::VisitForStatement(ForStatement* stmt) {
LoopBuilder for_loop(this);
VisitIfNotNull(stmt->init());
for_loop.BeginLoop(GetVariablesAssignedInLoop(stmt), CheckOsrEntry(stmt));
if (stmt->cond() != nullptr) {
VisitForTest(stmt->cond());
Node* condition = environment()->Pop();
for_loop.BreakUnless(condition);
} else {
for_loop.BreakUnless(jsgraph()->TrueConstant());
}
VisitIterationBody(stmt, &for_loop);
for_loop.EndBody();
VisitIfNotNull(stmt->next());
for_loop.EndLoop();
}
void AstGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
// Only the BytecodeGraphBuilder supports for-in.
return SetStackOverflow();
}
void AstGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
// Iterator looping is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
// Exception handling is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
// Exception handling is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
// Debugger statement is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
// Find or build a shared function info.
Handle<SharedFunctionInfo> shared_info = Compiler::GetSharedFunctionInfo(
expr, info()->script(), info()->isolate());
CHECK(!shared_info.is_null()); // TODO(mstarzinger): Set stack overflow?
// Create node to instantiate a new closure.
PretenureFlag pretenure = expr->pretenure() ? TENURED : NOT_TENURED;
VectorSlotPair pair = CreateVectorSlotPair(expr->LiteralFeedbackSlot());
const Operator* op =
javascript()->CreateClosure(shared_info, pair, pretenure);
Node* value = NewNode(op);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitClassLiteral(ClassLiteral* expr) { UNREACHABLE(); }
void AstGraphBuilder::VisitNativeFunctionLiteral(NativeFunctionLiteral* expr) {
UNREACHABLE();
}
void AstGraphBuilder::VisitDoExpression(DoExpression* expr) {
VisitBlock(expr->block());
VisitVariableProxy(expr->result());
ast_context()->ReplaceValue(expr);
}
void AstGraphBuilder::VisitConditional(Conditional* expr) {
IfBuilder compare_if(this);
VisitForTest(expr->condition());
Node* condition = environment()->Pop();
compare_if.If(condition);
compare_if.Then();
Visit(expr->then_expression());
compare_if.Else();
Visit(expr->else_expression());
compare_if.End();
// Skip plugging AST evaluation contexts of the test kind. This is to stay in
// sync with full codegen which doesn't prepare the proper bailout point (see
// the implementation of FullCodeGenerator::VisitForControl).
if (ast_context()->IsTest()) return;
ast_context()->ReplaceValue(expr);
}
void AstGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
VectorSlotPair pair = CreateVectorSlotPair(expr->VariableFeedbackSlot());
Node* value = BuildVariableLoad(expr->var(), pair);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitLiteral(Literal* expr) {
Node* value = jsgraph()->Constant(expr->value());
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
Node* closure = GetFunctionClosure();
// Create node to materialize a regular expression literal.
const Operator* op = javascript()->CreateLiteralRegExp(
expr->pattern(), expr->flags(),
FeedbackVector::GetIndex(expr->literal_slot()));
Node* literal = NewNode(op, closure);
ast_context()->ProduceValue(expr, literal);
}
void AstGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
Node* closure = GetFunctionClosure();
// Create node to deep-copy the literal boilerplate.
const Operator* op = javascript()->CreateLiteralObject(
expr->GetOrBuildConstantProperties(isolate()), expr->ComputeFlags(true),
FeedbackVector::GetIndex(expr->literal_slot()), expr->properties_count());
Node* literal = NewNode(op, closure);
// The object is expected on the operand stack during computation of the
// property values and is the value of the entire expression.
environment()->Push(literal);
// Create nodes to store computed values into the literal.
AccessorTable accessor_table(local_zone());
for (int i = 0; i < expr->properties()->length(); i++) {
ObjectLiteral::Property* property = expr->properties()->at(i);
DCHECK(!property->is_computed_name());
if (property->IsCompileTimeValue()) continue;
Literal* key = property->key()->AsLiteral();
switch (property->kind()) {
case ObjectLiteral::Property::SPREAD:
case ObjectLiteral::Property::CONSTANT:
UNREACHABLE();
case ObjectLiteral::Property::MATERIALIZED_LITERAL:
DCHECK(!CompileTimeValue::IsCompileTimeValue(property->value()));
// Fall through.
case ObjectLiteral::Property::COMPUTED: {
// It is safe to use [[Put]] here because the boilerplate already
// contains computed properties with an uninitialized value.
if (key->IsStringLiteral()) {
DCHECK(key->IsPropertyName());
if (property->emit_store()) {
VisitForValue(property->value());
Node* value = environment()->Pop();
Node* literal = environment()->Top();
Handle<Name> name = key->AsPropertyName();
VectorSlotPair feedback =
CreateVectorSlotPair(property->GetSlot(0));
BuildNamedStoreOwn(literal, name, value, feedback);
BuildSetHomeObject(value, literal, property, 1);
} else {
VisitForEffect(property->value());
}
break;
}
environment()->Push(environment()->Top()); // Duplicate receiver.
VisitForValue(property->key());
VisitForValue(property->value());
Node* value = environment()->Pop();
Node* key = environment()->Pop();
Node* receiver = environment()->Pop();
if (property->emit_store()) {
Node* language = jsgraph()->Constant(SLOPPY);
const Operator* op = javascript()->CallRuntime(Runtime::kSetProperty);
NewNode(op, receiver, key, value, language);
BuildSetHomeObject(value, receiver, property);
}
break;
}
case ObjectLiteral::Property::PROTOTYPE: {
environment()->Push(environment()->Top()); // Duplicate receiver.
VisitForValue(property->value());
Node* value = environment()->Pop();
Node* receiver = environment()->Pop();
DCHECK(property->emit_store());
const Operator* op =
javascript()->CallRuntime(Runtime::kInternalSetPrototype);
NewNode(op, receiver, value);
break;
}
case ObjectLiteral::Property::GETTER:
if (property->emit_store()) {
AccessorTable::Iterator it = accessor_table.lookup(key);
it->second->getter = property;
}
break;
case ObjectLiteral::Property::SETTER:
if (property->emit_store()) {
AccessorTable::Iterator it = accessor_table.lookup(key);
it->second->setter = property;
}
break;
}
}
// Create nodes to define accessors, using only a single call to the runtime
// for each pair of corresponding getters and setters.
literal = environment()->Top(); // Reload from operand stack.
for (AccessorTable::Iterator it = accessor_table.begin();
it != accessor_table.end(); ++it) {
VisitForValue(it->first);
VisitObjectLiteralAccessor(literal, it->second->getter);
VisitObjectLiteralAccessor(literal, it->second->setter);
Node* setter = environment()->Pop();
Node* getter = environment()->Pop();
Node* name = environment()->Pop();
Node* attr = jsgraph()->Constant(NONE);
const Operator* op =
javascript()->CallRuntime(Runtime::kDefineAccessorPropertyUnchecked);
NewNode(op, literal, name, getter, setter, attr);
}
ast_context()->ProduceValue(expr, environment()->Pop());
}
void AstGraphBuilder::VisitObjectLiteralAccessor(
Node* home_object, ObjectLiteralProperty* property) {
if (property == nullptr) {
VisitForValueOrNull(nullptr);
} else {
VisitForValue(property->value());
BuildSetHomeObject(environment()->Top(), home_object, property);
}
}
void AstGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
Node* closure = GetFunctionClosure();
// Create node to deep-copy the literal boilerplate.
const Operator* op = javascript()->CreateLiteralArray(
expr->GetOrBuildConstantElements(isolate()), expr->ComputeFlags(true),
FeedbackVector::GetIndex(expr->literal_slot()), expr->values()->length());
Node* literal = NewNode(op, closure);
// The array is expected on the operand stack during computation of the
// element values.
environment()->Push(literal);
// Create nodes to evaluate all the non-constant subexpressions and to store
// them into the newly cloned array.
for (int array_index = 0; array_index < expr->values()->length();
array_index++) {
Expression* subexpr = expr->values()->at(array_index);
DCHECK(!subexpr->IsSpread());
if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
VisitForValue(subexpr);
VectorSlotPair pair = CreateVectorSlotPair(expr->LiteralFeedbackSlot());
Node* value = environment()->Pop();
Node* index = jsgraph()->Constant(array_index);
Node* literal = environment()->Top();
BuildKeyedStore(literal, index, value, pair);
}
ast_context()->ProduceValue(expr, environment()->Pop());
}
void AstGraphBuilder::VisitAssignment(Assignment* expr) {
DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
// Left-hand side can only be a property, a global or a variable slot.
Property* property = expr->target()->AsProperty();
LhsKind assign_type = Property::GetAssignType(property);
// Evaluate LHS expression.
switch (assign_type) {
case VARIABLE:
break;
case NAMED_PROPERTY:
VisitForValue(property->obj());
break;
case KEYED_PROPERTY:
VisitForValue(property->obj());
VisitForValue(property->key());
break;
case NAMED_SUPER_PROPERTY:
case KEYED_SUPER_PROPERTY:
UNREACHABLE();
break;
}
// Evaluate the value and potentially handle compound assignments by loading
// the left-hand side value and performing a binary operation.
if (expr->is_compound()) {
Node* old_value = nullptr;
switch (assign_type) {
case VARIABLE: {
VariableProxy* proxy = expr->target()->AsVariableProxy();
VectorSlotPair pair =
CreateVectorSlotPair(proxy->VariableFeedbackSlot());
old_value = BuildVariableLoad(proxy->var(), pair);
break;
}
case NAMED_PROPERTY: {
Node* object = environment()->Top();
Handle<Name> name = property->key()->AsLiteral()->AsPropertyName();
VectorSlotPair pair =
CreateVectorSlotPair(property->PropertyFeedbackSlot());
old_value = BuildNamedLoad(object, name, pair);
break;
}
case KEYED_PROPERTY: {
Node* key = environment()->Top();
Node* object = environment()->Peek(1);
VectorSlotPair pair =
CreateVectorSlotPair(property->PropertyFeedbackSlot());
old_value = BuildKeyedLoad(object, key, pair);
break;
}
case NAMED_SUPER_PROPERTY:
case KEYED_SUPER_PROPERTY:
UNREACHABLE();
break;
}
environment()->Push(old_value);
VisitForValue(expr->value());
Node* right = environment()->Pop();
Node* left = environment()->Pop();
Node* value = BuildBinaryOp(left, right, expr->binary_op());
environment()->Push(value);
} else {
VisitForValue(expr->value());
}
// Store the value.
Node* value = environment()->Pop();
VectorSlotPair feedback = CreateVectorSlotPair(expr->AssignmentSlot());
switch (assign_type) {
case VARIABLE: {
Variable* variable = expr->target()->AsVariableProxy()->var();
BuildVariableAssignment(variable, value, expr->op(), feedback);
break;
}
case NAMED_PROPERTY: {
Node* object = environment()->Pop();
Handle<Name> name = property->key()->AsLiteral()->AsPropertyName();
BuildNamedStore(object, name, value, feedback);
break;
}
case KEYED_PROPERTY: {
Node* key = environment()->Pop();
Node* object = environment()->Pop();
BuildKeyedStore(object, key, value, feedback);
break;
}
case NAMED_SUPER_PROPERTY:
case KEYED_SUPER_PROPERTY:
UNREACHABLE();
break;
}
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitYield(Yield* expr) {
// Generator functions are supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitYieldStar(YieldStar* expr) {
// Generator functions are supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitAwait(Await* expr) {
// Generator functions are supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitThrow(Throw* expr) {
VisitForValue(expr->exception());
Node* exception = environment()->Pop();
Node* value = BuildThrowError(exception);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitProperty(Property* expr) {
Node* value = nullptr;
LhsKind property_kind = Property::GetAssignType(expr);
VectorSlotPair pair = CreateVectorSlotPair(expr->PropertyFeedbackSlot());
switch (property_kind) {
case VARIABLE:
UNREACHABLE();
break;
case NAMED_PROPERTY: {
VisitForValue(expr->obj());
Node* object = environment()->Pop();
Handle<Name> name = expr->key()->AsLiteral()->AsPropertyName();
value = BuildNamedLoad(object, name, pair);
break;
}
case KEYED_PROPERTY: {
VisitForValue(expr->obj());
VisitForValue(expr->key());
Node* key = environment()->Pop();
Node* object = environment()->Pop();
value = BuildKeyedLoad(object, key, pair);
break;
}
case NAMED_SUPER_PROPERTY:
case KEYED_SUPER_PROPERTY:
UNREACHABLE();
break;
}
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitCall(Call* expr) {
Expression* callee = expr->expression();
Call::CallType call_type = expr->GetCallType();
CHECK(!expr->is_possibly_eval());
// Prepare the callee and the receiver to the function call. This depends on
// the semantics of the underlying call type.
ConvertReceiverMode receiver_hint = ConvertReceiverMode::kAny;
Node* receiver_value = nullptr;
Node* callee_value = nullptr;
switch (call_type) {
case Call::GLOBAL_CALL: {
VariableProxy* proxy = callee->AsVariableProxy();
VectorSlotPair pair = CreateVectorSlotPair(proxy->VariableFeedbackSlot());
callee_value = BuildVariableLoad(proxy->var(), pair);
receiver_hint = ConvertReceiverMode::kNullOrUndefined;
receiver_value = jsgraph()->UndefinedConstant();
break;
}
case Call::NAMED_PROPERTY_CALL: {
Property* property = callee->AsProperty();
VectorSlotPair feedback =
CreateVectorSlotPair(property->PropertyFeedbackSlot());
VisitForValue(property->obj());
Handle<Name> name = property->key()->AsLiteral()->AsPropertyName();
Node* object = environment()->Top();
callee_value = BuildNamedLoad(object, name, feedback);
// Note that a property call requires the receiver to be wrapped into
// an object for sloppy callees. However the receiver is guaranteed
// not to be null or undefined at this point.
receiver_hint = ConvertReceiverMode::kNotNullOrUndefined;
receiver_value = environment()->Pop();
break;
}
case Call::KEYED_PROPERTY_CALL: {
Property* property = callee->AsProperty();
VectorSlotPair feedback =
CreateVectorSlotPair(property->PropertyFeedbackSlot());
VisitForValue(property->obj());
VisitForValue(property->key());
Node* key = environment()->Pop();
Node* object = environment()->Top();
callee_value = BuildKeyedLoad(object, key, feedback);
// Note that a property call requires the receiver to be wrapped into
// an object for sloppy callees. However the receiver is guaranteed
// not to be null or undefined at this point.
receiver_hint = ConvertReceiverMode::kNotNullOrUndefined;
receiver_value = environment()->Pop();
break;
}
case Call::OTHER_CALL:
VisitForValue(callee);
callee_value = environment()->Pop();
receiver_hint = ConvertReceiverMode::kNullOrUndefined;
receiver_value = jsgraph()->UndefinedConstant();
break;
case Call::NAMED_SUPER_PROPERTY_CALL:
case Call::KEYED_SUPER_PROPERTY_CALL:
case Call::SUPER_CALL:
case Call::WITH_CALL:
UNREACHABLE();
}
// The callee and the receiver both have to be pushed onto the operand stack
// before arguments are being evaluated.
environment()->Push(callee_value);
environment()->Push(receiver_value);
// Evaluate all arguments to the function call,
ZoneList<Expression*>* args = expr->arguments();
VisitForValues(args);
// Create node to perform the function call.
CallFrequency frequency = ComputeCallFrequency(expr->CallFeedbackICSlot());
VectorSlotPair feedback = CreateVectorSlotPair(expr->CallFeedbackICSlot());
const Operator* call = javascript()->Call(args->length() + 2, frequency,
feedback, receiver_hint);
Node* value = ProcessArguments(call, args->length() + 2);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitCallNew(CallNew* expr) {
VisitForValue(expr->expression());
// Evaluate all arguments to the construct call.
ZoneList<Expression*>* args = expr->arguments();
VisitForValues(args);
// The new target is the same as the callee.
environment()->Push(environment()->Peek(args->length()));
// Create node to perform the construct call.
CallFrequency frequency = ComputeCallFrequency(expr->CallNewFeedbackSlot());
VectorSlotPair feedback = CreateVectorSlotPair(expr->CallNewFeedbackSlot());
const Operator* call =
javascript()->Construct(args->length() + 2, frequency, feedback);
Node* value = ProcessArguments(call, args->length() + 2);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitCallJSRuntime(CallRuntime* expr) {
// The callee and the receiver both have to be pushed onto the operand stack
// before arguments are being evaluated.
Node* callee_value = BuildLoadNativeContextField(expr->context_index());
Node* receiver_value = jsgraph()->UndefinedConstant();
environment()->Push(callee_value);
environment()->Push(receiver_value);
// Evaluate all arguments to the JS runtime call.
ZoneList<Expression*>* args = expr->arguments();
VisitForValues(args);
// Create node to perform the JS runtime call.
const Operator* call = javascript()->Call(args->length() + 2);
Node* value = ProcessArguments(call, args->length() + 2);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
// Handle calls to runtime functions implemented in JavaScript separately as
// the call follows JavaScript ABI and the callee is statically unknown.
if (expr->is_jsruntime()) {
return VisitCallJSRuntime(expr);
}
// Evaluate all arguments to the runtime call.
ZoneList<Expression*>* args = expr->arguments();
VisitForValues(args);
// Create node to perform the runtime call.
Runtime::FunctionId functionId = expr->function()->function_id;
const Operator* call = javascript()->CallRuntime(functionId, args->length());
Node* value = ProcessArguments(call, args->length());
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
switch (expr->op()) {
case Token::DELETE:
return VisitDelete(expr);
case Token::VOID:
return VisitVoid(expr);
case Token::TYPEOF:
return VisitTypeof(expr);
case Token::NOT:
return VisitNot(expr);
default:
UNREACHABLE();
}
}
void AstGraphBuilder::VisitCountOperation(CountOperation* expr) {
DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
// Left-hand side can only be a property, a global or a variable slot.
Property* property = expr->expression()->AsProperty();
LhsKind assign_type = Property::GetAssignType(property);
// Reserve space for result of postfix operation.
bool is_postfix = expr->is_postfix() && !ast_context()->IsEffect();
if (is_postfix && assign_type != VARIABLE) {
environment()->Push(jsgraph()->ZeroConstant());
}
// Evaluate LHS expression and get old value.
Node* old_value = nullptr;
int stack_depth = -1;
switch (assign_type) {
case VARIABLE: {
VariableProxy* proxy = expr->expression()->AsVariableProxy();
VectorSlotPair pair = CreateVectorSlotPair(proxy->VariableFeedbackSlot());
old_value = BuildVariableLoad(proxy->var(), pair);
stack_depth = 0;
break;
}
case NAMED_PROPERTY: {
VisitForValue(property->obj());
Node* object = environment()->Top();
Handle<Name> name = property->key()->AsLiteral()->AsPropertyName();
VectorSlotPair pair =
CreateVectorSlotPair(property->PropertyFeedbackSlot());
old_value = BuildNamedLoad(object, name, pair);
stack_depth = 1;
break;
}
case KEYED_PROPERTY: {
VisitForValue(property->obj());
VisitForValue(property->key());
Node* key = environment()->Top();
Node* object = environment()->Peek(1);
VectorSlotPair pair =
CreateVectorSlotPair(property->PropertyFeedbackSlot());
old_value = BuildKeyedLoad(object, key, pair);
stack_depth = 2;
break;
}
case NAMED_SUPER_PROPERTY:
case KEYED_SUPER_PROPERTY:
UNREACHABLE();
break;
}
// Convert old value into a number.
old_value = NewNode(javascript()->ToNumber(), old_value);
// Create a proper eager frame state for the stores.
environment()->Push(old_value);
old_value = environment()->Pop();
// Save result for postfix expressions at correct stack depth.
if (is_postfix) {
if (assign_type != VARIABLE) {
environment()->Poke(stack_depth, old_value);
} else {
environment()->Push(old_value);
}
}
// Create node to perform +1/-1 operation.
Node* value =
BuildBinaryOp(old_value, jsgraph()->OneConstant(), expr->binary_op());
// Store the value.
VectorSlotPair feedback = CreateVectorSlotPair(expr->CountSlot());
switch (assign_type) {
case VARIABLE: {
Variable* variable = expr->expression()->AsVariableProxy()->var();
environment()->Push(value);
BuildVariableAssignment(variable, value, expr->op(), feedback);
environment()->Pop();
break;
}
case NAMED_PROPERTY: {
Node* object = environment()->Pop();
Handle<Name> name = property->key()->AsLiteral()->AsPropertyName();
BuildNamedStore(object, name, value, feedback);
break;
}
case KEYED_PROPERTY: {
Node* key = environment()->Pop();
Node* object = environment()->Pop();
BuildKeyedStore(object, key, value, feedback);
break;
}
case NAMED_SUPER_PROPERTY:
case KEYED_SUPER_PROPERTY:
UNREACHABLE();
break;
}
// Restore old value for postfix expressions.
if (is_postfix) value = environment()->Pop();
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
switch (expr->op()) {
case Token::COMMA:
return VisitComma(expr);
case Token::OR:
case Token::AND:
return VisitLogicalExpression(expr);
default: {
VisitForValue(expr->left());
VisitForValue(expr->right());
Node* right = environment()->Pop();
Node* left = environment()->Pop();
Node* value = BuildBinaryOp(left, right, expr->op());
ast_context()->ProduceValue(expr, value);
}
}
}
void AstGraphBuilder::VisitLiteralCompareNil(CompareOperation* expr,
Expression* sub_expr,
Node* nil_value) {
const Operator* op = nullptr;
switch (expr->op()) {
case Token::EQ:
op = javascript()->Equal(CompareOperationHint::kAny);
break;
case Token::EQ_STRICT:
op = javascript()->StrictEqual(CompareOperationHint::kAny);
break;
default:
UNREACHABLE();
}
VisitForValue(sub_expr);
Node* value_to_compare = environment()->Pop();
Node* value = NewNode(op, value_to_compare, nil_value);
return ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitLiteralCompareTypeof(CompareOperation* expr,
Expression* sub_expr,
Handle<String> check) {
VisitTypeofExpression(sub_expr);
Node* typeof_arg = NewNode(javascript()->TypeOf(), environment()->Pop());
Node* value = NewNode(javascript()->StrictEqual(CompareOperationHint::kAny),
typeof_arg, jsgraph()->Constant(check));
return ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
// Check for a few fast cases. The AST visiting behavior must be in sync
// with the full codegen: We don't push both left and right values onto
// the expression stack when one side is a special-case literal.
Expression* sub_expr = nullptr;
Literal* literal;
if (expr->IsLiteralCompareTypeof(&sub_expr, &literal)) {
return VisitLiteralCompareTypeof(expr, sub_expr,
Handle<String>::cast(literal->value()));
}
if (expr->IsLiteralCompareUndefined(&sub_expr)) {
return VisitLiteralCompareNil(expr, sub_expr,
jsgraph()->UndefinedConstant());
}
if (expr->IsLiteralCompareNull(&sub_expr)) {
return VisitLiteralCompareNil(expr, sub_expr, jsgraph()->NullConstant());
}
CompareOperationHint hint = CompareOperationHint::kAny;
const Operator* op;
switch (expr->op()) {
case Token::EQ:
op = javascript()->Equal(hint);
break;
case Token::EQ_STRICT:
op = javascript()->StrictEqual(hint);
break;
case Token::LT:
op = javascript()->LessThan(hint);
break;
case Token::GT:
op = javascript()->GreaterThan(hint);
break;
case Token::LTE:
op = javascript()->LessThanOrEqual(hint);
break;
case Token::GTE:
op = javascript()->GreaterThanOrEqual(hint);
break;
case Token::INSTANCEOF:
op = javascript()->InstanceOf();
break;
case Token::IN:
op = javascript()->HasProperty();
break;
default:
op = nullptr;
UNREACHABLE();
}
VisitForValue(expr->left());
VisitForValue(expr->right());
Node* right = environment()->Pop();
Node* left = environment()->Pop();
Node* value = NewNode(op, left, right);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitSpread(Spread* expr) {
// Handled entirely by the parser itself.
UNREACHABLE();
}
void AstGraphBuilder::VisitEmptyParentheses(EmptyParentheses* expr) {
// Handled entirely by the parser itself.
UNREACHABLE();
}
void AstGraphBuilder::VisitGetIterator(GetIterator* expr) {
// GetIterator is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitImportCallExpression(ImportCallExpression* expr) {
// ImportCallExpression is supported only by going through Ignition first.
UNREACHABLE();
}
void AstGraphBuilder::VisitThisFunction(ThisFunction* expr) {
Node* value = GetFunctionClosure();
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitSuperPropertyReference(
SuperPropertyReference* expr) {
UNREACHABLE();
}
void AstGraphBuilder::VisitSuperCallReference(SuperCallReference* expr) {
// Handled by VisitCall
UNREACHABLE();
}
void AstGraphBuilder::VisitCaseClause(CaseClause* expr) {
// Handled entirely in VisitSwitch.
UNREACHABLE();
}
void AstGraphBuilder::VisitDeclarations(Declaration::List* declarations) {
DCHECK(globals()->empty());
AstVisitor<AstGraphBuilder>::VisitDeclarations(declarations);
if (globals()->empty()) return;
int array_index = 0;
Handle<FeedbackVector> feedback_vector(info()->closure()->feedback_vector());
Handle<FixedArray> data = isolate()->factory()->NewFixedArray(
static_cast<int>(globals()->size()), TENURED);
for (Handle<Object> obj : *globals()) data->set(array_index++, *obj);
int encoded_flags = info()->GetDeclareGlobalsFlags();
Node* flags = jsgraph()->Constant(encoded_flags);
Node* decls = jsgraph()->Constant(data);
Node* vector = jsgraph()->Constant(feedback_vector);
const Operator* op = javascript()->CallRuntime(Runtime::kDeclareGlobals);
NewNode(op, decls, flags, vector);
globals()->clear();
}
void AstGraphBuilder::VisitIfNotNull(Statement* stmt) {
if (stmt == nullptr) return;
Visit(stmt);
}
void AstGraphBuilder::VisitIterationBody(IterationStatement* stmt,
LoopBuilder* loop) {
ControlScopeForIteration scope(this, stmt, loop);
NewNode(javascript()->StackCheck());
Visit(stmt->body());
}
void AstGraphBuilder::VisitDelete(UnaryOperation* expr) {
Node* value;
if (expr->expression()->IsVariableProxy()) {
// Delete of an unqualified identifier is disallowed in strict mode but
// "delete this" is allowed.
Variable* variable = expr->expression()->AsVariableProxy()->var();
DCHECK(is_sloppy(language_mode()) || variable->is_this());
value = BuildVariableDelete(variable);
} else if (expr->expression()->IsProperty()) {
Property* property = expr->expression()->AsProperty();
VisitForValue(property->obj());
VisitForValue(property->key());
Node* key = environment()->Pop();
Node* object = environment()->Pop();
Node* mode = jsgraph()->Constant(static_cast<int32_t>(language_mode()));
value = NewNode(javascript()->DeleteProperty(), object, key, mode);
} else {
VisitForEffect(expr->expression());
value = jsgraph()->TrueConstant();
}
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitVoid(UnaryOperation* expr) {
VisitForEffect(expr->expression());
Node* value = jsgraph()->UndefinedConstant();
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitTypeofExpression(Expression* expr) {
if (expr->IsVariableProxy()) {
// Typeof does not throw a reference error on global variables, hence we
// perform a non-contextual load in case the operand is a variable proxy.
VariableProxy* proxy = expr->AsVariableProxy();
VectorSlotPair pair = CreateVectorSlotPair(proxy->VariableFeedbackSlot());
Node* load = BuildVariableLoad(proxy->var(), pair, INSIDE_TYPEOF);
environment()->Push(load);
} else {
VisitForValue(expr);
}
}
void AstGraphBuilder::VisitTypeof(UnaryOperation* expr) {
VisitTypeofExpression(expr->expression());
Node* value = NewNode(javascript()->TypeOf(), environment()->Pop());
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitNot(UnaryOperation* expr) {
VisitForTest(expr->expression());
Node* input = environment()->Pop();
Node* value = NewNode(common()->Select(MachineRepresentation::kTagged), input,
jsgraph()->FalseConstant(), jsgraph()->TrueConstant());
// Skip plugging AST evaluation contexts of the test kind. This is to stay in
// sync with full codegen which doesn't prepare the proper bailout point (see
// the implementation of FullCodeGenerator::VisitForControl).
if (ast_context()->IsTest()) return environment()->Push(value);
ast_context()->ProduceValue(expr, value);
}
void AstGraphBuilder::VisitComma(BinaryOperation* expr) {
VisitForEffect(expr->left());
Visit(expr->right());
// Skip plugging AST evaluation contexts of the test kind. This is to stay in
// sync with full codegen which doesn't prepare the proper bailout point (see
// the implementation of FullCodeGenerator::VisitForControl).
if (ast_context()->IsTest()) return;
ast_context()->ReplaceValue(expr);
}
void AstGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
bool is_logical_and = expr->op() == Token::AND;
IfBuilder compare_if(this);
// Only use an AST evaluation context of the value kind when this expression
// is evaluated as value as well. Otherwise stick to a test context which is
// in sync with full codegen (see FullCodeGenerator::VisitLogicalExpression).
Node* condition = nullptr;
if (ast_context()->IsValue()) {
VisitForValue(expr->left());
Node* left = environment()->Top();
condition = BuildToBoolean(left);
} else {
VisitForTest(expr->left());
condition = environment()->Top();
}
compare_if.If(condition);
compare_if.Then();
if (is_logical_and) {
environment()->Pop();
Visit(expr->right());
} else if (ast_context()->IsEffect()) {
environment()->Pop();
} else if (ast_context()->IsTest()) {
environment()->Poke(0, jsgraph()->TrueConstant());
}
compare_if.Else();
if (!is_logical_and) {
environment()->Pop();
Visit(expr->right());
} else if (ast_context()->IsEffect()) {
environment()->Pop();
} else if (ast_context()->IsTest()) {
environment()->Poke(0, jsgraph()->FalseConstant());
}
compare_if.End();
// Skip plugging AST evaluation contexts of the test kind. This is to stay in
// sync with full codegen which doesn't prepare the proper bailout point (see
// the implementation of FullCodeGenerator::VisitForControl).
if (ast_context()->IsTest()) return;
ast_context()->ReplaceValue(expr);
}
LanguageMode AstGraphBuilder::language_mode() const {
return current_scope()->language_mode();
}
VectorSlotPair AstGraphBuilder::CreateVectorSlotPair(FeedbackSlot slot) const {
return VectorSlotPair(handle(info()->closure()->feedback_vector()), slot);
}
void AstGraphBuilder::VisitRewritableExpression(RewritableExpression* node) {
Visit(node->expression());
}
CallFrequency AstGraphBuilder::ComputeCallFrequency(FeedbackSlot slot) const {
if (invocation_frequency_.IsUnknown() || slot.IsInvalid()) {
return CallFrequency();
}
Handle<FeedbackVector> feedback_vector(info()->closure()->feedback_vector(),
isolate());
CallICNexus nexus(feedback_vector, slot);
return CallFrequency(nexus.ComputeCallFrequency() *
invocation_frequency_.value());
}
Node* AstGraphBuilder::ProcessArguments(const Operator* op, int arity) {
DCHECK(environment()->stack_height() >= arity);
Node** all = info()->zone()->NewArray<Node*>(arity);
for (int i = arity - 1; i >= 0; --i) {
all[i] = environment()->Pop();
}
Node* value = NewNode(op, arity, all);
return value;
}
Node* AstGraphBuilder::BuildLocalActivationContext(Node* context) {
DeclarationScope* scope = info()->scope();
// Allocate a new local context.
Node* local_context = scope->is_script_scope()
? BuildLocalScriptContext(scope)
: BuildLocalFunctionContext(scope);
if (scope->has_this_declaration() && scope->receiver()->IsContextSlot()) {
Node* receiver = environment()->RawParameterLookup(0);
// Context variable (at bottom of the context chain).
Variable* variable = scope->receiver();
DCHECK_EQ(0, scope->ContextChainLength(variable->scope()));
const Operator* op = javascript()->StoreContext(0, variable->index());
Node* node = NewNode(op, receiver);
NodeProperties::ReplaceContextInput(node, local_context);
}
// Copy parameters into context if necessary.
int num_parameters = scope->num_parameters();
for (int i = 0; i < num_parameters; i++) {
Variable* variable = scope->parameter(i);
if (!variable->IsContextSlot()) continue;
Node* parameter = environment()->RawParameterLookup(i + 1);
// Context variable (at bottom of the context chain).
DCHECK_EQ(0, scope->ContextChainLength(variable->scope()));
const Operator* op = javascript()->StoreContext(0, variable->index());
Node* node = NewNode(op, parameter);
NodeProperties::ReplaceContextInput(node, local_context);
}
return local_context;
}
Node* AstGraphBuilder::BuildLocalFunctionContext(Scope* scope) {
DCHECK(scope->is_function_scope() || scope->is_eval_scope());
// Allocate a new local context.
int slot_count = scope->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
const Operator* op =
javascript()->CreateFunctionContext(slot_count, scope->scope_type());
Node* local_context = NewNode(op, GetFunctionClosure());
return local_context;
}
Node* AstGraphBuilder::BuildLocalScriptContext(Scope* scope) {
DCHECK(scope->is_script_scope());
// Allocate a new local context.
Handle<ScopeInfo> scope_info = scope->scope_info();
const Operator* op = javascript()->CreateScriptContext(scope_info);
Node* local_context = NewNode(op, GetFunctionClosure());
return local_context;
}
Node* AstGraphBuilder::BuildLocalBlockContext(Scope* scope) {
DCHECK(scope->is_block_scope());
// Allocate a new local context.
Handle<ScopeInfo> scope_info = scope->scope_info();
const Operator* op = javascript()->CreateBlockContext(scope_info);
Node* local_context = NewNode(op, GetFunctionClosureForContext());
return local_context;
}
Node* AstGraphBuilder::BuildArgumentsObject(Variable* arguments) {
if (arguments == nullptr) return nullptr;
// Allocate and initialize a new arguments object.
CreateArgumentsType type =
is_strict(language_mode()) || !info()->has_simple_parameters()
? CreateArgumentsType::kUnmappedArguments
: CreateArgumentsType::kMappedArguments;
const Operator* op = javascript()->CreateArguments(type);
Node* object = NewNode(op, GetFunctionClosure());
// Assign the object to the {arguments} variable. This should never lazy
// deopt, so it is fine to send invalid bailout id.
DCHECK(arguments->IsContextSlot() || arguments->IsStackAllocated());
BuildVariableAssignment(arguments, object, Token::ASSIGN, VectorSlotPair());
return object;
}
Node* AstGraphBuilder::BuildHoleCheckThenThrow(Node* value, Variable* variable,
Node* not_hole) {
IfBuilder hole_check(this);
Node* the_hole = jsgraph()->TheHoleConstant();
Node* check = NewNode(javascript()->StrictEqual(CompareOperationHint::kAny),
value, the_hole);
hole_check.If(check);
hole_check.Then();
Node* error = BuildThrowReferenceError(variable);
environment()->Push(error);
hole_check.Else();
environment()->Push(not_hole);
hole_check.End();
return environment()->Pop();
}
Node* AstGraphBuilder::BuildHoleCheckElseThrow(Node* value, Variable* variable,
Node* for_hole) {
IfBuilder hole_check(this);
Node* the_hole = jsgraph()->TheHoleConstant();
Node* check = NewNode(javascript()->StrictEqual(CompareOperationHint::kAny),
value, the_hole);
hole_check.If(check);
hole_check.Then();
environment()->Push(for_hole);
hole_check.Else();
Node* error = BuildThrowReferenceError(variable);
environment()->Push(error);
hole_check.End();
return environment()->Pop();
}
Node* AstGraphBuilder::BuildVariableLoad(Variable* variable,
const VectorSlotPair& feedback,
TypeofMode typeof_mode) {
Node* the_hole = jsgraph()->TheHoleConstant();
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
// Global var, const, or let variable.
Handle<Name> name = variable->name();
if (Node* node = TryLoadGlobalConstant(name)) return node;
Node* value = BuildGlobalLoad(name, feedback, typeof_mode);
return value;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL: {
// Local var, const, or let variable.
Node* value = environment()->Lookup(variable);
if (variable->binding_needs_init()) {
// Perform check for uninitialized let/const variables.
if (value->op() == the_hole->op()) {
value = BuildThrowReferenceError(variable);
} else if (value->opcode() == IrOpcode::kPhi) {
value = BuildHoleCheckThenThrow(value, variable, value);
}
}
return value;
}
case VariableLocation::CONTEXT: {
// Context variable (potentially up the context chain).
int depth = current_scope()->ContextChainLength(variable->scope());
// TODO(mstarzinger): The {maybe_assigned} flag computed during variable
// resolution is highly inaccurate and cannot be trusted. We are only
// taking this information into account when asm.js compilation is used.
bool immutable = variable->maybe_assigned() == kNotAssigned &&
info()->is_function_context_specializing();
const Operator* op =
javascript()->LoadContext(depth, variable->index(), immutable);
Node* value = NewNode(op);
// TODO(titzer): initialization checks are redundant for already
// initialized immutable context loads, but only specialization knows.
// Maybe specializer should be a parameter to the graph builder?
if (variable->binding_needs_init()) {
// Perform check for uninitialized let/const variables.
value = BuildHoleCheckThenThrow(value, variable, value);
}
return value;
}
case VariableLocation::LOOKUP:
case VariableLocation::MODULE:
UNREACHABLE();
}
UNREACHABLE();
}
Node* AstGraphBuilder::BuildVariableDelete(Variable* variable) {
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
// Global var, const, or let variable.
Node* global = BuildLoadGlobalObject();
Node* name = jsgraph()->Constant(variable->name());
Node* mode = jsgraph()->Constant(static_cast<int32_t>(language_mode()));
const Operator* op = javascript()->DeleteProperty();
Node* result = NewNode(op, global, name, mode);
return result;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL:
case VariableLocation::CONTEXT: {
// Local var, const, or let variable or context variable.
return jsgraph()->BooleanConstant(variable->is_this());
}
case VariableLocation::LOOKUP:
case VariableLocation::MODULE:
UNREACHABLE();
}
UNREACHABLE();
}
Node* AstGraphBuilder::BuildVariableAssignment(Variable* variable, Node* value,
Token::Value op,
const VectorSlotPair& feedback) {
Node* the_hole = jsgraph()->TheHoleConstant();
VariableMode mode = variable->mode();
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
// Global var, const, or let variable.
Handle<Name> name = variable->name();
Node* store = BuildGlobalStore(name, value, feedback);
return store;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL:
// Local var, const, or let variable.
if (mode == LET && op == Token::INIT) {
// No initialization check needed because scoping guarantees it. Note
// that we still perform a lookup to keep the variable live, because
// baseline code might contain debug code that inspects the variable.
Node* current = environment()->Lookup(variable);
CHECK_NOT_NULL(current);
} else if (mode == LET && op != Token::INIT &&
variable->binding_needs_init()) {
// Perform an initialization check for let declared variables.
Node* current = environment()->Lookup(variable);
if (current->op() == the_hole->op()) {
return BuildThrowReferenceError(variable);
} else if (current->opcode() == IrOpcode::kPhi) {
BuildHoleCheckThenThrow(current, variable, value);
}
} else if (mode == CONST && op == Token::INIT) {
// Perform an initialization check for const {this} variables.
// Note that the {this} variable is the only const variable being able
// to trigger bind operations outside the TDZ, via {super} calls.
Node* current = environment()->Lookup(variable);
if (current->op() != the_hole->op() && variable->is_this()) {
value = BuildHoleCheckElseThrow(current, variable, value);
}
} else if (mode == CONST && op != Token::INIT &&
variable->is_sloppy_function_name()) {
// Non-initializing assignment to sloppy function names is
// - exception in strict mode.
// - ignored in sloppy mode.
DCHECK(!variable->binding_needs_init());
if (variable->throw_on_const_assignment(language_mode())) {
return BuildThrowConstAssignError();
}
return value;
} else if (mode == CONST && op != Token::INIT) {
if (variable->binding_needs_init()) {
Node* current = environment()->Lookup(variable);
if (current->op() == the_hole->op()) {
return BuildThrowReferenceError(variable);
} else if (current->opcode() == IrOpcode::kPhi) {
BuildHoleCheckThenThrow(current, variable, value);
}
}
// Assignment to const is exception in all modes.
return BuildThrowConstAssignError();
}
environment()->Bind(variable, value);
return value;
case VariableLocation::CONTEXT: {
// Context variable (potentially up the context chain).
int depth = current_scope()->ContextChainLength(variable->scope());
if (mode == LET && op != Token::INIT && variable->binding_needs_init()) {
// Perform an initialization check for let declared variables.
const Operator* op =
javascript()->LoadContext(depth, variable->index(), false);
Node* current = NewNode(op);
value = BuildHoleCheckThenThrow(current, variable, value);
} else if (mode == CONST && op == Token::INIT) {
// Perform an initialization check for const {this} variables.
// Note that the {this} variable is the only const variable being able
// to trigger bind operations outside the TDZ, via {super} calls.
if (variable->is_this()) {
const Operator* op =
javascript()->LoadContext(depth, variable->index(), false);
Node* current = NewNode(op);
value = BuildHoleCheckElseThrow(current, variable, value);
}
} else if (mode == CONST && op != Token::INIT &&
variable->is_sloppy_function_name()) {
// Non-initializing assignment to sloppy function names is
// - exception in strict mode.
// - ignored in sloppy mode.
DCHECK(!variable->binding_needs_init());
if (variable->throw_on_const_assignment(language_mode())) {
return BuildThrowConstAssignError();
}
return value;
} else if (mode == CONST && op != Token::INIT) {
if (variable->binding_needs_init()) {
const Operator* op =
javascript()->LoadContext(depth, variable->index(), false);
Node* current = NewNode(op);
BuildHoleCheckThenThrow(current, variable, value);
}
// Assignment to const is exception in all modes.
return BuildThrowConstAssignError();
}
const Operator* op = javascript()->StoreContext(depth, variable->index());
return NewNode(op, value);
}
case VariableLocation::LOOKUP:
case VariableLocation::MODULE:
UNREACHABLE();
}
UNREACHABLE();
}
Node* AstGraphBuilder::BuildKeyedLoad(Node* object, Node* key,
const VectorSlotPair& feedback) {
const Operator* op = javascript()->LoadProperty(feedback);
Node* node = NewNode(op, object, key);
return node;
}
Node* AstGraphBuilder::BuildNamedLoad(Node* object, Handle<Name> name,
const VectorSlotPair& feedback) {
const Operator* op = javascript()->LoadNamed(name, feedback);
Node* node = NewNode(op, object);
return node;
}
Node* AstGraphBuilder::BuildKeyedStore(Node* object, Node* key, Node* value,
const VectorSlotPair& feedback) {
DCHECK_EQ(feedback.vector()->GetLanguageMode(feedback.slot()),
language_mode());
const Operator* op = javascript()->StoreProperty(language_mode(), feedback);
Node* node = NewNode(op, object, key, value);
return node;
}
Node* AstGraphBuilder::BuildNamedStore(Node* object, Handle<Name> name,
Node* value,
const VectorSlotPair& feedback) {
DCHECK_EQ(feedback.vector()->GetLanguageMode(feedback.slot()),
language_mode());
const Operator* op =
javascript()->StoreNamed(language_mode(), name, feedback);
Node* node = NewNode(op, object, value);
return node;
}
Node* AstGraphBuilder::BuildNamedStoreOwn(Node* object, Handle<Name> name,
Node* value,
const VectorSlotPair& feedback) {
DCHECK_EQ(FeedbackSlotKind::kStoreOwnNamed,
feedback.vector()->GetKind(feedback.slot()));
const Operator* op = javascript()->StoreNamedOwn(name, feedback);
Node* node = NewNode(op, object, value);
return node;
}
Node* AstGraphBuilder::BuildGlobalLoad(Handle<Name> name,
const VectorSlotPair& feedback,
TypeofMode typeof_mode) {
DCHECK_EQ(feedback.vector()->GetTypeofMode(feedback.slot()), typeof_mode);
const Operator* op = javascript()->LoadGlobal(name, feedback, typeof_mode);
Node* node = NewNode(op);
return node;
}
Node* AstGraphBuilder::BuildGlobalStore(Handle<Name> name, Node* value,
const VectorSlotPair& feedback) {
const Operator* op =
javascript()->StoreGlobal(language_mode(), name, feedback);
Node* node = NewNode(op, value);
return node;
}
Node* AstGraphBuilder::BuildLoadGlobalObject() {
return BuildLoadNativeContextField(Context::EXTENSION_INDEX);
}
Node* AstGraphBuilder::BuildLoadNativeContextField(int index) {
const Operator* op =
javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true);
Node* native_context = NewNode(op);
Node* result = NewNode(javascript()->LoadContext(0, index, true));
NodeProperties::ReplaceContextInput(result, native_context);
return result;
}
Node* AstGraphBuilder::BuildToBoolean(Node* input) {
if (Node* node = TryFastToBoolean(input)) return node;
ToBooleanHints hints = ToBooleanHint::kAny;
return NewNode(javascript()->ToBoolean(hints), input);
}
Node* AstGraphBuilder::BuildSetHomeObject(Node* value, Node* home_object,
LiteralProperty* property,
int slot_number) {
Expression* expr = property->value();
if (!FunctionLiteral::NeedsHomeObject(expr)) return value;
Handle<Name> name = isolate()->factory()->home_object_symbol();
VectorSlotPair feedback =
CreateVectorSlotPair(property->GetSlot(slot_number));
Node* store = BuildNamedStore(value, name, home_object, feedback);
return store;
}
Node* AstGraphBuilder::BuildThrowError(Node* exception) {
const Operator* op = javascript()->CallRuntime(Runtime::kThrow);
Node* call = NewNode(op, exception);
Node* control = NewNode(common()->Throw());
UpdateControlDependencyToLeaveFunction(control);
return call;
}
Node* AstGraphBuilder::BuildThrowReferenceError(Variable* variable) {
Node* variable_name = jsgraph()->Constant(variable->name());
const Operator* op = javascript()->CallRuntime(Runtime::kThrowReferenceError);
Node* call = NewNode(op, variable_name);
Node* control = NewNode(common()->Throw());
UpdateControlDependencyToLeaveFunction(control);
return call;
}
Node* AstGraphBuilder::BuildThrowConstAssignError() {
const Operator* op =
javascript()->CallRuntime(Runtime::kThrowConstAssignError);
Node* call = NewNode(op);
Node* control = NewNode(common()->Throw());
UpdateControlDependencyToLeaveFunction(control);
return call;
}
Node* AstGraphBuilder::BuildReturn(Node* return_value) {
// Emit tracing call if requested to do so.
if (FLAG_trace) {
return_value =
NewNode(javascript()->CallRuntime(Runtime::kTraceExit), return_value);
}
Node* pop_node = jsgraph()->ZeroConstant();
Node* control = NewNode(common()->Return(), pop_node, return_value);
UpdateControlDependencyToLeaveFunction(control);
return control;
}
Node* AstGraphBuilder::BuildThrow(Node* exception_value) {
NewNode(javascript()->CallRuntime(Runtime::kReThrow), exception_value);
Node* control = NewNode(common()->Throw());
UpdateControlDependencyToLeaveFunction(control);
return control;
}
Node* AstGraphBuilder::BuildBinaryOp(Node* left, Node* right, Token::Value op) {
const Operator* js_op;
BinaryOperationHint hint = BinaryOperationHint::kAny;
switch (op) {
case Token::BIT_OR:
js_op = javascript()->BitwiseOr();
break;
case Token::BIT_AND:
js_op = javascript()->BitwiseAnd();
break;
case Token::BIT_XOR:
js_op = javascript()->BitwiseXor();
break;
case Token::SHL:
js_op = javascript()->ShiftLeft();
break;
case Token::SAR:
js_op = javascript()->ShiftRight();
break;
case Token::SHR:
js_op = javascript()->ShiftRightLogical();
break;
case Token::ADD:
js_op = javascript()->Add(hint);
break;
case Token::SUB:
js_op = javascript()->Subtract();
break;
case Token::MUL:
js_op = javascript()->Multiply();
break;
case Token::DIV:
js_op = javascript()->Divide();
break;
case Token::MOD:
js_op = javascript()->Modulus();
break;
default:
UNREACHABLE();
js_op = nullptr;
}
return NewNode(js_op, left, right);
}
Node* AstGraphBuilder::TryLoadGlobalConstant(Handle<Name> name) {
// Optimize global constants like "undefined", "Infinity", and "NaN".
Handle<Object> constant_value = isolate()->factory()->GlobalConstantFor(name);
if (!constant_value.is_null()) return jsgraph()->Constant(constant_value);
return nullptr;
}
Node* AstGraphBuilder::TryFastToBoolean(Node* input) {
switch (input->opcode()) {
case IrOpcode::kNumberConstant: {
NumberMatcher m(input);
return jsgraph_->BooleanConstant(!m.Is(0) && !m.IsNaN());
}
case IrOpcode::kHeapConstant: {
Handle<HeapObject> object = HeapObjectMatcher(input).Value();
return jsgraph_->BooleanConstant(object->BooleanValue());
}
case IrOpcode::kJSEqual:
case IrOpcode::kJSStrictEqual:
case IrOpcode::kJSLessThan:
case IrOpcode::kJSLessThanOrEqual:
case IrOpcode::kJSGreaterThan:
case IrOpcode::kJSGreaterThanOrEqual:
case IrOpcode::kJSToBoolean:
case IrOpcode::kJSDeleteProperty:
case IrOpcode::kJSHasProperty:
case IrOpcode::kJSInstanceOf:
return input;
default:
break;
}
return nullptr;
}
bool AstGraphBuilder::CheckOsrEntry(IterationStatement* stmt) {
if (info()->osr_ast_id() == stmt->OsrEntryId()) {
info()->set_osr_expr_stack_height(environment()->stack_height());
return true;
}
return false;
}
BitVector* AstGraphBuilder::GetVariablesAssignedInLoop(
IterationStatement* stmt) {
if (loop_assignment_analysis_ == nullptr) return nullptr;
return loop_assignment_analysis_->GetVariablesAssignedInLoop(stmt);
}
Node** AstGraphBuilder::EnsureInputBufferSize(int size) {
if (size > input_buffer_size_) {
size = size + kInputBufferSizeIncrement + input_buffer_size_;
input_buffer_ = local_zone()->NewArray<Node*>(size);
input_buffer_size_ = size;
}
return input_buffer_;
}
Node* AstGraphBuilder::MakeNode(const Operator* op, int value_input_count,
Node** value_inputs, bool incomplete) {
DCHECK_EQ(op->ValueInputCount(), value_input_count);
bool has_context = OperatorProperties::HasContextInput(op);
bool has_frame_state = OperatorProperties::HasFrameStateInput(op);
bool has_control = op->ControlInputCount() == 1;
bool has_effect = op->EffectInputCount() == 1;
DCHECK(op->ControlInputCount() < 2);
DCHECK(op->EffectInputCount() < 2);
Node* result = nullptr;
if (!has_context && !has_frame_state && !has_control && !has_effect) {
result = graph()->NewNode(op, value_input_count, value_inputs, incomplete);
} else {
int input_count_with_deps = value_input_count;
if (has_context) ++input_count_with_deps;
if (has_frame_state) ++input_count_with_deps;
if (has_control) ++input_count_with_deps;
if (has_effect) ++input_count_with_deps;
Node** buffer = EnsureInputBufferSize(input_count_with_deps);
memcpy(buffer, value_inputs, kPointerSize * value_input_count);
Node** current_input = buffer + value_input_count;
if (has_context) {
*current_input++ = current_context();
}
if (has_frame_state) {
DCHECK(!info()->is_deoptimization_enabled());
*current_input++ = GetEmptyFrameState();
}
if (has_effect) {
*current_input++ = environment_->GetEffectDependency();
}
if (has_control) {
*current_input++ = environment_->GetControlDependency();
}
result = graph()->NewNode(op, input_count_with_deps, buffer, incomplete);
if (!environment()->IsMarkedAsUnreachable()) {
// Update the current control dependency for control-producing nodes.
if (result->op()->ControlOutputCount() > 0) {
environment_->UpdateControlDependency(result);
}
// Update the current effect dependency for effect-producing nodes.
if (result->op()->EffectOutputCount() > 0) {
environment_->UpdateEffectDependency(result);
}
}
}
return result;
}
void AstGraphBuilder::UpdateControlDependencyToLeaveFunction(Node* exit) {
if (environment()->IsMarkedAsUnreachable()) return;
environment()->MarkAsUnreachable();
exit_controls_.push_back(exit);
}
void AstGraphBuilder::Environment::Merge(Environment* other) {
DCHECK(values_.size() == other->values_.size());
DCHECK(contexts_.size() == other->contexts_.size());
// Nothing to do if the other environment is dead.
if (other->IsMarkedAsUnreachable()) return;
// Resurrect a dead environment by copying the contents of the other one and
// placing a singleton merge as the new control dependency.
if (this->IsMarkedAsUnreachable()) {
Node* other_control = other->control_dependency_;
Node* inputs[] = {other_control};
control_dependency_ =
graph()->NewNode(common()->Merge(1), arraysize(inputs), inputs, true);
effect_dependency_ = other->effect_dependency_;
values_ = other->values_;
contexts_ = other->contexts_;
return;
}
// Create a merge of the control dependencies of both environments and update
// the current environment's control dependency accordingly.
Node* control = builder_->MergeControl(this->GetControlDependency(),
other->GetControlDependency());
UpdateControlDependency(control);
// Create a merge of the effect dependencies of both environments and update
// the current environment's effect dependency accordingly.
Node* effect = builder_->MergeEffect(this->GetEffectDependency(),
other->GetEffectDependency(), control);
UpdateEffectDependency(effect);
// Introduce Phi nodes for values that have differing input at merge points,
// potentially extending an existing Phi node if possible.
for (int i = 0; i < static_cast<int>(values_.size()); ++i) {
values_[i] = builder_->MergeValue(values_[i], other->values_[i], control);
}
for (int i = 0; i < static_cast<int>(contexts_.size()); ++i) {
contexts_[i] =
builder_->MergeValue(contexts_[i], other->contexts_[i], control);
}
}
void AstGraphBuilder::Environment::PrepareForOsrEntry() {
int size = static_cast<int>(values()->size());
Graph* graph = builder_->graph();
// Set the control and effect to the OSR loop entry.
Node* osr_loop_entry = graph->NewNode(builder_->common()->OsrLoopEntry(),
graph->start(), graph->start());
Node* effect = osr_loop_entry;
UpdateControlDependency(osr_loop_entry);
UpdateEffectDependency(effect);
// Set OSR values.
for (int i = 0; i < size; ++i) {
values()->at(i) =
graph->NewNode(builder_->common()->OsrValue(i), osr_loop_entry);
}
// Set the innermost context.
const Operator* op_inner =
builder_->common()->OsrValue(Linkage::kOsrContextSpillSlotIndex);
contexts()->back() = graph->NewNode(op_inner, osr_loop_entry);
// The innermost context is the OSR value, and the outer contexts are
// reconstructed by dynamically walking up the context chain.
const Operator* load_op =
builder_->javascript()->LoadContext(0, Context::PREVIOUS_INDEX, true);
Node* osr_context = contexts()->back();
int last = static_cast<int>(contexts()->size() - 1);
for (int i = last - 1; i >= 0; i--) {
osr_context = effect = graph->NewNode(load_op, osr_context, effect);
contexts()->at(i) = osr_context;
}
UpdateEffectDependency(effect);
}
void AstGraphBuilder::Environment::PrepareForLoop(BitVector* assigned) {
int size = static_cast<int>(values()->size());
Node* control = builder_->NewLoop();
if (assigned == nullptr) {
// Assume that everything is updated in the loop.
for (int i = 0; i < size; ++i) {
values()->at(i) = builder_->NewPhi(1, values()->at(i), control);
}
} else {
// Only build phis for those locals assigned in this loop.
for (int i = 0; i < size; ++i) {
if (i < assigned->length() && !assigned->Contains(i)) continue;
Node* phi = builder_->NewPhi(1, values()->at(i), control);
values()->at(i) = phi;
}
}
Node* effect = builder_->NewEffectPhi(1, GetEffectDependency(), control);
UpdateEffectDependency(effect);
// Connect the loop to end via Terminate if it's not marked as unreachable.
if (!IsMarkedAsUnreachable()) {
// Connect the Loop node to end via a Terminate node.
Node* terminate = builder_->graph()->NewNode(
builder_->common()->Terminate(), effect, control);
builder_->exit_controls_.push_back(terminate);
}
if (builder_->info()->is_osr()) {
// Introduce phis for all context values in the case of an OSR graph.
for (size_t i = 0; i < contexts()->size(); ++i) {
Node* context = contexts()->at(i);
contexts()->at(i) = builder_->NewPhi(1, context, control);
}
}
}
Node* AstGraphBuilder::NewPhi(int count, Node* input, Node* control) {
const Operator* phi_op = common()->Phi(MachineRepresentation::kTagged, count);
Node** buffer = EnsureInputBufferSize(count + 1);
MemsetPointer(buffer, input, count);
buffer[count] = control;
return graph()->NewNode(phi_op, count + 1, buffer, true);
}
Node* AstGraphBuilder::NewEffectPhi(int count, Node* input, Node* control) {
const Operator* phi_op = common()->EffectPhi(count);
Node** buffer = EnsureInputBufferSize(count + 1);
MemsetPointer(buffer, input, count);
buffer[count] = control;
return graph()->NewNode(phi_op, count + 1, buffer, true);
}
Node* AstGraphBuilder::MergeControl(Node* control, Node* other) {
int inputs = control->op()->ControlInputCount() + 1;
if (control->opcode() == IrOpcode::kLoop) {
// Control node for loop exists, add input.
const Operator* op = common()->Loop(inputs);
control->AppendInput(graph_zone(), other);
NodeProperties::ChangeOp(control, op);
} else if (control->opcode() == IrOpcode::kMerge) {
// Control node for merge exists, add input.
const Operator* op = common()->Merge(inputs);
control->AppendInput(graph_zone(), other);
NodeProperties::ChangeOp(control, op);
} else {
// Control node is a singleton, introduce a merge.
const Operator* op = common()->Merge(inputs);
Node* inputs[] = {control, other};
control = graph()->NewNode(op, arraysize(inputs), inputs, true);
}
return control;
}
Node* AstGraphBuilder::MergeEffect(Node* value, Node* other, Node* control) {
int inputs = control->op()->ControlInputCount();
if (value->opcode() == IrOpcode::kEffectPhi &&
NodeProperties::GetControlInput(value) == control) {
// Phi already exists, add input.
value->InsertInput(graph_zone(), inputs - 1, other);
NodeProperties::ChangeOp(value, common()->EffectPhi(inputs));
} else if (value != other) {
// Phi does not exist yet, introduce one.
value = NewEffectPhi(inputs, value, control);
value->ReplaceInput(inputs - 1, other);
}
return value;
}
Node* AstGraphBuilder::MergeValue(Node* value, Node* other, Node* control) {
int inputs = control->op()->ControlInputCount();
if (value->opcode() == IrOpcode::kPhi &&
NodeProperties::GetControlInput(value) == control) {
// Phi already exists, add input.
value->InsertInput(graph_zone(), inputs - 1, other);
NodeProperties::ChangeOp(
value, common()->Phi(MachineRepresentation::kTagged, inputs));
} else if (value != other) {
// Phi does not exist yet, introduce one.
value = NewPhi(inputs, value, control);
value->ReplaceInput(inputs - 1, other);
}
return value;
}
AstGraphBuilderWithPositions::AstGraphBuilderWithPositions(
Zone* local_zone, CompilationInfo* info, JSGraph* jsgraph,
CallFrequency invocation_frequency, LoopAssignmentAnalysis* loop_assignment,
SourcePositionTable* source_positions, int inlining_id)
: AstGraphBuilder(local_zone, info, jsgraph, invocation_frequency,
loop_assignment),
source_positions_(source_positions),
start_position_(info->shared_info()->start_position(), inlining_id) {}
} // namespace compiler
} // namespace internal
} // namespace v8
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_COMPILER_AST_GRAPH_BUILDER_H_
#define V8_COMPILER_AST_GRAPH_BUILDER_H_
#include "src/ast/ast.h"
#include "src/compiler/compiler-source-position-table.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/state-values-utils.h"
namespace v8 {
namespace internal {
// Forward declarations.
class BitVector;
class CompilationInfo;
namespace compiler {
// Forward declarations.
class ControlBuilder;
class Graph;
class LoopAssignmentAnalysis;
class LoopBuilder;
class Node;
// The AstGraphBuilder produces a high-level IR graph, based on an
// underlying AST. The produced graph can either be compiled into a
// stand-alone function or be wired into another graph for the purposes
// of function inlining.
// This AstVistor is not final, and provides the AstVisitor methods as virtual
// methods so they can be specialized by subclasses.
class AstGraphBuilder : public AstVisitor<AstGraphBuilder> {
public:
AstGraphBuilder(Zone* local_zone, CompilationInfo* info, JSGraph* jsgraph,
CallFrequency invocation_frequency,
LoopAssignmentAnalysis* loop_assignment = nullptr);
virtual ~AstGraphBuilder() {}
// Creates a graph by visiting the entire AST.
bool CreateGraph(bool stack_check = true);
// Helpers to create new control nodes.
Node* NewIfTrue() { return NewNode(common()->IfTrue()); }
Node* NewIfFalse() { return NewNode(common()->IfFalse()); }
Node* NewMerge() { return NewNode(common()->Merge(1), true); }
Node* NewLoop() { return NewNode(common()->Loop(1), true); }
Node* NewBranch(Node* condition, BranchHint hint = BranchHint::kNone) {
return NewNode(common()->Branch(hint), condition);
}
protected:
#define DECLARE_VISIT(type) virtual void Visit##type(type* node);
// Visiting functions for AST nodes make this an AstVisitor.
AST_NODE_LIST(DECLARE_VISIT)
#undef DECLARE_VISIT
// Visiting function for declarations list is overridden.
void VisitDeclarations(Declaration::List* declarations);
private:
class AstContext;
class AstEffectContext;
class AstValueContext;
class AstTestContext;
class ContextScope;
class ControlScope;
class ControlScopeForBreakable;
class ControlScopeForIteration;
class Environment;
friend class ControlBuilder;
Isolate* isolate_;
Zone* local_zone_;
CompilationInfo* info_;
JSGraph* jsgraph_;
CallFrequency const invocation_frequency_;
Environment* environment_;
AstContext* ast_context_;
// List of global declarations for functions and variables.
ZoneVector<Handle<Object>> globals_;
// Stack of control scopes currently entered by the visitor.
ControlScope* execution_control_;
// Stack of context objects pushed onto the chain by the visitor.
ContextScope* execution_context_;
// Nodes representing values in the activation record.
SetOncePointer<Node> function_closure_;
SetOncePointer<Node> function_context_;
// Temporary storage for building node input lists.
int input_buffer_size_;
Node** input_buffer_;
// Optimization to cache loaded feedback vector.
SetOncePointer<Node> feedback_vector_;
// Optimization to cache empty frame state.
SetOncePointer<Node> empty_frame_state_;
// Control nodes that exit the function body.
ZoneVector<Node*> exit_controls_;
// Result of loop assignment analysis performed before graph creation.
LoopAssignmentAnalysis* loop_assignment_analysis_;
// Cache for StateValues nodes for frame states.
StateValuesCache state_values_cache_;
// Growth increment for the temporary buffer used to construct input lists to
// new nodes.
static const int kInputBufferSizeIncrement = 64;
Zone* local_zone() const { return local_zone_; }
Environment* environment() const { return environment_; }
AstContext* ast_context() const { return ast_context_; }
ControlScope* execution_control() const { return execution_control_; }
ContextScope* execution_context() const { return execution_context_; }
CommonOperatorBuilder* common() const { return jsgraph_->common(); }
CompilationInfo* info() const { return info_; }
Isolate* isolate() const { return isolate_; }
LanguageMode language_mode() const;
JSGraph* jsgraph() { return jsgraph_; }
Graph* graph() { return jsgraph_->graph(); }
Zone* graph_zone() { return graph()->zone(); }
JSOperatorBuilder* javascript() { return jsgraph_->javascript(); }
ZoneVector<Handle<Object>>* globals() { return &globals_; }
Scope* current_scope() const;
Node* current_context() const;
void set_environment(Environment* env) { environment_ = env; }
void set_ast_context(AstContext* ctx) { ast_context_ = ctx; }
void set_execution_control(ControlScope* ctrl) { execution_control_ = ctrl; }
void set_execution_context(ContextScope* ctx) { execution_context_ = ctx; }
// Create the main graph body by visiting the AST.
void CreateGraphBody(bool stack_check);
// Get or create the node that represents the incoming function closure.
Node* GetFunctionClosureForContext();
Node* GetFunctionClosure();
// Get or create the node that represents the incoming function context.
Node* GetFunctionContext();
// Get or create the node that represents the empty frame state.
Node* GetEmptyFrameState();
// Node creation helpers.
Node* NewNode(const Operator* op, bool incomplete = false) {
return MakeNode(op, 0, static_cast<Node**>(nullptr), incomplete);
}
Node* NewNode(const Operator* op, Node* n1) {
return MakeNode(op, 1, &n1, false);
}
Node* NewNode(const Operator* op, Node* n1, Node* n2) {
Node* buffer[] = {n1, n2};
return MakeNode(op, arraysize(buffer), buffer, false);
}
Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3) {
Node* buffer[] = {n1, n2, n3};
return MakeNode(op, arraysize(buffer), buffer, false);
}
Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4) {
Node* buffer[] = {n1, n2, n3, n4};
return MakeNode(op, arraysize(buffer), buffer, false);
}
Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4,
Node* n5) {
Node* buffer[] = {n1, n2, n3, n4, n5};
return MakeNode(op, arraysize(buffer), buffer, false);
}
Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4,
Node* n5, Node* n6) {
Node* nodes[] = {n1, n2, n3, n4, n5, n6};
return MakeNode(op, arraysize(nodes), nodes, false);
}
Node* NewNode(const Operator* op, int value_input_count, Node** value_inputs,
bool incomplete = false) {
return MakeNode(op, value_input_count, value_inputs, incomplete);
}
// Creates a new Phi node having {count} input values.
Node* NewPhi(int count, Node* input, Node* control);
Node* NewEffectPhi(int count, Node* input, Node* control);
// Helpers for merging control, effect or value dependencies.
Node* MergeControl(Node* control, Node* other);
Node* MergeEffect(Node* value, Node* other, Node* control);
Node* MergeValue(Node* value, Node* other, Node* control);
// The main node creation chokepoint. Adds context, frame state, effect,
// and control dependencies depending on the operator.
Node* MakeNode(const Operator* op, int value_input_count, Node** value_inputs,
bool incomplete);
// Helper to indicate a node exits the function body.
void UpdateControlDependencyToLeaveFunction(Node* exit);
BitVector* GetVariablesAssignedInLoop(IterationStatement* stmt);
// Check if the given statement is an OSR entry.
// If so, record the stack height into the compilation and return {true}.
bool CheckOsrEntry(IterationStatement* stmt);
Node** EnsureInputBufferSize(int size);
// Named and keyed loads require a VectorSlotPair for successful lowering.
VectorSlotPair CreateVectorSlotPair(FeedbackSlot slot) const;
// Computes the frequency for JSCall and JSConstruct nodes.
CallFrequency ComputeCallFrequency(FeedbackSlot slot) const;
// ===========================================================================
// The following build methods all generate graph fragments and return one
// resulting node. The operand stack height remains the same, variables and
// other dependencies tracked by the environment might be mutated though.
// Builders to create local function, script and block contexts.
Node* BuildLocalActivationContext(Node* context);
Node* BuildLocalFunctionContext(Scope* scope);
Node* BuildLocalScriptContext(Scope* scope);
Node* BuildLocalBlockContext(Scope* scope);
// Builder to create an arguments object if it is used.
Node* BuildArgumentsObject(Variable* arguments);
// Builders for variable load and assignment.
Node* BuildVariableAssignment(Variable* variable, Node* value,
Token::Value op, const VectorSlotPair& slot);
Node* BuildVariableDelete(Variable* variable);
Node* BuildVariableLoad(Variable* variable, const VectorSlotPair& feedback,
TypeofMode typeof_mode = NOT_INSIDE_TYPEOF);
// Builders for property loads and stores.
Node* BuildKeyedLoad(Node* receiver, Node* key,
const VectorSlotPair& feedback);
Node* BuildNamedLoad(Node* receiver, Handle<Name> name,
const VectorSlotPair& feedback);
Node* BuildKeyedStore(Node* receiver, Node* key, Node* value,
const VectorSlotPair& feedback);
Node* BuildNamedStore(Node* receiver, Handle<Name> name, Node* value,
const VectorSlotPair& feedback);
Node* BuildNamedStoreOwn(Node* receiver, Handle<Name> name, Node* value,
const VectorSlotPair& feedback);
// Builders for global variable loads and stores.
Node* BuildGlobalLoad(Handle<Name> name, const VectorSlotPair& feedback,
TypeofMode typeof_mode);
Node* BuildGlobalStore(Handle<Name> name, Node* value,
const VectorSlotPair& feedback);
// Builders for accessing the function context.
Node* BuildLoadGlobalObject();
Node* BuildLoadNativeContextField(int index);
// Builders for automatic type conversion.
Node* BuildToBoolean(Node* input);
// Builder for adding the [[HomeObject]] to a value if the value came from a
// function literal and needs a home object. Do nothing otherwise.
Node* BuildSetHomeObject(Node* value, Node* home_object,
LiteralProperty* property, int slot_number = 0);
// Builders for error reporting at runtime.
Node* BuildThrowError(Node* exception);
Node* BuildThrowReferenceError(Variable* var);
Node* BuildThrowConstAssignError();
// Builders for dynamic hole-checks at runtime.
Node* BuildHoleCheckThenThrow(Node* value, Variable* var, Node* not_hole);
Node* BuildHoleCheckElseThrow(Node* value, Variable* var, Node* for_hole);
// Builders for non-local control flow.
Node* BuildReturn(Node* return_value);
Node* BuildThrow(Node* exception_value);
// Builders for binary operations.
Node* BuildBinaryOp(Node* left, Node* right, Token::Value op);
// Process arguments to a call by popping {arity} elements off the operand
// stack and build a call node using the given call operator.
Node* ProcessArguments(const Operator* op, int arity);
// ===========================================================================
// The following build methods have the same contract as the above ones, but
// they can also return {nullptr} to indicate that no fragment was built. Note
// that these are optimizations, disabling any of them should still produce
// correct graphs.
// Optimization for variable load from global object.
Node* TryLoadGlobalConstant(Handle<Name> name);
// Optimizations for automatic type conversion.
Node* TryFastToBoolean(Node* input);
// ===========================================================================
// The following visitation methods all recursively visit a subtree of the
// underlying AST and extent the graph. The operand stack is mutated in a way
// consistent with other compilers:
// - Expressions pop operands and push result, depending on {AstContext}.
// - Statements keep the operand stack balanced.
// Visit statements.
void VisitIfNotNull(Statement* stmt);
// Visit expressions.
void Visit(Expression* expr);
void VisitForTest(Expression* expr);
void VisitForEffect(Expression* expr);
void VisitForValue(Expression* expr);
void VisitForValueOrNull(Expression* expr);
void VisitForValueOrTheHole(Expression* expr);
void VisitForValues(ZoneList<Expression*>* exprs);
// Common for all IterationStatement bodies.
void VisitIterationBody(IterationStatement* stmt, LoopBuilder* loop);
// Dispatched from VisitCall.
void VisitCallSuper(Call* expr);
// Dispatched from VisitCallRuntime.
void VisitCallJSRuntime(CallRuntime* expr);
// Dispatched from VisitUnaryOperation.
void VisitDelete(UnaryOperation* expr);
void VisitVoid(UnaryOperation* expr);
void VisitTypeof(UnaryOperation* expr);
void VisitNot(UnaryOperation* expr);
// Dispatched from VisitTypeof, VisitLiteralCompareTypeof.
void VisitTypeofExpression(Expression* expr);
// Dispatched from VisitBinaryOperation.
void VisitComma(BinaryOperation* expr);
void VisitLogicalExpression(BinaryOperation* expr);
void VisitArithmeticExpression(BinaryOperation* expr);
// Dispatched from VisitCompareOperation.
void VisitLiteralCompareNil(CompareOperation* expr, Expression* sub_expr,
Node* nil_value);
void VisitLiteralCompareTypeof(CompareOperation* expr, Expression* sub_expr,
Handle<String> check);
// Dispatched from VisitObjectLiteral.
void VisitObjectLiteralAccessor(Node* home_object,
ObjectLiteralProperty* property);
DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
DISALLOW_COPY_AND_ASSIGN(AstGraphBuilder);
};
// The abstract execution environment for generated code consists of
// parameter variables, local variables and the operand stack. The
// environment will perform proper SSA-renaming of all tracked nodes
// at split and merge points in the control flow. Internally all the
// values are stored in one list using the following layout:
//
// [parameters (+receiver)] [locals] [operand stack]
//
class AstGraphBuilder::Environment : public ZoneObject {
public:
Environment(AstGraphBuilder* builder, DeclarationScope* scope,
Node* control_dependency);
int parameters_count() const { return parameters_count_; }
int locals_count() const { return locals_count_; }
int context_chain_length() { return static_cast<int>(contexts_.size()); }
int stack_height() {
return static_cast<int>(values()->size()) - parameters_count_ -
locals_count_;
}
// Operations on parameter or local variables.
void Bind(Variable* variable, Node* node);
Node* Lookup(Variable* variable);
// Raw operations on parameter variables.
void RawParameterBind(int index, Node* node);
Node* RawParameterLookup(int index);
// Operations on the context chain.
Node* Context() const { return contexts_.back(); }
void PushContext(Node* context) { contexts()->push_back(context); }
void PopContext() { contexts()->pop_back(); }
void TrimContextChain(int trim_to_length) {
contexts()->resize(trim_to_length);
}
// Operations on the operand stack.
void Push(Node* node) {
values()->push_back(node);
}
Node* Top() {
DCHECK(stack_height() > 0);
return values()->back();
}
Node* Pop() {
DCHECK(stack_height() > 0);
Node* back = values()->back();
values()->pop_back();
return back;
}
// Direct mutations of the operand stack.
void Poke(int depth, Node* node) {
DCHECK(depth >= 0 && depth < stack_height());
int index = static_cast<int>(values()->size()) - depth - 1;
values()->at(index) = node;
}
Node* Peek(int depth) {
DCHECK(depth >= 0 && depth < stack_height());
int index = static_cast<int>(values()->size()) - depth - 1;
return values()->at(index);
}
void Drop(int depth) {
DCHECK(depth >= 0 && depth <= stack_height());
values()->erase(values()->end() - depth, values()->end());
}
void TrimStack(int trim_to_height) {
int depth = stack_height() - trim_to_height;
DCHECK(depth >= 0 && depth <= stack_height());
values()->erase(values()->end() - depth, values()->end());
}
// Inserts a loop exit control node and renames the environment.
// This is useful for loop peeling to insert phis at loop exits.
void PrepareForLoopExit(Node* loop, BitVector* assigned_variables);
// Control dependency tracked by this environment.
Node* GetControlDependency() { return control_dependency_; }
void UpdateControlDependency(Node* dependency) {
control_dependency_ = dependency;
}
// Effect dependency tracked by this environment.
Node* GetEffectDependency() { return effect_dependency_; }
void UpdateEffectDependency(Node* dependency) {
effect_dependency_ = dependency;
}
// Mark this environment as being unreachable.
void MarkAsUnreachable() {
UpdateControlDependency(builder()->jsgraph()->Dead());
}
bool IsMarkedAsUnreachable() {
return GetControlDependency()->opcode() == IrOpcode::kDead;
}
// Merge another environment into this one.
void Merge(Environment* other);
// Copies this environment at a control-flow split point.
Environment* CopyForConditional();
// Copies this environment to a potentially unreachable control-flow point.
Environment* CopyAsUnreachable();
// Copies this environment at a loop header control-flow point.
Environment* CopyForLoop(BitVector* assigned, bool is_osr = false);
// Copies this environment for Osr entry. This only produces environment
// of the right shape, the caller is responsible for filling in the right
// values and dependencies.
Environment* CopyForOsrEntry();
private:
AstGraphBuilder* builder_;
int parameters_count_;
int locals_count_;
NodeVector values_;
NodeVector contexts_;
Node* control_dependency_;
Node* effect_dependency_;
Node* parameters_node_;
Node* locals_node_;
Node* stack_node_;
explicit Environment(Environment* copy);
Environment* CopyAndShareLiveness();
Zone* zone() const { return builder_->local_zone(); }
Graph* graph() const { return builder_->graph(); }
AstGraphBuilder* builder() const { return builder_; }
CommonOperatorBuilder* common() { return builder_->common(); }
NodeVector* values() { return &values_; }
NodeVector* contexts() { return &contexts_; }
// Prepare environment to be used as loop header.
void PrepareForLoop(BitVector* assigned);
void PrepareForOsrEntry();
};
class AstGraphBuilderWithPositions final : public AstGraphBuilder {
public:
AstGraphBuilderWithPositions(Zone* local_zone, CompilationInfo* info,
JSGraph* jsgraph,
CallFrequency invocation_frequency,
LoopAssignmentAnalysis* loop_assignment,
SourcePositionTable* source_positions,
int inlining_id = SourcePosition::kNotInlined);
bool CreateGraph(bool stack_check = true) {
SourcePositionTable::Scope pos_scope(source_positions_, start_position_);
return AstGraphBuilder::CreateGraph(stack_check);
}
#define DEF_VISIT(type) \
void Visit##type(type* node) override { \
SourcePositionTable::Scope pos( \
source_positions_, \
SourcePosition(node->position(), start_position_.InliningId())); \
AstGraphBuilder::Visit##type(node); \
}
AST_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT
private:
SourcePositionTable* const source_positions_;
SourcePosition const start_position_;
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_AST_GRAPH_BUILDER_H_
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/ast-loop-assignment-analyzer.h"
#include "src/ast/scopes.h"
#include "src/compilation-info.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
typedef class AstLoopAssignmentAnalyzer ALAA; // for code shortitude.
ALAA::AstLoopAssignmentAnalyzer(Zone* zone, CompilationInfo* info)
: info_(info), zone_(zone), loop_stack_(zone) {
InitializeAstVisitor(info->isolate());
}
LoopAssignmentAnalysis* ALAA::Analyze() {
LoopAssignmentAnalysis* a = new (zone_) LoopAssignmentAnalysis(zone_);
result_ = a;
VisitStatements(info()->literal()->body());
result_ = nullptr;
return a;
}
void ALAA::Enter(IterationStatement* loop) {
int num_variables = 1 + info()->scope()->num_parameters() +
info()->scope()->num_stack_slots();
BitVector* bits = new (zone_) BitVector(num_variables, zone_);
if (info()->is_osr() && info()->osr_ast_id() == loop->OsrEntryId())
bits->AddAll();
loop_stack_.push_back(bits);
}
void ALAA::Exit(IterationStatement* loop) {
DCHECK(loop_stack_.size() > 0);
BitVector* bits = loop_stack_.back();
loop_stack_.pop_back();
if (!loop_stack_.empty()) {
loop_stack_.back()->Union(*bits);
}
result_->list_.push_back(
std::pair<IterationStatement*, BitVector*>(loop, bits));
}
// ---------------------------------------------------------------------------
// -- Leaf nodes -------------------------------------------------------------
// ---------------------------------------------------------------------------
void ALAA::VisitVariableDeclaration(VariableDeclaration* leaf) {}
void ALAA::VisitFunctionDeclaration(FunctionDeclaration* leaf) {}
void ALAA::VisitEmptyStatement(EmptyStatement* leaf) {}
void ALAA::VisitContinueStatement(ContinueStatement* leaf) {}
void ALAA::VisitBreakStatement(BreakStatement* leaf) {}
void ALAA::VisitDebuggerStatement(DebuggerStatement* leaf) {}
void ALAA::VisitFunctionLiteral(FunctionLiteral* leaf) {}
void ALAA::VisitNativeFunctionLiteral(NativeFunctionLiteral* leaf) {}
void ALAA::VisitVariableProxy(VariableProxy* leaf) {}
void ALAA::VisitLiteral(Literal* leaf) {}
void ALAA::VisitRegExpLiteral(RegExpLiteral* leaf) {}
void ALAA::VisitThisFunction(ThisFunction* leaf) {}
void ALAA::VisitSuperPropertyReference(SuperPropertyReference* leaf) {}
void ALAA::VisitSuperCallReference(SuperCallReference* leaf) {}
// ---------------------------------------------------------------------------
// -- Pass-through nodes------------------------------------------------------
// ---------------------------------------------------------------------------
void ALAA::VisitBlock(Block* stmt) { VisitStatements(stmt->statements()); }
void ALAA::VisitDoExpression(DoExpression* expr) {
Visit(expr->block());
Visit(expr->result());
}
void ALAA::VisitExpressionStatement(ExpressionStatement* stmt) {
Visit(stmt->expression());
}
void ALAA::VisitIfStatement(IfStatement* stmt) {
Visit(stmt->condition());
Visit(stmt->then_statement());
Visit(stmt->else_statement());
}
void ALAA::VisitReturnStatement(ReturnStatement* stmt) {
Visit(stmt->expression());
}
void ALAA::VisitWithStatement(WithStatement* stmt) {
Visit(stmt->expression());
Visit(stmt->statement());
}
void ALAA::VisitSwitchStatement(SwitchStatement* stmt) {
Visit(stmt->tag());
ZoneList<CaseClause*>* clauses = stmt->cases();
for (int i = 0; i < clauses->length(); i++) {
Visit(clauses->at(i));
}
}
void ALAA::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
Visit(stmt->try_block());
Visit(stmt->finally_block());
}
void ALAA::VisitClassLiteral(ClassLiteral* e) {
VisitIfNotNull(e->extends());
VisitIfNotNull(e->constructor());
ZoneList<ClassLiteralProperty*>* properties = e->properties();
for (int i = 0; i < properties->length(); i++) {
Visit(properties->at(i)->key());
Visit(properties->at(i)->value());
}
}
void ALAA::VisitConditional(Conditional* e) {
Visit(e->condition());
Visit(e->then_expression());
Visit(e->else_expression());
}
void ALAA::VisitObjectLiteral(ObjectLiteral* e) {
ZoneList<ObjectLiteralProperty*>* properties = e->properties();
for (int i = 0; i < properties->length(); i++) {
Visit(properties->at(i)->key());
Visit(properties->at(i)->value());
}
}
void ALAA::VisitArrayLiteral(ArrayLiteral* e) { VisitExpressions(e->values()); }
void ALAA::VisitYield(Yield* e) { Visit(e->expression()); }
void ALAA::VisitYieldStar(YieldStar* e) { Visit(e->expression()); }
void ALAA::VisitAwait(Await* e) { Visit(e->expression()); }
void ALAA::VisitThrow(Throw* stmt) { Visit(stmt->exception()); }
void ALAA::VisitProperty(Property* e) {
Visit(e->obj());
Visit(e->key());
}
void ALAA::VisitCall(Call* e) {
Visit(e->expression());
VisitExpressions(e->arguments());
}
void ALAA::VisitCallNew(CallNew* e) {
Visit(e->expression());
VisitExpressions(e->arguments());
}
void ALAA::VisitCallRuntime(CallRuntime* e) {
VisitExpressions(e->arguments());
}
void ALAA::VisitUnaryOperation(UnaryOperation* e) { Visit(e->expression()); }
void ALAA::VisitBinaryOperation(BinaryOperation* e) {
Visit(e->left());
Visit(e->right());
}
void ALAA::VisitCompareOperation(CompareOperation* e) {
Visit(e->left());
Visit(e->right());
}
void ALAA::VisitSpread(Spread* e) { UNREACHABLE(); }
void ALAA::VisitEmptyParentheses(EmptyParentheses* e) { UNREACHABLE(); }
void ALAA::VisitGetIterator(GetIterator* e) { UNREACHABLE(); }
void ALAA::VisitImportCallExpression(ImportCallExpression* e) { UNREACHABLE(); }
void ALAA::VisitCaseClause(CaseClause* cc) {
if (!cc->is_default()) Visit(cc->label());
VisitStatements(cc->statements());
}
void ALAA::VisitSloppyBlockFunctionStatement(
SloppyBlockFunctionStatement* stmt) {
Visit(stmt->statement());
}
// ---------------------------------------------------------------------------
// -- Interesting nodes-------------------------------------------------------
// ---------------------------------------------------------------------------
void ALAA::VisitTryCatchStatement(TryCatchStatement* stmt) {
Visit(stmt->try_block());
Visit(stmt->catch_block());
AnalyzeAssignment(stmt->scope()->catch_variable());
}
void ALAA::VisitDoWhileStatement(DoWhileStatement* loop) {
Enter(loop);
Visit(loop->body());
Visit(loop->cond());
Exit(loop);
}
void ALAA::VisitWhileStatement(WhileStatement* loop) {
Enter(loop);
Visit(loop->cond());
Visit(loop->body());
Exit(loop);
}
void ALAA::VisitForStatement(ForStatement* loop) {
VisitIfNotNull(loop->init());
Enter(loop);
VisitIfNotNull(loop->cond());
Visit(loop->body());
VisitIfNotNull(loop->next());
Exit(loop);
}
void ALAA::VisitForInStatement(ForInStatement* loop) {
Expression* l = loop->each();
Enter(loop);
Visit(l);
Visit(loop->subject());
Visit(loop->body());
if (l->IsVariableProxy()) AnalyzeAssignment(l->AsVariableProxy()->var());
Exit(loop);
}
void ALAA::VisitForOfStatement(ForOfStatement* loop) {
Visit(loop->assign_iterator());
Enter(loop);
Visit(loop->next_result());
Visit(loop->result_done());
Visit(loop->assign_each());
Visit(loop->body());
Exit(loop);
}
void ALAA::VisitAssignment(Assignment* stmt) {
Expression* l = stmt->target();
Visit(l);
Visit(stmt->value());
if (l->IsVariableProxy()) AnalyzeAssignment(l->AsVariableProxy()->var());
}
void ALAA::VisitCountOperation(CountOperation* e) {
Expression* l = e->expression();
Visit(l);
if (l->IsVariableProxy()) AnalyzeAssignment(l->AsVariableProxy()->var());
}
void ALAA::VisitRewritableExpression(RewritableExpression* expr) {
Visit(expr->expression());
}
void ALAA::AnalyzeAssignment(Variable* var) {
if (!loop_stack_.empty() && var->IsStackAllocated()) {
loop_stack_.back()->Add(GetVariableIndex(info()->scope(), var));
}
}
int ALAA::GetVariableIndex(DeclarationScope* scope, Variable* var) {
CHECK(var->IsStackAllocated());
if (var->is_this()) return 0;
if (var->IsParameter()) return 1 + var->index();
return 1 + scope->num_parameters() + var->index();
}
int LoopAssignmentAnalysis::GetAssignmentCountForTesting(
DeclarationScope* scope, Variable* var) {
int count = 0;
int var_index = AstLoopAssignmentAnalyzer::GetVariableIndex(scope, var);
for (size_t i = 0; i < list_.size(); i++) {
if (list_[i].second->Contains(var_index)) count++;
}
return count;
}
} // namespace compiler
} // namespace internal
} // namespace v8
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_COMPILER_AST_LOOP_ASSIGNMENT_ANALYZER_H_
#define V8_COMPILER_AST_LOOP_ASSIGNMENT_ANALYZER_H_
#include "src/ast/ast.h"
#include "src/bit-vector.h"
#include "src/zone/zone-containers.h"
namespace v8 {
namespace internal {
class CompilationInfo;
class Scope;
class Variable;
namespace compiler {
// The result of analyzing loop assignments.
class LoopAssignmentAnalysis : public ZoneObject {
public:
BitVector* GetVariablesAssignedInLoop(IterationStatement* loop) {
for (size_t i = 0; i < list_.size(); i++) {
// TODO(turbofan): hashmap or binary search for loop assignments.
if (list_[i].first == loop) return list_[i].second;
}
UNREACHABLE(); // should never ask for loops that aren't here!
return nullptr;
}
int GetAssignmentCountForTesting(DeclarationScope* scope, Variable* var);
private:
friend class AstLoopAssignmentAnalyzer;
explicit LoopAssignmentAnalysis(Zone* zone) : list_(zone) {}
ZoneVector<std::pair<IterationStatement*, BitVector*>> list_;
};
// The class that performs loop assignment analysis by walking the AST.
class AstLoopAssignmentAnalyzer final
: public AstVisitor<AstLoopAssignmentAnalyzer> {
public:
AstLoopAssignmentAnalyzer(Zone* zone, CompilationInfo* info);
LoopAssignmentAnalysis* Analyze();
#define DECLARE_VISIT(type) void Visit##type(type* node);
AST_NODE_LIST(DECLARE_VISIT)
#undef DECLARE_VISIT
static int GetVariableIndex(DeclarationScope* scope, Variable* var);
private:
CompilationInfo* info_;
Zone* zone_;
ZoneDeque<BitVector*> loop_stack_;
LoopAssignmentAnalysis* result_;
CompilationInfo* info() { return info_; }
void Enter(IterationStatement* loop);
void Exit(IterationStatement* loop);
void VisitIfNotNull(AstNode* node) {
if (node != nullptr) Visit(node);
}
void AnalyzeAssignment(Variable* var);
DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
DISALLOW_COPY_AND_ASSIGN(AstLoopAssignmentAnalyzer);
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_AST_LOOP_ASSIGNMENT_ANALYZER_H_
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/control-builders.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
void IfBuilder::If(Node* condition, BranchHint hint) {
builder_->NewBranch(condition, hint);
else_environment_ = environment()->CopyForConditional();
}
void IfBuilder::Then() { builder_->NewIfTrue(); }
void IfBuilder::Else() {
builder_->NewMerge();
then_environment_ = environment();
set_environment(else_environment_);
builder_->NewIfFalse();
}
void IfBuilder::End() {
then_environment_->Merge(environment());
set_environment(then_environment_);
}
void LoopBuilder::BeginLoop(BitVector* assigned, bool is_osr) {
loop_environment_ = environment()->CopyForLoop(assigned, is_osr);
continue_environment_ = environment()->CopyAsUnreachable();
break_environment_ = environment()->CopyAsUnreachable();
assigned_ = assigned;
}
void LoopBuilder::Continue() {
continue_environment_->Merge(environment());
environment()->MarkAsUnreachable();
}
void LoopBuilder::Break() {
break_environment_->Merge(environment());
environment()->MarkAsUnreachable();
}
void LoopBuilder::EndBody() {
continue_environment_->Merge(environment());
set_environment(continue_environment_);
}
void LoopBuilder::EndLoop() {
loop_environment_->Merge(environment());
set_environment(break_environment_);
ExitLoop();
}
void LoopBuilder::BreakUnless(Node* condition) {
IfBuilder control_if(builder_);
control_if.If(condition);
control_if.Then();
control_if.Else();
Break();
control_if.End();
}
void LoopBuilder::BreakWhen(Node* condition) {
IfBuilder control_if(builder_);
control_if.If(condition);
control_if.Then();
Break();
control_if.Else();
control_if.End();
}
void LoopBuilder::ExitLoop(Node** extra_value_to_rename) {
if (extra_value_to_rename) {
environment()->Push(*extra_value_to_rename);
}
environment()->PrepareForLoopExit(loop_environment_->GetControlDependency(),
assigned_);
if (extra_value_to_rename) {
*extra_value_to_rename = environment()->Pop();
}
}
void SwitchBuilder::BeginSwitch() {
body_environment_ = environment()->CopyAsUnreachable();
label_environment_ = environment()->CopyAsUnreachable();
break_environment_ = environment()->CopyAsUnreachable();
}
void SwitchBuilder::BeginLabel(int index, Node* condition) {
builder_->NewBranch(condition);
label_environment_ = environment()->CopyForConditional();
builder_->NewIfTrue();
body_environments_[index] = environment();
}
void SwitchBuilder::EndLabel() {
set_environment(label_environment_);
builder_->NewIfFalse();
}
void SwitchBuilder::DefaultAt(int index) {
label_environment_ = environment()->CopyAsUnreachable();
body_environments_[index] = environment();
}
void SwitchBuilder::BeginCase(int index) {
set_environment(body_environments_[index]);
environment()->Merge(body_environment_);
}
void SwitchBuilder::Break() {
break_environment_->Merge(environment());
environment()->MarkAsUnreachable();
}
void SwitchBuilder::EndCase() { body_environment_ = environment(); }
void SwitchBuilder::EndSwitch() {
break_environment_->Merge(label_environment_);
break_environment_->Merge(environment());
set_environment(break_environment_);
}
void BlockBuilder::BeginBlock() {
break_environment_ = environment()->CopyAsUnreachable();
}
void BlockBuilder::Break() {
break_environment_->Merge(environment());
environment()->MarkAsUnreachable();
}
void BlockBuilder::BreakWhen(Node* condition, BranchHint hint) {
IfBuilder control_if(builder_);
control_if.If(condition, hint);
control_if.Then();
Break();
control_if.Else();
control_if.End();
}
void BlockBuilder::BreakUnless(Node* condition, BranchHint hint) {
IfBuilder control_if(builder_);
control_if.If(condition, hint);
control_if.Then();
control_if.Else();
Break();
control_if.End();
}
void BlockBuilder::EndBlock() {
break_environment_->Merge(environment());
set_environment(break_environment_);
}
} // namespace compiler
} // namespace internal
} // namespace v8
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_COMPILER_CONTROL_BUILDERS_H_
#define V8_COMPILER_CONTROL_BUILDERS_H_
#include "src/compiler/ast-graph-builder.h"
#include "src/compiler/node.h"
namespace v8 {
namespace internal {
namespace compiler {
// Base class for all control builders. Also provides a common interface for
// control builders to handle 'break' statements when they are used to model
// breakable statements.
class ControlBuilder {
public:
explicit ControlBuilder(AstGraphBuilder* builder) : builder_(builder) {}
virtual ~ControlBuilder() {}
// Interface for break.
virtual void Break() { UNREACHABLE(); }
protected:
typedef AstGraphBuilder Builder;
typedef AstGraphBuilder::Environment Environment;
Zone* zone() const { return builder_->local_zone(); }
Environment* environment() { return builder_->environment(); }
void set_environment(Environment* env) { builder_->set_environment(env); }
Node* the_hole() const { return builder_->jsgraph()->TheHoleConstant(); }
Builder* builder_;
};
// Tracks control flow for a conditional statement.
class IfBuilder final : public ControlBuilder {
public:
explicit IfBuilder(AstGraphBuilder* builder)
: ControlBuilder(builder),
then_environment_(nullptr),
else_environment_(nullptr) {}
// Primitive control commands.
void If(Node* condition, BranchHint hint = BranchHint::kNone);
void Then();
void Else();
void End();
private:
Environment* then_environment_; // Environment after the 'then' body.
Environment* else_environment_; // Environment for the 'else' body.
};
// Tracks control flow for an iteration statement.
class LoopBuilder final : public ControlBuilder {
public:
explicit LoopBuilder(AstGraphBuilder* builder)
: ControlBuilder(builder),
loop_environment_(nullptr),
continue_environment_(nullptr),
break_environment_(nullptr),
assigned_(nullptr) {}
// Primitive control commands.
void BeginLoop(BitVector* assigned, bool is_osr = false);
void Continue();
void EndBody();
void EndLoop();
// Primitive support for break.
void Break() final;
// Loop exit support. Used to introduce explicit loop exit control
// node and variable markers.
void ExitLoop(Node** extra_value_to_rename = nullptr);
// Compound control commands for conditional break.
void BreakUnless(Node* condition);
void BreakWhen(Node* condition);
private:
Environment* loop_environment_; // Environment of the loop header.
Environment* continue_environment_; // Environment after the loop body.
Environment* break_environment_; // Environment after the loop exits.
BitVector* assigned_; // Assigned values in the environment.
};
// Tracks control flow for a switch statement.
class SwitchBuilder final : public ControlBuilder {
public:
explicit SwitchBuilder(AstGraphBuilder* builder, int case_count)
: ControlBuilder(builder),
body_environment_(nullptr),
label_environment_(nullptr),
break_environment_(nullptr),
body_environments_(case_count, zone()) {}
// Primitive control commands.
void BeginSwitch();
void BeginLabel(int index, Node* condition);
void EndLabel();
void DefaultAt(int index);
void BeginCase(int index);
void EndCase();
void EndSwitch();
// Primitive support for break.
void Break() final;
// The number of cases within a switch is statically known.
size_t case_count() const { return body_environments_.size(); }
private:
Environment* body_environment_; // Environment after last case body.
Environment* label_environment_; // Environment for next label condition.
Environment* break_environment_; // Environment after the switch exits.
ZoneVector<Environment*> body_environments_;
};
// Tracks control flow for a block statement.
class BlockBuilder final : public ControlBuilder {
public:
explicit BlockBuilder(AstGraphBuilder* builder)
: ControlBuilder(builder), break_environment_(nullptr) {}
// Primitive control commands.
void BeginBlock();
void EndBlock();
// Primitive support for break.
void Break() final;
// Compound control commands for conditional break.
void BreakWhen(Node* condition, BranchHint = BranchHint::kNone);
void BreakUnless(Node* condition, BranchHint hint = BranchHint::kNone);
private:
Environment* break_environment_; // Environment after the block exits.
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_CONTROL_BUILDERS_H_
......@@ -98,12 +98,10 @@ class JSCallReduction {
};
JSBuiltinReducer::JSBuiltinReducer(Editor* editor, JSGraph* jsgraph,
Flags flags,
CompilationDependencies* dependencies,
Handle<Context> native_context)
: AdvancedReducer(editor),
dependencies_(dependencies),
flags_(flags),
jsgraph_(jsgraph),
native_context_(native_context),
type_cache_(TypeCache::Get()) {}
......
......@@ -6,7 +6,6 @@
#define V8_COMPILER_JS_BUILTIN_REDUCER_H_
#include "src/base/compiler-specific.h"
#include "src/base/flags.h"
#include "src/compiler/graph-reducer.h"
#include "src/globals.h"
......@@ -30,14 +29,7 @@ class TypeCache;
class V8_EXPORT_PRIVATE JSBuiltinReducer final
: public NON_EXPORTED_BASE(AdvancedReducer) {
public:
// Flags that control the mode of operation.
enum Flag {
kNoFlags = 0u,
kDeoptimizationEnabled = 1u << 0,
};
typedef base::Flags<Flag> Flags;
JSBuiltinReducer(Editor* editor, JSGraph* jsgraph, Flags flags,
JSBuiltinReducer(Editor* editor, JSGraph* jsgraph,
CompilationDependencies* dependencies,
Handle<Context> native_context);
~JSBuiltinReducer() final {}
......@@ -132,7 +124,6 @@ class V8_EXPORT_PRIVATE JSBuiltinReducer final
Node* ToNumber(Node* value);
Node* ToUint32(Node* value);
Flags flags() const { return flags_; }
Graph* graph() const;
Factory* factory() const;
JSGraph* jsgraph() const { return jsgraph_; }
......@@ -144,14 +135,11 @@ class V8_EXPORT_PRIVATE JSBuiltinReducer final
CompilationDependencies* dependencies() const { return dependencies_; }
CompilationDependencies* const dependencies_;
Flags const flags_;
JSGraph* const jsgraph_;
Handle<Context> const native_context_;
TypeCache const& type_cache_;
};
DEFINE_OPERATORS_FOR_FLAGS(JSBuiltinReducer::Flags)
} // namespace compiler
} // namespace internal
} // namespace v8
......
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/js-frame-specialization.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/linkage.h"
#include "src/frames-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
Reduction JSFrameSpecialization::Reduce(Node* node) {
switch (node->opcode()) {
case IrOpcode::kOsrValue:
return ReduceOsrValue(node);
case IrOpcode::kParameter:
return ReduceParameter(node);
default:
break;
}
return NoChange();
}
Reduction JSFrameSpecialization::ReduceOsrValue(Node* node) {
// JSFrameSpecialization should never run on interpreted frames, since the
// code below assumes standard stack frame layouts.
DCHECK(!frame()->is_interpreted());
DCHECK_EQ(IrOpcode::kOsrValue, node->opcode());
Handle<Object> value;
int index = OsrValueIndexOf(node->op());
int const parameters_count = frame()->ComputeParametersCount() + 1;
if (index == Linkage::kOsrContextSpillSlotIndex) {
value = handle(frame()->context(), isolate());
} else if (index >= parameters_count) {
value = handle(frame()->GetExpression(index - parameters_count), isolate());
} else {
// The OsrValue index 0 is the receiver.
value =
handle(index ? frame()->GetParameter(index - 1) : frame()->receiver(),
isolate());
}
return Replace(jsgraph()->Constant(value));
}
Reduction JSFrameSpecialization::ReduceParameter(Node* node) {
DCHECK_EQ(IrOpcode::kParameter, node->opcode());
Handle<Object> value;
int const index = ParameterIndexOf(node->op());
int const parameters_count = frame()->ComputeParametersCount() + 1;
if (index == Linkage::kJSCallClosureParamIndex) {
// The Parameter index references the closure.
value = handle(frame()->function(), isolate());
} else if (index == Linkage::GetJSCallArgCountParamIndex(parameters_count)) {
// The Parameter index references the parameter count.
value = handle(Smi::FromInt(parameters_count - 1), isolate());
} else if (index == Linkage::GetJSCallContextParamIndex(parameters_count)) {
// The Parameter index references the context.
value = handle(frame()->context(), isolate());
} else {
// The Parameter index 0 is the receiver.
value =
handle(index ? frame()->GetParameter(index - 1) : frame()->receiver(),
isolate());
}
return Replace(jsgraph()->Constant(value));
}
Isolate* JSFrameSpecialization::isolate() const { return jsgraph()->isolate(); }
} // namespace compiler
} // namespace internal
} // namespace v8
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_COMPILER_JS_FRAME_SPECIALIZATION_H_
#define V8_COMPILER_JS_FRAME_SPECIALIZATION_H_
#include "src/compiler/graph-reducer.h"
namespace v8 {
namespace internal {
// Forward declarations.
class JavaScriptFrame;
namespace compiler {
// Forward declarations.
class JSGraph;
class JSFrameSpecialization final : public AdvancedReducer {
public:
JSFrameSpecialization(Editor* editor, JavaScriptFrame const* frame,
JSGraph* jsgraph)
: AdvancedReducer(editor), frame_(frame), jsgraph_(jsgraph) {}
~JSFrameSpecialization() final {}
const char* reducer_name() const override { return "JSFrameSpecialization"; }
Reduction Reduce(Node* node) final;
private:
Reduction ReduceOsrValue(Node* node);
Reduction ReduceParameter(Node* node);
Isolate* isolate() const;
JavaScriptFrame const* frame() const { return frame_; }
JSGraph* jsgraph() const { return jsgraph_; }
JavaScriptFrame const* const frame_;
JSGraph* const jsgraph_;
DISALLOW_COPY_AND_ASSIGN(JSFrameSpecialization);
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_JS_FRAME_SPECIALIZATION_H_
......@@ -438,14 +438,6 @@ Reduction JSInliner::ReduceJSCall(Node* node) {
// Determine the call target.
if (!DetermineCallTarget(node, shared_info)) return NoChange();
// Inlining is only supported in the bytecode pipeline.
if (!info_->is_optimizing_from_bytecode()) {
TRACE("Not inlining %s into %s due to use of the deprecated pipeline\n",
shared_info->DebugName()->ToCString().get(),
info_->shared_info()->DebugName()->ToCString().get());
return NoChange();
}
// Function must be inlineable.
if (!shared_info->IsInlineable()) {
TRACE("Not inlining %s into %s because callee is not inlineable\n",
......
......@@ -20,9 +20,8 @@ namespace v8 {
namespace internal {
namespace compiler {
JSIntrinsicLowering::JSIntrinsicLowering(Editor* editor, JSGraph* jsgraph,
DeoptimizationMode mode)
: AdvancedReducer(editor), jsgraph_(jsgraph), mode_(mode) {}
JSIntrinsicLowering::JSIntrinsicLowering(Editor* editor, JSGraph* jsgraph)
: AdvancedReducer(editor), jsgraph_(jsgraph) {}
Reduction JSIntrinsicLowering::Reduce(Node* node) {
if (node->opcode() != IrOpcode::kJSCallRuntime) return NoChange();
......@@ -134,7 +133,6 @@ Reduction JSIntrinsicLowering::ReduceDebugIsActive(Node* node) {
}
Reduction JSIntrinsicLowering::ReduceDeoptimizeNow(Node* node) {
if (mode() != kDeoptimizationEnabled) return NoChange();
Node* const frame_state = NodeProperties::GetFrameStateInput(node);
Node* const effect = NodeProperties::GetEffectInput(node);
Node* const control = NodeProperties::GetControlInput(node);
......
......@@ -31,10 +31,7 @@ class SimplifiedOperatorBuilder;
class V8_EXPORT_PRIVATE JSIntrinsicLowering final
: public NON_EXPORTED_BASE(AdvancedReducer) {
public:
enum DeoptimizationMode { kDeoptimizationEnabled, kDeoptimizationDisabled };
JSIntrinsicLowering(Editor* editor, JSGraph* jsgraph,
DeoptimizationMode mode);
JSIntrinsicLowering(Editor* editor, JSGraph* jsgraph);
~JSIntrinsicLowering() final {}
const char* reducer_name() const override { return "JSIntrinsicLowering"; }
......@@ -96,10 +93,8 @@ class V8_EXPORT_PRIVATE JSIntrinsicLowering final
CommonOperatorBuilder* common() const;
JSOperatorBuilder* javascript() const;
SimplifiedOperatorBuilder* simplified() const;
DeoptimizationMode mode() const { return mode_; }
JSGraph* const jsgraph_;
DeoptimizationMode const mode_;
};
} // namespace compiler
......
......@@ -32,7 +32,6 @@ class JSBinopReduction final {
: lowering_(lowering), node_(node) {}
bool GetCompareNumberOperationHint(NumberOperationHint* hint) {
if (lowering_->flags() & JSTypedLowering::kDeoptimizationEnabled) {
DCHECK_EQ(1, node_->op()->EffectOutputCount());
switch (CompareOperationHintOf(node_->op())) {
case CompareOperationHint::kSignedSmall:
......@@ -52,49 +51,36 @@ class JSBinopReduction final {
case CompareOperationHint::kInternalizedString:
break;
}
}
return false;
}
bool IsInternalizedStringCompareOperation() {
if (lowering_->flags() & JSTypedLowering::kDeoptimizationEnabled) {
DCHECK_EQ(1, node_->op()->EffectOutputCount());
return (CompareOperationHintOf(node_->op()) ==
CompareOperationHint::kInternalizedString) &&
BothInputsMaybe(Type::InternalizedString());
}
return false;
}
bool IsReceiverCompareOperation() {
if (lowering_->flags() & JSTypedLowering::kDeoptimizationEnabled) {
DCHECK_EQ(1, node_->op()->EffectOutputCount());
return (CompareOperationHintOf(node_->op()) ==
CompareOperationHint::kReceiver) &&
BothInputsMaybe(Type::Receiver());
}
return false;
}
bool IsStringCompareOperation() {
if (lowering_->flags() & JSTypedLowering::kDeoptimizationEnabled) {
DCHECK_EQ(1, node_->op()->EffectOutputCount());
return (CompareOperationHintOf(node_->op()) ==
CompareOperationHint::kString) &&
BothInputsMaybe(Type::String());
}
return false;
}
bool IsSymbolCompareOperation() {
if (lowering_->flags() & JSTypedLowering::kDeoptimizationEnabled) {
DCHECK_EQ(1, node_->op()->EffectOutputCount());
return (CompareOperationHintOf(node_->op()) ==
CompareOperationHint::kSymbol) &&
BothInputsMaybe(Type::Symbol());
}
return false;
}
// Check if a string addition will definitely result in creating a ConsString,
// i.e. if the combined length of the resulting string exceeds the ConsString
......@@ -103,8 +89,7 @@ class JSBinopReduction final {
DCHECK_EQ(IrOpcode::kJSAdd, node_->opcode());
DCHECK(OneInputIs(Type::String()));
if (BothInputsAre(Type::String()) ||
((lowering_->flags() & JSTypedLowering::kDeoptimizationEnabled) &&
BinaryOperationHintOf(node_->op()) == BinaryOperationHint::kString)) {
BinaryOperationHintOf(node_->op()) == BinaryOperationHint::kString) {
HeapObjectBinopMatcher m(node_);
if (m.right().HasValue() && m.right().Value()->IsString()) {
Handle<String> right_string = Handle<String>::cast(m.right().Value());
......@@ -204,36 +189,10 @@ class JSBinopReduction final {
}
void ConvertInputsToNumber() {
// To convert the inputs to numbers, we have to provide frame states
// for lazy bailouts in the ToNumber conversions.
// We use a little hack here: we take the frame state before the binary
// operation and use it to construct the frame states for the conversion
// so that after the deoptimization, the binary operation IC gets
// already converted values from full code. This way we are sure that we
// will not re-do any of the side effects.
Node* left_input = nullptr;
Node* right_input = nullptr;
bool left_is_primitive = left_type()->Is(Type::PlainPrimitive());
bool right_is_primitive = right_type()->Is(Type::PlainPrimitive());
bool handles_exception = NodeProperties::IsExceptionalCall(node_);
if (!left_is_primitive && !right_is_primitive && handles_exception) {
ConvertBothInputsToNumber(&left_input, &right_input);
} else {
left_input = left_is_primitive
? ConvertPlainPrimitiveToNumber(left())
: ConvertSingleInputToNumber(
left(), CreateFrameStateForLeftInput());
right_input =
right_is_primitive
? ConvertPlainPrimitiveToNumber(right())
: ConvertSingleInputToNumber(
right(), CreateFrameStateForRightInput(left_input));
}
node_->ReplaceInput(0, left_input);
node_->ReplaceInput(1, right_input);
DCHECK(left_type()->Is(Type::PlainPrimitive()));
DCHECK(right_type()->Is(Type::PlainPrimitive()));
node_->ReplaceInput(0, ConvertPlainPrimitiveToNumber(left()));
node_->ReplaceInput(1, ConvertPlainPrimitiveToNumber(right()));
}
void ConvertInputsToUI32(Signedness left_signedness,
......@@ -402,20 +361,6 @@ class JSBinopReduction final {
JSTypedLowering* lowering_; // The containing lowering instance.
Node* node_; // The original node.
Node* CreateFrameStateForLeftInput() {
// Deoptimization is disabled => return dummy frame state instead.
Node* dummy_state = NodeProperties::GetFrameStateInput(node_);
DCHECK(OpParameter<FrameStateInfo>(dummy_state).bailout_id().IsNone());
return dummy_state;
}
Node* CreateFrameStateForRightInput(Node* converted_left) {
// Deoptimization is disabled => return dummy frame state instead.
Node* dummy_state = NodeProperties::GetFrameStateInput(node_);
DCHECK(OpParameter<FrameStateInfo>(dummy_state).bailout_id().IsNone());
return dummy_state;
}
Node* ConvertPlainPrimitiveToNumber(Node* node) {
DCHECK(NodeProperties::GetType(node)->Is(Type::PlainPrimitive()));
// Avoid inserting too many eager ToNumber() operations.
......@@ -427,61 +372,6 @@ class JSBinopReduction final {
return graph()->NewNode(simplified()->PlainPrimitiveToNumber(), node);
}
Node* ConvertSingleInputToNumber(Node* node, Node* frame_state) {
DCHECK(!NodeProperties::GetType(node)->Is(Type::PlainPrimitive()));
Node* const n = graph()->NewNode(javascript()->ToNumber(), node, context(),
frame_state, effect(), control());
NodeProperties::ReplaceControlInput(node_, n);
update_effect(n);
return n;
}
void ConvertBothInputsToNumber(Node** left_result, Node** right_result) {
Node* projections[2];
// Find {IfSuccess} and {IfException} continuations of the operation.
NodeProperties::CollectControlProjections(node_, projections, 2);
Node* if_exception = projections[1];
Node* if_success = projections[0];
// Insert two ToNumber() operations that both potentially throw.
Node* left_state = CreateFrameStateForLeftInput();
Node* left_conv =
graph()->NewNode(javascript()->ToNumber(), left(), context(),
left_state, effect(), control());
Node* left_success = graph()->NewNode(common()->IfSuccess(), left_conv);
Node* right_state = CreateFrameStateForRightInput(left_conv);
Node* right_conv =
graph()->NewNode(javascript()->ToNumber(), right(), context(),
right_state, left_conv, left_success);
Node* left_exception =
graph()->NewNode(common()->IfException(), left_conv, left_conv);
Node* right_exception =
graph()->NewNode(common()->IfException(), right_conv, right_conv);
NodeProperties::ReplaceControlInput(if_success, right_conv);
update_effect(right_conv);
// Wire conversions to existing {IfException} continuation.
Node* exception_merge = if_exception;
Node* exception_value =
graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
left_exception, right_exception, exception_merge);
Node* exception_effect =
graph()->NewNode(common()->EffectPhi(2), left_exception,
right_exception, exception_merge);
for (Edge edge : exception_merge->use_edges()) {
if (NodeProperties::IsEffectEdge(edge)) edge.UpdateTo(exception_effect);
if (NodeProperties::IsValueEdge(edge)) edge.UpdateTo(exception_value);
}
NodeProperties::RemoveType(exception_merge);
exception_merge->ReplaceInput(0, left_exception);
exception_merge->ReplaceInput(1, right_exception);
NodeProperties::ChangeOp(exception_merge, common()->Merge(2));
*left_result = left_conv;
*right_result = right_conv;
}
Node* ConvertToUI32(Node* node, Signedness signedness) {
// Avoid introducing too many eager NumberToXXnt32() operations.
Type* type = NodeProperties::GetType(node);
......@@ -510,10 +400,9 @@ class JSBinopReduction final {
JSTypedLowering::JSTypedLowering(Editor* editor,
CompilationDependencies* dependencies,
Flags flags, JSGraph* jsgraph, Zone* zone)
JSGraph* jsgraph, Zone* zone)
: AdvancedReducer(editor),
dependencies_(dependencies),
flags_(flags),
jsgraph_(jsgraph),
empty_string_type_(
Type::HeapConstant(factory()->empty_string(), graph()->zone())),
......@@ -552,8 +441,7 @@ Reduction JSTypedLowering::ReduceJSAdd(Node* node) {
r.ConvertInputsToNumber();
return r.ChangeToPureOperator(simplified()->NumberAdd(), Type::Number());
}
if ((r.BothInputsAre(Type::PlainPrimitive()) ||
!(flags() & kDeoptimizationEnabled)) &&
if (r.BothInputsAre(Type::PlainPrimitive()) &&
r.NeitherInputCanBe(Type::StringOrReceiver())) {
// JSAdd(x:-string, y:-string) => NumberAdd(ToNumber(x), ToNumber(y))
r.ConvertInputsToNumber();
......@@ -564,8 +452,7 @@ Reduction JSTypedLowering::ReduceJSAdd(Node* node) {
return ReduceCreateConsString(node);
}
// Eliminate useless concatenation of empty string.
if ((flags() & kDeoptimizationEnabled) &&
BinaryOperationHintOf(node->op()) == BinaryOperationHint::kString) {
if (BinaryOperationHintOf(node->op()) == BinaryOperationHint::kString) {
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (r.LeftInputIs(empty_string_type_)) {
......@@ -611,8 +498,7 @@ Reduction JSTypedLowering::ReduceJSAdd(Node* node) {
Reduction JSTypedLowering::ReduceNumberBinop(Node* node) {
JSBinopReduction r(this, node);
if (r.BothInputsAre(Type::PlainPrimitive()) ||
!(flags() & kDeoptimizationEnabled)) {
if (r.BothInputsAre(Type::PlainPrimitive())) {
r.ConvertInputsToNumber();
return r.ChangeToPureOperator(r.NumberOp(), Type::Number());
}
......@@ -634,8 +520,7 @@ Reduction JSTypedLowering::ReduceSpeculativeNumberBinop(Node* node) {
Reduction JSTypedLowering::ReduceInt32Binop(Node* node) {
JSBinopReduction r(this, node);
if (r.BothInputsAre(Type::PlainPrimitive()) ||
!(flags() & kDeoptimizationEnabled)) {
if (r.BothInputsAre(Type::PlainPrimitive())) {
r.ConvertInputsToNumber();
r.ConvertInputsToUI32(kSigned, kSigned);
return r.ChangeToPureOperator(r.NumberOp(), Type::Signed32());
......@@ -645,8 +530,7 @@ Reduction JSTypedLowering::ReduceInt32Binop(Node* node) {
Reduction JSTypedLowering::ReduceUI32Shift(Node* node, Signedness signedness) {
JSBinopReduction r(this, node);
if (r.BothInputsAre(Type::PlainPrimitive()) ||
!(flags() & kDeoptimizationEnabled)) {
if (r.BothInputsAre(Type::PlainPrimitive())) {
r.ConvertInputsToNumber();
r.ConvertInputsToUI32(signedness, kUnsigned);
return r.ChangeToPureOperator(r.NumberOp(), signedness == kUnsigned
......@@ -824,8 +708,7 @@ Reduction JSTypedLowering::ReduceJSComparison(Node* node) {
less_than = simplified()->NumberLessThan();
less_than_or_equal = simplified()->NumberLessThanOrEqual();
} else if (r.OneInputCannotBe(Type::StringOrReceiver()) &&
(r.BothInputsAre(Type::PlainPrimitive()) ||
!(flags() & kDeoptimizationEnabled))) {
r.BothInputsAre(Type::PlainPrimitive())) {
r.ConvertInputsToNumber();
less_than = simplified()->NumberLessThan();
less_than_or_equal = simplified()->NumberLessThanOrEqual();
......
......@@ -6,7 +6,6 @@
#define V8_COMPILER_JS_TYPED_LOWERING_H_
#include "src/base/compiler-specific.h"
#include "src/base/flags.h"
#include "src/compiler/graph-reducer.h"
#include "src/compiler/opcodes.h"
#include "src/globals.h"
......@@ -31,15 +30,8 @@ class TypeCache;
class V8_EXPORT_PRIVATE JSTypedLowering final
: public NON_EXPORTED_BASE(AdvancedReducer) {
public:
// Flags that control the mode of operation.
enum Flag {
kNoFlags = 0u,
kDeoptimizationEnabled = 1u << 0,
};
typedef base::Flags<Flag> Flags;
JSTypedLowering(Editor* editor, CompilationDependencies* dependencies,
Flags flags, JSGraph* jsgraph, Zone* zone);
JSGraph* jsgraph, Zone* zone);
~JSTypedLowering() final {}
const char* reducer_name() const override { return "JSTypedLowering"; }
......@@ -106,10 +98,8 @@ class V8_EXPORT_PRIVATE JSTypedLowering final
CommonOperatorBuilder* common() const;
SimplifiedOperatorBuilder* simplified() const;
CompilationDependencies* dependencies() const;
Flags flags() const { return flags_; }
CompilationDependencies* dependencies_;
Flags flags_;
JSGraph* jsgraph_;
Type* empty_string_type_;
Type* shifted_int32_ranges_[4];
......@@ -117,8 +107,6 @@ class V8_EXPORT_PRIVATE JSTypedLowering final
TypeCache const& type_cache_;
};
DEFINE_OPERATORS_FOR_FLAGS(JSTypedLowering::Flags)
} // namespace compiler
} // namespace internal
} // namespace v8
......
......@@ -3,22 +3,12 @@
// found in the LICENSE file.
#include "src/compiler/osr.h"
#include "src/ast/scopes.h"
#include "src/compilation-info.h"
#include "src/compiler/all-nodes.h"
#include "src/compiler/common-operator-reducer.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/dead-code-elimination.h"
#include "src/compiler/frame.h"
#include "src/compiler/graph-reducer.h"
#include "src/compiler/graph-trimmer.h"
#include "src/compiler/graph-visualizer.h"
#include "src/compiler/graph.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/loop-analysis.h"
#include "src/compiler/node-marker.h"
#include "src/compiler/node.h"
#include "src/objects-inl.h"
#include "src/objects.h"
#include "src/objects/shared-function-info.h"
namespace v8 {
namespace internal {
......@@ -26,309 +16,10 @@ namespace compiler {
OsrHelper::OsrHelper(CompilationInfo* info)
: parameter_count_(
info->is_optimizing_from_bytecode()
? info->shared_info()->bytecode_array()->parameter_count()
: info->scope()->num_parameters()),
info->shared_info()->bytecode_array()->parameter_count()),
stack_slot_count_(
info->is_optimizing_from_bytecode()
? info->shared_info()->bytecode_array()->register_count() +
InterpreterFrameConstants::kExtraSlotCount
: info->scope()->num_stack_slots() +
info->osr_expr_stack_height()) {}
#ifdef DEBUG
#define TRACE_COND (FLAG_trace_turbo_graph && FLAG_trace_osr)
#else
#define TRACE_COND false
#endif
#define TRACE(...) \
do { \
if (TRACE_COND) PrintF(__VA_ARGS__); \
} while (false)
namespace {
// Peel outer loops and rewire the graph so that control reduction can
// produce a properly formed graph.
void PeelOuterLoopsForOsr(Graph* graph, CommonOperatorBuilder* common,
Zone* tmp_zone, Node* dead, LoopTree* loop_tree,
LoopTree::Loop* osr_loop, Node* osr_normal_entry,
Node* osr_loop_entry) {
const size_t original_count = graph->NodeCount();
AllNodes all(tmp_zone, graph);
NodeVector tmp_inputs(tmp_zone);
Node* sentinel = graph->NewNode(dead->op());
// Make a copy of the graph for each outer loop.
ZoneVector<NodeVector*> copies(tmp_zone);
for (LoopTree::Loop* loop = osr_loop->parent(); loop; loop = loop->parent()) {
void* stuff = tmp_zone->New(sizeof(NodeVector));
NodeVector* mapping =
new (stuff) NodeVector(original_count, sentinel, tmp_zone);
copies.push_back(mapping);
TRACE("OsrDuplication #%zu, depth %zu, header #%d:%s\n", copies.size(),
loop->depth(), loop_tree->HeaderNode(loop)->id(),
loop_tree->HeaderNode(loop)->op()->mnemonic());
// Prepare the mapping for OSR values and the OSR loop entry.
mapping->at(osr_normal_entry->id()) = dead;
mapping->at(osr_loop_entry->id()) = dead;
// The outer loops are dead in this copy.
for (LoopTree::Loop* outer = loop->parent(); outer;
outer = outer->parent()) {
for (Node* node : loop_tree->HeaderNodes(outer)) {
mapping->at(node->id()) = dead;
TRACE(" ---- #%d:%s -> dead (header)\n", node->id(),
node->op()->mnemonic());
}
}
// Copy all nodes.
for (size_t i = 0; i < all.reachable.size(); i++) {
Node* orig = all.reachable[i];
Node* copy = mapping->at(orig->id());
if (copy != sentinel) {
// Mapping already exists.
continue;
}
if (orig->InputCount() == 0 || orig->opcode() == IrOpcode::kParameter ||
orig->opcode() == IrOpcode::kOsrValue) {
// No need to copy leaf nodes or parameters.
mapping->at(orig->id()) = orig;
continue;
}
// Copy the node.
tmp_inputs.clear();
for (Node* input : orig->inputs()) {
tmp_inputs.push_back(mapping->at(input->id()));
}
copy = graph->NewNode(orig->op(), orig->InputCount(), &tmp_inputs[0]);
mapping->at(orig->id()) = copy;
TRACE(" copy #%d:%s -> #%d\n", orig->id(), orig->op()->mnemonic(),
copy->id());
}
// Fix missing inputs.
for (Node* orig : all.reachable) {
Node* copy = mapping->at(orig->id());
for (int j = 0; j < copy->InputCount(); j++) {
if (copy->InputAt(j) == sentinel) {
copy->ReplaceInput(j, mapping->at(orig->InputAt(j)->id()));
}
}
}
// Construct the entry into this loop from previous copies.
// Gather the live loop header nodes, {loop_header} first.
Node* loop_header = loop_tree->HeaderNode(loop);
NodeVector header_nodes(tmp_zone);
header_nodes.reserve(loop->HeaderSize());
header_nodes.push_back(loop_header); // put the loop header first.
for (Node* node : loop_tree->HeaderNodes(loop)) {
if (node != loop_header && all.IsLive(node)) {
header_nodes.push_back(node);
}
}
// Gather backedges from the previous copies of the inner loops of {loop}.
NodeVectorVector backedges(tmp_zone);
TRACE("Gathering backedges...\n");
for (int i = 1; i < loop_header->InputCount(); i++) {
if (TRACE_COND) {
Node* control = loop_header->InputAt(i);
size_t incoming_depth = 0;
for (int j = 0; j < control->op()->ControlInputCount(); j++) {
Node* k = NodeProperties::GetControlInput(control, j);
incoming_depth =
std::max(incoming_depth, loop_tree->ContainingLoop(k)->depth());
}
TRACE(" edge @%d #%d:%s, incoming depth %zu\n", i, control->id(),
control->op()->mnemonic(), incoming_depth);
}
for (int pos = static_cast<int>(copies.size()) - 1; pos >= 0; pos--) {
backedges.push_back(NodeVector(tmp_zone));
backedges.back().reserve(header_nodes.size());
NodeVector* previous_map = pos > 0 ? copies[pos - 1] : nullptr;
for (Node* node : header_nodes) {
Node* input = node->InputAt(i);
if (previous_map) input = previous_map->at(input->id());
backedges.back().push_back(input);
TRACE(" node #%d:%s(@%d) = #%d:%s\n", node->id(),
node->op()->mnemonic(), i, input->id(),
input->op()->mnemonic());
}
}
}
int backedge_count = static_cast<int>(backedges.size());
if (backedge_count == 1) {
// Simple case of single backedge, therefore a single entry.
int index = 0;
for (Node* node : header_nodes) {
Node* copy = mapping->at(node->id());
Node* input = backedges[0][index];
copy->ReplaceInput(0, input);
TRACE(" header #%d:%s(0) => #%d:%s\n", copy->id(),
copy->op()->mnemonic(), input->id(), input->op()->mnemonic());
index++;
}
} else {
// Complex case of multiple backedges from previous copies requires
// merging the backedges to create the entry into the loop header.
Node* merge = nullptr;
int index = 0;
for (Node* node : header_nodes) {
// Gather edge inputs into {tmp_inputs}.
tmp_inputs.clear();
for (int edge = 0; edge < backedge_count; edge++) {
tmp_inputs.push_back(backedges[edge][index]);
}
Node* copy = mapping->at(node->id());
Node* input;
if (node == loop_header) {
// Create the merge for the entry into the loop header.
input = merge = graph->NewNode(common->Merge(backedge_count),
backedge_count, &tmp_inputs[0]);
copy->ReplaceInput(0, merge);
} else {
// Create a phi that merges values at entry into the loop header.
DCHECK_NOT_NULL(merge);
DCHECK(IrOpcode::IsPhiOpcode(node->opcode()));
tmp_inputs.push_back(merge);
Node* phi = input = graph->NewNode(
common->ResizeMergeOrPhi(node->op(), backedge_count),
backedge_count + 1, &tmp_inputs[0]);
copy->ReplaceInput(0, phi);
}
// Print the merge.
if (TRACE_COND) {
TRACE(" header #%d:%s(0) => #%d:%s(", copy->id(),
copy->op()->mnemonic(), input->id(), input->op()->mnemonic());
for (size_t i = 0; i < tmp_inputs.size(); i++) {
if (i > 0) TRACE(", ");
Node* input = tmp_inputs[i];
TRACE("#%d:%s", input->id(), input->op()->mnemonic());
}
TRACE(")\n");
}
index++;
}
}
}
// Kill the outer loops in the original graph.
TRACE("Killing outer loop headers...\n");
for (LoopTree::Loop* outer = osr_loop->parent(); outer;
outer = outer->parent()) {
Node* loop_header = loop_tree->HeaderNode(outer);
loop_header->ReplaceUses(dead);
TRACE(" ---- #%d:%s\n", loop_header->id(), loop_header->op()->mnemonic());
}
// Merge the ends of the graph copies.
Node* const end = graph->end();
int const input_count = end->InputCount();
for (int i = 0; i < input_count; ++i) {
NodeId const id = end->InputAt(i)->id();
for (NodeVector* const copy : copies) {
end->AppendInput(graph->zone(), copy->at(id));
NodeProperties::ChangeOp(end, common->End(end->InputCount()));
}
}
if (FLAG_trace_turbo_graph) { // Simple textual RPO.
OFStream os(stdout);
os << "-- Graph after OSR duplication -- " << std::endl;
os << AsRPO(*graph);
}
}
} // namespace
void OsrHelper::Deconstruct(CompilationInfo* info, JSGraph* jsgraph,
CommonOperatorBuilder* common, Zone* tmp_zone) {
DCHECK(!info->is_optimizing_from_bytecode());
Graph* graph = jsgraph->graph();
Node* osr_normal_entry = nullptr;
Node* osr_loop_entry = nullptr;
Node* osr_loop = nullptr;
for (Node* node : graph->start()->uses()) {
if (node->opcode() == IrOpcode::kOsrLoopEntry) {
osr_loop_entry = node; // found the OSR loop entry
} else if (node->opcode() == IrOpcode::kOsrNormalEntry) {
osr_normal_entry = node;
}
}
CHECK_NOT_NULL(osr_normal_entry); // Should have found the OSR normal entry.
CHECK_NOT_NULL(osr_loop_entry); // Should have found the OSR loop entry.
for (Node* use : osr_loop_entry->uses()) {
if (use->opcode() == IrOpcode::kLoop) {
CHECK(!osr_loop); // should be only one OSR loop.
osr_loop = use; // found the OSR loop.
}
}
CHECK(osr_loop); // Should have found the OSR loop.
// Analyze the graph to determine how deeply nested the OSR loop is.
LoopTree* loop_tree = LoopFinder::BuildLoopTree(graph, tmp_zone);
Node* dead = jsgraph->Dead();
LoopTree::Loop* loop = loop_tree->ContainingLoop(osr_loop);
if (loop->depth() > 0) {
PeelOuterLoopsForOsr(graph, common, tmp_zone, dead, loop_tree, loop,
osr_normal_entry, osr_loop_entry);
}
// Replace the normal entry with {Dead} and the loop entry with {Start}
// and run the control reducer to clean up the graph.
osr_normal_entry->ReplaceUses(dead);
osr_normal_entry->Kill();
osr_loop_entry->ReplaceUses(graph->start());
osr_loop_entry->Kill();
// Remove the first input to the {osr_loop}.
int const live_input_count = osr_loop->InputCount() - 1;
CHECK_NE(0, live_input_count);
for (Node* const use : osr_loop->uses()) {
if (NodeProperties::IsPhi(use)) {
use->RemoveInput(0);
NodeProperties::ChangeOp(
use, common->ResizeMergeOrPhi(use->op(), live_input_count));
}
}
osr_loop->RemoveInput(0);
NodeProperties::ChangeOp(
osr_loop, common->ResizeMergeOrPhi(osr_loop->op(), live_input_count));
// Run control reduction and graph trimming.
// TODO(bmeurer): The OSR deconstruction could be a regular reducer and play
// nice together with the rest, instead of having this custom stuff here.
GraphReducer graph_reducer(tmp_zone, graph);
DeadCodeElimination dce(&graph_reducer, graph, common);
CommonOperatorReducer cor(&graph_reducer, graph, common, jsgraph->machine());
graph_reducer.AddReducer(&dce);
graph_reducer.AddReducer(&cor);
graph_reducer.ReduceGraph();
GraphTrimmer trimmer(tmp_zone, graph);
NodeVector roots(tmp_zone);
jsgraph->GetCachedNodes(&roots);
trimmer.TrimGraph(roots.begin(), roots.end());
}
info->shared_info()->bytecode_array()->register_count() +
InterpreterFrameConstants::kExtraSlotCount) {}
void OsrHelper::SetupFrame(Frame* frame) {
// The optimized frame will subsume the unoptimized frame. Do so by reserving
......@@ -336,8 +27,6 @@ void OsrHelper::SetupFrame(Frame* frame) {
frame->ReserveSpillSlots(UnoptimizedFrameSlots());
}
#undef TRACE
} // namespace compiler
} // namespace internal
} // namespace v8
......@@ -6,77 +6,6 @@
#define V8_COMPILER_OSR_H_
#include "src/zone/zone.h"
// TODO(6409) This phase (and then the below explanations) are now only used
// when osring from the ast graph builder. When using Ignition bytecode, the OSR
// implementation is integrated directly to the graph building phase.
// TurboFan structures OSR graphs in a way that separates almost all phases of
// compilation from OSR implementation details. This is accomplished with
// special control nodes that are added at graph building time. In particular,
// the graph is built in such a way that typing still computes the best types
// and optimizations and lowering work unchanged. All that remains is to
// deconstruct the OSR artifacts before scheduling and code generation.
// Graphs built for OSR from the AstGraphBuilder are structured as follows:
// Start
// +-------------------^^-----+
// | |
// OsrNormalEntry OsrLoopEntry <-------------+
// | | |
// control flow before loop | A OsrValue
// | | | |
// | +------------------------+ | +-------+
// | | +-------------+ | | +--------+
// | | | | | | | |
// ( Loop )<-----------|------------------ ( phi ) |
// | | |
// loop body | backedge(s) |
// | | | |
// | +--------------+ B <-----+
// |
// end
// The control structure expresses the relationship that the loop has a separate
// entrypoint which corresponds to entering the loop directly from the middle
// of unoptimized code.
// Similarly, the values that come in from unoptimized code are represented with
// {OsrValue} nodes that merge into any phis associated with the OSR loop.
// In the above diagram, nodes {A} and {B} represent values in the "normal"
// graph that correspond to the values of those phis before the loop and on any
// backedges, respectively.
// To deconstruct OSR, we simply replace the uses of the {OsrNormalEntry}
// control node with {Dead} and {OsrLoopEntry} with start and run the
// {ControlReducer}. Control reduction propagates the dead control forward,
// essentially "killing" all the code before the OSR loop. The entrypoint to the
// loop corresponding to the "normal" entry path will also be removed, as well
// as the inputs to the loop phis, resulting in the reduced graph:
// Start
// Dead |^-------------------------+
// | | |
// | | |
// | | |
// disconnected, dead | A=dead OsrValue
// | |
// +------------------+ +------+
// | +-------------+ | +--------+
// | | | | | |
// ( Loop )<-----------|------------------ ( phi ) |
// | | |
// loop body | backedge(s) |
// | | | |
// | +--------------+ B <-----+
// |
// end
// Other than the presences of the OsrValue nodes, this is a normal, schedulable
// graph. OsrValue nodes are handled specially in the instruction selector to
// simply load from the unoptimized frame.
// For nested OSR loops, loop peeling must first be applied as many times as
// necessary in order to bring the OSR loop up to the top level (i.e. to be
// an outer loop).
namespace v8 {
namespace internal {
......@@ -85,10 +14,7 @@ class CompilationInfo;
namespace compiler {
class JSGraph;
class CommonOperatorBuilder;
class Frame;
class Linkage;
// Encapsulates logic relating to OSR compilations as well has handles some
// details of the frame layout.
......@@ -96,11 +22,6 @@ class OsrHelper {
public:
explicit OsrHelper(CompilationInfo* info);
// Deconstructs the artificial {OsrNormalEntry} and rewrites the graph so
// that only the path corresponding to {OsrLoopEntry} remains.
void Deconstruct(CompilationInfo* info, JSGraph* jsgraph,
CommonOperatorBuilder* common, Zone* tmp_zone);
// Prepares the frame w.r.t. OSR.
void SetupFrame(Frame* frame);
......@@ -109,7 +30,7 @@ class OsrHelper {
// Returns the environment index of the first stack slot.
static int FirstStackSlotIndex(int parameter_count) {
// n.b. unlike Crankshaft, TurboFan environments do not contain the context.
// TurboFan environments do not contain the context.
return 1 + parameter_count; // receiver + params
}
......
......@@ -13,14 +13,13 @@
#include "src/base/platform/elapsed-timer.h"
#include "src/compilation-info.h"
#include "src/compiler.h"
#include "src/compiler/ast-graph-builder.h"
#include "src/compiler/ast-loop-assignment-analyzer.h"
#include "src/compiler/basic-block-instrumentor.h"
#include "src/compiler/branch-elimination.h"
#include "src/compiler/bytecode-graph-builder.h"
#include "src/compiler/checkpoint-elimination.h"
#include "src/compiler/code-generator.h"
#include "src/compiler/common-operator-reducer.h"
#include "src/compiler/compiler-source-position-table.h"
#include "src/compiler/control-flow-optimizer.h"
#include "src/compiler/dead-code-elimination.h"
#include "src/compiler/effect-control-linearizer.h"
......@@ -35,7 +34,6 @@
#include "src/compiler/js-call-reducer.h"
#include "src/compiler/js-context-specialization.h"
#include "src/compiler/js-create-lowering.h"
#include "src/compiler/js-frame-specialization.h"
#include "src/compiler/js-generic-lowering.h"
#include "src/compiler/js-inlining-heuristic.h"
#include "src/compiler/js-intrinsic-lowering.h"
......@@ -229,12 +227,6 @@ class PipelineData {
return handle(info()->global_object(), isolate());
}
LoopAssignmentAnalysis* loop_assignment() const { return loop_assignment_; }
void set_loop_assignment(LoopAssignmentAnalysis* loop_assignment) {
DCHECK(!loop_assignment_);
loop_assignment_ = loop_assignment;
}
Schedule* schedule() const { return schedule_; }
void set_schedule(Schedule* schedule) {
DCHECK(!schedule_);
......@@ -275,7 +267,6 @@ class PipelineData {
graph_zone_ = nullptr;
graph_ = nullptr;
source_positions_ = nullptr;
loop_assignment_ = nullptr;
simplified_ = nullptr;
machine_ = nullptr;
common_ = nullptr;
......@@ -389,7 +380,6 @@ class PipelineData {
Zone* graph_zone_ = nullptr;
Graph* graph_ = nullptr;
SourcePositionTable* source_positions_ = nullptr;
LoopAssignmentAnalysis* loop_assignment_ = nullptr;
SimplifiedOperatorBuilder* simplified_ = nullptr;
MachineOperatorBuilder* machine_ = nullptr;
CommonOperatorBuilder* common_ = nullptr;
......@@ -637,10 +627,6 @@ class PipelineCompilationJob final : public CompilationJob {
PipelineCompilationJob::Status PipelineCompilationJob::PrepareJobImpl() {
if (compilation_info()->shared_info()->asm_function()) {
if (compilation_info()->osr_frame() &&
!compilation_info()->is_optimizing_from_bytecode()) {
compilation_info()->MarkAsFrameSpecializing();
}
compilation_info()->MarkAsFunctionContextSpecializing();
} else {
if (!FLAG_always_opt) {
......@@ -650,8 +636,6 @@ PipelineCompilationJob::Status PipelineCompilationJob::PrepareJobImpl() {
compilation_info()->MarkAsLoopPeelingEnabled();
}
}
if (compilation_info()->is_optimizing_from_bytecode()) {
compilation_info()->MarkAsDeoptimizationEnabled();
if (FLAG_turbo_inlining) {
compilation_info()->MarkAsInliningEnabled();
}
......@@ -662,8 +646,6 @@ PipelineCompilationJob::Status PipelineCompilationJob::PrepareJobImpl() {
isolate()->heap()->one_closure_cell_map()) {
compilation_info()->MarkAsFunctionContextSpecializing();
}
compilation_info()->MarkAsInliningEnabled();
}
data_.set_start_source_position(
compilation_info()->shared_info()->start_position());
......@@ -702,10 +684,9 @@ PipelineCompilationJob::Status PipelineCompilationJob::FinalizeJobImpl() {
}
compilation_info()->dependencies()->Commit(code);
compilation_info()->SetCode(code);
if (compilation_info()->is_deoptimization_enabled()) {
compilation_info()->context()->native_context()->AddOptimizedCode(*code);
RegisterWeakObjectsInOptimizedCode(code);
}
return SUCCEEDED;
}
......@@ -906,26 +887,10 @@ void PipelineImpl::Run(Arg0 arg_0, Arg1 arg_1) {
phase.Run(this->data_, scope.zone(), arg_0, arg_1);
}
struct LoopAssignmentAnalysisPhase {
static const char* phase_name() { return "loop assignment analysis"; }
void Run(PipelineData* data, Zone* temp_zone) {
if (!data->info()->is_optimizing_from_bytecode()) {
AstLoopAssignmentAnalyzer analyzer(data->graph_zone(), data->info());
LoopAssignmentAnalysis* loop_assignment = analyzer.Analyze();
data->set_loop_assignment(loop_assignment);
}
}
};
struct GraphBuilderPhase {
static const char* phase_name() { return "graph builder"; }
void Run(PipelineData* data, Zone* temp_zone) {
if (data->info()->is_optimizing_from_bytecode()) {
// Bytecode graph builder assumes deoptimization is enabled.
DCHECK(data->info()->is_deoptimization_enabled());
JSTypeHintLowering::Flags flags = JSTypeHintLowering::kNoFlags;
if (data->info()->is_bailout_on_uninitialized()) {
flags |= JSTypeHintLowering::kBailoutOnUninitialized;
......@@ -936,16 +901,6 @@ struct GraphBuilderPhase {
data->info()->osr_ast_id(), data->jsgraph(), CallFrequency(1.0f),
data->source_positions(), SourcePosition::kNotInlined, flags);
graph_builder.CreateGraph();
} else {
// AST-based graph builder assumes deoptimization is disabled.
DCHECK(!data->info()->is_deoptimization_enabled());
AstGraphBuilderWithPositions graph_builder(
temp_zone, data->info(), data->jsgraph(), CallFrequency(1.0f),
data->loop_assignment(), data->source_positions());
if (!graph_builder.CreateGraph()) {
data->set_compilation_failed();
}
}
}
};
......@@ -996,8 +951,6 @@ struct InliningPhase {
data->info()->is_function_context_specializing()
? data->info()->closure()
: MaybeHandle<JSFunction>());
JSFrameSpecialization frame_specialization(
&graph_reducer, data->info()->osr_frame(), data->jsgraph());
JSNativeContextSpecialization::Flags flags =
JSNativeContextSpecialization::kNoFlags;
if (data->info()->is_accessor_inlining_enabled()) {
......@@ -1014,25 +967,14 @@ struct InliningPhase {
? JSInliningHeuristic::kGeneralInlining
: JSInliningHeuristic::kRestrictedInlining,
temp_zone, data->info(), data->jsgraph(), data->source_positions());
JSIntrinsicLowering intrinsic_lowering(
&graph_reducer, data->jsgraph(),
data->info()->is_deoptimization_enabled()
? JSIntrinsicLowering::kDeoptimizationEnabled
: JSIntrinsicLowering::kDeoptimizationDisabled);
JSIntrinsicLowering intrinsic_lowering(&graph_reducer, data->jsgraph());
AddReducer(data, &graph_reducer, &dead_code_elimination);
AddReducer(data, &graph_reducer, &checkpoint_elimination);
AddReducer(data, &graph_reducer, &common_reducer);
if (data->info()->is_frame_specializing()) {
AddReducer(data, &graph_reducer, &frame_specialization);
}
if (data->info()->is_deoptimization_enabled()) {
AddReducer(data, &graph_reducer, &native_context_specialization);
}
AddReducer(data, &graph_reducer, &context_specialization);
AddReducer(data, &graph_reducer, &intrinsic_lowering);
if (data->info()->is_deoptimization_enabled()) {
AddReducer(data, &graph_reducer, &call_reducer);
}
AddReducer(data, &graph_reducer, &inlining);
graph_reducer.ReduceGraph();
}
......@@ -1081,28 +1023,6 @@ struct UntyperPhase {
}
};
struct OsrDeconstructionPhase {
static const char* phase_name() { return "OSR deconstruction"; }
void Run(PipelineData* data, Zone* temp_zone) {
// When the bytecode comes from Ignition, we do the OSR implementation
// during the graph building phase.
if (data->info()->is_optimizing_from_bytecode()) return;
GraphTrimmer trimmer(temp_zone, data->graph());
NodeVector roots(temp_zone);
data->jsgraph()->GetCachedNodes(&roots);
trimmer.TrimGraph(roots.begin(), roots.end());
// TODO(neis): Remove (the whole OsrDeconstructionPhase) when AST graph
// builder is gone.
OsrHelper osr_helper(data->info());
osr_helper.Deconstruct(data->info(), data->jsgraph(), data->common(),
temp_zone);
}
};
struct TypedLoweringPhase {
static const char* phase_name() { return "typed lowering"; }
......@@ -1112,37 +1032,23 @@ struct TypedLoweringPhase {
data->common());
JSBuiltinReducer builtin_reducer(
&graph_reducer, data->jsgraph(),
data->info()->is_deoptimization_enabled()
? JSBuiltinReducer::kDeoptimizationEnabled
: JSBuiltinReducer::kNoFlags,
data->info()->dependencies(), data->native_context());
Handle<FeedbackVector> feedback_vector(
data->info()->closure()->feedback_vector());
JSCreateLowering create_lowering(
&graph_reducer, data->info()->dependencies(), data->jsgraph(),
feedback_vector, data->native_context(), temp_zone);
JSTypedLowering::Flags typed_lowering_flags = JSTypedLowering::kNoFlags;
if (data->info()->is_deoptimization_enabled()) {
typed_lowering_flags |= JSTypedLowering::kDeoptimizationEnabled;
}
JSTypedLowering typed_lowering(&graph_reducer, data->info()->dependencies(),
typed_lowering_flags, data->jsgraph(),
temp_zone);
data->jsgraph(), temp_zone);
TypedOptimization typed_optimization(
&graph_reducer, data->info()->dependencies(),
data->info()->is_deoptimization_enabled()
? TypedOptimization::kDeoptimizationEnabled
: TypedOptimization::kNoFlags,
data->jsgraph());
&graph_reducer, data->info()->dependencies(), data->jsgraph());
SimplifiedOperatorReducer simple_reducer(&graph_reducer, data->jsgraph());
CheckpointElimination checkpoint_elimination(&graph_reducer);
CommonOperatorReducer common_reducer(&graph_reducer, data->graph(),
data->common(), data->machine());
AddReducer(data, &graph_reducer, &dead_code_elimination);
AddReducer(data, &graph_reducer, &builtin_reducer);
if (data->info()->is_deoptimization_enabled()) {
AddReducer(data, &graph_reducer, &create_lowering);
}
AddReducer(data, &graph_reducer, &typed_optimization);
AddReducer(data, &graph_reducer, &typed_lowering);
AddReducer(data, &graph_reducer, &simple_reducer);
......@@ -1720,23 +1626,9 @@ bool PipelineImpl::CreateGraph() {
data->source_positions()->AddDecorator();
if (FLAG_loop_assignment_analysis) {
Run<LoopAssignmentAnalysisPhase>();
}
Run<GraphBuilderPhase>();
if (data->compilation_failed()) {
data->EndPhaseKind();
return false;
}
RunPrintAndVerify("Initial untyped", true);
// Perform OSR deconstruction.
if (info()->is_osr()) {
Run<OsrDeconstructionPhase>();
RunPrintAndVerify("OSR deconstruction", true);
}
// Perform function context specialization and inlining (if enabled).
Run<InliningPhase>();
RunPrintAndVerify("Inlined", true);
......
......@@ -17,10 +17,9 @@ namespace compiler {
TypedOptimization::TypedOptimization(Editor* editor,
CompilationDependencies* dependencies,
Flags flags, JSGraph* jsgraph)
JSGraph* jsgraph)
: AdvancedReducer(editor),
dependencies_(dependencies),
flags_(flags),
jsgraph_(jsgraph),
true_type_(Type::HeapConstant(factory()->true_value(), graph()->zone())),
false_type_(
......@@ -212,11 +211,7 @@ Reduction TypedOptimization::ReduceLoadField(Node* node) {
Handle<Map> object_map;
if (GetStableMapFromObjectType(object_type).ToHandle(&object_map)) {
if (object_map->CanTransition()) {
if (flags() & kDeoptimizationEnabled) {
dependencies()->AssumeMapStable(object_map);
} else {
return NoChange();
}
}
Node* const value = jsgraph()->HeapConstant(object_map);
ReplaceWithValue(node, value);
......
......@@ -6,7 +6,6 @@
#define V8_COMPILER_TYPED_OPTIMIZATION_H_
#include "src/base/compiler-specific.h"
#include "src/base/flags.h"
#include "src/compiler/graph-reducer.h"
#include "src/globals.h"
......@@ -28,15 +27,8 @@ class TypeCache;
class V8_EXPORT_PRIVATE TypedOptimization final
: public NON_EXPORTED_BASE(AdvancedReducer) {
public:
// Flags that control the mode of operation.
enum Flag {
kNoFlags = 0u,
kDeoptimizationEnabled = 1u << 0,
};
typedef base::Flags<Flag> Flags;
TypedOptimization(Editor* editor, CompilationDependencies* dependencies,
Flags flags, JSGraph* jsgraph);
JSGraph* jsgraph);
~TypedOptimization();
const char* reducer_name() const override { return "TypedOptimization"; }
......@@ -61,14 +53,12 @@ class V8_EXPORT_PRIVATE TypedOptimization final
CompilationDependencies* dependencies() const { return dependencies_; }
Factory* factory() const;
Flags flags() const { return flags_; }
Graph* graph() const;
Isolate* isolate() const;
JSGraph* jsgraph() const { return jsgraph_; }
SimplifiedOperatorBuilder* simplified() const;
CompilationDependencies* const dependencies_;
Flags const flags_;
JSGraph* const jsgraph_;
Type* const true_type_;
Type* const false_type_;
......@@ -77,8 +67,6 @@ class V8_EXPORT_PRIVATE TypedOptimization final
DISALLOW_COPY_AND_ASSIGN(TypedOptimization);
};
DEFINE_OPERATORS_FOR_FLAGS(TypedOptimization::Flags)
} // namespace compiler
} // namespace internal
} // namespace v8
......
......@@ -443,7 +443,6 @@ DEFINE_BOOL(turbo_inline_array_builtins, true,
DEFINE_BOOL(turbo_load_elimination, true, "enable load elimination in TurboFan")
DEFINE_BOOL(trace_turbo_load_elimination, false,
"trace TurboFan load elimination")
DEFINE_BOOL(loop_assignment_analysis, true, "perform loop assignment analysis")
DEFINE_BOOL(turbo_profiling, false, "enable profiling in TurboFan")
DEFINE_BOOL(turbo_verify_allocation, DEBUG_BOOL,
"verify register allocation in TurboFan")
......
......@@ -687,10 +687,6 @@
'compiler/access-info.h',
'compiler/all-nodes.cc',
'compiler/all-nodes.h',
'compiler/ast-graph-builder.cc',
'compiler/ast-graph-builder.h',
'compiler/ast-loop-assignment-analyzer.cc',
'compiler/ast-loop-assignment-analyzer.h',
'compiler/basic-block-instrumentor.cc',
'compiler/basic-block-instrumentor.h',
'compiler/branch-elimination.cc',
......@@ -715,8 +711,6 @@
'compiler/common-operator-reducer.h',
'compiler/common-operator.cc',
'compiler/common-operator.h',
'compiler/control-builders.cc',
'compiler/control-builders.h',
'compiler/control-equivalence.cc',
'compiler/control-equivalence.h',
'compiler/control-flow-optimizer.cc',
......@@ -766,8 +760,6 @@
'compiler/js-context-specialization.h',
'compiler/js-create-lowering.cc',
'compiler/js-create-lowering.h',
'compiler/js-frame-specialization.cc',
'compiler/js-frame-specialization.h',
'compiler/js-generic-lowering.cc',
'compiler/js-generic-lowering.h',
'compiler/js-graph.cc',
......
......@@ -37,7 +37,6 @@ v8_executable("cctest") {
"compiler/test-jump-threading.cc",
"compiler/test-linkage.cc",
"compiler/test-loop-analysis.cc",
"compiler/test-loop-assignment-analysis.cc",
"compiler/test-machine-operator-reducer.cc",
"compiler/test-multiple-return.cc",
"compiler/test-node.cc",
......
......@@ -53,7 +53,6 @@
'compiler/test-js-typed-lowering.cc',
'compiler/test-jump-threading.cc',
'compiler/test-linkage.cc',
'compiler/test-loop-assignment-analysis.cc',
'compiler/test-loop-analysis.cc',
'compiler/test-machine-operator-reducer.cc',
'compiler/test-multiple-return.cc',
......
......@@ -148,8 +148,6 @@ Handle<JSFunction> FunctionTester::Compile(Handle<JSFunction> function) {
CHECK(Compiler::Compile(function, Compiler::CLEAR_EXCEPTION));
CHECK(info.shared_info()->HasBytecodeArray());
info.MarkAsDeoptimizationEnabled();
info.MarkAsOptimizeFromBytecode();
JSFunction::EnsureLiterals(function);
Handle<Code> code = Pipeline::GenerateCodeForTesting(&info);
......
......@@ -26,9 +26,7 @@ namespace compiler {
class JSTypedLoweringTester : public HandleAndZoneScope {
public:
JSTypedLoweringTester(
int num_parameters = 0,
JSTypedLowering::Flags flags = JSTypedLowering::kDeoptimizationEnabled)
explicit JSTypedLoweringTester(int num_parameters = 0)
: isolate(main_isolate()),
binop(NULL),
unop(NULL),
......@@ -39,8 +37,7 @@ class JSTypedLoweringTester : public HandleAndZoneScope {
deps(main_isolate(), main_zone()),
graph(main_zone()),
typer(main_isolate(), Typer::kNoFlags, &graph),
context_node(NULL),
flags(flags) {
context_node(NULL) {
graph.SetStart(graph.NewNode(common.Start(num_parameters)));
graph.SetEnd(graph.NewNode(common.End(1), graph.start()));
typer.Run();
......@@ -57,7 +54,6 @@ class JSTypedLoweringTester : public HandleAndZoneScope {
Graph graph;
Typer typer;
Node* context_node;
JSTypedLowering::Flags flags;
BinaryOperationHint const binop_hints = BinaryOperationHint::kAny;
CompareOperationHint const compare_hints = CompareOperationHint::kAny;
......@@ -97,8 +93,7 @@ class JSTypedLoweringTester : public HandleAndZoneScope {
&machine);
// TODO(titzer): mock the GraphReducer here for better unit testing.
GraphReducer graph_reducer(main_zone(), &graph);
JSTypedLowering reducer(&graph_reducer, &deps, flags, &jsgraph,
main_zone());
JSTypedLowering reducer(&graph_reducer, &deps, &jsgraph, main_zone());
Reduction reduction = reducer.Reduce(node);
if (reduction.Changed()) return reduction.replacement();
return node;
......@@ -754,10 +749,8 @@ TEST(RemoveToNumberEffects) {
// Helper class for testing the reduction of a single binop.
class BinopEffectsTester {
public:
BinopEffectsTester(
const Operator* op, Type* t0, Type* t1,
JSTypedLowering::Flags flags = JSTypedLowering::kDeoptimizationEnabled)
: R(0, flags),
BinopEffectsTester(const Operator* op, Type* t0, Type* t1)
: R(0),
p0(R.Parameter(t0, 0)),
p1(R.Parameter(t1, 1)),
binop(R.Binop(op, p0, p1)),
......@@ -915,133 +908,11 @@ TEST(RemovePureNumberBinopEffects) {
}
}
TEST(OrderNumberBinopEffects1) {
JSTypedLoweringTester R;
const Operator* ops[] = {
R.javascript.Subtract(), R.simplified.NumberSubtract(),
R.javascript.Multiply(), R.simplified.NumberMultiply(),
};
for (size_t j = 0; j < arraysize(ops); j += 2) {
BinopEffectsTester B(ops[j], Type::Symbol(), Type::Symbol(),
JSTypedLowering::kNoFlags);
CHECK_EQ(ops[j + 1]->opcode(), B.result->op()->opcode());
Node* i0 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 0, true);
Node* i1 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 1, true);
CHECK_EQ(B.p0, i0->InputAt(0));
CHECK_EQ(B.p1, i1->InputAt(0));
// Effects should be ordered start -> i0 -> i1 -> effect_use
B.CheckEffectOrdering(i0, i1);
}
}
TEST(OrderNumberBinopEffects2) {
JSTypedLoweringTester R;
const Operator* ops[] = {
R.javascript.Add(R.binop_hints), R.simplified.NumberAdd(),
R.javascript.Subtract(), R.simplified.NumberSubtract(),
R.javascript.Multiply(), R.simplified.NumberMultiply(),
};
for (size_t j = 0; j < arraysize(ops); j += 2) {
BinopEffectsTester B(ops[j], Type::Number(), Type::Symbol(),
JSTypedLowering::kNoFlags);
Node* i0 = B.CheckNoOp(0);
Node* i1 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 1, true);
CHECK_EQ(B.p0, i0);
CHECK_EQ(B.p1, i1->InputAt(0));
// Effects should be ordered start -> i1 -> effect_use
B.CheckEffectOrdering(i1);
}
for (size_t j = 0; j < arraysize(ops); j += 2) {
BinopEffectsTester B(ops[j], Type::Symbol(), Type::Number(),
JSTypedLowering::kNoFlags);
Node* i0 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 0, true);
Node* i1 = B.CheckNoOp(1);
CHECK_EQ(B.p0, i0->InputAt(0));
CHECK_EQ(B.p1, i1);
// Effects should be ordered start -> i0 -> effect_use
B.CheckEffectOrdering(i0);
}
}
TEST(OrderCompareEffects) {
JSTypedLoweringTester R;
const Operator* ops[] = {
R.javascript.GreaterThan(R.compare_hints), R.simplified.NumberLessThan(),
R.javascript.GreaterThanOrEqual(R.compare_hints),
R.simplified.NumberLessThanOrEqual(),
};
for (size_t j = 0; j < arraysize(ops); j += 2) {
BinopEffectsTester B(ops[j], Type::Symbol(), Type::String(),
JSTypedLowering::kNoFlags);
CHECK_EQ(ops[j + 1]->opcode(), B.result->op()->opcode());
Node* i0 =
B.CheckConvertedInput(IrOpcode::kPlainPrimitiveToNumber, 0, false);
Node* i1 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 1, true);
// Inputs should be commuted.
CHECK_EQ(B.p1, i0->InputAt(0));
CHECK_EQ(B.p0, i1->InputAt(0));
// But effects should be ordered start -> i1 -> effect_use
B.CheckEffectOrdering(i1);
}
for (size_t j = 0; j < arraysize(ops); j += 2) {
BinopEffectsTester B(ops[j], Type::Number(), Type::Symbol(),
JSTypedLowering::kNoFlags);
Node* i0 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 0, true);
Node* i1 = B.result->InputAt(1);
CHECK_EQ(B.p1, i0->InputAt(0)); // Should be commuted.
CHECK_EQ(B.p0, i1);
// Effects should be ordered start -> i1 -> effect_use
B.CheckEffectOrdering(i0);
}
for (size_t j = 0; j < arraysize(ops); j += 2) {
BinopEffectsTester B(ops[j], Type::Symbol(), Type::Number(),
JSTypedLowering::kNoFlags);
Node* i0 = B.result->InputAt(0);
Node* i1 = B.CheckConvertedInput(IrOpcode::kJSToNumber, 1, true);
CHECK_EQ(B.p1, i0); // Should be commuted.
CHECK_EQ(B.p0, i1->InputAt(0));
// Effects should be ordered start -> i0 -> effect_use
B.CheckEffectOrdering(i1);
}
}
TEST(Int32BinopEffects) {
JSBitwiseTypedLoweringTester R;
for (int j = 0; j < R.kNumberOps; j += 2) {
bool signed_left = R.signedness[j], signed_right = R.signedness[j + 1];
BinopEffectsTester B(R.ops[j], I32Type(signed_left), I32Type(signed_right),
JSTypedLowering::kNoFlags);
BinopEffectsTester B(R.ops[j], I32Type(signed_left), I32Type(signed_right));
CHECK_EQ(R.ops[j + 1]->opcode(), B.result->op()->opcode());
B.R.CheckBinop(B.result->opcode(), B.result);
......@@ -1054,8 +925,7 @@ TEST(Int32BinopEffects) {
for (int j = 0; j < R.kNumberOps; j += 2) {
bool signed_left = R.signedness[j], signed_right = R.signedness[j + 1];
BinopEffectsTester B(R.ops[j], Type::Number(), Type::Number(),
JSTypedLowering::kNoFlags);
BinopEffectsTester B(R.ops[j], Type::Number(), Type::Number());
CHECK_EQ(R.ops[j + 1]->opcode(), B.result->op()->opcode());
B.R.CheckBinop(B.result->opcode(), B.result);
......@@ -1067,58 +937,38 @@ TEST(Int32BinopEffects) {
}
for (int j = 0; j < R.kNumberOps; j += 2) {
bool signed_left = R.signedness[j], signed_right = R.signedness[j + 1];
BinopEffectsTester B(R.ops[j], Type::Number(), Type::Primitive(),
JSTypedLowering::kNoFlags);
bool signed_left = R.signedness[j];
BinopEffectsTester B(R.ops[j], Type::Number(), Type::Boolean());
B.R.CheckBinop(B.result->opcode(), B.result);
Node* i0 = B.CheckConvertedInput(NumberToI32(signed_left), 0, false);
Node* i1 = B.CheckConvertedInput(NumberToI32(signed_right), 1, false);
CHECK_EQ(B.p0, i0->InputAt(0));
Node* ii1 = B.CheckConverted(IrOpcode::kJSToNumber, i1->InputAt(0), true);
CHECK_EQ(B.p1, ii1->InputAt(0));
B.CheckConvertedInput(NumberToI32(signed_left), 0, false);
B.CheckConvertedInput(IrOpcode::kPlainPrimitiveToNumber, 1, false);
B.CheckEffectOrdering(ii1);
B.CheckEffectsRemoved();
}
for (int j = 0; j < R.kNumberOps; j += 2) {
bool signed_left = R.signedness[j], signed_right = R.signedness[j + 1];
BinopEffectsTester B(R.ops[j], Type::Primitive(), Type::Number(),
JSTypedLowering::kNoFlags);
bool signed_right = R.signedness[j + 1];
BinopEffectsTester B(R.ops[j], Type::Boolean(), Type::Number());
B.R.CheckBinop(B.result->opcode(), B.result);
Node* i0 = B.CheckConvertedInput(NumberToI32(signed_left), 0, false);
Node* i1 = B.CheckConvertedInput(NumberToI32(signed_right), 1, false);
Node* ii0 = B.CheckConverted(IrOpcode::kJSToNumber, i0->InputAt(0), true);
CHECK_EQ(B.p1, i1->InputAt(0));
CHECK_EQ(B.p0, ii0->InputAt(0));
B.CheckConvertedInput(IrOpcode::kPlainPrimitiveToNumber, 0, false);
B.CheckConvertedInput(NumberToI32(signed_right), 1, false);
B.CheckEffectOrdering(ii0);
B.CheckEffectsRemoved();
}
for (int j = 0; j < R.kNumberOps; j += 2) {
bool signed_left = R.signedness[j], signed_right = R.signedness[j + 1];
BinopEffectsTester B(R.ops[j], Type::Primitive(), Type::Primitive(),
JSTypedLowering::kNoFlags);
BinopEffectsTester B(R.ops[j], Type::Boolean(), Type::Boolean());
B.R.CheckBinop(B.result->opcode(), B.result);
Node* i0 = B.CheckConvertedInput(NumberToI32(signed_left), 0, false);
Node* i1 = B.CheckConvertedInput(NumberToI32(signed_right), 1, false);
Node* ii0 = B.CheckConverted(IrOpcode::kJSToNumber, i0->InputAt(0), true);
Node* ii1 = B.CheckConverted(IrOpcode::kJSToNumber, i1->InputAt(0), true);
CHECK_EQ(B.p0, ii0->InputAt(0));
CHECK_EQ(B.p1, ii1->InputAt(0));
B.CheckConvertedInput(IrOpcode::kPlainPrimitiveToNumber, 0, false);
B.CheckConvertedInput(IrOpcode::kPlainPrimitiveToNumber, 1, false);
B.CheckEffectOrdering(ii0, ii1);
B.CheckEffectsRemoved();
}
}
......
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ast/scopes.h"
#include "src/compilation-info.h"
#include "src/compiler/ast-loop-assignment-analyzer.h"
#include "src/objects-inl.h"
#include "src/parsing/parse-info.h"
#include "src/parsing/parsing.h"
#include "src/parsing/rewriter.h"
#include "test/cctest/cctest.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
const int kBufferSize = 1024;
struct TestHelper : public HandleAndZoneScope {
Handle<JSFunction> function;
LoopAssignmentAnalysis* result;
explicit TestHelper(const char* body)
: function(Handle<JSFunction>::null()), result(NULL) {
ScopedVector<char> program(kBufferSize);
SNPrintF(program, "function f(a,b,c) { %s; } f;", body);
v8::Local<v8::Value> v = CompileRun(program.start());
Handle<Object> obj = v8::Utils::OpenHandle(*v);
function = Handle<JSFunction>::cast(obj);
}
void CheckLoopAssignedCount(int expected, const char* var_name) {
// TODO(titzer): don't scope analyze every single time.
Handle<SharedFunctionInfo> shared(function->shared());
ParseInfo parse_info(shared);
CompilationInfo info(parse_info.zone(), function->GetIsolate(),
parse_info.script(), shared, function);
CHECK(parsing::ParseFunction(&parse_info, info.shared_info(),
info.isolate()));
info.set_literal(parse_info.literal());
CHECK(Rewriter::Rewrite(&parse_info));
DeclarationScope::Analyze(&parse_info);
DeclarationScope* scope = info.literal()->scope();
AstValueFactory* factory = parse_info.ast_value_factory();
CHECK(scope);
if (result == NULL) {
AstLoopAssignmentAnalyzer analyzer(main_zone(), &info);
result = analyzer.Analyze();
CHECK(result);
}
const i::AstRawString* name = factory->GetOneByteString(var_name);
i::Variable* var = scope->Lookup(name);
CHECK(var);
if (var->location() == VariableLocation::UNALLOCATED) {
CHECK_EQ(0, expected);
} else {
CHECK(var->IsStackAllocated());
CHECK_EQ(expected, result->GetAssignmentCountForTesting(scope, var));
}
}
};
} // namespace
TEST(SimpleLoop1) {
TestHelper f("var x = 0; while (x) ;");
f.CheckLoopAssignedCount(0, "x");
}
TEST(ForIn1) {
const char* loops[] = {"for(x in 0) { }"};
for (size_t i = 0; i < arraysize(loops); i++) {
TestHelper f(loops[i]);
f.CheckLoopAssignedCount(0, "x");
}
}
TEST(Param1) {
TestHelper f("while (1) a = 0;");
f.CheckLoopAssignedCount(1, "a");
f.CheckLoopAssignedCount(0, "b");
f.CheckLoopAssignedCount(0, "c");
}
TEST(Param2) {
TestHelper f("for (;;) b = 0;");
f.CheckLoopAssignedCount(0, "a");
f.CheckLoopAssignedCount(1, "b");
f.CheckLoopAssignedCount(0, "c");
}
TEST(Param2b) {
TestHelper f("a; b; c; for (;;) b = 0;");
f.CheckLoopAssignedCount(0, "a");
f.CheckLoopAssignedCount(1, "b");
f.CheckLoopAssignedCount(0, "c");
}
TEST(Param3) {
TestHelper f("for(x in 0) c = 0;");
f.CheckLoopAssignedCount(0, "a");
f.CheckLoopAssignedCount(0, "b");
f.CheckLoopAssignedCount(1, "c");
}
TEST(Param3b) {
TestHelper f("a; b; c; for(x in 0) c = 0;");
f.CheckLoopAssignedCount(0, "a");
f.CheckLoopAssignedCount(0, "b");
f.CheckLoopAssignedCount(1, "c");
}
TEST(NestedLoop1) {
TestHelper f("while (x) { while (x) { var x = 0; } }");
f.CheckLoopAssignedCount(2, "x");
}
TEST(NestedLoop2) {
TestHelper f("while (0) { while (0) { var x = 0; } }");
f.CheckLoopAssignedCount(2, "x");
}
TEST(NestedLoop3) {
TestHelper f("while (0) { var y = 1; while (0) { var x = 0; } }");
f.CheckLoopAssignedCount(2, "x");
f.CheckLoopAssignedCount(1, "y");
}
TEST(NestedInc1) {
const char* loops[] = {
"while (1) a(b++);",
"while (1) a(0, b++);",
"while (1) a(0, 0, b++);",
"while (1) a(b++, 1, 1);",
"while (1) a(++b);",
"while (1) a + (b++);",
"while (1) (b++) + a;",
"while (1) a + c(b++);",
"while (1) throw b++;",
"while (1) switch (b++) {} ;",
"while (1) switch (a) {case (b++): 0; } ;",
"while (1) switch (a) {case b: b++; } ;",
"while (1) a == (b++);",
"while (1) a === (b++);",
"while (1) +(b++);",
"while (1) ~(b++);",
"while (1) new a(b++);",
"while (1) (b++).f;",
"while (1) a[b++];",
"while (1) (b++)();",
"while (1) [b++];",
"while (1) [0,b++];",
"while (1) var y = [11,b++,12];",
"while (1) var y = {f:11,g:(b++),h:12};",
"while (1) try {b++;} finally {};",
"while (1) try {} finally {b++};",
"while (1) try {b++;} catch (e) {};",
"while (1) try {} catch (e) {b++};",
"while (1) return b++;",
"while (1) (b++) ? b : b;",
"while (1) b ? (b++) : b;",
"while (1) b ? b : (b++);",
};
for (size_t i = 0; i < arraysize(loops); i++) {
TestHelper f(loops[i]);
f.CheckLoopAssignedCount(1, "b");
}
}
TEST(NestedAssign1) {
const char* loops[] = {
"while (1) a(b=1);",
"while (1) a(0, b=1);",
"while (1) a(0, 0, b=1);",
"while (1) a(b=1, 1, 1);",
"while (1) a + (b=1);",
"while (1) (b=1) + a;",
"while (1) a + c(b=1);",
"while (1) throw b=1;",
"while (1) switch (b=1) {} ;",
"while (1) switch (a) {case b=1: 0; } ;",
"while (1) switch (a) {case b: b=1; } ;",
"while (1) a == (b=1);",
"while (1) a === (b=1);",
"while (1) +(b=1);",
"while (1) ~(b=1);",
"while (1) new a(b=1);",
"while (1) (b=1).f;",
"while (1) a[b=1];",
"while (1) (b=1)();",
"while (1) [b=1];",
"while (1) [0,b=1];",
"while (1) var z = [11,b=1,12];",
"while (1) var y = {f:11,g:(b=1),h:12};",
"while (1) try {b=1;} finally {};",
"while (1) try {} finally {b=1};",
"while (1) try {b=1;} catch (e) {};",
"while (1) try {} catch (e) {b=1};",
"while (1) return b=1;",
"while (1) (b=1) ? b : b;",
"while (1) b ? (b=1) : b;",
"while (1) b ? b : (b=1);",
};
for (size_t i = 0; i < arraysize(loops); i++) {
TestHelper f(loops[i]);
f.CheckLoopAssignedCount(1, "b");
}
}
TEST(NestedLoops3) {
TestHelper f("var x, y, z, w; while (x++) while (y++) while (z++) ; w;");
f.CheckLoopAssignedCount(1, "x");
f.CheckLoopAssignedCount(2, "y");
f.CheckLoopAssignedCount(3, "z");
f.CheckLoopAssignedCount(0, "w");
}
TEST(NestedLoops3b) {
TestHelper f(
"var x, y, z, w;"
"while (1) { x=1; while (1) { y=1; while (1) z=1; } }"
"w;");
f.CheckLoopAssignedCount(1, "x");
f.CheckLoopAssignedCount(2, "y");
f.CheckLoopAssignedCount(3, "z");
f.CheckLoopAssignedCount(0, "w");
}
TEST(NestedLoops3c) {
TestHelper f(
"var x, y, z, w;"
"while (1) {"
" x++;"
" while (1) {"
" y++;"
" while (1) z++;"
" }"
" while (1) {"
" y++;"
" while (1) z++;"
" }"
"}"
"w;");
f.CheckLoopAssignedCount(1, "x");
f.CheckLoopAssignedCount(3, "y");
f.CheckLoopAssignedCount(5, "z");
f.CheckLoopAssignedCount(0, "w");
}
} // namespace compiler
} // namespace internal
} // namespace v8
......@@ -77,7 +77,6 @@ class BytecodeGraphTester {
: isolate_(isolate), script_(script) {
i::FLAG_always_opt = false;
i::FLAG_allow_natives_syntax = true;
i::FLAG_loop_assignment_analysis = false;
}
virtual ~BytecodeGraphTester() {}
......@@ -122,8 +121,6 @@ class BytecodeGraphTester {
Handle<Script> script(Script::cast(shared->script()));
CompilationInfo compilation_info(&zone, function->GetIsolate(), script,
shared, function);
compilation_info.MarkAsDeoptimizationEnabled();
compilation_info.MarkAsOptimizeFromBytecode();
Handle<Code> code = Pipeline::GenerateCodeForTesting(&compilation_info);
function->ReplaceCode(*code);
......
......@@ -34,8 +34,7 @@ class JSBuiltinReducerTest : public TypedGraphTest {
// TODO(titzer): mock the GraphReducer here for better unit testing.
GraphReducer graph_reducer(zone(), graph());
JSBuiltinReducer reducer(&graph_reducer, &jsgraph,
JSBuiltinReducer::kNoFlags, nullptr,
JSBuiltinReducer reducer(&graph_reducer, &jsgraph, nullptr,
native_context());
return reducer.Reduce(node);
}
......
......@@ -37,8 +37,7 @@ class JSIntrinsicLoweringTest : public GraphTest {
&machine);
// TODO(titzer): mock the GraphReducer here for better unit testing.
GraphReducer graph_reducer(zone(), graph());
JSIntrinsicLowering reducer(&graph_reducer, &jsgraph,
JSIntrinsicLowering::kDeoptimizationEnabled);
JSIntrinsicLowering reducer(&graph_reducer, &jsgraph);
return reducer.Reduce(node);
}
......
......@@ -58,9 +58,7 @@ class JSTypedLoweringTest : public TypedGraphTest {
&machine);
// TODO(titzer): mock the GraphReducer here for better unit testing.
GraphReducer graph_reducer(zone(), graph());
JSTypedLowering reducer(&graph_reducer, &deps_,
JSTypedLowering::kDeoptimizationEnabled, &jsgraph,
zone());
JSTypedLowering reducer(&graph_reducer, &deps_, &jsgraph, zone());
return reducer.Reduce(node);
}
......
......@@ -72,9 +72,7 @@ class TypedOptimizationTest : public TypedGraphTest {
&machine);
// TODO(titzer): mock the GraphReducer here for better unit testing.
GraphReducer graph_reducer(zone(), graph());
TypedOptimization reducer(&graph_reducer, &deps_,
TypedOptimization::kDeoptimizationEnabled,
&jsgraph);
TypedOptimization reducer(&graph_reducer, &deps_, &jsgraph);
return reducer.Reduce(node);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment