1 // Copyright 2012 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.
10 #include "src/accessors.h"
11 #include "src/allocation.h"
13 #include "src/bailout-reason.h"
14 #include "src/compiler.h"
15 #include "src/hydrogen-instructions.h"
16 #include "src/scopes.h"
22 // Forward declarations.
27 class HLoopInformation;
35 class HBasicBlock FINAL : public ZoneObject {
37 explicit HBasicBlock(HGraph* graph);
41 int block_id() const { return block_id_; }
42 void set_block_id(int id) { block_id_ = id; }
43 HGraph* graph() const { return graph_; }
44 Isolate* isolate() const;
45 const ZoneList<HPhi*>* phis() const { return &phis_; }
46 HInstruction* first() const { return first_; }
47 HInstruction* last() const { return last_; }
48 void set_last(HInstruction* instr) { last_ = instr; }
49 HControlInstruction* end() const { return end_; }
50 HLoopInformation* loop_information() const { return loop_information_; }
51 HLoopInformation* current_loop() const {
52 return IsLoopHeader() ? loop_information()
53 : (parent_loop_header() != NULL
54 ? parent_loop_header()->loop_information() : NULL);
56 const ZoneList<HBasicBlock*>* predecessors() const { return &predecessors_; }
57 bool HasPredecessor() const { return predecessors_.length() > 0; }
58 const ZoneList<HBasicBlock*>* dominated_blocks() const {
59 return &dominated_blocks_;
61 const ZoneList<int>* deleted_phis() const {
62 return &deleted_phis_;
64 void RecordDeletedPhi(int merge_index) {
65 deleted_phis_.Add(merge_index, zone());
67 HBasicBlock* dominator() const { return dominator_; }
68 HEnvironment* last_environment() const { return last_environment_; }
69 int argument_count() const { return argument_count_; }
70 void set_argument_count(int count) { argument_count_ = count; }
71 int first_instruction_index() const { return first_instruction_index_; }
72 void set_first_instruction_index(int index) {
73 first_instruction_index_ = index;
75 int last_instruction_index() const { return last_instruction_index_; }
76 void set_last_instruction_index(int index) {
77 last_instruction_index_ = index;
79 bool is_osr_entry() { return is_osr_entry_; }
80 void set_osr_entry() { is_osr_entry_ = true; }
82 void AttachLoopInformation();
83 void DetachLoopInformation();
84 bool IsLoopHeader() const { return loop_information() != NULL; }
85 bool IsStartBlock() const { return block_id() == 0; }
86 void PostProcessLoopHeader(IterationStatement* stmt);
88 bool IsFinished() const { return end_ != NULL; }
89 void AddPhi(HPhi* phi);
90 void RemovePhi(HPhi* phi);
91 void AddInstruction(HInstruction* instr, HSourcePosition position);
92 bool Dominates(HBasicBlock* other) const;
93 bool EqualToOrDominates(HBasicBlock* other) const;
94 int LoopNestingDepth() const;
96 void SetInitialEnvironment(HEnvironment* env);
97 void ClearEnvironment() {
99 DCHECK(end()->SuccessorCount() == 0);
100 last_environment_ = NULL;
102 bool HasEnvironment() const { return last_environment_ != NULL; }
103 void UpdateEnvironment(HEnvironment* env);
104 HBasicBlock* parent_loop_header() const { return parent_loop_header_; }
106 void set_parent_loop_header(HBasicBlock* block) {
107 DCHECK(parent_loop_header_ == NULL);
108 parent_loop_header_ = block;
111 bool HasParentLoopHeader() const { return parent_loop_header_ != NULL; }
113 void SetJoinId(BailoutId ast_id);
115 int PredecessorIndexOf(HBasicBlock* predecessor) const;
116 HPhi* AddNewPhi(int merged_index);
117 HSimulate* AddNewSimulate(BailoutId ast_id,
118 HSourcePosition position,
119 RemovableSimulate removable = FIXED_SIMULATE) {
120 HSimulate* instr = CreateSimulate(ast_id, removable);
121 AddInstruction(instr, position);
124 void AssignCommonDominator(HBasicBlock* other);
125 void AssignLoopSuccessorDominators();
127 // If a target block is tagged as an inline function return, all
128 // predecessors should contain the inlined exit sequence:
131 // Simulate (caller's environment)
132 // Goto (target block)
133 bool IsInlineReturnTarget() const { return is_inline_return_target_; }
134 void MarkAsInlineReturnTarget(HBasicBlock* inlined_entry_block) {
135 is_inline_return_target_ = true;
136 inlined_entry_block_ = inlined_entry_block;
138 HBasicBlock* inlined_entry_block() { return inlined_entry_block_; }
140 bool IsDeoptimizing() const {
141 return end() != NULL && end()->IsDeoptimize();
144 void MarkUnreachable();
145 bool IsUnreachable() const { return !is_reachable_; }
146 bool IsReachable() const { return is_reachable_; }
148 bool IsLoopSuccessorDominator() const {
149 return dominates_loop_successors_;
151 void MarkAsLoopSuccessorDominator() {
152 dominates_loop_successors_ = true;
155 bool IsOrdered() const { return is_ordered_; }
156 void MarkAsOrdered() { is_ordered_ = true; }
158 void MarkSuccEdgeUnreachable(int succ);
160 inline Zone* zone() const;
167 friend class HGraphBuilder;
169 HSimulate* CreateSimulate(BailoutId ast_id, RemovableSimulate removable);
170 void Finish(HControlInstruction* last, HSourcePosition position);
171 void FinishExit(HControlInstruction* instruction, HSourcePosition position);
172 void Goto(HBasicBlock* block,
173 HSourcePosition position,
174 FunctionState* state = NULL,
175 bool add_simulate = true);
176 void GotoNoSimulate(HBasicBlock* block, HSourcePosition position) {
177 Goto(block, position, NULL, false);
180 // Add the inlined function exit sequence, adding an HLeaveInlined
181 // instruction and updating the bailout environment.
182 void AddLeaveInlined(HValue* return_value,
183 FunctionState* state,
184 HSourcePosition position);
187 void RegisterPredecessor(HBasicBlock* pred);
188 void AddDominatedBlock(HBasicBlock* block);
192 ZoneList<HPhi*> phis_;
193 HInstruction* first_;
195 HControlInstruction* end_;
196 HLoopInformation* loop_information_;
197 ZoneList<HBasicBlock*> predecessors_;
198 HBasicBlock* dominator_;
199 ZoneList<HBasicBlock*> dominated_blocks_;
200 HEnvironment* last_environment_;
201 // Outgoing parameter count at block exit, set during lithium translation.
203 // Instruction indices into the lithium code stream.
204 int first_instruction_index_;
205 int last_instruction_index_;
206 ZoneList<int> deleted_phis_;
207 HBasicBlock* parent_loop_header_;
208 // For blocks marked as inline return target: the block with HEnterInlined.
209 HBasicBlock* inlined_entry_block_;
210 bool is_inline_return_target_ : 1;
211 bool is_reachable_ : 1;
212 bool dominates_loop_successors_ : 1;
213 bool is_osr_entry_ : 1;
214 bool is_ordered_ : 1;
218 OStream& operator<<(OStream& os, const HBasicBlock& b);
221 class HPredecessorIterator FINAL BASE_EMBEDDED {
223 explicit HPredecessorIterator(HBasicBlock* block)
224 : predecessor_list_(block->predecessors()), current_(0) { }
226 bool Done() { return current_ >= predecessor_list_->length(); }
227 HBasicBlock* Current() { return predecessor_list_->at(current_); }
228 void Advance() { current_++; }
231 const ZoneList<HBasicBlock*>* predecessor_list_;
236 class HInstructionIterator FINAL BASE_EMBEDDED {
238 explicit HInstructionIterator(HBasicBlock* block)
239 : instr_(block->first()) {
240 next_ = Done() ? NULL : instr_->next();
243 inline bool Done() const { return instr_ == NULL; }
244 inline HInstruction* Current() { return instr_; }
245 inline void Advance() {
247 next_ = Done() ? NULL : instr_->next();
251 HInstruction* instr_;
256 class HLoopInformation FINAL : public ZoneObject {
258 HLoopInformation(HBasicBlock* loop_header, Zone* zone)
259 : back_edges_(4, zone),
260 loop_header_(loop_header),
263 blocks_.Add(loop_header, zone);
265 ~HLoopInformation() {}
267 const ZoneList<HBasicBlock*>* back_edges() const { return &back_edges_; }
268 const ZoneList<HBasicBlock*>* blocks() const { return &blocks_; }
269 HBasicBlock* loop_header() const { return loop_header_; }
270 HBasicBlock* GetLastBackEdge() const;
271 void RegisterBackEdge(HBasicBlock* block);
273 HStackCheck* stack_check() const { return stack_check_; }
274 void set_stack_check(HStackCheck* stack_check) {
275 stack_check_ = stack_check;
278 bool IsNestedInThisLoop(HLoopInformation* other) {
279 while (other != NULL) {
283 other = other->parent_loop();
287 HLoopInformation* parent_loop() {
288 HBasicBlock* parent_header = loop_header()->parent_loop_header();
289 return parent_header != NULL ? parent_header->loop_information() : NULL;
293 void AddBlock(HBasicBlock* block);
295 ZoneList<HBasicBlock*> back_edges_;
296 HBasicBlock* loop_header_;
297 ZoneList<HBasicBlock*> blocks_;
298 HStackCheck* stack_check_;
302 class BoundsCheckTable;
303 class InductionVariableBlocksTable;
304 class HGraph FINAL : public ZoneObject {
306 explicit HGraph(CompilationInfo* info);
308 Isolate* isolate() const { return isolate_; }
309 Zone* zone() const { return zone_; }
310 CompilationInfo* info() const { return info_; }
312 const ZoneList<HBasicBlock*>* blocks() const { return &blocks_; }
313 const ZoneList<HPhi*>* phi_list() const { return phi_list_; }
314 HBasicBlock* entry_block() const { return entry_block_; }
315 HEnvironment* start_environment() const { return start_environment_; }
317 void FinalizeUniqueness();
318 bool ProcessArgumentsObject();
320 void AssignDominators();
321 void RestoreActualValues();
323 // Returns false if there are phi-uses of the arguments-object
324 // which are not supported by the optimizing compiler.
325 bool CheckArgumentsPhiUses();
327 // Returns false if there are phi-uses of an uninitialized const
328 // which are not supported by the optimizing compiler.
329 bool CheckConstPhiUses();
333 HConstant* GetConstantUndefined();
334 HConstant* GetConstant0();
335 HConstant* GetConstant1();
336 HConstant* GetConstantMinus1();
337 HConstant* GetConstantTrue();
338 HConstant* GetConstantFalse();
339 HConstant* GetConstantHole();
340 HConstant* GetConstantNull();
341 HConstant* GetInvalidContext();
343 bool IsConstantUndefined(HConstant* constant);
344 bool IsConstant0(HConstant* constant);
345 bool IsConstant1(HConstant* constant);
346 bool IsConstantMinus1(HConstant* constant);
347 bool IsConstantTrue(HConstant* constant);
348 bool IsConstantFalse(HConstant* constant);
349 bool IsConstantHole(HConstant* constant);
350 bool IsConstantNull(HConstant* constant);
351 bool IsStandardConstant(HConstant* constant);
353 HBasicBlock* CreateBasicBlock();
354 HArgumentsObject* GetArgumentsObject() const {
355 return arguments_object_.get();
358 void SetArgumentsObject(HArgumentsObject* object) {
359 arguments_object_.set(object);
362 int GetMaximumValueID() const { return values_.length(); }
363 int GetNextBlockID() { return next_block_id_++; }
364 int GetNextValueID(HValue* value) {
365 DCHECK(!disallow_adding_new_values_);
366 values_.Add(value, zone());
367 return values_.length() - 1;
369 HValue* LookupValue(int id) const {
370 if (id >= 0 && id < values_.length()) return values_[id];
373 void DisallowAddingNewValues() {
374 disallow_adding_new_values_ = true;
377 bool Optimize(BailoutReason* bailout_reason);
380 void Verify(bool do_full_verify) const;
387 void set_osr(HOsrBuilder* osr) {
395 int update_type_change_checksum(int delta) {
396 type_change_checksum_ += delta;
397 return type_change_checksum_;
400 void update_maximum_environment_size(int environment_size) {
401 if (environment_size > maximum_environment_size_) {
402 maximum_environment_size_ = environment_size;
405 int maximum_environment_size() { return maximum_environment_size_; }
407 bool use_optimistic_licm() {
408 return use_optimistic_licm_;
411 void set_use_optimistic_licm(bool value) {
412 use_optimistic_licm_ = value;
415 void MarkRecursive() {
416 is_recursive_ = true;
419 bool is_recursive() const {
420 return is_recursive_;
423 void MarkDependsOnEmptyArrayProtoElements() {
424 // Add map dependency if not already added.
425 if (depends_on_empty_array_proto_elements_) return;
426 Map::AddDependentCompilationInfo(
427 handle(isolate()->initial_object_prototype()->map()),
428 DependentCode::kElementsCantBeAddedGroup, info());
429 Map::AddDependentCompilationInfo(
430 handle(isolate()->initial_array_prototype()->map()),
431 DependentCode::kElementsCantBeAddedGroup, info());
432 depends_on_empty_array_proto_elements_ = true;
435 bool depends_on_empty_array_proto_elements() {
436 return depends_on_empty_array_proto_elements_;
439 bool has_uint32_instructions() {
440 DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
441 return uint32_instructions_ != NULL;
444 ZoneList<HInstruction*>* uint32_instructions() {
445 DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
446 return uint32_instructions_;
449 void RecordUint32Instruction(HInstruction* instr) {
450 DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
451 if (uint32_instructions_ == NULL) {
452 uint32_instructions_ = new(zone()) ZoneList<HInstruction*>(4, zone());
454 uint32_instructions_->Add(instr, zone());
457 void IncrementInNoSideEffectsScope() { no_side_effects_scope_count_++; }
458 void DecrementInNoSideEffectsScope() { no_side_effects_scope_count_--; }
459 bool IsInsideNoSideEffectsScope() { return no_side_effects_scope_count_ > 0; }
461 // If we are tracking source positions then this function assigns a unique
462 // identifier to each inlining and dumps function source if it was inlined
463 // for the first time during the current optimization.
464 int TraceInlinedFunction(Handle<SharedFunctionInfo> shared,
465 HSourcePosition position);
467 // Converts given HSourcePosition to the absolute offset from the start of
468 // the corresponding script.
469 int SourcePositionToScriptPosition(HSourcePosition position);
472 HConstant* ReinsertConstantIfNecessary(HConstant* constant);
473 HConstant* GetConstant(SetOncePointer<HConstant>* pointer,
474 int32_t integer_value);
476 template<class Phase>
482 void EliminateRedundantBoundsChecksUsingInductionVariables();
486 HBasicBlock* entry_block_;
487 HEnvironment* start_environment_;
488 ZoneList<HBasicBlock*> blocks_;
489 ZoneList<HValue*> values_;
490 ZoneList<HPhi*>* phi_list_;
491 ZoneList<HInstruction*>* uint32_instructions_;
492 SetOncePointer<HConstant> constant_undefined_;
493 SetOncePointer<HConstant> constant_0_;
494 SetOncePointer<HConstant> constant_1_;
495 SetOncePointer<HConstant> constant_minus1_;
496 SetOncePointer<HConstant> constant_true_;
497 SetOncePointer<HConstant> constant_false_;
498 SetOncePointer<HConstant> constant_the_hole_;
499 SetOncePointer<HConstant> constant_null_;
500 SetOncePointer<HConstant> constant_invalid_context_;
501 SetOncePointer<HArgumentsObject> arguments_object_;
505 CompilationInfo* info_;
509 bool use_optimistic_licm_;
510 bool depends_on_empty_array_proto_elements_;
511 int type_change_checksum_;
512 int maximum_environment_size_;
513 int no_side_effects_scope_count_;
514 bool disallow_adding_new_values_;
516 class InlinedFunctionInfo {
518 explicit InlinedFunctionInfo(Handle<SharedFunctionInfo> shared)
519 : shared_(shared), start_position_(shared->start_position()) {
522 Handle<SharedFunctionInfo> shared() const { return shared_; }
523 int start_position() const { return start_position_; }
526 Handle<SharedFunctionInfo> shared_;
531 ZoneList<InlinedFunctionInfo> inlined_functions_;
533 DISALLOW_COPY_AND_ASSIGN(HGraph);
537 Zone* HBasicBlock::zone() const { return graph_->zone(); }
540 // Type of stack frame an environment might refer to.
551 class HEnvironment FINAL : public ZoneObject {
553 HEnvironment(HEnvironment* outer,
555 Handle<JSFunction> closure,
558 HEnvironment(Zone* zone, int parameter_count);
560 HEnvironment* arguments_environment() {
561 return outer()->frame_type() == ARGUMENTS_ADAPTOR ? outer() : this;
565 Handle<JSFunction> closure() const { return closure_; }
566 const ZoneList<HValue*>* values() const { return &values_; }
567 const GrowableBitVector* assigned_variables() const {
568 return &assigned_variables_;
570 FrameType frame_type() const { return frame_type_; }
571 int parameter_count() const { return parameter_count_; }
572 int specials_count() const { return specials_count_; }
573 int local_count() const { return local_count_; }
574 HEnvironment* outer() const { return outer_; }
575 int pop_count() const { return pop_count_; }
576 int push_count() const { return push_count_; }
578 BailoutId ast_id() const { return ast_id_; }
579 void set_ast_id(BailoutId id) { ast_id_ = id; }
581 HEnterInlined* entry() const { return entry_; }
582 void set_entry(HEnterInlined* entry) { entry_ = entry; }
584 int length() const { return values_.length(); }
586 int first_expression_index() const {
587 return parameter_count() + specials_count() + local_count();
590 int first_local_index() const {
591 return parameter_count() + specials_count();
594 void Bind(Variable* variable, HValue* value) {
595 Bind(IndexFor(variable), value);
598 void Bind(int index, HValue* value);
600 void BindContext(HValue* value) {
601 Bind(parameter_count(), value);
604 HValue* Lookup(Variable* variable) const {
605 return Lookup(IndexFor(variable));
608 HValue* Lookup(int index) const {
609 HValue* result = values_[index];
610 DCHECK(result != NULL);
614 HValue* context() const {
615 // Return first special.
616 return Lookup(parameter_count());
619 void Push(HValue* value) {
620 DCHECK(value != NULL);
622 values_.Add(value, zone());
626 DCHECK(!ExpressionStackIsEmpty());
627 if (push_count_ > 0) {
632 return values_.RemoveLast();
635 void Drop(int count);
637 HValue* Top() const { return ExpressionStackAt(0); }
639 bool ExpressionStackIsEmpty() const;
641 HValue* ExpressionStackAt(int index_from_top) const {
642 int index = length() - index_from_top - 1;
643 DCHECK(HasExpressionAt(index));
644 return values_[index];
647 void SetExpressionStackAt(int index_from_top, HValue* value);
649 HEnvironment* Copy() const;
650 HEnvironment* CopyWithoutHistory() const;
651 HEnvironment* CopyAsLoopHeader(HBasicBlock* block) const;
653 // Create an "inlined version" of this environment, where the original
654 // environment is the outer environment but the top expression stack
655 // elements are moved to an inner environment as parameters.
656 HEnvironment* CopyForInlining(Handle<JSFunction> target,
658 FunctionLiteral* function,
659 HConstant* undefined,
660 InliningKind inlining_kind) const;
662 HEnvironment* DiscardInlined(bool drop_extra) {
663 HEnvironment* outer = outer_;
664 while (outer->frame_type() != JS_FUNCTION) outer = outer->outer_;
665 if (drop_extra) outer->Drop(1);
669 void AddIncomingEdge(HBasicBlock* block, HEnvironment* other);
671 void ClearHistory() {
674 assigned_variables_.Clear();
677 void SetValueAt(int index, HValue* value) {
678 DCHECK(index < length());
679 values_[index] = value;
682 // Map a variable to an environment index. Parameter indices are shifted
683 // by 1 (receiver is parameter index -1 but environment index 0).
684 // Stack-allocated local indices are shifted by the number of parameters.
685 int IndexFor(Variable* variable) const {
686 DCHECK(variable->IsStackAllocated());
687 int shift = variable->IsParameter()
689 : parameter_count_ + specials_count_;
690 return variable->index() + shift;
693 bool is_local_index(int i) const {
694 return i >= first_local_index() && i < first_expression_index();
697 bool is_parameter_index(int i) const {
698 return i >= 0 && i < parameter_count();
701 bool is_special_index(int i) const {
702 return i >= parameter_count() && i < parameter_count() + specials_count();
705 Zone* zone() const { return zone_; }
708 HEnvironment(const HEnvironment* other, Zone* zone);
710 HEnvironment(HEnvironment* outer,
711 Handle<JSFunction> closure,
712 FrameType frame_type,
716 // Create an artificial stub environment (e.g. for argument adaptor or
717 // constructor stub).
718 HEnvironment* CreateStubEnvironment(HEnvironment* outer,
719 Handle<JSFunction> target,
720 FrameType frame_type,
721 int arguments) const;
723 // True if index is included in the expression stack part of the environment.
724 bool HasExpressionAt(int index) const;
726 void Initialize(int parameter_count, int local_count, int stack_height);
727 void Initialize(const HEnvironment* other);
729 Handle<JSFunction> closure_;
730 // Value array [parameters] [specials] [locals] [temporaries].
731 ZoneList<HValue*> values_;
732 GrowableBitVector assigned_variables_;
733 FrameType frame_type_;
734 int parameter_count_;
737 HEnvironment* outer_;
738 HEnterInlined* entry_;
746 OStream& operator<<(OStream& os, const HEnvironment& env);
749 class HOptimizedGraphBuilder;
751 enum ArgumentsAllowedFlag {
752 ARGUMENTS_NOT_ALLOWED,
757 class HIfContinuation;
759 // This class is not BASE_EMBEDDED because our inlining implementation uses
763 bool IsEffect() const { return kind_ == Expression::kEffect; }
764 bool IsValue() const { return kind_ == Expression::kValue; }
765 bool IsTest() const { return kind_ == Expression::kTest; }
767 // 'Fill' this context with a hydrogen value. The value is assumed to
768 // have already been inserted in the instruction stream (or not need to
769 // be, e.g., HPhi). Call this function in tail position in the Visit
770 // functions for expressions.
771 virtual void ReturnValue(HValue* value) = 0;
773 // Add a hydrogen instruction to the instruction stream (recording an
774 // environment simulation if necessary) and then fill this context with
775 // the instruction as value.
776 virtual void ReturnInstruction(HInstruction* instr, BailoutId ast_id) = 0;
778 // Finishes the current basic block and materialize a boolean for
779 // value context, nothing for effect, generate a branch for test context.
780 // Call this function in tail position in the Visit functions for
782 virtual void ReturnControl(HControlInstruction* instr, BailoutId ast_id) = 0;
784 // Finishes the current basic block and materialize a boolean for
785 // value context, nothing for effect, generate a branch for test context.
786 // Call this function in tail position in the Visit functions for
787 // expressions that use an IfBuilder.
788 virtual void ReturnContinuation(HIfContinuation* continuation,
789 BailoutId ast_id) = 0;
791 void set_for_typeof(bool for_typeof) { for_typeof_ = for_typeof; }
792 bool is_for_typeof() { return for_typeof_; }
795 AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind);
796 virtual ~AstContext();
798 HOptimizedGraphBuilder* owner() const { return owner_; }
800 inline Zone* zone() const;
802 // We want to be able to assert, in a context-specific way, that the stack
803 // height makes sense when the context is filled.
805 int original_length_;
809 HOptimizedGraphBuilder* owner_;
810 Expression::Context kind_;
816 class EffectContext FINAL : public AstContext {
818 explicit EffectContext(HOptimizedGraphBuilder* owner)
819 : AstContext(owner, Expression::kEffect) {
821 virtual ~EffectContext();
823 virtual void ReturnValue(HValue* value) OVERRIDE;
824 virtual void ReturnInstruction(HInstruction* instr,
825 BailoutId ast_id) OVERRIDE;
826 virtual void ReturnControl(HControlInstruction* instr,
827 BailoutId ast_id) OVERRIDE;
828 virtual void ReturnContinuation(HIfContinuation* continuation,
829 BailoutId ast_id) OVERRIDE;
833 class ValueContext FINAL : public AstContext {
835 ValueContext(HOptimizedGraphBuilder* owner, ArgumentsAllowedFlag flag)
836 : AstContext(owner, Expression::kValue), flag_(flag) {
838 virtual ~ValueContext();
840 virtual void ReturnValue(HValue* value) OVERRIDE;
841 virtual void ReturnInstruction(HInstruction* instr,
842 BailoutId ast_id) OVERRIDE;
843 virtual void ReturnControl(HControlInstruction* instr,
844 BailoutId ast_id) OVERRIDE;
845 virtual void ReturnContinuation(HIfContinuation* continuation,
846 BailoutId ast_id) OVERRIDE;
848 bool arguments_allowed() { return flag_ == ARGUMENTS_ALLOWED; }
851 ArgumentsAllowedFlag flag_;
855 class TestContext FINAL : public AstContext {
857 TestContext(HOptimizedGraphBuilder* owner,
858 Expression* condition,
859 HBasicBlock* if_true,
860 HBasicBlock* if_false)
861 : AstContext(owner, Expression::kTest),
862 condition_(condition),
864 if_false_(if_false) {
867 virtual void ReturnValue(HValue* value) OVERRIDE;
868 virtual void ReturnInstruction(HInstruction* instr,
869 BailoutId ast_id) OVERRIDE;
870 virtual void ReturnControl(HControlInstruction* instr,
871 BailoutId ast_id) OVERRIDE;
872 virtual void ReturnContinuation(HIfContinuation* continuation,
873 BailoutId ast_id) OVERRIDE;
875 static TestContext* cast(AstContext* context) {
876 DCHECK(context->IsTest());
877 return reinterpret_cast<TestContext*>(context);
880 Expression* condition() const { return condition_; }
881 HBasicBlock* if_true() const { return if_true_; }
882 HBasicBlock* if_false() const { return if_false_; }
885 // Build the shared core part of the translation unpacking a value into
887 void BuildBranch(HValue* value);
889 Expression* condition_;
890 HBasicBlock* if_true_;
891 HBasicBlock* if_false_;
895 class FunctionState FINAL {
897 FunctionState(HOptimizedGraphBuilder* owner,
898 CompilationInfo* info,
899 InliningKind inlining_kind,
903 CompilationInfo* compilation_info() { return compilation_info_; }
904 AstContext* call_context() { return call_context_; }
905 InliningKind inlining_kind() const { return inlining_kind_; }
906 HBasicBlock* function_return() { return function_return_; }
907 TestContext* test_context() { return test_context_; }
908 void ClearInlinedTestContext() {
909 delete test_context_;
910 test_context_ = NULL;
913 FunctionState* outer() { return outer_; }
915 HEnterInlined* entry() { return entry_; }
916 void set_entry(HEnterInlined* entry) { entry_ = entry; }
918 HArgumentsObject* arguments_object() { return arguments_object_; }
919 void set_arguments_object(HArgumentsObject* arguments_object) {
920 arguments_object_ = arguments_object;
923 HArgumentsElements* arguments_elements() { return arguments_elements_; }
924 void set_arguments_elements(HArgumentsElements* arguments_elements) {
925 arguments_elements_ = arguments_elements;
928 bool arguments_pushed() { return arguments_elements() != NULL; }
930 int inlining_id() const { return inlining_id_; }
933 HOptimizedGraphBuilder* owner_;
935 CompilationInfo* compilation_info_;
937 // During function inlining, expression context of the call being
938 // inlined. NULL when not inlining.
939 AstContext* call_context_;
941 // The kind of call which is currently being inlined.
942 InliningKind inlining_kind_;
944 // When inlining in an effect or value context, this is the return block.
945 // It is NULL otherwise. When inlining in a test context, there are a
946 // pair of return blocks in the context. When not inlining, there is no
947 // local return point.
948 HBasicBlock* function_return_;
950 // When inlining a call in a test context, a context containing a pair of
951 // return blocks. NULL in all other cases.
952 TestContext* test_context_;
954 // When inlining HEnterInlined instruction corresponding to the function
956 HEnterInlined* entry_;
958 HArgumentsObject* arguments_object_;
959 HArgumentsElements* arguments_elements_;
962 HSourcePosition outer_source_position_;
964 FunctionState* outer_;
968 class HIfContinuation FINAL {
971 : continuation_captured_(false),
973 false_branch_(NULL) {}
974 HIfContinuation(HBasicBlock* true_branch,
975 HBasicBlock* false_branch)
976 : continuation_captured_(true), true_branch_(true_branch),
977 false_branch_(false_branch) {}
978 ~HIfContinuation() { DCHECK(!continuation_captured_); }
980 void Capture(HBasicBlock* true_branch,
981 HBasicBlock* false_branch) {
982 DCHECK(!continuation_captured_);
983 true_branch_ = true_branch;
984 false_branch_ = false_branch;
985 continuation_captured_ = true;
988 void Continue(HBasicBlock** true_branch,
989 HBasicBlock** false_branch) {
990 DCHECK(continuation_captured_);
991 *true_branch = true_branch_;
992 *false_branch = false_branch_;
993 continuation_captured_ = false;
996 bool IsTrueReachable() { return true_branch_ != NULL; }
997 bool IsFalseReachable() { return false_branch_ != NULL; }
998 bool TrueAndFalseReachable() {
999 return IsTrueReachable() || IsFalseReachable();
1002 HBasicBlock* true_branch() const { return true_branch_; }
1003 HBasicBlock* false_branch() const { return false_branch_; }
1006 bool continuation_captured_;
1007 HBasicBlock* true_branch_;
1008 HBasicBlock* false_branch_;
1012 class HAllocationMode FINAL BASE_EMBEDDED {
1014 explicit HAllocationMode(Handle<AllocationSite> feedback_site)
1015 : current_site_(NULL), feedback_site_(feedback_site),
1016 pretenure_flag_(NOT_TENURED) {}
1017 explicit HAllocationMode(HValue* current_site)
1018 : current_site_(current_site), pretenure_flag_(NOT_TENURED) {}
1019 explicit HAllocationMode(PretenureFlag pretenure_flag)
1020 : current_site_(NULL), pretenure_flag_(pretenure_flag) {}
1022 : current_site_(NULL), pretenure_flag_(NOT_TENURED) {}
1024 HValue* current_site() const { return current_site_; }
1025 Handle<AllocationSite> feedback_site() const { return feedback_site_; }
1027 bool CreateAllocationMementos() const WARN_UNUSED_RESULT {
1028 return current_site() != NULL;
1031 PretenureFlag GetPretenureMode() const WARN_UNUSED_RESULT {
1032 if (!feedback_site().is_null()) return feedback_site()->GetPretenureMode();
1033 return pretenure_flag_;
1037 HValue* current_site_;
1038 Handle<AllocationSite> feedback_site_;
1039 PretenureFlag pretenure_flag_;
1043 class HGraphBuilder {
1045 explicit HGraphBuilder(CompilationInfo* info)
1048 current_block_(NULL),
1049 scope_(info->scope()),
1050 position_(HSourcePosition::Unknown()),
1051 start_position_(0) {}
1052 virtual ~HGraphBuilder() {}
1054 Scope* scope() const { return scope_; }
1055 void set_scope(Scope* scope) { scope_ = scope; }
1057 HBasicBlock* current_block() const { return current_block_; }
1058 void set_current_block(HBasicBlock* block) { current_block_ = block; }
1059 HEnvironment* environment() const {
1060 return current_block()->last_environment();
1062 Zone* zone() const { return info_->zone(); }
1063 HGraph* graph() const { return graph_; }
1064 Isolate* isolate() const { return graph_->isolate(); }
1065 CompilationInfo* top_info() { return info_; }
1067 HGraph* CreateGraph();
1069 // Bailout environment manipulation.
1070 void Push(HValue* value) { environment()->Push(value); }
1071 HValue* Pop() { return environment()->Pop(); }
1073 virtual HValue* context() = 0;
1075 // Adding instructions.
1076 HInstruction* AddInstruction(HInstruction* instr);
1077 void FinishCurrentBlock(HControlInstruction* last);
1078 void FinishExitCurrentBlock(HControlInstruction* instruction);
1080 void Goto(HBasicBlock* from,
1081 HBasicBlock* target,
1082 FunctionState* state = NULL,
1083 bool add_simulate = true) {
1084 from->Goto(target, source_position(), state, add_simulate);
1086 void Goto(HBasicBlock* target,
1087 FunctionState* state = NULL,
1088 bool add_simulate = true) {
1089 Goto(current_block(), target, state, add_simulate);
1091 void GotoNoSimulate(HBasicBlock* from, HBasicBlock* target) {
1092 Goto(from, target, NULL, false);
1094 void GotoNoSimulate(HBasicBlock* target) {
1095 Goto(target, NULL, false);
1097 void AddLeaveInlined(HBasicBlock* block,
1098 HValue* return_value,
1099 FunctionState* state) {
1100 block->AddLeaveInlined(return_value, state, source_position());
1102 void AddLeaveInlined(HValue* return_value, FunctionState* state) {
1103 return AddLeaveInlined(current_block(), return_value, state);
1107 HInstruction* NewUncasted() { return I::New(zone(), context()); }
1110 I* New() { return I::New(zone(), context()); }
1113 HInstruction* AddUncasted() { return AddInstruction(NewUncasted<I>());}
1116 I* Add() { return AddInstructionTyped(New<I>());}
1118 template<class I, class P1>
1119 HInstruction* NewUncasted(P1 p1) {
1120 return I::New(zone(), context(), p1);
1123 template<class I, class P1>
1124 I* New(P1 p1) { return I::New(zone(), context(), p1); }
1126 template<class I, class P1>
1127 HInstruction* AddUncasted(P1 p1) {
1128 HInstruction* result = AddInstruction(NewUncasted<I>(p1));
1129 // Specializations must have their parameters properly casted
1130 // to avoid landing here.
1131 DCHECK(!result->IsReturn() && !result->IsSimulate() &&
1132 !result->IsDeoptimize());
1136 template<class I, class P1>
1138 I* result = AddInstructionTyped(New<I>(p1));
1139 // Specializations must have their parameters properly casted
1140 // to avoid landing here.
1141 DCHECK(!result->IsReturn() && !result->IsSimulate() &&
1142 !result->IsDeoptimize());
1146 template<class I, class P1, class P2>
1147 HInstruction* NewUncasted(P1 p1, P2 p2) {
1148 return I::New(zone(), context(), p1, p2);
1151 template<class I, class P1, class P2>
1152 I* New(P1 p1, P2 p2) {
1153 return I::New(zone(), context(), p1, p2);
1156 template<class I, class P1, class P2>
1157 HInstruction* AddUncasted(P1 p1, P2 p2) {
1158 HInstruction* result = AddInstruction(NewUncasted<I>(p1, p2));
1159 // Specializations must have their parameters properly casted
1160 // to avoid landing here.
1161 DCHECK(!result->IsSimulate());
1165 template<class I, class P1, class P2>
1166 I* Add(P1 p1, P2 p2) {
1167 I* result = AddInstructionTyped(New<I>(p1, p2));
1168 // Specializations must have their parameters properly casted
1169 // to avoid landing here.
1170 DCHECK(!result->IsSimulate());
1174 template<class I, class P1, class P2, class P3>
1175 HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3) {
1176 return I::New(zone(), context(), p1, p2, p3);
1179 template<class I, class P1, class P2, class P3>
1180 I* New(P1 p1, P2 p2, P3 p3) {
1181 return I::New(zone(), context(), p1, p2, p3);
1184 template<class I, class P1, class P2, class P3>
1185 HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3) {
1186 return AddInstruction(NewUncasted<I>(p1, p2, p3));
1189 template<class I, class P1, class P2, class P3>
1190 I* Add(P1 p1, P2 p2, P3 p3) {
1191 return AddInstructionTyped(New<I>(p1, p2, p3));
1194 template<class I, class P1, class P2, class P3, class P4>
1195 HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4) {
1196 return I::New(zone(), context(), p1, p2, p3, p4);
1199 template<class I, class P1, class P2, class P3, class P4>
1200 I* New(P1 p1, P2 p2, P3 p3, P4 p4) {
1201 return I::New(zone(), context(), p1, p2, p3, p4);
1204 template<class I, class P1, class P2, class P3, class P4>
1205 HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4) {
1206 return AddInstruction(NewUncasted<I>(p1, p2, p3, p4));
1209 template<class I, class P1, class P2, class P3, class P4>
1210 I* Add(P1 p1, P2 p2, P3 p3, P4 p4) {
1211 return AddInstructionTyped(New<I>(p1, p2, p3, p4));
1214 template<class I, class P1, class P2, class P3, class P4, class P5>
1215 HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1216 return I::New(zone(), context(), p1, p2, p3, p4, p5);
1219 template<class I, class P1, class P2, class P3, class P4, class P5>
1220 I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1221 return I::New(zone(), context(), p1, p2, p3, p4, p5);
1224 template<class I, class P1, class P2, class P3, class P4, class P5>
1225 HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1226 return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5));
1229 template<class I, class P1, class P2, class P3, class P4, class P5>
1230 I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1231 return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5));
1234 template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1235 HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1236 return I::New(zone(), context(), p1, p2, p3, p4, p5, p6);
1239 template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1240 I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1241 return I::New(zone(), context(), p1, p2, p3, p4, p5, p6);
1244 template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1245 HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1246 return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6));
1249 template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
1250 I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1251 return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6));
1254 template<class I, class P1, class P2, class P3, class P4,
1255 class P5, class P6, class P7>
1256 HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1257 return I::New(zone(), context(), p1, p2, p3, p4, p5, p6, p7);
1260 template<class I, class P1, class P2, class P3, class P4,
1261 class P5, class P6, class P7>
1262 I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1263 return I::New(zone(), context(), p1, p2, p3, p4, p5, p6, p7);
1266 template<class I, class P1, class P2, class P3,
1267 class P4, class P5, class P6, class P7>
1268 HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1269 return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6, p7));
1272 template<class I, class P1, class P2, class P3,
1273 class P4, class P5, class P6, class P7>
1274 I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1275 return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6, p7));
1278 template<class I, class P1, class P2, class P3, class P4,
1279 class P5, class P6, class P7, class P8>
1280 HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4,
1281 P5 p5, P6 p6, P7 p7, P8 p8) {
1282 return I::New(zone(), context(), p1, p2, p3, p4, p5, p6, p7, p8);
1285 template<class I, class P1, class P2, class P3, class P4,
1286 class P5, class P6, class P7, class P8>
1287 I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
1288 return I::New(zone(), context(), p1, p2, p3, p4, p5, p6, p7, p8);
1291 template<class I, class P1, class P2, class P3, class P4,
1292 class P5, class P6, class P7, class P8>
1293 HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4,
1294 P5 p5, P6 p6, P7 p7, P8 p8) {
1295 return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6, p7, p8));
1298 template<class I, class P1, class P2, class P3, class P4,
1299 class P5, class P6, class P7, class P8>
1300 I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
1301 return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6, p7, p8));
1304 void AddSimulate(BailoutId id, RemovableSimulate removable = FIXED_SIMULATE);
1306 // When initializing arrays, we'll unfold the loop if the number of elements
1307 // is known at compile time and is <= kElementLoopUnrollThreshold.
1308 static const int kElementLoopUnrollThreshold = 8;
1311 virtual bool BuildGraph() = 0;
1313 HBasicBlock* CreateBasicBlock(HEnvironment* env);
1314 HBasicBlock* CreateLoopHeaderBlock();
1316 template <class BitFieldClass>
1317 HValue* BuildDecodeField(HValue* encoded_field) {
1318 HValue* mask_value = Add<HConstant>(static_cast<int>(BitFieldClass::kMask));
1319 HValue* masked_field =
1320 AddUncasted<HBitwise>(Token::BIT_AND, encoded_field, mask_value);
1321 return AddUncasted<HShr>(masked_field,
1322 Add<HConstant>(static_cast<int>(BitFieldClass::kShift)));
1325 HValue* BuildGetElementsKind(HValue* object);
1327 HValue* BuildCheckHeapObject(HValue* object);
1328 HValue* BuildCheckString(HValue* string);
1329 HValue* BuildWrapReceiver(HValue* object, HValue* function);
1331 // Building common constructs
1332 HValue* BuildCheckForCapacityGrow(HValue* object,
1338 PropertyAccessType access_type);
1340 HValue* BuildCopyElementsOnWrite(HValue* object,
1345 void BuildTransitionElementsKind(HValue* object,
1347 ElementsKind from_kind,
1348 ElementsKind to_kind,
1351 HValue* BuildNumberToString(HValue* object, Type* type);
1353 void BuildJSObjectCheck(HValue* receiver,
1354 int bit_field_mask);
1356 // Checks a key value that's being used for a keyed element access context. If
1357 // the key is a index, i.e. a smi or a number in a unique string with a cached
1358 // numeric value, the "true" of the continuation is joined. Otherwise,
1359 // if the key is a name or a unique string, the "false" of the continuation is
1360 // joined. Otherwise, a deoptimization is triggered. In both paths of the
1361 // continuation, the key is pushed on the top of the environment.
1362 void BuildKeyedIndexCheck(HValue* key,
1363 HIfContinuation* join_continuation);
1365 // Checks the properties of an object if they are in dictionary case, in which
1366 // case "true" of continuation is taken, otherwise the "false"
1367 void BuildTestForDictionaryProperties(HValue* object,
1368 HIfContinuation* continuation);
1370 void BuildNonGlobalObjectCheck(HValue* receiver);
1372 HValue* BuildKeyedLookupCacheHash(HValue* object,
1375 HValue* BuildUncheckedDictionaryElementLoad(HValue* receiver,
1380 HValue* BuildRegExpConstructResult(HValue* length,
1384 // Allocates a new object according with the given allocation properties.
1385 HAllocate* BuildAllocate(HValue* object_size,
1387 InstanceType instance_type,
1388 HAllocationMode allocation_mode);
1389 // Computes the sum of two string lengths, taking care of overflow handling.
1390 HValue* BuildAddStringLengths(HValue* left_length, HValue* right_length);
1391 // Creates a cons string using the two input strings.
1392 HValue* BuildCreateConsString(HValue* length,
1395 HAllocationMode allocation_mode);
1396 // Copies characters from one sequential string to another.
1397 void BuildCopySeqStringChars(HValue* src,
1399 String::Encoding src_encoding,
1402 String::Encoding dst_encoding,
1405 // Align an object size to object alignment boundary
1406 HValue* BuildObjectSizeAlignment(HValue* unaligned_size, int header_size);
1408 // Both operands are non-empty strings.
1409 HValue* BuildUncheckedStringAdd(HValue* left,
1411 HAllocationMode allocation_mode);
1412 // Add two strings using allocation mode, validating type feedback.
1413 HValue* BuildStringAdd(HValue* left,
1415 HAllocationMode allocation_mode);
1417 HInstruction* BuildUncheckedMonomorphicElementAccess(
1418 HValue* checked_object,
1422 ElementsKind elements_kind,
1423 PropertyAccessType access_type,
1424 LoadKeyedHoleMode load_mode,
1425 KeyedAccessStoreMode store_mode,
1426 BuiltinFunctionId id = kNumberOfBuiltinFunction);
1428 HInstruction* AddElementAccess(
1430 HValue* checked_key,
1433 ElementsKind elements_kind,
1434 PropertyAccessType access_type,
1435 LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE,
1436 BuiltinFunctionId id = kNumberOfBuiltinFunction);
1438 HInstruction* AddLoadStringInstanceType(HValue* string);
1439 HInstruction* AddLoadStringLength(HValue* string);
1440 HStoreNamedField* AddStoreMapConstant(HValue* object, Handle<Map> map) {
1441 return Add<HStoreNamedField>(object, HObjectAccess::ForMap(),
1442 Add<HConstant>(map));
1444 HLoadNamedField* AddLoadMap(HValue* object,
1445 HValue* dependency = NULL);
1446 HLoadNamedField* AddLoadElements(HValue* object,
1447 HValue* dependency = NULL);
1449 bool MatchRotateRight(HValue* left,
1452 HValue** shift_amount);
1454 HValue* BuildBinaryOperation(Token::Value op,
1460 Maybe<int> fixed_right_arg,
1461 HAllocationMode allocation_mode);
1463 HLoadNamedField* AddLoadFixedArrayLength(HValue *object,
1464 HValue *dependency = NULL);
1466 HLoadNamedField* AddLoadArrayLength(HValue *object,
1468 HValue *dependency = NULL);
1470 HValue* AddLoadJSBuiltin(Builtins::JavaScript builtin);
1472 HValue* EnforceNumberType(HValue* number, Type* expected);
1473 HValue* TruncateToNumber(HValue* value, Type** expected);
1475 void FinishExitWithHardDeoptimization(const char* reason);
1477 void AddIncrementCounter(StatsCounter* counter);
1479 class IfBuilder FINAL {
1481 // If using this constructor, Initialize() must be called explicitly!
1484 explicit IfBuilder(HGraphBuilder* builder);
1485 IfBuilder(HGraphBuilder* builder,
1486 HIfContinuation* continuation);
1489 if (!finished_) End();
1492 void Initialize(HGraphBuilder* builder);
1494 template<class Condition>
1495 Condition* If(HValue *p) {
1496 Condition* compare = builder()->New<Condition>(p);
1497 AddCompare(compare);
1501 template<class Condition, class P2>
1502 Condition* If(HValue* p1, P2 p2) {
1503 Condition* compare = builder()->New<Condition>(p1, p2);
1504 AddCompare(compare);
1508 template<class Condition, class P2, class P3>
1509 Condition* If(HValue* p1, P2 p2, P3 p3) {
1510 Condition* compare = builder()->New<Condition>(p1, p2, p3);
1511 AddCompare(compare);
1515 template<class Condition>
1516 Condition* IfNot(HValue* p) {
1517 Condition* compare = If<Condition>(p);
1522 template<class Condition, class P2>
1523 Condition* IfNot(HValue* p1, P2 p2) {
1524 Condition* compare = If<Condition>(p1, p2);
1529 template<class Condition, class P2, class P3>
1530 Condition* IfNot(HValue* p1, P2 p2, P3 p3) {
1531 Condition* compare = If<Condition>(p1, p2, p3);
1536 template<class Condition>
1537 Condition* OrIf(HValue *p) {
1539 return If<Condition>(p);
1542 template<class Condition, class P2>
1543 Condition* OrIf(HValue* p1, P2 p2) {
1545 return If<Condition>(p1, p2);
1548 template<class Condition, class P2, class P3>
1549 Condition* OrIf(HValue* p1, P2 p2, P3 p3) {
1551 return If<Condition>(p1, p2, p3);
1554 template<class Condition>
1555 Condition* AndIf(HValue *p) {
1557 return If<Condition>(p);
1560 template<class Condition, class P2>
1561 Condition* AndIf(HValue* p1, P2 p2) {
1563 return If<Condition>(p1, p2);
1566 template<class Condition, class P2, class P3>
1567 Condition* AndIf(HValue* p1, P2 p2, P3 p3) {
1569 return If<Condition>(p1, p2, p3);
1575 // Captures the current state of this IfBuilder in the specified
1576 // continuation and ends this IfBuilder.
1577 void CaptureContinuation(HIfContinuation* continuation);
1579 // Joins the specified continuation from this IfBuilder and ends this
1580 // IfBuilder. This appends a Goto instruction from the true branch of
1581 // this IfBuilder to the true branch of the continuation unless the
1582 // true branch of this IfBuilder is already finished. And vice versa
1583 // for the false branch.
1585 // The basic idea is as follows: You have several nested IfBuilder's
1586 // that you want to join based on two possible outcomes (i.e. success
1587 // and failure, or whatever). You can do this easily using this method
1588 // now, for example:
1590 // HIfContinuation cont(graph()->CreateBasicBlock(),
1591 // graph()->CreateBasicBlock());
1593 // IfBuilder if_whatever(this);
1594 // if_whatever.If<Condition>(arg);
1595 // if_whatever.Then();
1597 // if_whatever.Else();
1599 // if_whatever.JoinContinuation(&cont);
1601 // IfBuilder if_something(this);
1602 // if_something.If<Condition>(arg1, arg2);
1603 // if_something.Then();
1605 // if_something.Else();
1607 // if_something.JoinContinuation(&cont);
1609 // IfBuilder if_finally(this, &cont);
1610 // if_finally.Then();
1611 // // continues after then code of if_whatever or if_something.
1613 // if_finally.Else();
1614 // // continues after else code of if_whatever or if_something.
1616 // if_finally.End();
1617 void JoinContinuation(HIfContinuation* continuation);
1623 void Deopt(const char* reason);
1624 void ThenDeopt(const char* reason) {
1628 void ElseDeopt(const char* reason) {
1633 void Return(HValue* value);
1636 void InitializeDontCreateBlocks(HGraphBuilder* builder);
1638 HControlInstruction* AddCompare(HControlInstruction* compare);
1640 HGraphBuilder* builder() const {
1641 DCHECK(builder_ != NULL); // Have you called "Initialize"?
1645 void AddMergeAtJoinBlock(bool deopt);
1648 void Finish(HBasicBlock** then_continuation,
1649 HBasicBlock** else_continuation);
1651 class MergeAtJoinBlock : public ZoneObject {
1653 MergeAtJoinBlock(HBasicBlock* block,
1655 MergeAtJoinBlock* next)
1659 HBasicBlock* block_;
1661 MergeAtJoinBlock* next_;
1664 HGraphBuilder* builder_;
1668 bool did_else_if_ : 1;
1672 bool needs_compare_ : 1;
1673 bool pending_merge_block_ : 1;
1674 HBasicBlock* first_true_block_;
1675 HBasicBlock* first_false_block_;
1676 HBasicBlock* split_edge_merge_block_;
1677 MergeAtJoinBlock* merge_at_join_blocks_;
1678 int normal_merge_at_join_block_count_;
1679 int deopt_merge_at_join_block_count_;
1682 class LoopBuilder FINAL {
1692 explicit LoopBuilder(HGraphBuilder* builder); // while (true) {...}
1693 LoopBuilder(HGraphBuilder* builder,
1695 Direction direction);
1696 LoopBuilder(HGraphBuilder* builder,
1698 Direction direction,
1699 HValue* increment_amount);
1707 HValue* terminating,
1708 Token::Value token);
1710 void BeginBody(int drop_count);
1717 void Initialize(HGraphBuilder* builder, HValue* context,
1718 Direction direction, HValue* increment_amount);
1719 Zone* zone() { return builder_->zone(); }
1721 HGraphBuilder* builder_;
1723 HValue* increment_amount_;
1724 HInstruction* increment_;
1726 HBasicBlock* header_block_;
1727 HBasicBlock* body_block_;
1728 HBasicBlock* exit_block_;
1729 HBasicBlock* exit_trampoline_block_;
1730 Direction direction_;
1734 HValue* BuildNewElementsCapacity(HValue* old_capacity);
1736 class JSArrayBuilder FINAL {
1738 JSArrayBuilder(HGraphBuilder* builder,
1740 HValue* allocation_site_payload,
1741 HValue* constructor_function,
1742 AllocationSiteOverrideMode override_mode);
1744 JSArrayBuilder(HGraphBuilder* builder,
1746 HValue* constructor_function = NULL);
1749 DONT_FILL_WITH_HOLE,
1753 ElementsKind kind() { return kind_; }
1754 HAllocate* elements_location() { return elements_location_; }
1756 HAllocate* AllocateEmptyArray();
1757 HAllocate* AllocateArray(HValue* capacity,
1758 HValue* length_field,
1759 FillMode fill_mode = FILL_WITH_HOLE);
1760 // Use these allocators when capacity could be unknown at compile time
1761 // but its limit is known. For constant |capacity| the value of
1762 // |capacity_upper_bound| is ignored and the actual |capacity|
1763 // value is used as an upper bound.
1764 HAllocate* AllocateArray(HValue* capacity,
1765 int capacity_upper_bound,
1766 HValue* length_field,
1767 FillMode fill_mode = FILL_WITH_HOLE);
1768 HAllocate* AllocateArray(HValue* capacity,
1769 HConstant* capacity_upper_bound,
1770 HValue* length_field,
1771 FillMode fill_mode = FILL_WITH_HOLE);
1772 HValue* GetElementsLocation() { return elements_location_; }
1773 HValue* EmitMapCode();
1776 Zone* zone() const { return builder_->zone(); }
1777 int elements_size() const {
1778 return IsFastDoubleElementsKind(kind_) ? kDoubleSize : kPointerSize;
1780 HGraphBuilder* builder() { return builder_; }
1781 HGraph* graph() { return builder_->graph(); }
1782 int initial_capacity() {
1783 STATIC_ASSERT(JSArray::kPreallocatedArrayElements > 0);
1784 return JSArray::kPreallocatedArrayElements;
1787 HValue* EmitInternalMapCode();
1789 HGraphBuilder* builder_;
1791 AllocationSiteMode mode_;
1792 HValue* allocation_site_payload_;
1793 HValue* constructor_function_;
1794 HAllocate* elements_location_;
1797 HValue* BuildAllocateArrayFromLength(JSArrayBuilder* array_builder,
1798 HValue* length_argument);
1799 HValue* BuildCalculateElementsSize(ElementsKind kind,
1801 HAllocate* AllocateJSArrayObject(AllocationSiteMode mode);
1802 HConstant* EstablishElementsAllocationSize(ElementsKind kind, int capacity);
1804 HAllocate* BuildAllocateElements(ElementsKind kind, HValue* size_in_bytes);
1806 void BuildInitializeElementsHeader(HValue* elements,
1810 HValue* BuildAllocateElementsAndInitializeElementsHeader(ElementsKind kind,
1813 // |array| must have been allocated with enough room for
1814 // 1) the JSArray and 2) an AllocationMemento if mode requires it.
1815 // If the |elements| value provided is NULL then the array elements storage
1816 // is initialized with empty array.
1817 void BuildJSArrayHeader(HValue* array,
1820 AllocationSiteMode mode,
1821 ElementsKind elements_kind,
1822 HValue* allocation_site_payload,
1823 HValue* length_field);
1825 HValue* BuildGrowElementsCapacity(HValue* object,
1828 ElementsKind new_kind,
1830 HValue* new_capacity);
1832 void BuildFillElementsWithValue(HValue* elements,
1833 ElementsKind elements_kind,
1838 void BuildFillElementsWithHole(HValue* elements,
1839 ElementsKind elements_kind,
1843 void BuildCopyElements(HValue* from_elements,
1844 ElementsKind from_elements_kind,
1845 HValue* to_elements,
1846 ElementsKind to_elements_kind,
1850 HValue* BuildCloneShallowArrayCow(HValue* boilerplate,
1851 HValue* allocation_site,
1852 AllocationSiteMode mode,
1855 HValue* BuildCloneShallowArrayEmpty(HValue* boilerplate,
1856 HValue* allocation_site,
1857 AllocationSiteMode mode);
1859 HValue* BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
1860 HValue* allocation_site,
1861 AllocationSiteMode mode,
1864 HValue* BuildElementIndexHash(HValue* index);
1866 void BuildCompareNil(
1869 HIfContinuation* continuation);
1871 void BuildCreateAllocationMemento(HValue* previous_object,
1872 HValue* previous_object_size,
1875 HInstruction* BuildConstantMapCheck(Handle<JSObject> constant);
1876 HInstruction* BuildCheckPrototypeMaps(Handle<JSObject> prototype,
1877 Handle<JSObject> holder);
1879 HInstruction* BuildGetNativeContext(HValue* closure);
1880 HInstruction* BuildGetNativeContext();
1881 HInstruction* BuildGetArrayFunction();
1884 void SetSourcePosition(int position) {
1885 DCHECK(position != RelocInfo::kNoPosition);
1886 position_.set_position(position - start_position_);
1889 void EnterInlinedSource(int start_position, int id) {
1890 if (FLAG_hydrogen_track_positions) {
1891 start_position_ = start_position;
1892 position_.set_inlining_id(id);
1896 // Convert the given absolute offset from the start of the script to
1897 // the HSourcePosition assuming that this position corresponds to the
1898 // same function as current position_.
1899 HSourcePosition ScriptPositionToSourcePosition(int position) {
1900 HSourcePosition pos = position_;
1901 pos.set_position(position - start_position_);
1905 HSourcePosition source_position() { return position_; }
1906 void set_source_position(HSourcePosition position) {
1907 position_ = position;
1910 template <typename ViewClass>
1911 void BuildArrayBufferViewInitialization(HValue* obj,
1913 HValue* byte_offset,
1914 HValue* byte_length);
1920 I* AddInstructionTyped(I* instr) {
1921 return I::cast(AddInstruction(instr));
1924 CompilationInfo* info_;
1926 HBasicBlock* current_block_;
1928 HSourcePosition position_;
1929 int start_position_;
1934 inline HDeoptimize* HGraphBuilder::Add<HDeoptimize>(
1935 const char* reason, Deoptimizer::BailoutType type) {
1936 if (type == Deoptimizer::SOFT) {
1937 isolate()->counters()->soft_deopts_requested()->Increment();
1938 if (FLAG_always_opt) return NULL;
1940 if (current_block()->IsDeoptimizing()) return NULL;
1941 HBasicBlock* after_deopt_block = CreateBasicBlock(
1942 current_block()->last_environment());
1943 HDeoptimize* instr = New<HDeoptimize>(reason, type, after_deopt_block);
1944 if (type == Deoptimizer::SOFT) {
1945 isolate()->counters()->soft_deopts_inserted()->Increment();
1947 FinishCurrentBlock(instr);
1948 set_current_block(after_deopt_block);
1954 inline HInstruction* HGraphBuilder::AddUncasted<HDeoptimize>(
1955 const char* reason, Deoptimizer::BailoutType type) {
1956 return Add<HDeoptimize>(reason, type);
1961 inline HSimulate* HGraphBuilder::Add<HSimulate>(
1963 RemovableSimulate removable) {
1964 HSimulate* instr = current_block()->CreateSimulate(id, removable);
1965 AddInstruction(instr);
1971 inline HSimulate* HGraphBuilder::Add<HSimulate>(
1973 return Add<HSimulate>(id, FIXED_SIMULATE);
1978 inline HInstruction* HGraphBuilder::AddUncasted<HSimulate>(BailoutId id) {
1979 return Add<HSimulate>(id, FIXED_SIMULATE);
1984 inline HReturn* HGraphBuilder::Add<HReturn>(HValue* value) {
1985 int num_parameters = graph()->info()->num_parameters();
1986 HValue* params = AddUncasted<HConstant>(num_parameters);
1987 HReturn* return_instruction = New<HReturn>(value, params);
1988 FinishExitCurrentBlock(return_instruction);
1989 return return_instruction;
1994 inline HReturn* HGraphBuilder::Add<HReturn>(HConstant* value) {
1995 return Add<HReturn>(static_cast<HValue*>(value));
1999 inline HInstruction* HGraphBuilder::AddUncasted<HReturn>(HValue* value) {
2000 return Add<HReturn>(value);
2005 inline HInstruction* HGraphBuilder::AddUncasted<HReturn>(HConstant* value) {
2006 return Add<HReturn>(value);
2011 inline HCallRuntime* HGraphBuilder::Add<HCallRuntime>(
2012 Handle<String> name,
2013 const Runtime::Function* c_function,
2014 int argument_count) {
2015 HCallRuntime* instr = New<HCallRuntime>(name, c_function, argument_count);
2016 if (graph()->info()->IsStub()) {
2017 // When compiling code stubs, we don't want to save all double registers
2018 // upon entry to the stub, but instead have the call runtime instruction
2019 // save the double registers only on-demand (in the fallback case).
2020 instr->set_save_doubles(kSaveFPRegs);
2022 AddInstruction(instr);
2028 inline HInstruction* HGraphBuilder::AddUncasted<HCallRuntime>(
2029 Handle<String> name,
2030 const Runtime::Function* c_function,
2031 int argument_count) {
2032 return Add<HCallRuntime>(name, c_function, argument_count);
2037 inline HContext* HGraphBuilder::New<HContext>() {
2038 return HContext::New(zone());
2043 inline HInstruction* HGraphBuilder::NewUncasted<HContext>() {
2044 return New<HContext>();
2047 class HOptimizedGraphBuilder : public HGraphBuilder, public AstVisitor {
2049 // A class encapsulating (lazily-allocated) break and continue blocks for
2050 // a breakable statement. Separated from BreakAndContinueScope so that it
2051 // can have a separate lifetime.
2052 class BreakAndContinueInfo FINAL BASE_EMBEDDED {
2054 explicit BreakAndContinueInfo(BreakableStatement* target,
2059 continue_block_(NULL),
2061 drop_extra_(drop_extra) {
2064 BreakableStatement* target() { return target_; }
2065 HBasicBlock* break_block() { return break_block_; }
2066 void set_break_block(HBasicBlock* block) { break_block_ = block; }
2067 HBasicBlock* continue_block() { return continue_block_; }
2068 void set_continue_block(HBasicBlock* block) { continue_block_ = block; }
2069 Scope* scope() { return scope_; }
2070 int drop_extra() { return drop_extra_; }
2073 BreakableStatement* target_;
2074 HBasicBlock* break_block_;
2075 HBasicBlock* continue_block_;
2080 // A helper class to maintain a stack of current BreakAndContinueInfo
2081 // structures mirroring BreakableStatement nesting.
2082 class BreakAndContinueScope FINAL BASE_EMBEDDED {
2084 BreakAndContinueScope(BreakAndContinueInfo* info,
2085 HOptimizedGraphBuilder* owner)
2086 : info_(info), owner_(owner), next_(owner->break_scope()) {
2087 owner->set_break_scope(this);
2090 ~BreakAndContinueScope() { owner_->set_break_scope(next_); }
2092 BreakAndContinueInfo* info() { return info_; }
2093 HOptimizedGraphBuilder* owner() { return owner_; }
2094 BreakAndContinueScope* next() { return next_; }
2096 // Search the break stack for a break or continue target.
2097 enum BreakType { BREAK, CONTINUE };
2098 HBasicBlock* Get(BreakableStatement* stmt, BreakType type,
2099 Scope** scope, int* drop_extra);
2102 BreakAndContinueInfo* info_;
2103 HOptimizedGraphBuilder* owner_;
2104 BreakAndContinueScope* next_;
2107 explicit HOptimizedGraphBuilder(CompilationInfo* info);
2109 virtual bool BuildGraph() OVERRIDE;
2111 // Simple accessors.
2112 BreakAndContinueScope* break_scope() const { return break_scope_; }
2113 void set_break_scope(BreakAndContinueScope* head) { break_scope_ = head; }
2115 HValue* context() { return environment()->context(); }
2117 HOsrBuilder* osr() const { return osr_; }
2119 void Bailout(BailoutReason reason);
2121 HBasicBlock* CreateJoin(HBasicBlock* first,
2122 HBasicBlock* second,
2125 FunctionState* function_state() const { return function_state_; }
2127 void VisitDeclarations(ZoneList<Declaration*>* declarations);
2129 void* operator new(size_t size, Zone* zone) {
2130 return zone->New(static_cast<int>(size));
2132 void operator delete(void* pointer, Zone* zone) { }
2133 void operator delete(void* pointer) { }
2135 DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
2138 // Type of a member function that generates inline code for a native function.
2139 typedef void (HOptimizedGraphBuilder::*InlineFunctionGenerator)
2140 (CallRuntime* call);
2142 // Forward declarations for inner scope classes.
2143 class SubgraphScope;
2145 static const InlineFunctionGenerator kInlineFunctionGenerators[];
2147 static const int kMaxCallPolymorphism = 4;
2148 static const int kMaxLoadPolymorphism = 4;
2149 static const int kMaxStorePolymorphism = 4;
2151 // Even in the 'unlimited' case we have to have some limit in order not to
2152 // overflow the stack.
2153 static const int kUnlimitedMaxInlinedSourceSize = 100000;
2154 static const int kUnlimitedMaxInlinedNodes = 10000;
2155 static const int kUnlimitedMaxInlinedNodesCumulative = 10000;
2157 // Maximum depth and total number of elements and properties for literal
2158 // graphs to be considered for fast deep-copying.
2159 static const int kMaxFastLiteralDepth = 3;
2160 static const int kMaxFastLiteralProperties = 8;
2162 // Simple accessors.
2163 void set_function_state(FunctionState* state) { function_state_ = state; }
2165 AstContext* ast_context() const { return ast_context_; }
2166 void set_ast_context(AstContext* context) { ast_context_ = context; }
2168 // Accessors forwarded to the function state.
2169 CompilationInfo* current_info() const {
2170 return function_state()->compilation_info();
2172 AstContext* call_context() const {
2173 return function_state()->call_context();
2175 HBasicBlock* function_return() const {
2176 return function_state()->function_return();
2178 TestContext* inlined_test_context() const {
2179 return function_state()->test_context();
2181 void ClearInlinedTestContext() {
2182 function_state()->ClearInlinedTestContext();
2184 StrictMode function_strict_mode() {
2185 return function_state()->compilation_info()->strict_mode();
2188 // Generators for inline runtime functions.
2189 #define INLINE_FUNCTION_GENERATOR_DECLARATION(Name, argc, ressize) \
2190 void Generate##Name(CallRuntime* call);
2192 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_DECLARATION)
2193 INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_DECLARATION)
2194 #undef INLINE_FUNCTION_GENERATOR_DECLARATION
2196 void VisitDelete(UnaryOperation* expr);
2197 void VisitVoid(UnaryOperation* expr);
2198 void VisitTypeof(UnaryOperation* expr);
2199 void VisitNot(UnaryOperation* expr);
2201 void VisitComma(BinaryOperation* expr);
2202 void VisitLogicalExpression(BinaryOperation* expr);
2203 void VisitArithmeticExpression(BinaryOperation* expr);
2205 bool PreProcessOsrEntry(IterationStatement* statement);
2206 void VisitLoopBody(IterationStatement* stmt,
2207 HBasicBlock* loop_entry);
2209 // Create a back edge in the flow graph. body_exit is the predecessor
2210 // block and loop_entry is the successor block. loop_successor is the
2211 // block where control flow exits the loop normally (e.g., via failure of
2212 // the condition) and break_block is the block where control flow breaks
2213 // from the loop. All blocks except loop_entry can be NULL. The return
2214 // value is the new successor block which is the join of loop_successor
2215 // and break_block, or NULL.
2216 HBasicBlock* CreateLoop(IterationStatement* statement,
2217 HBasicBlock* loop_entry,
2218 HBasicBlock* body_exit,
2219 HBasicBlock* loop_successor,
2220 HBasicBlock* break_block);
2222 // Build a loop entry
2223 HBasicBlock* BuildLoopEntry();
2225 // Builds a loop entry respectful of OSR requirements
2226 HBasicBlock* BuildLoopEntry(IterationStatement* statement);
2228 HBasicBlock* JoinContinue(IterationStatement* statement,
2229 HBasicBlock* exit_block,
2230 HBasicBlock* continue_block);
2232 HValue* Top() const { return environment()->Top(); }
2233 void Drop(int n) { environment()->Drop(n); }
2234 void Bind(Variable* var, HValue* value) { environment()->Bind(var, value); }
2235 bool IsEligibleForEnvironmentLivenessAnalysis(Variable* var,
2238 HEnvironment* env) {
2239 if (!FLAG_analyze_environment_liveness) return false;
2240 // |this| and |arguments| are always live; zapping parameters isn't
2241 // safe because function.arguments can inspect them at any time.
2242 return !var->is_this() &&
2243 !var->is_arguments() &&
2244 !value->IsArgumentsObject() &&
2245 env->is_local_index(index);
2247 void BindIfLive(Variable* var, HValue* value) {
2248 HEnvironment* env = environment();
2249 int index = env->IndexFor(var);
2250 env->Bind(index, value);
2251 if (IsEligibleForEnvironmentLivenessAnalysis(var, index, value, env)) {
2252 HEnvironmentMarker* bind =
2253 Add<HEnvironmentMarker>(HEnvironmentMarker::BIND, index);
2256 bind->set_closure(env->closure());
2261 HValue* LookupAndMakeLive(Variable* var) {
2262 HEnvironment* env = environment();
2263 int index = env->IndexFor(var);
2264 HValue* value = env->Lookup(index);
2265 if (IsEligibleForEnvironmentLivenessAnalysis(var, index, value, env)) {
2266 HEnvironmentMarker* lookup =
2267 Add<HEnvironmentMarker>(HEnvironmentMarker::LOOKUP, index);
2270 lookup->set_closure(env->closure());
2276 // The value of the arguments object is allowed in some but not most value
2277 // contexts. (It's allowed in all effect contexts and disallowed in all
2279 void VisitForValue(Expression* expr,
2280 ArgumentsAllowedFlag flag = ARGUMENTS_NOT_ALLOWED);
2281 void VisitForTypeOf(Expression* expr);
2282 void VisitForEffect(Expression* expr);
2283 void VisitForControl(Expression* expr,
2284 HBasicBlock* true_block,
2285 HBasicBlock* false_block);
2287 // Visit a list of expressions from left to right, each in a value context.
2288 void VisitExpressions(ZoneList<Expression*>* exprs);
2290 // Remove the arguments from the bailout environment and emit instructions
2291 // to push them as outgoing parameters.
2292 template <class Instruction> HInstruction* PreProcessCall(Instruction* call);
2293 void PushArgumentsFromEnvironment(int count);
2295 void SetUpScope(Scope* scope);
2296 virtual void VisitStatements(ZoneList<Statement*>* statements) OVERRIDE;
2298 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
2299 AST_NODE_LIST(DECLARE_VISIT)
2300 #undef DECLARE_VISIT
2302 Type* ToType(Handle<Map> map);
2305 // Helpers for flow graph construction.
2306 enum GlobalPropertyAccess {
2310 GlobalPropertyAccess LookupGlobalProperty(Variable* var, LookupIterator* it,
2311 PropertyAccessType access_type);
2313 void EnsureArgumentsArePushedForAccess();
2314 bool TryArgumentsAccess(Property* expr);
2316 // Try to optimize fun.apply(receiver, arguments) pattern.
2317 bool TryCallApply(Call* expr);
2319 bool TryHandleArrayCall(Call* expr, HValue* function);
2320 bool TryHandleArrayCallNew(CallNew* expr, HValue* function);
2321 void BuildArrayCall(Expression* expr, int arguments_count, HValue* function,
2322 Handle<AllocationSite> cell);
2324 enum ArrayIndexOfMode { kFirstIndexOf, kLastIndexOf };
2325 HValue* BuildArrayIndexOf(HValue* receiver,
2326 HValue* search_element,
2328 ArrayIndexOfMode mode);
2330 HValue* ImplicitReceiverFor(HValue* function,
2331 Handle<JSFunction> target);
2333 int InliningAstSize(Handle<JSFunction> target);
2334 bool TryInline(Handle<JSFunction> target,
2335 int arguments_count,
2336 HValue* implicit_return_value,
2338 BailoutId return_id,
2339 InliningKind inlining_kind,
2340 HSourcePosition position);
2342 bool TryInlineCall(Call* expr);
2343 bool TryInlineConstruct(CallNew* expr, HValue* implicit_return_value);
2344 bool TryInlineGetter(Handle<JSFunction> getter,
2345 Handle<Map> receiver_map,
2347 BailoutId return_id);
2348 bool TryInlineSetter(Handle<JSFunction> setter,
2349 Handle<Map> receiver_map,
2351 BailoutId assignment_id,
2352 HValue* implicit_return_value);
2353 bool TryInlineApply(Handle<JSFunction> function,
2355 int arguments_count);
2356 bool TryInlineBuiltinMethodCall(Call* expr,
2358 Handle<Map> receiver_map);
2359 bool TryInlineBuiltinFunctionCall(Call* expr);
2366 bool TryInlineApiMethodCall(Call* expr,
2368 SmallMapList* receiver_types);
2369 bool TryInlineApiFunctionCall(Call* expr, HValue* receiver);
2370 bool TryInlineApiGetter(Handle<JSFunction> function,
2371 Handle<Map> receiver_map,
2373 bool TryInlineApiSetter(Handle<JSFunction> function,
2374 Handle<Map> receiver_map,
2376 bool TryInlineApiCall(Handle<JSFunction> function,
2378 SmallMapList* receiver_maps,
2381 ApiCallType call_type);
2383 // If --trace-inlining, print a line of the inlining trace. Inlining
2384 // succeeded if the reason string is NULL and failed if there is a
2385 // non-NULL reason string.
2386 void TraceInline(Handle<JSFunction> target,
2387 Handle<JSFunction> caller,
2388 const char* failure_reason);
2390 void HandleGlobalVariableAssignment(Variable* var,
2394 void HandlePropertyAssignment(Assignment* expr);
2395 void HandleCompoundAssignment(Assignment* expr);
2396 void HandlePolymorphicNamedFieldAccess(PropertyAccessType access_type,
2399 BailoutId return_id,
2402 SmallMapList* types,
2403 Handle<String> name);
2405 HValue* BuildAllocateExternalElements(
2406 ExternalArrayType array_type,
2407 bool is_zero_byte_offset,
2408 HValue* buffer, HValue* byte_offset, HValue* length);
2409 HValue* BuildAllocateFixedTypedArray(
2410 ExternalArrayType array_type, size_t element_size,
2411 ElementsKind fixed_elements_kind,
2412 HValue* byte_length, HValue* length);
2414 Handle<JSFunction> array_function() {
2415 return handle(isolate()->native_context()->array_function());
2418 bool IsCallArrayInlineable(int argument_count, Handle<AllocationSite> site);
2419 void BuildInlinedCallArray(Expression* expression, int argument_count,
2420 Handle<AllocationSite> site);
2422 class PropertyAccessInfo {
2424 PropertyAccessInfo(HOptimizedGraphBuilder* builder,
2425 PropertyAccessType access_type,
2427 Handle<String> name,
2428 InstanceType instance_type)
2429 : lookup_(builder->isolate()),
2431 access_type_(access_type),
2434 field_type_(HType::Tagged()),
2435 access_(HObjectAccess::ForMap()),
2436 instance_type_(instance_type) { }
2438 // Checkes whether this PropertyAccessInfo can be handled as a monomorphic
2439 // load named. It additionally fills in the fields necessary to generate the
2441 bool CanAccessMonomorphic();
2443 // Checks whether all types behave uniform when loading name. If all maps
2444 // behave the same, a single monomorphic load instruction can be emitted,
2445 // guarded by a single map-checks instruction that whether the receiver is
2446 // an instance of any of the types.
2447 // This method skips the first type in types, assuming that this
2448 // PropertyAccessInfo is built for types->first().
2449 bool CanAccessAsMonomorphic(SmallMapList* types);
2452 Type* type() const { return type_; }
2453 Handle<String> name() const { return name_; }
2455 bool IsJSObjectFieldAccessor() {
2456 int offset; // unused
2457 return Accessors::IsJSObjectFieldAccessor<Type>(type_, name_, &offset);
2460 bool GetJSObjectFieldAccess(HObjectAccess* access) {
2462 if (Accessors::IsJSObjectFieldAccessor<Type>(type_, name_, &offset)) {
2463 if (type_->Is(Type::String())) {
2464 DCHECK(String::Equals(isolate()->factory()->length_string(), name_));
2465 *access = HObjectAccess::ForStringLength();
2466 } else if (type_->Is(Type::Array())) {
2467 DCHECK(String::Equals(isolate()->factory()->length_string(), name_));
2468 *access = HObjectAccess::ForArrayLength(map()->elements_kind());
2470 *access = HObjectAccess::ForMapAndOffset(map(), offset);
2477 bool has_holder() { return !holder_.is_null(); }
2478 bool IsLoad() const { return access_type_ == LOAD; }
2480 Handle<JSObject> holder() { return holder_; }
2481 Handle<JSFunction> accessor() { return accessor_; }
2482 Handle<Object> constant() { return constant_; }
2483 Handle<Map> transition() { return handle(lookup_.GetTransitionTarget()); }
2484 SmallMapList* field_maps() { return &field_maps_; }
2485 HType field_type() const { return field_type_; }
2486 HObjectAccess access() { return access_; }
2488 bool IsFound() const { return lookup_.IsFound(); }
2489 bool IsProperty() const { return lookup_.IsProperty(); }
2490 bool IsField() const { return lookup_.IsField(); }
2491 bool IsConstant() const { return lookup_.IsConstant(); }
2492 bool IsAccessor() const { return lookup_.IsPropertyCallbacks(); }
2493 bool IsTransition() const { return lookup_.IsTransition(); }
2495 bool IsConfigurable() const { return lookup_.IsConfigurable(); }
2496 bool IsReadOnly() const { return lookup_.IsReadOnly(); }
2497 bool IsSIMD128PropertyCallback() {
2498 return (((instance_type_ == Float32x4::kInstanceType ||
2499 instance_type_ == Int32x4::kInstanceType) &&
2500 (name_->Equals(isolate()->heap()->signMask()) ||
2501 name_->Equals(isolate()->heap()->x()) ||
2502 name_->Equals(isolate()->heap()->y()) ||
2503 name_->Equals(isolate()->heap()->z()) ||
2504 name_->Equals(isolate()->heap()->w()))) ||
2505 (instance_type_ == Int32x4::kInstanceType &&
2506 (name_->Equals(isolate()->heap()->flagX()) ||
2507 name_->Equals(isolate()->heap()->flagY()) ||
2508 name_->Equals(isolate()->heap()->flagZ()) ||
2509 name_->Equals(isolate()->heap()->flagW()))) ||
2510 (instance_type_ == Float64x2::kInstanceType &&
2511 (name_->Equals(isolate()->heap()->signMask()) ||
2512 name_->Equals(isolate()->heap()->x()) ||
2513 name_->Equals(isolate()->heap()->y()))));
2517 Handle<Object> GetAccessorsFromMap(Handle<Map> map) const {
2518 return handle(lookup_.GetValueFromMap(*map), isolate());
2520 Handle<Object> GetConstantFromMap(Handle<Map> map) const {
2521 return handle(lookup_.GetConstantFromMap(*map), isolate());
2523 Handle<HeapType> GetFieldTypeFromMap(Handle<Map> map) const {
2524 return handle(lookup_.GetFieldTypeFromMap(*map), isolate());
2526 Handle<Map> GetFieldOwnerFromMap(Handle<Map> map) const {
2527 return handle(lookup_.GetFieldOwnerFromMap(*map));
2529 int GetLocalFieldIndexFromMap(Handle<Map> map) const {
2530 return lookup_.GetLocalFieldIndexFromMap(*map);
2532 Representation representation() const { return lookup_.representation(); }
2534 Type* ToType(Handle<Map> map) { return builder_->ToType(map); }
2535 Zone* zone() { return builder_->zone(); }
2536 Isolate* isolate() const { return lookup_.isolate(); }
2537 CompilationInfo* top_info() { return builder_->top_info(); }
2538 CompilationInfo* current_info() { return builder_->current_info(); }
2540 bool LoadResult(Handle<Map> map);
2541 void LoadFieldMaps(Handle<Map> map);
2542 bool LookupDescriptor();
2543 bool LookupInPrototypes();
2544 bool IsCompatible(PropertyAccessInfo* other);
2546 void GeneralizeRepresentation(Representation r) {
2547 access_ = access_.WithRepresentation(
2548 access_.representation().generalize(r));
2551 LookupResult lookup_;
2552 HOptimizedGraphBuilder* builder_;
2553 PropertyAccessType access_type_;
2555 Handle<String> name_;
2556 Handle<JSObject> holder_;
2557 Handle<JSFunction> accessor_;
2558 Handle<JSObject> api_holder_;
2559 Handle<Object> constant_;
2560 SmallMapList field_maps_;
2562 HObjectAccess access_;
2563 InstanceType instance_type_;
2566 HInstruction* BuildMonomorphicAccess(PropertyAccessInfo* info,
2568 HValue* checked_object,
2571 BailoutId return_id,
2572 bool can_inline_accessor = true);
2574 HInstruction* BuildNamedAccess(PropertyAccessType access,
2576 BailoutId reutrn_id,
2579 Handle<String> name,
2581 bool is_uninitialized = false);
2583 void HandlePolymorphicCallNamed(Call* expr,
2585 SmallMapList* types,
2586 Handle<String> name);
2587 void HandleLiteralCompareTypeof(CompareOperation* expr,
2588 Expression* sub_expr,
2589 Handle<String> check);
2590 void HandleLiteralCompareNil(CompareOperation* expr,
2591 Expression* sub_expr,
2594 enum PushBeforeSimulateBehavior {
2595 PUSH_BEFORE_SIMULATE,
2596 NO_PUSH_BEFORE_SIMULATE
2599 HControlInstruction* BuildCompareInstruction(
2605 Type* combined_type,
2606 HSourcePosition left_position,
2607 HSourcePosition right_position,
2608 PushBeforeSimulateBehavior push_sim_result,
2609 BailoutId bailout_id);
2611 HInstruction* BuildStringCharCodeAt(HValue* string,
2614 HValue* BuildBinaryOperation(
2615 BinaryOperation* expr,
2618 PushBeforeSimulateBehavior push_sim_result);
2619 HInstruction* BuildIncrement(bool returns_original_input,
2620 CountOperation* expr);
2621 HInstruction* BuildKeyedGeneric(PropertyAccessType access_type,
2627 HInstruction* TryBuildConsolidatedElementLoad(HValue* object,
2630 SmallMapList* maps);
2632 LoadKeyedHoleMode BuildKeyedHoleMode(Handle<Map> map);
2634 HInstruction* BuildMonomorphicElementAccess(HValue* object,
2639 PropertyAccessType access_type,
2640 KeyedAccessStoreMode store_mode);
2642 HValue* HandlePolymorphicElementAccess(Expression* expr,
2647 PropertyAccessType access_type,
2648 KeyedAccessStoreMode store_mode,
2649 bool* has_side_effects);
2651 HValue* HandleKeyedElementAccess(HValue* obj, HValue* key, HValue* val,
2652 Expression* expr, BailoutId ast_id,
2653 BailoutId return_id,
2654 PropertyAccessType access_type,
2655 bool* has_side_effects);
2657 HInstruction* BuildNamedGeneric(PropertyAccessType access,
2660 Handle<String> name,
2662 bool is_uninitialized = false);
2664 HCheckMaps* AddCheckMap(HValue* object, Handle<Map> map);
2666 void BuildLoad(Property* property,
2668 void PushLoad(Property* property,
2672 void BuildStoreForEffect(Expression* expression,
2675 BailoutId return_id,
2680 void BuildStore(Expression* expression,
2683 BailoutId return_id,
2684 bool is_uninitialized = false);
2686 HInstruction* BuildLoadNamedField(PropertyAccessInfo* info,
2687 HValue* checked_object);
2688 HInstruction* BuildStoreNamedField(PropertyAccessInfo* info,
2689 HValue* checked_object,
2692 HValue* BuildContextChainWalk(Variable* var);
2694 HInstruction* BuildThisFunction();
2696 HInstruction* BuildFastLiteral(Handle<JSObject> boilerplate_object,
2697 AllocationSiteUsageContext* site_context);
2699 void BuildEmitObjectHeader(Handle<JSObject> boilerplate_object,
2700 HInstruction* object);
2702 void BuildInitElementsInObjectHeader(Handle<JSObject> boilerplate_object,
2703 HInstruction* object,
2704 HInstruction* object_elements);
2706 void BuildEmitInObjectProperties(Handle<JSObject> boilerplate_object,
2707 HInstruction* object,
2708 AllocationSiteUsageContext* site_context,
2709 PretenureFlag pretenure_flag);
2711 void BuildEmitElements(Handle<JSObject> boilerplate_object,
2712 Handle<FixedArrayBase> elements,
2713 HValue* object_elements,
2714 AllocationSiteUsageContext* site_context);
2716 void BuildEmitFixedDoubleArray(Handle<FixedArrayBase> elements,
2718 HValue* object_elements);
2720 void BuildEmitFixedArray(Handle<FixedArrayBase> elements,
2722 HValue* object_elements,
2723 AllocationSiteUsageContext* site_context);
2725 void AddCheckPrototypeMaps(Handle<JSObject> holder,
2726 Handle<Map> receiver_map);
2728 HInstruction* NewPlainFunctionCall(HValue* fun,
2730 bool pass_argument_count);
2732 HInstruction* NewArgumentAdaptorCall(HValue* fun, HValue* context,
2734 HValue* expected_param_count);
2736 HInstruction* BuildCallConstantFunction(Handle<JSFunction> target,
2737 int argument_count);
2739 // The translation state of the currently-being-translated function.
2740 FunctionState* function_state_;
2742 // The base of the function state stack.
2743 FunctionState initial_function_state_;
2745 // Expression context of the currently visited subexpression. NULL when
2746 // visiting statements.
2747 AstContext* ast_context_;
2749 // A stack of breakable statements entered.
2750 BreakAndContinueScope* break_scope_;
2753 ZoneList<Handle<Object> > globals_;
2755 bool inline_bailout_;
2759 friend class FunctionState; // Pushes and pops the state stack.
2760 friend class AstContext; // Pushes and pops the AST context stack.
2761 friend class KeyedLoadFastElementStub;
2762 friend class HOsrBuilder;
2764 DISALLOW_COPY_AND_ASSIGN(HOptimizedGraphBuilder);
2768 Zone* AstContext::zone() const { return owner_->zone(); }
2771 class HStatistics FINAL: public Malloced {
2780 void Initialize(CompilationInfo* info);
2781 void Print(const char* stats_name);
2782 void SaveTiming(const char* name, base::TimeDelta time, unsigned size);
2784 void IncrementFullCodeGen(base::TimeDelta full_code_gen) {
2785 full_code_gen_ += full_code_gen;
2788 void IncrementCreateGraph(base::TimeDelta delta) { create_graph_ += delta; }
2790 void IncrementOptimizeGraph(base::TimeDelta delta) {
2791 optimize_graph_ += delta;
2794 void IncrementGenerateCode(base::TimeDelta delta) { generate_code_ += delta; }
2796 void IncrementSubtotals(base::TimeDelta create_graph,
2797 base::TimeDelta optimize_graph,
2798 base::TimeDelta generate_code) {
2799 IncrementCreateGraph(create_graph);
2800 IncrementOptimizeGraph(optimize_graph);
2801 IncrementGenerateCode(generate_code);
2805 List<base::TimeDelta> times_;
2806 List<const char*> names_;
2807 List<unsigned> sizes_;
2808 base::TimeDelta create_graph_;
2809 base::TimeDelta optimize_graph_;
2810 base::TimeDelta generate_code_;
2811 unsigned total_size_;
2812 base::TimeDelta full_code_gen_;
2813 double source_size_;
2817 class HPhase : public CompilationPhase {
2819 HPhase(const char* name, HGraph* graph)
2820 : CompilationPhase(name, graph->info()),
2825 HGraph* graph() const { return graph_; }
2830 DISALLOW_COPY_AND_ASSIGN(HPhase);
2834 class HTracer FINAL : public Malloced {
2836 explicit HTracer(int isolate_id)
2837 : trace_(&string_allocator_), indent_(0) {
2838 if (FLAG_trace_hydrogen_file == NULL) {
2840 "hydrogen-%d-%d.cfg",
2841 base::OS::GetCurrentProcessId(),
2844 StrNCpy(filename_, FLAG_trace_hydrogen_file, filename_.length());
2846 WriteChars(filename_.start(), "", 0, false);
2849 void TraceCompilation(CompilationInfo* info);
2850 void TraceHydrogen(const char* name, HGraph* graph);
2851 void TraceLithium(const char* name, LChunk* chunk);
2852 void TraceLiveRanges(const char* name, LAllocator* allocator);
2855 class Tag FINAL BASE_EMBEDDED {
2857 Tag(HTracer* tracer, const char* name) {
2860 tracer->PrintIndent();
2861 tracer->trace_.Add("begin_%s\n", name);
2867 tracer_->PrintIndent();
2868 tracer_->trace_.Add("end_%s\n", name_);
2869 DCHECK(tracer_->indent_ >= 0);
2870 tracer_->FlushToFile();
2878 void TraceLiveRange(LiveRange* range, const char* type, Zone* zone);
2879 void Trace(const char* name, HGraph* graph, LChunk* chunk);
2882 void PrintEmptyProperty(const char* name) {
2884 trace_.Add("%s\n", name);
2887 void PrintStringProperty(const char* name, const char* value) {
2889 trace_.Add("%s \"%s\"\n", name, value);
2892 void PrintLongProperty(const char* name, int64_t value) {
2894 trace_.Add("%s %d000\n", name, static_cast<int>(value / 1000));
2897 void PrintBlockProperty(const char* name, int block_id) {
2899 trace_.Add("%s \"B%d\"\n", name, block_id);
2902 void PrintIntProperty(const char* name, int value) {
2904 trace_.Add("%s %d\n", name, value);
2907 void PrintIndent() {
2908 for (int i = 0; i < indent_; i++) {
2913 EmbeddedVector<char, 64> filename_;
2914 HeapStringAllocator string_allocator_;
2915 StringStream trace_;
2920 class NoObservableSideEffectsScope FINAL {
2922 explicit NoObservableSideEffectsScope(HGraphBuilder* builder) :
2924 builder_->graph()->IncrementInNoSideEffectsScope();
2926 ~NoObservableSideEffectsScope() {
2927 builder_->graph()->DecrementInNoSideEffectsScope();
2931 HGraphBuilder* builder_;
2935 } } // namespace v8::internal
2937 #endif // V8_HYDROGEN_H_