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_H_
6 #define V8_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"
23 // Forward declarations.
26 // AST node visitor which can tell whether a given statement will be breakable
27 // when the code is compiled by the full compiler in the debugger. This means
28 // that there will be an IC (load/store/call) in the code generated for the
29 // debugger to piggybag on.
30 class BreakableStatementChecker: public AstVisitor {
32 BreakableStatementChecker(Isolate* isolate, Zone* zone)
33 : is_breakable_(false) {
34 InitializeAstVisitor(isolate, zone);
37 void Check(Statement* stmt);
38 void Check(Expression* stmt);
40 bool is_breakable() { return is_breakable_; }
43 // AST node visit functions.
44 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
45 AST_NODE_LIST(DECLARE_VISIT)
50 DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
51 DISALLOW_COPY_AND_ASSIGN(BreakableStatementChecker);
55 // -----------------------------------------------------------------------------
56 // Full code generator.
58 class FullCodeGenerator: public AstVisitor {
65 FullCodeGenerator(MacroAssembler* masm, CompilationInfo* info)
68 scope_(info->scope()),
73 bailout_entries_(info->HasDeoptimizationSupport()
74 ? info->function()->ast_node_count() : 0,
76 back_edges_(2, info->zone()),
78 DCHECK(!info->IsStub());
84 static bool MakeCode(CompilationInfo* info);
86 // Encode state and pc-offset as a BitField<type, start, size>.
87 // Only use 30 bits because we encode the result as a smi.
88 class StateField : public BitField<State, 0, 1> { };
89 class PcField : public BitField<unsigned, 1, 30-1> { };
91 static const char* State2String(State state) {
93 case NO_REGISTERS: return "NO_REGISTERS";
94 case TOS_REG: return "TOS_REG";
100 static const int kMaxBackEdgeWeight = 127;
102 // Platform-specific code size multiplier.
103 #if V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87
104 static const int kCodeSizeMultiplier = 105;
105 #elif V8_TARGET_ARCH_X64
106 static const int kCodeSizeMultiplier = 170;
107 #elif V8_TARGET_ARCH_ARM
108 static const int kCodeSizeMultiplier = 149;
109 #elif V8_TARGET_ARCH_ARM64
110 // TODO(all): Copied ARM value. Check this is sensible for ARM64.
111 static const int kCodeSizeMultiplier = 149;
112 #elif V8_TARGET_ARCH_PPC64
113 static const int kCodeSizeMultiplier = 200;
114 #elif V8_TARGET_ARCH_PPC
115 static const int kCodeSizeMultiplier = 200;
116 #elif V8_TARGET_ARCH_MIPS
117 static const int kCodeSizeMultiplier = 149;
118 #elif V8_TARGET_ARCH_MIPS64
119 static const int kCodeSizeMultiplier = 149;
121 #error Unsupported target architecture.
130 class NestedStatement BASE_EMBEDDED {
132 explicit NestedStatement(FullCodeGenerator* codegen) : codegen_(codegen) {
133 // Link into codegen's nesting stack.
134 previous_ = codegen->nesting_stack_;
135 codegen->nesting_stack_ = this;
137 virtual ~NestedStatement() {
138 // Unlink from codegen's nesting stack.
139 DCHECK_EQ(this, codegen_->nesting_stack_);
140 codegen_->nesting_stack_ = previous_;
143 virtual Breakable* AsBreakable() { return NULL; }
144 virtual Iteration* AsIteration() { return NULL; }
146 virtual bool IsContinueTarget(Statement* target) { return false; }
147 virtual bool IsBreakTarget(Statement* target) { return false; }
149 // Notify the statement that we are exiting it via break, continue, or
150 // return and give it a chance to generate cleanup code. Return the
151 // next outer statement in the nesting stack. We accumulate in
152 // *stack_depth the amount to drop the stack and in *context_length the
153 // number of context chain links to unwind as we traverse the nesting
154 // stack from an exit to its target.
155 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
160 MacroAssembler* masm() { return codegen_->masm(); }
162 FullCodeGenerator* codegen_;
163 NestedStatement* previous_;
166 DISALLOW_COPY_AND_ASSIGN(NestedStatement);
169 // A breakable statement such as a block.
170 class Breakable : public NestedStatement {
172 Breakable(FullCodeGenerator* codegen, BreakableStatement* statement)
173 : NestedStatement(codegen), statement_(statement) {
175 virtual ~Breakable() {}
177 virtual Breakable* AsBreakable() { return this; }
178 virtual bool IsBreakTarget(Statement* target) {
179 return statement() == target;
182 BreakableStatement* statement() { return statement_; }
183 Label* break_label() { return &break_label_; }
186 BreakableStatement* statement_;
190 // An iteration statement such as a while, for, or do loop.
191 class Iteration : public Breakable {
193 Iteration(FullCodeGenerator* codegen, IterationStatement* statement)
194 : Breakable(codegen, statement) {
196 virtual ~Iteration() {}
198 virtual Iteration* AsIteration() { return this; }
199 virtual bool IsContinueTarget(Statement* target) {
200 return statement() == target;
203 Label* continue_label() { return &continue_label_; }
206 Label continue_label_;
209 // A nested block statement.
210 class NestedBlock : public Breakable {
212 NestedBlock(FullCodeGenerator* codegen, Block* block)
213 : Breakable(codegen, block) {
215 virtual ~NestedBlock() {}
217 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
218 if (statement()->AsBlock()->scope() != NULL) {
225 // The try block of a try/catch statement.
226 class TryCatch : public NestedStatement {
228 explicit TryCatch(FullCodeGenerator* codegen) : NestedStatement(codegen) {
230 virtual ~TryCatch() {}
232 virtual NestedStatement* Exit(int* stack_depth, int* context_length);
235 // The try block of a try/finally statement.
236 class TryFinally : public NestedStatement {
238 TryFinally(FullCodeGenerator* codegen, Label* finally_entry)
239 : NestedStatement(codegen), finally_entry_(finally_entry) {
241 virtual ~TryFinally() {}
243 virtual NestedStatement* Exit(int* stack_depth, int* context_length);
246 Label* finally_entry_;
249 // The finally block of a try/finally statement.
250 class Finally : public NestedStatement {
252 static const int kElementCount = 5;
254 explicit Finally(FullCodeGenerator* codegen) : NestedStatement(codegen) { }
255 virtual ~Finally() {}
257 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
258 *stack_depth += kElementCount;
263 // The body of a for/in loop.
264 class ForIn : public Iteration {
266 static const int kElementCount = 5;
268 ForIn(FullCodeGenerator* codegen, ForInStatement* statement)
269 : Iteration(codegen, statement) {
273 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
274 *stack_depth += kElementCount;
280 // The body of a with or catch.
281 class WithOrCatch : public NestedStatement {
283 explicit WithOrCatch(FullCodeGenerator* codegen)
284 : NestedStatement(codegen) {
286 virtual ~WithOrCatch() {}
288 virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
294 // Type of a member function that generates inline code for a native function.
295 typedef void (FullCodeGenerator::*InlineFunctionGenerator)(CallRuntime* expr);
297 static const InlineFunctionGenerator kInlineFunctionGenerators[];
299 // A platform-specific utility to overwrite the accumulator register
300 // with a GC-safe value.
301 void ClearAccumulator();
303 // Determine whether or not to inline the smi case for the given
305 bool ShouldInlineSmiCase(Token::Value op);
307 // Helper function to convert a pure value into a test context. The value
308 // is expected on the stack or the accumulator, depending on the platform.
309 // See the platform-specific implementation for details.
310 void DoTest(Expression* condition,
313 Label* fall_through);
314 void DoTest(const TestContext* context);
316 // Helper function to split control flow and avoid a branch to the
317 // fall-through label if it is set up.
318 #if V8_TARGET_ARCH_MIPS
319 void Split(Condition cc,
324 Label* fall_through);
325 #elif V8_TARGET_ARCH_MIPS64
326 void Split(Condition cc,
331 Label* fall_through);
332 #elif V8_TARGET_ARCH_PPC
333 void Split(Condition cc, Label* if_true, Label* if_false, Label* fall_through,
335 #else // All other arch.
336 void Split(Condition cc,
339 Label* fall_through);
342 // Load the value of a known (PARAMETER, LOCAL, or CONTEXT) variable into
343 // a register. Emits a context chain walk if if necessary (so does
344 // SetVar) so avoid calling both on the same variable.
345 void GetVar(Register destination, Variable* var);
347 // Assign to a known (PARAMETER, LOCAL, or CONTEXT) variable. If it's in
348 // the context, the write barrier will be emitted and source, scratch0,
349 // scratch1 will be clobbered. Emits a context chain walk if if necessary
350 // (so does GetVar) so avoid calling both on the same variable.
351 void SetVar(Variable* var,
356 // An operand used to read/write a stack-allocated (PARAMETER or LOCAL)
357 // variable. Writing does not need the write barrier.
358 MemOperand StackOperand(Variable* var);
360 // An operand used to read/write a known (PARAMETER, LOCAL, or CONTEXT)
361 // variable. May emit code to traverse the context chain, loading the
362 // found context into the scratch register. Writing to this operand will
363 // need the write barrier if location is CONTEXT.
364 MemOperand VarOperand(Variable* var, Register scratch);
366 void VisitForEffect(Expression* expr) {
367 EffectContext context(this);
369 PrepareForBailout(expr, NO_REGISTERS);
372 void VisitForAccumulatorValue(Expression* expr) {
373 AccumulatorValueContext context(this);
375 PrepareForBailout(expr, TOS_REG);
378 void VisitForStackValue(Expression* expr) {
379 StackValueContext context(this);
381 PrepareForBailout(expr, NO_REGISTERS);
384 void VisitForControl(Expression* expr,
387 Label* fall_through) {
388 TestContext context(this, expr, if_true, if_false, fall_through);
390 // For test contexts, we prepare for bailout before branching, not at
391 // the end of the entire expression. This happens as part of visiting
395 void VisitInDuplicateContext(Expression* expr);
397 void VisitDeclarations(ZoneList<Declaration*>* declarations) OVERRIDE;
398 void DeclareModules(Handle<FixedArray> descriptions);
399 void DeclareGlobals(Handle<FixedArray> pairs);
400 int DeclareGlobalsFlags();
402 // Generate code to allocate all (including nested) modules and contexts.
403 // Because of recursive linking and the presence of module alias declarations,
404 // this has to be a separate pass _before_ populating or executing any module.
405 void AllocateModules(ZoneList<Declaration*>* declarations);
407 // Generate code to create an iterator result object. The "value" property is
408 // set to a value popped from the stack, and "done" is set according to the
409 // argument. The result object is left in the result register.
410 void EmitCreateIteratorResult(bool done);
412 // Try to perform a comparison as a fast inlined literal compare if
413 // the operands allow it. Returns true if the compare operations
414 // has been matched and all code generated; false otherwise.
415 bool TryLiteralCompare(CompareOperation* compare);
417 // Platform-specific code for comparing the type of a value with
418 // a given literal string.
419 void EmitLiteralCompareTypeof(Expression* expr,
420 Expression* sub_expr,
421 Handle<String> check);
423 // Platform-specific code for equality comparison with a nil-like value.
424 void EmitLiteralCompareNil(CompareOperation* expr,
425 Expression* sub_expr,
429 void PrepareForBailout(Expression* node, State state);
430 void PrepareForBailoutForId(BailoutId id, State state);
432 // Feedback slot support. The feedback vector will be cleared during gc and
433 // collected by the type-feedback oracle.
434 Handle<TypeFeedbackVector> FeedbackVector() const {
435 return info_->feedback_vector();
437 void EnsureSlotContainsAllocationSite(FeedbackVectorSlot slot);
438 void EnsureSlotContainsAllocationSite(FeedbackVectorICSlot slot);
440 // Returns a smi for the index into the FixedArray that backs the feedback
442 Smi* SmiFromSlot(FeedbackVectorSlot slot) const {
443 return Smi::FromInt(FeedbackVector()->GetIndex(slot));
446 Smi* SmiFromSlot(FeedbackVectorICSlot slot) const {
447 return Smi::FromInt(FeedbackVector()->GetIndex(slot));
450 // Record a call's return site offset, used to rebuild the frame if the
451 // called function was inlined at the site.
452 void RecordJSReturnSite(Call* call);
454 // Prepare for bailout before a test (or compare) and branch. If
455 // should_normalize, then the following comparison will not handle the
456 // canonical JS true value so we will insert a (dead) test against true at
457 // the actual bailout target from the optimized code. If not
458 // should_normalize, the true and false labels are ignored.
459 void PrepareForBailoutBeforeSplit(Expression* expr,
460 bool should_normalize,
464 // If enabled, emit debug code for checking that the current context is
465 // neither a with nor a catch context.
466 void EmitDebugCheckDeclarationContext(Variable* variable);
468 // This is meant to be called at loop back edges, |back_edge_target| is
469 // the jump target of the back edge and is used to approximate the amount
470 // of code inside the loop.
471 void EmitBackEdgeBookkeeping(IterationStatement* stmt,
472 Label* back_edge_target);
473 // Record the OSR AST id corresponding to a back edge in the code.
474 void RecordBackEdge(BailoutId osr_ast_id);
475 // Emit a table of back edge ids, pcs and loop depths into the code stream.
476 // Return the offset of the start of the table.
477 unsigned EmitBackEdgeTable();
479 void EmitProfilingCounterDecrement(int delta);
480 void EmitProfilingCounterReset();
482 // Emit code to pop values from the stack associated with nested statements
483 // like try/catch, try/finally, etc, running the finallies and unwinding the
484 // handlers as needed.
485 void EmitUnwindBeforeReturn();
487 // Platform-specific return sequence
488 void EmitReturnSequence();
490 // Platform-specific code sequences for calls
491 void EmitCall(Call* expr, CallICState::CallType = CallICState::FUNCTION);
492 void EmitSuperConstructorCall(Call* expr);
493 void EmitCallWithLoadIC(Call* expr);
494 void EmitSuperCallWithLoadIC(Call* expr);
495 void EmitKeyedCallWithLoadIC(Call* expr, Expression* key);
496 void EmitKeyedSuperCallWithLoadIC(Call* expr);
498 // Platform-specific code for inline runtime calls.
499 InlineFunctionGenerator FindInlineFunctionGenerator(Runtime::FunctionId id);
501 void EmitInlineRuntimeCall(CallRuntime* expr);
503 #define EMIT_INLINE_RUNTIME_CALL(name, x, y) \
504 void Emit##name(CallRuntime* expr);
505 INLINE_FUNCTION_LIST(EMIT_INLINE_RUNTIME_CALL)
506 #undef EMIT_INLINE_RUNTIME_CALL
508 // Platform-specific code for resuming generators.
509 void EmitGeneratorResume(Expression *generator,
511 JSGeneratorObject::ResumeMode resume_mode);
513 // Platform-specific code for loading variables.
514 void EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
515 TypeofState typeof_state,
517 MemOperand ContextSlotOperandCheckExtensions(Variable* var, Label* slow);
518 void EmitDynamicLookupFastCase(VariableProxy* proxy,
519 TypeofState typeof_state,
522 void EmitVariableLoad(VariableProxy* proxy);
524 void EmitAccessor(Expression* expression);
526 // Expects the arguments and the function already pushed.
527 void EmitResolvePossiblyDirectEval(int arg_count);
529 // Platform-specific support for allocating a new closure based on
530 // the given function info.
531 void EmitNewClosure(Handle<SharedFunctionInfo> info, bool pretenure);
533 // Platform-specific support for compiling assignments.
535 // Left-hand side can only be a property, a global or a (parameter or local)
541 NAMED_SUPER_PROPERTY,
545 static LhsKind GetAssignType(Property* property) {
546 if (property == NULL) return VARIABLE;
547 bool super_access = property->IsSuperAccess();
548 return (property->key()->IsPropertyName())
549 ? (super_access ? NAMED_SUPER_PROPERTY : NAMED_PROPERTY)
550 : (super_access ? KEYED_SUPER_PROPERTY : KEYED_PROPERTY);
553 // Load a value from a named property.
554 // The receiver is left on the stack by the IC.
555 void EmitNamedPropertyLoad(Property* expr);
557 // Load a value from super.named property.
558 // Expect receiver ('this' value) and home_object on the stack.
559 void EmitNamedSuperPropertyLoad(Property* expr);
561 // Load a value from super[keyed] property.
562 // Expect receiver ('this' value), home_object and key on the stack.
563 void EmitKeyedSuperPropertyLoad(Property* expr);
565 // Load a value from a keyed property.
566 // The receiver and the key is left on the stack by the IC.
567 void EmitKeyedPropertyLoad(Property* expr);
569 // Adds the properties to the class (function) object and to its prototype.
570 // Expects the class (function) in the accumulator. The class (function) is
571 // in the accumulator after installing all the properties.
572 void EmitClassDefineProperties(ClassLiteral* lit);
574 // Pushes the property key as a Name on the stack.
575 void EmitPropertyKey(ObjectLiteralProperty* property, BailoutId bailout_id);
577 // Apply the compound assignment operator. Expects the left operand on top
578 // of the stack and the right one in the accumulator.
579 void EmitBinaryOp(BinaryOperation* expr, Token::Value op);
581 // Helper functions for generating inlined smi code for certain
582 // binary operations.
583 void EmitInlineSmiBinaryOp(BinaryOperation* expr,
588 // Assign to the given expression as if via '='. The right-hand-side value
589 // is expected in the accumulator.
590 void EmitAssignment(Expression* expr);
592 // Shall an error be thrown if assignment with 'op' operation is perfomed
593 // on this variable in given language mode?
594 static bool IsSignallingAssignmentToConst(Variable* var, Token::Value op,
595 LanguageMode language_mode) {
596 if (var->mode() == CONST) return op != Token::INIT_CONST;
598 if (var->mode() == CONST_LEGACY) {
599 return is_strict(language_mode) && op != Token::INIT_CONST_LEGACY;
605 // Complete a variable assignment. The right-hand-side value is expected
606 // in the accumulator.
607 void EmitVariableAssignment(Variable* var,
610 // Helper functions to EmitVariableAssignment
611 void EmitStoreToStackLocalOrContextSlot(Variable* var,
612 MemOperand location);
614 // Complete a named property assignment. The receiver is expected on top
615 // of the stack and the right-hand-side value in the accumulator.
616 void EmitNamedPropertyAssignment(Assignment* expr);
618 // Complete a super named property assignment. The right-hand-side value
619 // is expected in accumulator.
620 void EmitNamedSuperPropertyStore(Property* prop);
622 // Complete a super named property assignment. The right-hand-side value
623 // is expected in accumulator.
624 void EmitKeyedSuperPropertyStore(Property* prop);
626 // Complete a keyed property assignment. The receiver and key are
627 // expected on top of the stack and the right-hand-side value in the
629 void EmitKeyedPropertyAssignment(Assignment* expr);
631 void EmitLoadHomeObject(SuperReference* expr);
633 static bool NeedsHomeObject(Expression* expr) {
634 return FunctionLiteral::NeedsHomeObject(expr);
637 // Adds the [[HomeObject]] to |initializer| if it is a FunctionLiteral.
638 // The value of the initializer is expected to be at the top of the stack.
639 // |offset| is the offset in the stack where the home object can be found.
640 void EmitSetHomeObjectIfNeeded(Expression* initializer, int offset);
642 void EmitLoadSuperConstructor();
643 bool ValidateSuperCall(Call* expr);
645 void CallIC(Handle<Code> code,
646 TypeFeedbackId id = TypeFeedbackId::None());
648 void CallLoadIC(ContextualMode mode,
649 TypeFeedbackId id = TypeFeedbackId::None());
650 void CallStoreIC(TypeFeedbackId id = TypeFeedbackId::None());
652 void SetFunctionPosition(FunctionLiteral* fun);
653 void SetReturnPosition(FunctionLiteral* fun);
654 void SetStatementPosition(Statement* stmt);
655 void SetExpressionPosition(Expression* expr);
656 void SetSourcePosition(int pos);
658 // Non-local control flow support.
659 void EnterFinallyBlock();
660 void ExitFinallyBlock();
662 // Loop nesting counter.
663 int loop_depth() { return loop_depth_; }
664 void increment_loop_depth() { loop_depth_++; }
665 void decrement_loop_depth() {
666 DCHECK(loop_depth_ > 0);
670 MacroAssembler* masm() const { return masm_; }
672 class ExpressionContext;
673 const ExpressionContext* context() { return context_; }
674 void set_new_context(const ExpressionContext* context) { context_ = context; }
676 Handle<Script> script() { return info_->script(); }
677 bool is_eval() { return info_->is_eval(); }
678 bool is_native() { return info_->is_native(); }
679 LanguageMode language_mode() { return function()->language_mode(); }
680 bool is_simple_parameter_list() { return info_->is_simple_parameter_list(); }
681 FunctionLiteral* function() { return info_->function(); }
682 Scope* scope() { return scope_; }
684 static Register result_register();
685 static Register context_register();
687 // Set fields in the stack frame. Offsets are the frame pointer relative
688 // offsets defined in, e.g., StandardFrameConstants.
689 void StoreToFrameField(int frame_offset, Register value);
691 // Load a value from the current context. Indices are defined as an enum
692 // in v8::internal::Context.
693 void LoadContextField(Register dst, int context_index);
695 // Push the function argument for the runtime functions PushWithContext
696 // and PushCatchContext.
697 void PushFunctionArgumentForContextAllocation();
699 // AST node visit functions.
700 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
701 AST_NODE_LIST(DECLARE_VISIT)
704 void VisitComma(BinaryOperation* expr);
705 void VisitLogicalExpression(BinaryOperation* expr);
706 void VisitArithmeticExpression(BinaryOperation* expr);
708 void VisitForTypeofValue(Expression* expr);
711 void PopulateDeoptimizationData(Handle<Code> code);
712 void PopulateTypeFeedbackInfo(Handle<Code> code);
714 bool MustCreateObjectLiteralWithRuntime(ObjectLiteral* expr) const;
715 bool MustCreateArrayLiteralWithRuntime(ArrayLiteral* expr) const;
717 Handle<FixedArray> handler_table() { return handler_table_; }
719 struct BailoutEntry {
721 unsigned pc_and_state;
724 struct BackEdgeEntry {
730 class ExpressionContext BASE_EMBEDDED {
732 explicit ExpressionContext(FullCodeGenerator* codegen)
733 : masm_(codegen->masm()), old_(codegen->context()), codegen_(codegen) {
734 codegen->set_new_context(this);
737 virtual ~ExpressionContext() {
738 codegen_->set_new_context(old_);
741 Isolate* isolate() const { return codegen_->isolate(); }
743 // Convert constant control flow (true or false) to the result expected for
744 // this expression context.
745 virtual void Plug(bool flag) const = 0;
747 // Emit code to convert a pure value (in a register, known variable
748 // location, as a literal, or on top of the stack) into the result
749 // expected according to this expression context.
750 virtual void Plug(Register reg) const = 0;
751 virtual void Plug(Variable* var) const = 0;
752 virtual void Plug(Handle<Object> lit) const = 0;
753 virtual void Plug(Heap::RootListIndex index) const = 0;
754 virtual void PlugTOS() const = 0;
756 // Emit code to convert pure control flow to a pair of unbound labels into
757 // the result expected according to this expression context. The
758 // implementation will bind both labels unless it's a TestContext, which
759 // won't bind them at this point.
760 virtual void Plug(Label* materialize_true,
761 Label* materialize_false) const = 0;
763 // Emit code to discard count elements from the top of stack, then convert
764 // a pure value into the result expected according to this expression
766 virtual void DropAndPlug(int count, Register reg) const = 0;
768 // Set up branch labels for a test expression. The three Label** parameters
769 // are output parameters.
770 virtual void PrepareTest(Label* materialize_true,
771 Label* materialize_false,
774 Label** fall_through) const = 0;
776 // Returns true if we are evaluating only for side effects (i.e. if the
777 // result will be discarded).
778 virtual bool IsEffect() const { return false; }
780 // Returns true if we are evaluating for the value (in accu/on stack).
781 virtual bool IsAccumulatorValue() const { return false; }
782 virtual bool IsStackValue() const { return false; }
784 // Returns true if we are branching on the value rather than materializing
785 // it. Only used for asserts.
786 virtual bool IsTest() const { return false; }
789 FullCodeGenerator* codegen() const { return codegen_; }
790 MacroAssembler* masm() const { return masm_; }
791 MacroAssembler* masm_;
794 const ExpressionContext* old_;
795 FullCodeGenerator* codegen_;
798 class AccumulatorValueContext : public ExpressionContext {
800 explicit AccumulatorValueContext(FullCodeGenerator* codegen)
801 : ExpressionContext(codegen) { }
803 virtual void Plug(bool flag) const;
804 virtual void Plug(Register reg) const;
805 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
806 virtual void Plug(Variable* var) const;
807 virtual void Plug(Handle<Object> lit) const;
808 virtual void Plug(Heap::RootListIndex) const;
809 virtual void PlugTOS() const;
810 virtual void DropAndPlug(int count, Register reg) const;
811 virtual void PrepareTest(Label* materialize_true,
812 Label* materialize_false,
815 Label** fall_through) const;
816 virtual bool IsAccumulatorValue() const { return true; }
819 class StackValueContext : public ExpressionContext {
821 explicit StackValueContext(FullCodeGenerator* codegen)
822 : ExpressionContext(codegen) { }
824 virtual void Plug(bool flag) const;
825 virtual void Plug(Register reg) const;
826 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
827 virtual void Plug(Variable* var) const;
828 virtual void Plug(Handle<Object> lit) const;
829 virtual void Plug(Heap::RootListIndex) const;
830 virtual void PlugTOS() const;
831 virtual void DropAndPlug(int count, Register reg) const;
832 virtual void PrepareTest(Label* materialize_true,
833 Label* materialize_false,
836 Label** fall_through) const;
837 virtual bool IsStackValue() const { return true; }
840 class TestContext : public ExpressionContext {
842 TestContext(FullCodeGenerator* codegen,
843 Expression* condition,
847 : ExpressionContext(codegen),
848 condition_(condition),
849 true_label_(true_label),
850 false_label_(false_label),
851 fall_through_(fall_through) { }
853 static const TestContext* cast(const ExpressionContext* context) {
854 DCHECK(context->IsTest());
855 return reinterpret_cast<const TestContext*>(context);
858 Expression* condition() const { return condition_; }
859 Label* true_label() const { return true_label_; }
860 Label* false_label() const { return false_label_; }
861 Label* fall_through() const { return fall_through_; }
863 virtual void Plug(bool flag) const;
864 virtual void Plug(Register reg) const;
865 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
866 virtual void Plug(Variable* var) const;
867 virtual void Plug(Handle<Object> lit) const;
868 virtual void Plug(Heap::RootListIndex) const;
869 virtual void PlugTOS() const;
870 virtual void DropAndPlug(int count, Register reg) const;
871 virtual void PrepareTest(Label* materialize_true,
872 Label* materialize_false,
875 Label** fall_through) const;
876 virtual bool IsTest() const { return true; }
879 Expression* condition_;
882 Label* fall_through_;
885 class EffectContext : public ExpressionContext {
887 explicit EffectContext(FullCodeGenerator* codegen)
888 : ExpressionContext(codegen) { }
890 virtual void Plug(bool flag) const;
891 virtual void Plug(Register reg) const;
892 virtual void Plug(Label* materialize_true, Label* materialize_false) const;
893 virtual void Plug(Variable* var) const;
894 virtual void Plug(Handle<Object> lit) const;
895 virtual void Plug(Heap::RootListIndex) const;
896 virtual void PlugTOS() const;
897 virtual void DropAndPlug(int count, Register reg) const;
898 virtual void PrepareTest(Label* materialize_true,
899 Label* materialize_false,
902 Label** fall_through) const;
903 virtual bool IsEffect() const { return true; }
906 class EnterBlockScopeIfNeeded {
908 EnterBlockScopeIfNeeded(FullCodeGenerator* codegen, Scope* scope,
909 BailoutId entry_id, BailoutId declarations_id,
911 ~EnterBlockScopeIfNeeded();
914 MacroAssembler* masm() const { return codegen_->masm(); }
916 FullCodeGenerator* codegen_;
922 MacroAssembler* masm_;
923 CompilationInfo* info_;
926 NestedStatement* nesting_stack_;
928 ZoneList<Handle<Object> >* globals_;
929 Handle<FixedArray> modules_;
931 const ExpressionContext* context_;
932 ZoneList<BailoutEntry> bailout_entries_;
933 ZoneList<BackEdgeEntry> back_edges_;
935 Handle<FixedArray> handler_table_;
936 Handle<Cell> profiling_counter_;
937 bool generate_debug_code_;
939 friend class NestedStatement;
941 DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
942 DISALLOW_COPY_AND_ASSIGN(FullCodeGenerator);
946 // A map from property names to getter/setter pairs allocated in the zone.
947 class AccessorTable: public TemplateHashMap<Literal,
948 ObjectLiteral::Accessors,
949 ZoneAllocationPolicy> {
951 explicit AccessorTable(Zone* zone) :
952 TemplateHashMap<Literal, ObjectLiteral::Accessors,
953 ZoneAllocationPolicy>(Literal::Match,
954 ZoneAllocationPolicy(zone)),
957 Iterator lookup(Literal* literal) {
958 Iterator it = find(literal, true, ZoneAllocationPolicy(zone_));
959 if (it->second == NULL) it->second = new(zone_) ObjectLiteral::Accessors();
968 class BackEdgeTable {
970 BackEdgeTable(Code* code, DisallowHeapAllocation* required) {
971 DCHECK(code->kind() == Code::FUNCTION);
972 instruction_start_ = code->instruction_start();
973 Address table_address = instruction_start_ + code->back_edge_table_offset();
974 length_ = Memory::uint32_at(table_address);
975 start_ = table_address + kTableLengthSize;
978 uint32_t length() { return length_; }
980 BailoutId ast_id(uint32_t index) {
981 return BailoutId(static_cast<int>(
982 Memory::uint32_at(entry_at(index) + kAstIdOffset)));
985 uint32_t loop_depth(uint32_t index) {
986 return Memory::uint32_at(entry_at(index) + kLoopDepthOffset);
989 uint32_t pc_offset(uint32_t index) {
990 return Memory::uint32_at(entry_at(index) + kPcOffsetOffset);
993 Address pc(uint32_t index) {
994 return instruction_start_ + pc_offset(index);
999 ON_STACK_REPLACEMENT,
1000 OSR_AFTER_STACK_CHECK
1003 // Increase allowed loop nesting level by one and patch those matching loops.
1004 static void Patch(Isolate* isolate, Code* unoptimized_code);
1006 // Patch the back edge to the target state, provided the correct callee.
1007 static void PatchAt(Code* unoptimized_code,
1009 BackEdgeState target_state,
1010 Code* replacement_code);
1012 // Change all patched back edges back to normal interrupts.
1013 static void Revert(Isolate* isolate,
1014 Code* unoptimized_code);
1016 // Change a back edge patched for on-stack replacement to perform a
1017 // stack check first.
1018 static void AddStackCheck(Handle<Code> code, uint32_t pc_offset);
1020 // Revert the patch by AddStackCheck.
1021 static void RemoveStackCheck(Handle<Code> code, uint32_t pc_offset);
1023 // Return the current patch state of the back edge.
1024 static BackEdgeState GetBackEdgeState(Isolate* isolate,
1025 Code* unoptimized_code,
1029 // Verify that all back edges of a certain loop depth are patched.
1030 static bool Verify(Isolate* isolate, Code* unoptimized_code);
1034 Address entry_at(uint32_t index) {
1035 DCHECK(index < length_);
1036 return start_ + index * kEntrySize;
1039 static const int kTableLengthSize = kIntSize;
1040 static const int kAstIdOffset = 0 * kIntSize;
1041 static const int kPcOffsetOffset = 1 * kIntSize;
1042 static const int kLoopDepthOffset = 2 * kIntSize;
1043 static const int kEntrySize = 3 * kIntSize;
1046 Address instruction_start_;
1051 } } // namespace v8::internal
1053 #endif // V8_FULL_CODEGEN_H_