1 // Copyright 2014 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef V8_COMPILER_AST_GRAPH_BUILDER_H_ 6 #define V8_COMPILER_AST_GRAPH_BUILDER_H_ 7 8 #include "src/ast/ast.h" 9 #include "src/compiler/compiler-source-position-table.h" 10 #include "src/compiler/js-graph.h" 11 #include "src/compiler/liveness-analyzer.h" 12 #include "src/compiler/state-values-utils.h" 13 14 namespace v8 { 15 namespace internal { 16 17 // Forward declarations. 18 class BitVector; 19 class CompilationInfo; 20 21 namespace compiler { 22 23 // Forward declarations. 24 class ControlBuilder; 25 class Graph; 26 class LoopAssignmentAnalysis; 27 class LoopBuilder; 28 class Node; 29 30 31 // The AstGraphBuilder produces a high-level IR graph, based on an 32 // underlying AST. The produced graph can either be compiled into a 33 // stand-alone function or be wired into another graph for the purposes 34 // of function inlining. 35 // This AstVistor is not final, and provides the AstVisitor methods as virtual 36 // methods so they can be specialized by subclasses. 37 class AstGraphBuilder : public AstVisitor<AstGraphBuilder> { 38 public: 39 AstGraphBuilder(Zone* local_zone, CompilationInfo* info, JSGraph* jsgraph, 40 float invocation_frequency, 41 LoopAssignmentAnalysis* loop_assignment = nullptr); 42 virtual ~AstGraphBuilder() {} 43 44 // Creates a graph by visiting the entire AST. 45 bool CreateGraph(bool stack_check = true); 46 47 // Helpers to create new control nodes. 48 Node* NewIfTrue() { return NewNode(common()->IfTrue()); } 49 Node* NewIfFalse() { return NewNode(common()->IfFalse()); } 50 Node* NewMerge() { return NewNode(common()->Merge(1), true); } 51 Node* NewLoop() { return NewNode(common()->Loop(1), true); } 52 Node* NewBranch(Node* condition, BranchHint hint = BranchHint::kNone) { 53 return NewNode(common()->Branch(hint), condition); 54 } 55 56 protected: 57 #define DECLARE_VISIT(type) virtual void Visit##type(type* node); 58 // Visiting functions for AST nodes make this an AstVisitor. 59 AST_NODE_LIST(DECLARE_VISIT) 60 #undef DECLARE_VISIT 61 62 // Visiting function for declarations list is overridden. 63 void VisitDeclarations(Declaration::List* declarations); 64 65 private: 66 class AstContext; 67 class AstEffectContext; 68 class AstValueContext; 69 class AstTestContext; 70 class ContextScope; 71 class ControlScope; 72 class ControlScopeForBreakable; 73 class ControlScopeForIteration; 74 class Environment; 75 friend class ControlBuilder; 76 77 Isolate* isolate_; 78 Zone* local_zone_; 79 CompilationInfo* info_; 80 JSGraph* jsgraph_; 81 float const invocation_frequency_; 82 Environment* environment_; 83 AstContext* ast_context_; 84 85 // List of global declarations for functions and variables. 86 ZoneVector<Handle<Object>> globals_; 87 88 // Stack of control scopes currently entered by the visitor. 89 ControlScope* execution_control_; 90 91 // Stack of context objects pushed onto the chain by the visitor. 92 ContextScope* execution_context_; 93 94 // Nodes representing values in the activation record. 95 SetOncePointer<Node> function_closure_; 96 SetOncePointer<Node> function_context_; 97 98 // Temporary storage for building node input lists. 99 int input_buffer_size_; 100 Node** input_buffer_; 101 102 // Optimization to cache loaded feedback vector. 103 SetOncePointer<Node> feedback_vector_; 104 105 // Optimization to cache empty frame state. 106 SetOncePointer<Node> empty_frame_state_; 107 108 // Control nodes that exit the function body. 109 ZoneVector<Node*> exit_controls_; 110 111 // Result of loop assignment analysis performed before graph creation. 112 LoopAssignmentAnalysis* loop_assignment_analysis_; 113 114 // Cache for StateValues nodes for frame states. 115 StateValuesCache state_values_cache_; 116 117 // Analyzer of local variable liveness. 118 LivenessAnalyzer liveness_analyzer_; 119 120 // Function info for frame state construction. 121 const FrameStateFunctionInfo* const frame_state_function_info_; 122 123 // Growth increment for the temporary buffer used to construct input lists to 124 // new nodes. 125 static const int kInputBufferSizeIncrement = 64; 126 127 Zone* local_zone() const { return local_zone_; } 128 Environment* environment() const { return environment_; } 129 AstContext* ast_context() const { return ast_context_; } 130 ControlScope* execution_control() const { return execution_control_; } 131 ContextScope* execution_context() const { return execution_context_; } 132 CommonOperatorBuilder* common() const { return jsgraph_->common(); } 133 CompilationInfo* info() const { return info_; } 134 Isolate* isolate() const { return isolate_; } 135 LanguageMode language_mode() const; 136 JSGraph* jsgraph() { return jsgraph_; } 137 Graph* graph() { return jsgraph_->graph(); } 138 Zone* graph_zone() { return graph()->zone(); } 139 JSOperatorBuilder* javascript() { return jsgraph_->javascript(); } 140 ZoneVector<Handle<Object>>* globals() { return &globals_; } 141 Scope* current_scope() const; 142 Node* current_context() const; 143 LivenessAnalyzer* liveness_analyzer() { return &liveness_analyzer_; } 144 const FrameStateFunctionInfo* frame_state_function_info() const { 145 return frame_state_function_info_; 146 } 147 148 void set_environment(Environment* env) { environment_ = env; } 149 void set_ast_context(AstContext* ctx) { ast_context_ = ctx; } 150 void set_execution_control(ControlScope* ctrl) { execution_control_ = ctrl; } 151 void set_execution_context(ContextScope* ctx) { execution_context_ = ctx; } 152 153 // Create the main graph body by visiting the AST. 154 void CreateGraphBody(bool stack_check); 155 156 // Get or create the node that represents the incoming function closure. 157 Node* GetFunctionClosureForContext(); 158 Node* GetFunctionClosure(); 159 160 // Get or create the node that represents the incoming function context. 161 Node* GetFunctionContext(); 162 163 // Get or create the node that represents the empty frame state. 164 Node* GetEmptyFrameState(); 165 166 // Node creation helpers. 167 Node* NewNode(const Operator* op, bool incomplete = false) { 168 return MakeNode(op, 0, static_cast<Node**>(nullptr), incomplete); 169 } 170 171 Node* NewNode(const Operator* op, Node* n1) { 172 return MakeNode(op, 1, &n1, false); 173 } 174 175 Node* NewNode(const Operator* op, Node* n1, Node* n2) { 176 Node* buffer[] = {n1, n2}; 177 return MakeNode(op, arraysize(buffer), buffer, false); 178 } 179 180 Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3) { 181 Node* buffer[] = {n1, n2, n3}; 182 return MakeNode(op, arraysize(buffer), buffer, false); 183 } 184 185 Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4) { 186 Node* buffer[] = {n1, n2, n3, n4}; 187 return MakeNode(op, arraysize(buffer), buffer, false); 188 } 189 190 Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4, 191 Node* n5) { 192 Node* buffer[] = {n1, n2, n3, n4, n5}; 193 return MakeNode(op, arraysize(buffer), buffer, false); 194 } 195 196 Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4, 197 Node* n5, Node* n6) { 198 Node* nodes[] = {n1, n2, n3, n4, n5, n6}; 199 return MakeNode(op, arraysize(nodes), nodes, false); 200 } 201 202 Node* NewNode(const Operator* op, int value_input_count, Node** value_inputs, 203 bool incomplete = false) { 204 return MakeNode(op, value_input_count, value_inputs, incomplete); 205 } 206 207 // Creates a new Phi node having {count} input values. 208 Node* NewPhi(int count, Node* input, Node* control); 209 Node* NewEffectPhi(int count, Node* input, Node* control); 210 211 // Helpers for merging control, effect or value dependencies. 212 Node* MergeControl(Node* control, Node* other); 213 Node* MergeEffect(Node* value, Node* other, Node* control); 214 Node* MergeValue(Node* value, Node* other, Node* control); 215 216 // The main node creation chokepoint. Adds context, frame state, effect, 217 // and control dependencies depending on the operator. 218 Node* MakeNode(const Operator* op, int value_input_count, Node** value_inputs, 219 bool incomplete); 220 221 // Helper to indicate a node exits the function body. 222 void UpdateControlDependencyToLeaveFunction(Node* exit); 223 224 // Prepare information for lazy deoptimization. This information is attached 225 // to the given node and the output value produced by the node is combined. 226 // Conceptually this frame state is "after" a given operation. 227 void PrepareFrameState(Node* node, BailoutId ast_id, 228 OutputFrameStateCombine framestate_combine = 229 OutputFrameStateCombine::Ignore()); 230 231 // Prepare information for eager deoptimization. This information is carried 232 // by dedicated {Checkpoint} nodes that are wired into the effect chain. 233 // Conceptually this frame state is "before" a given operation. 234 void PrepareEagerCheckpoint(BailoutId ast_id); 235 236 BitVector* GetVariablesAssignedInLoop(IterationStatement* stmt); 237 238 // Check if the given statement is an OSR entry. 239 // If so, record the stack height into the compilation and return {true}. 240 bool CheckOsrEntry(IterationStatement* stmt); 241 242 // Computes local variable liveness and replaces dead variables in 243 // frame states with the undefined values. 244 void ClearNonLiveSlotsInFrameStates(); 245 246 Node** EnsureInputBufferSize(int size); 247 248 // Named and keyed loads require a VectorSlotPair for successful lowering. 249 VectorSlotPair CreateVectorSlotPair(FeedbackSlot slot) const; 250 251 // Computes the frequency for JSCall and JSConstruct nodes. 252 float ComputeCallFrequency(FeedbackSlot slot) const; 253 254 // =========================================================================== 255 // The following build methods all generate graph fragments and return one 256 // resulting node. The operand stack height remains the same, variables and 257 // other dependencies tracked by the environment might be mutated though. 258 259 // Builders to create local function, script and block contexts. 260 Node* BuildLocalActivationContext(Node* context); 261 Node* BuildLocalFunctionContext(Scope* scope); 262 Node* BuildLocalScriptContext(Scope* scope); 263 Node* BuildLocalBlockContext(Scope* scope); 264 265 // Builder to create an arguments object if it is used. 266 Node* BuildArgumentsObject(Variable* arguments); 267 268 // Builders for variable load and assignment. 269 Node* BuildVariableAssignment(Variable* variable, Node* value, 270 Token::Value op, const VectorSlotPair& slot, 271 BailoutId bailout_id, 272 OutputFrameStateCombine framestate_combine = 273 OutputFrameStateCombine::Ignore()); 274 Node* BuildVariableDelete(Variable* variable, BailoutId bailout_id, 275 OutputFrameStateCombine framestate_combine); 276 Node* BuildVariableLoad(Variable* variable, BailoutId bailout_id, 277 const VectorSlotPair& feedback, 278 OutputFrameStateCombine framestate_combine, 279 TypeofMode typeof_mode = NOT_INSIDE_TYPEOF); 280 281 // Builders for property loads and stores. 282 Node* BuildKeyedLoad(Node* receiver, Node* key, 283 const VectorSlotPair& feedback); 284 Node* BuildNamedLoad(Node* receiver, Handle<Name> name, 285 const VectorSlotPair& feedback); 286 Node* BuildKeyedStore(Node* receiver, Node* key, Node* value, 287 const VectorSlotPair& feedback); 288 Node* BuildNamedStore(Node* receiver, Handle<Name> name, Node* value, 289 const VectorSlotPair& feedback); 290 Node* BuildNamedStoreOwn(Node* receiver, Handle<Name> name, Node* value, 291 const VectorSlotPair& feedback); 292 293 // Builders for global variable loads and stores. 294 Node* BuildGlobalLoad(Handle<Name> name, const VectorSlotPair& feedback, 295 TypeofMode typeof_mode); 296 Node* BuildGlobalStore(Handle<Name> name, Node* value, 297 const VectorSlotPair& feedback); 298 299 // Builders for accessing the function context. 300 Node* BuildLoadGlobalObject(); 301 Node* BuildLoadNativeContextField(int index); 302 303 // Builders for automatic type conversion. 304 Node* BuildToBoolean(Node* input, TypeFeedbackId feedback_id); 305 Node* BuildToObject(Node* input, BailoutId bailout_id); 306 307 // Builder for adding the [[HomeObject]] to a value if the value came from a 308 // function literal and needs a home object. Do nothing otherwise. 309 Node* BuildSetHomeObject(Node* value, Node* home_object, 310 LiteralProperty* property, int slot_number = 0); 311 312 // Builders for error reporting at runtime. 313 Node* BuildThrowError(Node* exception, BailoutId bailout_id); 314 Node* BuildThrowReferenceError(Variable* var, BailoutId bailout_id); 315 Node* BuildThrowConstAssignError(BailoutId bailout_id); 316 317 // Builders for dynamic hole-checks at runtime. 318 Node* BuildHoleCheckThenThrow(Node* value, Variable* var, Node* not_hole, 319 BailoutId bailout_id); 320 Node* BuildHoleCheckElseThrow(Node* value, Variable* var, Node* for_hole, 321 BailoutId bailout_id); 322 323 // Builders for non-local control flow. 324 Node* BuildReturn(Node* return_value); 325 Node* BuildThrow(Node* exception_value); 326 327 // Builders for binary operations. 328 Node* BuildBinaryOp(Node* left, Node* right, Token::Value op, 329 TypeFeedbackId feedback_id); 330 331 // Process arguments to a call by popping {arity} elements off the operand 332 // stack and build a call node using the given call operator. 333 Node* ProcessArguments(const Operator* op, int arity); 334 335 // =========================================================================== 336 // The following build methods have the same contract as the above ones, but 337 // they can also return {nullptr} to indicate that no fragment was built. Note 338 // that these are optimizations, disabling any of them should still produce 339 // correct graphs. 340 341 // Optimization for variable load from global object. 342 Node* TryLoadGlobalConstant(Handle<Name> name); 343 344 // Optimizations for automatic type conversion. 345 Node* TryFastToBoolean(Node* input); 346 347 // =========================================================================== 348 // The following visitation methods all recursively visit a subtree of the 349 // underlying AST and extent the graph. The operand stack is mutated in a way 350 // consistent with other compilers: 351 // - Expressions pop operands and push result, depending on {AstContext}. 352 // - Statements keep the operand stack balanced. 353 354 // Visit statements. 355 void VisitIfNotNull(Statement* stmt); 356 357 // Visit expressions. 358 void Visit(Expression* expr); 359 void VisitForTest(Expression* expr); 360 void VisitForEffect(Expression* expr); 361 void VisitForValue(Expression* expr); 362 void VisitForValueOrNull(Expression* expr); 363 void VisitForValueOrTheHole(Expression* expr); 364 void VisitForValues(ZoneList<Expression*>* exprs); 365 366 // Common for all IterationStatement bodies. 367 void VisitIterationBody(IterationStatement* stmt, LoopBuilder* loop, 368 BailoutId stack_check_id); 369 370 // Dispatched from VisitCall. 371 void VisitCallSuper(Call* expr); 372 373 // Dispatched from VisitCallRuntime. 374 void VisitCallJSRuntime(CallRuntime* expr); 375 376 // Dispatched from VisitUnaryOperation. 377 void VisitDelete(UnaryOperation* expr); 378 void VisitVoid(UnaryOperation* expr); 379 void VisitTypeof(UnaryOperation* expr); 380 void VisitNot(UnaryOperation* expr); 381 382 // Dispatched from VisitTypeof, VisitLiteralCompareTypeof. 383 void VisitTypeofExpression(Expression* expr); 384 385 // Dispatched from VisitBinaryOperation. 386 void VisitComma(BinaryOperation* expr); 387 void VisitLogicalExpression(BinaryOperation* expr); 388 void VisitArithmeticExpression(BinaryOperation* expr); 389 390 // Dispatched from VisitCompareOperation. 391 void VisitLiteralCompareNil(CompareOperation* expr, Expression* sub_expr, 392 Node* nil_value); 393 void VisitLiteralCompareTypeof(CompareOperation* expr, Expression* sub_expr, 394 Handle<String> check); 395 396 // Dispatched from VisitObjectLiteral. 397 void VisitObjectLiteralAccessor(Node* home_object, 398 ObjectLiteralProperty* property); 399 400 DEFINE_AST_VISITOR_SUBCLASS_MEMBERS(); 401 DISALLOW_COPY_AND_ASSIGN(AstGraphBuilder); 402 }; 403 404 405 // The abstract execution environment for generated code consists of 406 // parameter variables, local variables and the operand stack. The 407 // environment will perform proper SSA-renaming of all tracked nodes 408 // at split and merge points in the control flow. Internally all the 409 // values are stored in one list using the following layout: 410 // 411 // [parameters (+receiver)] [locals] [operand stack] 412 // 413 class AstGraphBuilder::Environment : public ZoneObject { 414 public: 415 Environment(AstGraphBuilder* builder, DeclarationScope* scope, 416 Node* control_dependency); 417 418 int parameters_count() const { return parameters_count_; } 419 int locals_count() const { return locals_count_; } 420 int context_chain_length() { return static_cast<int>(contexts_.size()); } 421 int stack_height() { 422 return static_cast<int>(values()->size()) - parameters_count_ - 423 locals_count_; 424 } 425 426 // Operations on parameter or local variables. 427 void Bind(Variable* variable, Node* node); 428 Node* Lookup(Variable* variable); 429 void MarkAllLocalsLive(); 430 431 // Raw operations on parameter variables. 432 void RawParameterBind(int index, Node* node); 433 Node* RawParameterLookup(int index); 434 435 // Operations on the context chain. 436 Node* Context() const { return contexts_.back(); } 437 void PushContext(Node* context) { contexts()->push_back(context); } 438 void PopContext() { contexts()->pop_back(); } 439 void TrimContextChain(int trim_to_length) { 440 contexts()->resize(trim_to_length); 441 } 442 443 // Operations on the operand stack. 444 void Push(Node* node) { 445 values()->push_back(node); 446 } 447 Node* Top() { 448 DCHECK(stack_height() > 0); 449 return values()->back(); 450 } 451 Node* Pop() { 452 DCHECK(stack_height() > 0); 453 Node* back = values()->back(); 454 values()->pop_back(); 455 return back; 456 } 457 458 // Direct mutations of the operand stack. 459 void Poke(int depth, Node* node) { 460 DCHECK(depth >= 0 && depth < stack_height()); 461 int index = static_cast<int>(values()->size()) - depth - 1; 462 values()->at(index) = node; 463 } 464 Node* Peek(int depth) { 465 DCHECK(depth >= 0 && depth < stack_height()); 466 int index = static_cast<int>(values()->size()) - depth - 1; 467 return values()->at(index); 468 } 469 void Drop(int depth) { 470 DCHECK(depth >= 0 && depth <= stack_height()); 471 values()->erase(values()->end() - depth, values()->end()); 472 } 473 void TrimStack(int trim_to_height) { 474 int depth = stack_height() - trim_to_height; 475 DCHECK(depth >= 0 && depth <= stack_height()); 476 values()->erase(values()->end() - depth, values()->end()); 477 } 478 479 // Preserve a checkpoint of the environment for the IR graph. Any 480 // further mutation of the environment will not affect checkpoints. 481 Node* Checkpoint(BailoutId ast_id, OutputFrameStateCombine combine = 482 OutputFrameStateCombine::Ignore(), 483 bool node_has_exception = false); 484 485 // Inserts a loop exit control node and renames the environment. 486 // This is useful for loop peeling to insert phis at loop exits. 487 void PrepareForLoopExit(Node* loop, BitVector* assigned_variables); 488 489 // Control dependency tracked by this environment. 490 Node* GetControlDependency() { return control_dependency_; } 491 void UpdateControlDependency(Node* dependency) { 492 control_dependency_ = dependency; 493 } 494 495 // Effect dependency tracked by this environment. 496 Node* GetEffectDependency() { return effect_dependency_; } 497 void UpdateEffectDependency(Node* dependency) { 498 effect_dependency_ = dependency; 499 } 500 501 // Mark this environment as being unreachable. 502 void MarkAsUnreachable() { 503 UpdateControlDependency(builder()->jsgraph()->Dead()); 504 liveness_block_ = nullptr; 505 } 506 bool IsMarkedAsUnreachable() { 507 return GetControlDependency()->opcode() == IrOpcode::kDead; 508 } 509 510 // Merge another environment into this one. 511 void Merge(Environment* other); 512 513 // Copies this environment at a control-flow split point. 514 Environment* CopyForConditional(); 515 516 // Copies this environment to a potentially unreachable control-flow point. 517 Environment* CopyAsUnreachable(); 518 519 // Copies this environment at a loop header control-flow point. 520 Environment* CopyForLoop(BitVector* assigned, bool is_osr = false); 521 522 // Copies this environment for Osr entry. This only produces environment 523 // of the right shape, the caller is responsible for filling in the right 524 // values and dependencies. 525 Environment* CopyForOsrEntry(); 526 527 private: 528 AstGraphBuilder* builder_; 529 int parameters_count_; 530 int locals_count_; 531 LivenessAnalyzerBlock* liveness_block_; 532 NodeVector values_; 533 NodeVector contexts_; 534 Node* control_dependency_; 535 Node* effect_dependency_; 536 Node* parameters_node_; 537 Node* locals_node_; 538 Node* stack_node_; 539 540 explicit Environment(Environment* copy, 541 LivenessAnalyzerBlock* liveness_block); 542 Environment* CopyAndShareLiveness(); 543 void UpdateStateValues(Node** state_values, int offset, int count); 544 Zone* zone() const { return builder_->local_zone(); } 545 Graph* graph() const { return builder_->graph(); } 546 AstGraphBuilder* builder() const { return builder_; } 547 CommonOperatorBuilder* common() { return builder_->common(); } 548 NodeVector* values() { return &values_; } 549 NodeVector* contexts() { return &contexts_; } 550 LivenessAnalyzerBlock* liveness_block() { return liveness_block_; } 551 bool IsLivenessAnalysisEnabled(); 552 bool IsLivenessBlockConsistent(); 553 554 // Prepare environment to be used as loop header. 555 void PrepareForLoop(BitVector* assigned); 556 void PrepareForOsrEntry(); 557 }; 558 559 class AstGraphBuilderWithPositions final : public AstGraphBuilder { 560 public: 561 AstGraphBuilderWithPositions(Zone* local_zone, CompilationInfo* info, 562 JSGraph* jsgraph, float invocation_frequency, 563 LoopAssignmentAnalysis* loop_assignment, 564 SourcePositionTable* source_positions, 565 int inlining_id = SourcePosition::kNotInlined); 566 567 bool CreateGraph(bool stack_check = true) { 568 SourcePositionTable::Scope pos_scope(source_positions_, start_position_); 569 return AstGraphBuilder::CreateGraph(stack_check); 570 } 571 572 #define DEF_VISIT(type) \ 573 void Visit##type(type* node) override { \ 574 SourcePositionTable::Scope pos( \ 575 source_positions_, \ 576 SourcePosition(node->position(), start_position_.InliningId())); \ 577 AstGraphBuilder::Visit##type(node); \ 578 } 579 AST_NODE_LIST(DEF_VISIT) 580 #undef DEF_VISIT 581 582 private: 583 SourcePositionTable* const source_positions_; 584 SourcePosition const start_position_; 585 }; 586 587 } // namespace compiler 588 } // namespace internal 589 } // namespace v8 590 591 #endif // V8_COMPILER_AST_GRAPH_BUILDER_H_ 592