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.
5 #ifndef V8_FULL_CODEGEN_FULL_CODEGEN_H_
6 #define V8_FULL_CODEGEN_FULL_CODEGEN_H_
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
13 #include "src/bit-vector.h"
14 #include "src/code-stubs.h"
15 #include "src/codegen.h"
16 #include "src/compiler.h"
17 #include "src/globals.h"
18 #include "src/objects.h"
19 #include "src/scopes.h"
24 // Forward declarations.
27 // -----------------------------------------------------------------------------
28 // Full code generator.
30 class FullCodeGenerator: public AstVisitor {
37 FullCodeGenerator(MacroAssembler* masm, CompilationInfo* info)
40 scope_(info->scope()),
46 bailout_entries_(info->HasDeoptimizationSupport()
47 ? info->function()->ast_node_count()
50 back_edges_(2, info->zone()),
51 handler_table_(info->zone()),
53 DCHECK(!info->IsStub());
59 static bool MakeCode(CompilationInfo* info);
61 // Encode state and pc-offset as a BitField<type, start, size>.
62 // Only use 30 bits because we encode the result as a smi.
63 class StateField : public BitField<State, 0, 1> { };
64 class PcField : public BitField<unsigned, 1, 30-1> { };
66 static const char* State2String(State state) {
68 case NO_REGISTERS: return "NO_REGISTERS";
69 case TOS_REG: return "TOS_REG";
75 static const int kMaxBackEdgeWeight = 127;
77 // Platform-specific code size multiplier.
78 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
79 static const int kCodeSizeMultiplier = 105;
80 #elif V8_TARGET_ARCH_X64
81 static const int kCodeSizeMultiplier = 170;
82 #elif V8_TARGET_ARCH_ARM
83 static const int kCodeSizeMultiplier = 149;
84 #elif V8_TARGET_ARCH_ARM64
85 // TODO(all): Copied ARM value. Check this is sensible for ARM64.
86 static const int kCodeSizeMultiplier = 149;
87 #elif V8_TARGET_ARCH_PPC64
88 static const int kCodeSizeMultiplier = 200;
89 #elif V8_TARGET_ARCH_PPC
90 static const int kCodeSizeMultiplier = 200;
91 #elif V8_TARGET_ARCH_MIPS
92 static const int kCodeSizeMultiplier = 149;
93 #elif V8_TARGET_ARCH_MIPS64
94 static const int kCodeSizeMultiplier = 149;
96 #error Unsupported target architecture.
105 class NestedStatement BASE_EMBEDDED {
107 explicit NestedStatement(FullCodeGenerator* codegen) : codegen_(codegen) {
108 // Link into codegen's nesting stack.
109 previous_ = codegen->nesting_stack_;
110 codegen->nesting_stack_ = this;
112 virtual ~NestedStatement() {
113 // Unlink from codegen's nesting stack.
114 DCHECK_EQ(this, codegen_->nesting_stack_);
115 codegen_->nesting_stack_ = previous_;
118 virtual Breakable* AsBreakable() { return NULL; }
119 virtual Iteration* AsIteration() { return NULL; }
121 virtual bool IsContinueTarget(Statement* target) { return false; }
122 virtual bool IsBreakTarget(Statement* target) { return false; }
124 // Notify the statement that we are exiting it via break, continue, or
125 // return and give it a chance to generate cleanup code. Return the
126 // next outer statement in the nesting stack. We accumulate in
127 // *stack_depth the amount to drop the stack and in *context_length the
128 // number of context chain links to unwind as we traverse the nesting
129 // stack from an exit to its target.
130 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
134 // Like the Exit() method above, but limited to accumulating stack depth.
135 virtual NestedStatement* AccumulateDepth(int* stack_depth) {
140 MacroAssembler* masm() { return codegen_->masm(); }
142 FullCodeGenerator* codegen_;
143 NestedStatement* previous_;
146 DISALLOW_COPY_AND_ASSIGN(NestedStatement);
149 // A breakable statement such as a block.
150 class Breakable : public NestedStatement {
152 Breakable(FullCodeGenerator* codegen, BreakableStatement* statement)
153 : NestedStatement(codegen), statement_(statement) {
155 virtual ~Breakable() {}
157 virtual Breakable* AsBreakable() { return this; }
158 virtual bool IsBreakTarget(Statement* target) {
159 return statement() == target;
162 BreakableStatement* statement() { return statement_; }
163 Label* break_label() { return &break_label_; }
166 BreakableStatement* statement_;
170 // An iteration statement such as a while, for, or do loop.
171 class Iteration : public Breakable {
173 Iteration(FullCodeGenerator* codegen, IterationStatement* statement)
174 : Breakable(codegen, statement) {
176 virtual ~Iteration() {}
178 virtual Iteration* AsIteration() { return this; }
179 virtual bool IsContinueTarget(Statement* target) {
180 return statement() == target;
183 Label* continue_label() { return &continue_label_; }
186 Label continue_label_;
189 // A nested block statement.
190 class NestedBlock : public Breakable {
192 NestedBlock(FullCodeGenerator* codegen, Block* block)
193 : Breakable(codegen, block) {
195 virtual ~NestedBlock() {}
197 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
198 auto block_scope = statement()->AsBlock()->scope();
199 if (block_scope != nullptr) {
200 if (block_scope->ContextLocalCount() > 0) ++(*context_length);
206 // The try block of a try/catch statement.
207 class TryCatch : public NestedStatement {
209 static const int kElementCount = TryBlockConstant::kElementCount;
211 explicit TryCatch(FullCodeGenerator* codegen) : NestedStatement(codegen) {}
212 virtual ~TryCatch() {}
214 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
215 *stack_depth += kElementCount;
218 virtual NestedStatement* AccumulateDepth(int* stack_depth) {
219 *stack_depth += kElementCount;
224 // The try block of a try/finally statement.
225 class TryFinally : public NestedStatement {
227 static const int kElementCount = TryBlockConstant::kElementCount;
229 TryFinally(FullCodeGenerator* codegen, Label* finally_entry)
230 : NestedStatement(codegen), finally_entry_(finally_entry) {
232 virtual ~TryFinally() {}
234 virtual NestedStatement* Exit(int* stack_depth, int* context_length);
235 virtual NestedStatement* AccumulateDepth(int* stack_depth) {
236 *stack_depth += kElementCount;
241 Label* finally_entry_;
244 // The finally block of a try/finally statement.
245 class Finally : public NestedStatement {
247 static const int kElementCount = 3;
249 explicit Finally(FullCodeGenerator* codegen) : NestedStatement(codegen) {}
250 virtual ~Finally() {}
252 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
253 *stack_depth += kElementCount;
256 virtual NestedStatement* AccumulateDepth(int* stack_depth) {
257 *stack_depth += kElementCount;
262 // The body of a for/in loop.
263 class ForIn : public Iteration {
265 static const int kElementCount = 5;
267 ForIn(FullCodeGenerator* codegen, ForInStatement* statement)
268 : Iteration(codegen, statement) {
272 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
273 *stack_depth += kElementCount;
276 virtual NestedStatement* AccumulateDepth(int* stack_depth) {
277 *stack_depth += kElementCount;
283 // The body of a with or catch.
284 class WithOrCatch : public NestedStatement {
286 explicit WithOrCatch(FullCodeGenerator* codegen)
287 : NestedStatement(codegen) {
289 virtual ~WithOrCatch() {}
291 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
297 // A platform-specific utility to overwrite the accumulator register
298 // with a GC-safe value.
299 void ClearAccumulator();
301 // Determine whether or not to inline the smi case for the given
303 bool ShouldInlineSmiCase(Token::Value op);
305 // Helper function to convert a pure value into a test context. The value
306 // is expected on the stack or the accumulator, depending on the platform.
307 // See the platform-specific implementation for details.
308 void DoTest(Expression* condition,
311 Label* fall_through);
312 void DoTest(const TestContext* context);
314 // Helper function to split control flow and avoid a branch to the
315 // fall-through label if it is set up.
316 #if V8_TARGET_ARCH_MIPS
317 void Split(Condition cc,
322 Label* fall_through);
323 #elif V8_TARGET_ARCH_MIPS64
324 void Split(Condition cc,
329 Label* fall_through);
330 #elif V8_TARGET_ARCH_PPC
331 void Split(Condition cc, Label* if_true, Label* if_false, Label* fall_through,
333 #else // All other arch.
334 void Split(Condition cc,
337 Label* fall_through);
340 // Load the value of a known (PARAMETER, LOCAL, or CONTEXT) variable into
341 // a register. Emits a context chain walk if if necessary (so does
342 // SetVar) so avoid calling both on the same variable.
343 void GetVar(Register destination, Variable* var);
345 // Assign to a known (PARAMETER, LOCAL, or CONTEXT) variable. If it's in
346 // the context, the write barrier will be emitted and source, scratch0,
347 // scratch1 will be clobbered. Emits a context chain walk if if necessary
348 // (so does GetVar) so avoid calling both on the same variable.
349 void SetVar(Variable* var,
354 // An operand used to read/write a stack-allocated (PARAMETER or LOCAL)
355 // variable. Writing does not need the write barrier.
356 MemOperand StackOperand(Variable* var);
358 // An operand used to read/write a known (PARAMETER, LOCAL, or CONTEXT)
359 // variable. May emit code to traverse the context chain, loading the
360 // found context into the scratch register. Writing to this operand will
361 // need the write barrier if location is CONTEXT.
362 MemOperand VarOperand(Variable* var, Register scratch);
364 void VisitForEffect(Expression* expr) {
365 EffectContext context(this);
367 PrepareForBailout(expr, NO_REGISTERS);
370 void VisitForAccumulatorValue(Expression* expr) {
371 AccumulatorValueContext context(this);
373 PrepareForBailout(expr, TOS_REG);
376 void VisitForStackValue(Expression* expr) {
377 StackValueContext context(this);
379 PrepareForBailout(expr, NO_REGISTERS);
382 void VisitForControl(Expression* expr,
385 Label* fall_through) {
386 TestContext context(this, expr, if_true, if_false, fall_through);
388 // For test contexts, we prepare for bailout before branching, not at
389 // the end of the entire expression. This happens as part of visiting
393 void VisitInDuplicateContext(Expression* expr);
395 void VisitDeclarations(ZoneList<Declaration*>* declarations) override;
396 void DeclareModules(Handle<FixedArray> descriptions);
397 void DeclareGlobals(Handle<FixedArray> pairs);
398 int DeclareGlobalsFlags();
400 // Generate code to create an iterator result object. The "value" property is
401 // set to a value popped from the stack, and "done" is set according to the
402 // argument. The result object is left in the result register.
403 void EmitCreateIteratorResult(bool done);
405 // Try to perform a comparison as a fast inlined literal compare if
406 // the operands allow it. Returns true if the compare operations
407 // has been matched and all code generated; false otherwise.
408 bool TryLiteralCompare(CompareOperation* compare);
410 // Platform-specific code for comparing the type of a value with
411 // a given literal string.
412 void EmitLiteralCompareTypeof(Expression* expr,
413 Expression* sub_expr,
414 Handle<String> check);
416 // Platform-specific code for equality comparison with a nil-like value.
417 void EmitLiteralCompareNil(CompareOperation* expr,
418 Expression* sub_expr,
422 void PrepareForBailout(Expression* node, State state);
423 void PrepareForBailoutForId(BailoutId id, State state);
425 // Feedback slot support. The feedback vector will be cleared during gc and
426 // collected by the type-feedback oracle.
427 Handle<TypeFeedbackVector> FeedbackVector() const {
428 return info_->feedback_vector();
430 void EnsureSlotContainsAllocationSite(FeedbackVectorSlot slot);
431 void EnsureSlotContainsAllocationSite(FeedbackVectorICSlot slot);
433 // Returns a smi for the index into the FixedArray that backs the feedback
435 Smi* SmiFromSlot(FeedbackVectorSlot slot) const {
436 return Smi::FromInt(FeedbackVector()->GetIndex(slot));
439 Smi* SmiFromSlot(FeedbackVectorICSlot slot) const {
440 return Smi::FromInt(FeedbackVector()->GetIndex(slot));
443 // Record a call's return site offset, used to rebuild the frame if the
444 // called function was inlined at the site.
445 void RecordJSReturnSite(Call* call);
447 // Prepare for bailout before a test (or compare) and branch. If
448 // should_normalize, then the following comparison will not handle the
449 // canonical JS true value so we will insert a (dead) test against true at
450 // the actual bailout target from the optimized code. If not
451 // should_normalize, the true and false labels are ignored.
452 void PrepareForBailoutBeforeSplit(Expression* expr,
453 bool should_normalize,
457 // If enabled, emit debug code for checking that the current context is
458 // neither a with nor a catch context.
459 void EmitDebugCheckDeclarationContext(Variable* variable);
461 // This is meant to be called at loop back edges, |back_edge_target| is
462 // the jump target of the back edge and is used to approximate the amount
463 // of code inside the loop.
464 void EmitBackEdgeBookkeeping(IterationStatement* stmt,
465 Label* back_edge_target);
466 // Record the OSR AST id corresponding to a back edge in the code.
467 void RecordBackEdge(BailoutId osr_ast_id);
468 // Emit a table of back edge ids, pcs and loop depths into the code stream.
469 // Return the offset of the start of the table.
470 unsigned EmitBackEdgeTable();
472 void EmitProfilingCounterDecrement(int delta);
473 void EmitProfilingCounterReset();
475 // Emit code to pop values from the stack associated with nested statements
476 // like try/catch, try/finally, etc, running the finallies and unwinding the
477 // handlers as needed.
478 void EmitUnwindBeforeReturn();
480 // Platform-specific return sequence
481 void EmitReturnSequence();
483 // Platform-specific code sequences for calls
484 void EmitCall(Call* expr, CallICState::CallType = CallICState::FUNCTION);
485 void EmitSuperConstructorCall(Call* expr);
486 void EmitCallWithLoadIC(Call* expr);
487 void EmitSuperCallWithLoadIC(Call* expr);
488 void EmitKeyedCallWithLoadIC(Call* expr, Expression* key);
489 void EmitKeyedSuperCallWithLoadIC(Call* expr);
491 #define FOR_EACH_FULL_CODE_INTRINSIC(F) \
493 F(IsNonNegativeSmi) \
500 F(DefaultConstructorCallSuper) \
507 F(StringCharFromCode) \
509 F(OneByteSeqStringSetChar) \
510 F(TwoByteSeqStringSetChar) \
514 F(IsUndetectableObject) \
516 F(IsStringWrapperSafeForDefaultValueOf) \
519 F(HasCachedArrayIndex) \
520 F(GetCachedArrayIndex) \
521 F(FastOneByteArrayJoin) \
524 F(DebugBreakInOptimizedCode) \
526 F(StringCharCodeAt) \
531 F(RegExpConstructResult) \
537 #define GENERATOR_DECLARATION(Name) void Emit##Name(CallRuntime* call);
538 FOR_EACH_FULL_CODE_INTRINSIC(GENERATOR_DECLARATION)
539 #undef GENERATOR_DECLARATION
541 // Platform-specific code for resuming generators.
542 void EmitGeneratorResume(Expression *generator,
544 JSGeneratorObject::ResumeMode resume_mode);
546 // Platform-specific code for loading variables.
547 void EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
548 TypeofMode typeof_mode, Label* slow);
549 MemOperand ContextSlotOperandCheckExtensions(Variable* var, Label* slow);
550 void EmitDynamicLookupFastCase(VariableProxy* proxy, TypeofMode typeof_mode,
551 Label* slow, Label* done);
552 void EmitGlobalVariableLoad(VariableProxy* proxy, TypeofMode typeof_mode);
553 void EmitVariableLoad(VariableProxy* proxy,
554 TypeofMode typeof_mode = NOT_INSIDE_TYPEOF);
556 void EmitAccessor(Expression* expression);
558 // Expects the arguments and the function already pushed.
559 void EmitResolvePossiblyDirectEval(int arg_count);
561 // Platform-specific support for allocating a new closure based on
562 // the given function info.
563 void EmitNewClosure(Handle<SharedFunctionInfo> info, bool pretenure);
565 // Re-usable portions of CallRuntime
566 void EmitLoadJSRuntimeFunction(CallRuntime* expr);
567 void EmitCallJSRuntimeFunction(CallRuntime* expr);
569 // Load a value from a named property.
570 // The receiver is left on the stack by the IC.
571 void EmitNamedPropertyLoad(Property* expr);
573 // Load a value from super.named property.
574 // Expect receiver ('this' value) and home_object on the stack.
575 void EmitNamedSuperPropertyLoad(Property* expr);
577 // Load a value from super[keyed] property.
578 // Expect receiver ('this' value), home_object and key on the stack.
579 void EmitKeyedSuperPropertyLoad(Property* expr);
581 // Load a value from a keyed property.
582 // The receiver and the key is left on the stack by the IC.
583 void EmitKeyedPropertyLoad(Property* expr);
585 // Adds the properties to the class (function) object and to its prototype.
586 // Expects the class (function) in the accumulator. The class (function) is
587 // in the accumulator after installing all the properties.
588 void EmitClassDefineProperties(ClassLiteral* lit, int* used_store_slots);
590 // Pushes the property key as a Name on the stack.
591 void EmitPropertyKey(ObjectLiteralProperty* property, BailoutId bailout_id);
593 // Apply the compound assignment operator. Expects the left operand on top
594 // of the stack and the right one in the accumulator.
595 void EmitBinaryOp(BinaryOperation* expr, Token::Value op);
597 // Helper functions for generating inlined smi code for certain
598 // binary operations.
599 void EmitInlineSmiBinaryOp(BinaryOperation* expr,
604 // Assign to the given expression as if via '='. The right-hand-side value
605 // is expected in the accumulator. slot is only used if FLAG_vector_stores
607 void EmitAssignment(Expression* expr, FeedbackVectorICSlot slot);
609 // Complete a variable assignment. The right-hand-side value is expected
610 // in the accumulator.
611 void EmitVariableAssignment(Variable* var, Token::Value op,
612 FeedbackVectorICSlot slot);
614 // Helper functions to EmitVariableAssignment
615 void EmitStoreToStackLocalOrContextSlot(Variable* var,
616 MemOperand location);
618 // Complete a named property assignment. The receiver is expected on top
619 // of the stack and the right-hand-side value in the accumulator.
620 void EmitNamedPropertyAssignment(Assignment* expr);
622 // Complete a super named property assignment. The right-hand-side value
623 // is expected in accumulator.
624 void EmitNamedSuperPropertyStore(Property* prop);
626 // Complete a super named property assignment. The right-hand-side value
627 // is expected in accumulator.
628 void EmitKeyedSuperPropertyStore(Property* prop);
630 // Complete a keyed property assignment. The receiver and key are
631 // expected on top of the stack and the right-hand-side value in the
633 void EmitKeyedPropertyAssignment(Assignment* expr);
635 static bool NeedsHomeObject(Expression* expr) {
636 return FunctionLiteral::NeedsHomeObject(expr);
639 // Adds the [[HomeObject]] to |initializer| if it is a FunctionLiteral.
640 // The value of the initializer is expected to be at the top of the stack.
641 // |offset| is the offset in the stack where the home object can be found.
642 void EmitSetHomeObjectIfNeeded(
643 Expression* initializer, int offset,
644 FeedbackVectorICSlot slot = FeedbackVectorICSlot::Invalid());
646 void EmitLoadSuperConstructor(SuperCallReference* super_call_ref);
648 void CallIC(Handle<Code> code,
649 TypeFeedbackId id = TypeFeedbackId::None());
651 // Inside typeof reference errors are never thrown.
652 void CallLoadIC(TypeofMode typeof_mode, LanguageMode language_mode = SLOPPY,
653 TypeFeedbackId id = TypeFeedbackId::None());
654 void CallStoreIC(TypeFeedbackId id = TypeFeedbackId::None());
656 void SetFunctionPosition(FunctionLiteral* fun);
657 void SetReturnPosition(FunctionLiteral* fun);
659 enum InsertBreak { INSERT_BREAK, SKIP_BREAK };
661 // During stepping we want to be able to break at each statement, but not at
662 // every (sub-)expression. That is why by default we insert breaks at every
663 // statement position, but not at every expression position, unless stated
665 void SetStatementPosition(Statement* stmt,
666 InsertBreak insert_break = INSERT_BREAK);
667 void SetExpressionPosition(Expression* expr,
668 InsertBreak insert_break = SKIP_BREAK);
670 // Consider an expression a statement. As such, we also insert a break.
671 // This is used in loop headers where we want to break for each iteration.
672 void SetExpressionAsStatementPosition(Expression* expr);
674 void SetCallPosition(Expression* expr, int argc);
676 void SetConstructCallPosition(Expression* expr);
678 // Non-local control flow support.
679 void EnterTryBlock(int handler_index, Label* handler);
680 void ExitTryBlock(int handler_index);
681 void EnterFinallyBlock();
682 void ExitFinallyBlock();
683 void ClearPendingMessage();
685 // Loop nesting counter.
686 int loop_depth() { return loop_depth_; }
687 void increment_loop_depth() { loop_depth_++; }
688 void decrement_loop_depth() {
689 DCHECK(loop_depth_ > 0);
693 MacroAssembler* masm() const { return masm_; }
695 class ExpressionContext;
696 const ExpressionContext* context() { return context_; }
697 void set_new_context(const ExpressionContext* context) { context_ = context; }
699 Handle<Script> script() { return info_->script(); }
700 bool is_eval() { return info_->is_eval(); }
701 bool is_native() { return info_->is_native(); }
702 LanguageMode language_mode() { return function()->language_mode(); }
703 bool is_simple_parameter_list() { return info_->is_simple_parameter_list(); }
704 FunctionLiteral* function() { return info_->function(); }
705 Scope* scope() { return scope_; }
707 static Register result_register();
708 static Register context_register();
710 // Set fields in the stack frame. Offsets are the frame pointer relative
711 // offsets defined in, e.g., StandardFrameConstants.
712 void StoreToFrameField(int frame_offset, Register value);
714 // Load a value from the current context. Indices are defined as an enum
715 // in v8::internal::Context.
716 void LoadContextField(Register dst, int context_index);
718 // Push the function argument for the runtime functions PushWithContext
719 // and PushCatchContext.
720 void PushFunctionArgumentForContextAllocation();
722 void PushCalleeAndWithBaseObject(Call* expr);
724 // AST node visit functions.
725 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) override;
726 AST_NODE_LIST(DECLARE_VISIT)
729 void VisitComma(BinaryOperation* expr);
730 void VisitLogicalExpression(BinaryOperation* expr);
731 void VisitArithmeticExpression(BinaryOperation* expr);
733 void VisitForTypeofValue(Expression* expr);
736 void PopulateDeoptimizationData(Handle<Code> code);
737 void PopulateTypeFeedbackInfo(Handle<Code> code);
738 void PopulateHandlerTable(Handle<Code> code);
740 bool MustCreateObjectLiteralWithRuntime(ObjectLiteral* expr) const;
741 bool MustCreateArrayLiteralWithRuntime(ArrayLiteral* expr) const;
743 void EmitLoadStoreICSlot(FeedbackVectorICSlot slot);
745 int NewHandlerTableEntry();
747 struct BailoutEntry {
749 unsigned pc_and_state;
752 struct BackEdgeEntry {
758 struct HandlerTableEntry {
759 unsigned range_start;
761 unsigned handler_offset;
766 class ExpressionContext BASE_EMBEDDED {
768 explicit ExpressionContext(FullCodeGenerator* codegen)
769 : masm_(codegen->masm()), old_(codegen->context()), codegen_(codegen) {
770 codegen->set_new_context(this);
773 virtual ~ExpressionContext() {
774 codegen_->set_new_context(old_);
777 Isolate* isolate() const { return codegen_->isolate(); }
779 // Convert constant control flow (true or false) to the result expected for
780 // this expression context.
781 virtual void Plug(bool flag) const = 0;
783 // Emit code to convert a pure value (in a register, known variable
784 // location, as a literal, or on top of the stack) into the result
785 // expected according to this expression context.
786 virtual void Plug(Register reg) const = 0;
787 virtual void Plug(Variable* var) const = 0;
788 virtual void Plug(Handle<Object> lit) const = 0;
789 virtual void Plug(Heap::RootListIndex index) const = 0;
790 virtual void PlugTOS() const = 0;
792 // Emit code to convert pure control flow to a pair of unbound labels into
793 // the result expected according to this expression context. The
794 // implementation will bind both labels unless it's a TestContext, which
795 // won't bind them at this point.
796 virtual void Plug(Label* materialize_true,
797 Label* materialize_false) const = 0;
799 // Emit code to discard count elements from the top of stack, then convert
800 // a pure value into the result expected according to this expression
802 virtual void DropAndPlug(int count, Register reg) const = 0;
804 // Set up branch labels for a test expression. The three Label** parameters
805 // are output parameters.
806 virtual void PrepareTest(Label* materialize_true,
807 Label* materialize_false,
810 Label** fall_through) const = 0;
812 // Returns true if we are evaluating only for side effects (i.e. if the
813 // result will be discarded).
814 virtual bool IsEffect() const { return false; }
816 // Returns true if we are evaluating for the value (in accu/on stack).
817 virtual bool IsAccumulatorValue() const { return false; }
818 virtual bool IsStackValue() const { return false; }
820 // Returns true if we are branching on the value rather than materializing
821 // it. Only used for asserts.
822 virtual bool IsTest() const { return false; }
825 FullCodeGenerator* codegen() const { return codegen_; }
826 MacroAssembler* masm() const { return masm_; }
827 MacroAssembler* masm_;
830 const ExpressionContext* old_;
831 FullCodeGenerator* codegen_;
834 class AccumulatorValueContext : public ExpressionContext {
836 explicit AccumulatorValueContext(FullCodeGenerator* codegen)
837 : ExpressionContext(codegen) { }
839 virtual void Plug(bool flag) const;
840 virtual void Plug(Register reg) const;
841 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
842 virtual void Plug(Variable* var) const;
843 virtual void Plug(Handle<Object> lit) const;
844 virtual void Plug(Heap::RootListIndex) const;
845 virtual void PlugTOS() const;
846 virtual void DropAndPlug(int count, Register reg) const;
847 virtual void PrepareTest(Label* materialize_true,
848 Label* materialize_false,
851 Label** fall_through) const;
852 virtual bool IsAccumulatorValue() const { return true; }
855 class StackValueContext : public ExpressionContext {
857 explicit StackValueContext(FullCodeGenerator* codegen)
858 : ExpressionContext(codegen) { }
860 virtual void Plug(bool flag) const;
861 virtual void Plug(Register reg) const;
862 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
863 virtual void Plug(Variable* var) const;
864 virtual void Plug(Handle<Object> lit) const;
865 virtual void Plug(Heap::RootListIndex) const;
866 virtual void PlugTOS() const;
867 virtual void DropAndPlug(int count, Register reg) const;
868 virtual void PrepareTest(Label* materialize_true,
869 Label* materialize_false,
872 Label** fall_through) const;
873 virtual bool IsStackValue() const { return true; }
876 class TestContext : public ExpressionContext {
878 TestContext(FullCodeGenerator* codegen,
879 Expression* condition,
883 : ExpressionContext(codegen),
884 condition_(condition),
885 true_label_(true_label),
886 false_label_(false_label),
887 fall_through_(fall_through) { }
889 static const TestContext* cast(const ExpressionContext* context) {
890 DCHECK(context->IsTest());
891 return reinterpret_cast<const TestContext*>(context);
894 Expression* condition() const { return condition_; }
895 Label* true_label() const { return true_label_; }
896 Label* false_label() const { return false_label_; }
897 Label* fall_through() const { return fall_through_; }
899 virtual void Plug(bool flag) const;
900 virtual void Plug(Register reg) const;
901 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
902 virtual void Plug(Variable* var) const;
903 virtual void Plug(Handle<Object> lit) const;
904 virtual void Plug(Heap::RootListIndex) const;
905 virtual void PlugTOS() const;
906 virtual void DropAndPlug(int count, Register reg) const;
907 virtual void PrepareTest(Label* materialize_true,
908 Label* materialize_false,
911 Label** fall_through) const;
912 virtual bool IsTest() const { return true; }
915 Expression* condition_;
918 Label* fall_through_;
921 class EffectContext : public ExpressionContext {
923 explicit EffectContext(FullCodeGenerator* codegen)
924 : ExpressionContext(codegen) { }
926 virtual void Plug(bool flag) const;
927 virtual void Plug(Register reg) const;
928 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
929 virtual void Plug(Variable* var) const;
930 virtual void Plug(Handle<Object> lit) const;
931 virtual void Plug(Heap::RootListIndex) const;
932 virtual void PlugTOS() const;
933 virtual void DropAndPlug(int count, Register reg) const;
934 virtual void PrepareTest(Label* materialize_true,
935 Label* materialize_false,
938 Label** fall_through) const;
939 virtual bool IsEffect() const { return true; }
942 class EnterBlockScopeIfNeeded {
944 EnterBlockScopeIfNeeded(FullCodeGenerator* codegen, Scope* scope,
945 BailoutId entry_id, BailoutId declarations_id,
947 ~EnterBlockScopeIfNeeded();
950 MacroAssembler* masm() const { return codegen_->masm(); }
952 FullCodeGenerator* codegen_;
955 bool needs_block_context_;
958 MacroAssembler* masm_;
959 CompilationInfo* info_;
962 NestedStatement* nesting_stack_;
964 int try_catch_depth_;
965 ZoneList<Handle<Object> >* globals_;
966 Handle<FixedArray> modules_;
968 const ExpressionContext* context_;
969 ZoneList<BailoutEntry> bailout_entries_;
970 ZoneList<BackEdgeEntry> back_edges_;
971 ZoneVector<HandlerTableEntry> handler_table_;
973 Handle<Cell> profiling_counter_;
974 bool generate_debug_code_;
976 friend class NestedStatement;
978 DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
979 DISALLOW_COPY_AND_ASSIGN(FullCodeGenerator);
983 // A map from property names to getter/setter pairs allocated in the zone.
984 class AccessorTable: public TemplateHashMap<Literal,
985 ObjectLiteral::Accessors,
986 ZoneAllocationPolicy> {
988 explicit AccessorTable(Zone* zone) :
989 TemplateHashMap<Literal, ObjectLiteral::Accessors,
990 ZoneAllocationPolicy>(Literal::Match,
991 ZoneAllocationPolicy(zone)),
994 Iterator lookup(Literal* literal) {
995 Iterator it = find(literal, true, ZoneAllocationPolicy(zone_));
996 if (it->second == NULL) it->second = new(zone_) ObjectLiteral::Accessors();
1005 class BackEdgeTable {
1007 BackEdgeTable(Code* code, DisallowHeapAllocation* required) {
1008 DCHECK(code->kind() == Code::FUNCTION);
1009 instruction_start_ = code->instruction_start();
1010 Address table_address = instruction_start_ + code->back_edge_table_offset();
1011 length_ = Memory::uint32_at(table_address);
1012 start_ = table_address + kTableLengthSize;
1015 uint32_t length() { return length_; }
1017 BailoutId ast_id(uint32_t index) {
1018 return BailoutId(static_cast<int>(
1019 Memory::uint32_at(entry_at(index) + kAstIdOffset)));
1022 uint32_t loop_depth(uint32_t index) {
1023 return Memory::uint32_at(entry_at(index) + kLoopDepthOffset);
1026 uint32_t pc_offset(uint32_t index) {
1027 return Memory::uint32_at(entry_at(index) + kPcOffsetOffset);
1030 Address pc(uint32_t index) {
1031 return instruction_start_ + pc_offset(index);
1034 enum BackEdgeState {
1036 ON_STACK_REPLACEMENT,
1037 OSR_AFTER_STACK_CHECK
1040 // Increase allowed loop nesting level by one and patch those matching loops.
1041 static void Patch(Isolate* isolate, Code* unoptimized_code);
1043 // Patch the back edge to the target state, provided the correct callee.
1044 static void PatchAt(Code* unoptimized_code,
1046 BackEdgeState target_state,
1047 Code* replacement_code);
1049 // Change all patched back edges back to normal interrupts.
1050 static void Revert(Isolate* isolate,
1051 Code* unoptimized_code);
1053 // Change a back edge patched for on-stack replacement to perform a
1054 // stack check first.
1055 static void AddStackCheck(Handle<Code> code, uint32_t pc_offset);
1057 // Revert the patch by AddStackCheck.
1058 static void RemoveStackCheck(Handle<Code> code, uint32_t pc_offset);
1060 // Return the current patch state of the back edge.
1061 static BackEdgeState GetBackEdgeState(Isolate* isolate,
1062 Code* unoptimized_code,
1066 // Verify that all back edges of a certain loop depth are patched.
1067 static bool Verify(Isolate* isolate, Code* unoptimized_code);
1071 Address entry_at(uint32_t index) {
1072 DCHECK(index < length_);
1073 return start_ + index * kEntrySize;
1076 static const int kTableLengthSize = kIntSize;
1077 static const int kAstIdOffset = 0 * kIntSize;
1078 static const int kPcOffsetOffset = 1 * kIntSize;
1079 static const int kLoopDepthOffset = 2 * kIntSize;
1080 static const int kEntrySize = 3 * kIntSize;
1083 Address instruction_start_;
1088 } } // namespace v8::internal
1090 #endif // V8_FULL_CODEGEN_FULL_CODEGEN_H_