6e0ac6253c28107adab5d2cbf0c4949ef00247c0
[platform/upstream/nodejs.git] / deps / v8 / src / full-codegen.h
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.
4
5 #ifndef V8_FULL_CODEGEN_H_
6 #define V8_FULL_CODEGEN_H_
7
8 #include "src/v8.h"
9
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/ast.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
20 namespace v8 {
21 namespace internal {
22
23 // Forward declarations.
24 class JumpPatchSite;
25
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 {
31  public:
32   BreakableStatementChecker(Isolate* isolate, Zone* zone)
33       : is_breakable_(false) {
34     InitializeAstVisitor(isolate, zone);
35   }
36
37   void Check(Statement* stmt);
38   void Check(Expression* stmt);
39
40   bool is_breakable() { return is_breakable_; }
41
42  private:
43   // AST node visit functions.
44 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
45   AST_NODE_LIST(DECLARE_VISIT)
46 #undef DECLARE_VISIT
47
48   bool is_breakable_;
49
50   DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
51   DISALLOW_COPY_AND_ASSIGN(BreakableStatementChecker);
52 };
53
54
55 // -----------------------------------------------------------------------------
56 // Full code generator.
57
58 class FullCodeGenerator: public AstVisitor {
59  public:
60   enum State {
61     NO_REGISTERS,
62     TOS_REG
63   };
64
65   FullCodeGenerator(MacroAssembler* masm, CompilationInfo* info)
66       : masm_(masm),
67         info_(info),
68         scope_(info->scope()),
69         nesting_stack_(NULL),
70         loop_depth_(0),
71         globals_(NULL),
72         context_(NULL),
73         bailout_entries_(info->HasDeoptimizationSupport()
74                          ? info->function()->ast_node_count() : 0,
75                          info->zone()),
76         back_edges_(2, info->zone()),
77         ic_total_count_(0) {
78     DCHECK(!info->IsStub());
79     Initialize();
80   }
81
82   void Initialize();
83
84   static bool MakeCode(CompilationInfo* info);
85
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> { };
90
91   static const char* State2String(State state) {
92     switch (state) {
93       case NO_REGISTERS: return "NO_REGISTERS";
94       case TOS_REG: return "TOS_REG";
95     }
96     UNREACHABLE();
97     return NULL;
98   }
99
100   static const int kMaxBackEdgeWeight = 127;
101
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;
120 #else
121 #error Unsupported target architecture.
122 #endif
123
124  private:
125   class Breakable;
126   class Iteration;
127
128   class TestContext;
129
130   class NestedStatement BASE_EMBEDDED {
131    public:
132     explicit NestedStatement(FullCodeGenerator* codegen) : codegen_(codegen) {
133       // Link into codegen's nesting stack.
134       previous_ = codegen->nesting_stack_;
135       codegen->nesting_stack_ = this;
136     }
137     virtual ~NestedStatement() {
138       // Unlink from codegen's nesting stack.
139       DCHECK_EQ(this, codegen_->nesting_stack_);
140       codegen_->nesting_stack_ = previous_;
141     }
142
143     virtual Breakable* AsBreakable() { return NULL; }
144     virtual Iteration* AsIteration() { return NULL; }
145
146     virtual bool IsContinueTarget(Statement* target) { return false; }
147     virtual bool IsBreakTarget(Statement* target) { return false; }
148
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) {
156       return previous_;
157     }
158
159    protected:
160     MacroAssembler* masm() { return codegen_->masm(); }
161
162     FullCodeGenerator* codegen_;
163     NestedStatement* previous_;
164
165    private:
166     DISALLOW_COPY_AND_ASSIGN(NestedStatement);
167   };
168
169   // A breakable statement such as a block.
170   class Breakable : public NestedStatement {
171    public:
172     Breakable(FullCodeGenerator* codegen, BreakableStatement* statement)
173         : NestedStatement(codegen), statement_(statement) {
174     }
175     virtual ~Breakable() {}
176
177     virtual Breakable* AsBreakable() { return this; }
178     virtual bool IsBreakTarget(Statement* target) {
179       return statement() == target;
180     }
181
182     BreakableStatement* statement() { return statement_; }
183     Label* break_label() { return &break_label_; }
184
185    private:
186     BreakableStatement* statement_;
187     Label break_label_;
188   };
189
190   // An iteration statement such as a while, for, or do loop.
191   class Iteration : public Breakable {
192    public:
193     Iteration(FullCodeGenerator* codegen, IterationStatement* statement)
194         : Breakable(codegen, statement) {
195     }
196     virtual ~Iteration() {}
197
198     virtual Iteration* AsIteration() { return this; }
199     virtual bool IsContinueTarget(Statement* target) {
200       return statement() == target;
201     }
202
203     Label* continue_label() { return &continue_label_; }
204
205    private:
206     Label continue_label_;
207   };
208
209   // A nested block statement.
210   class NestedBlock : public Breakable {
211    public:
212     NestedBlock(FullCodeGenerator* codegen, Block* block)
213         : Breakable(codegen, block) {
214     }
215     virtual ~NestedBlock() {}
216
217     virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
218       if (statement()->AsBlock()->scope() != NULL) {
219         ++(*context_length);
220       }
221       return previous_;
222     }
223   };
224
225   // The try block of a try/catch statement.
226   class TryCatch : public NestedStatement {
227    public:
228     explicit TryCatch(FullCodeGenerator* codegen) : NestedStatement(codegen) {
229     }
230     virtual ~TryCatch() {}
231
232     virtual NestedStatement* Exit(int* stack_depth, int* context_length);
233   };
234
235   // The try block of a try/finally statement.
236   class TryFinally : public NestedStatement {
237    public:
238     TryFinally(FullCodeGenerator* codegen, Label* finally_entry)
239         : NestedStatement(codegen), finally_entry_(finally_entry) {
240     }
241     virtual ~TryFinally() {}
242
243     virtual NestedStatement* Exit(int* stack_depth, int* context_length);
244
245    private:
246     Label* finally_entry_;
247   };
248
249   // The finally block of a try/finally statement.
250   class Finally : public NestedStatement {
251    public:
252     static const int kElementCount = 5;
253
254     explicit Finally(FullCodeGenerator* codegen) : NestedStatement(codegen) { }
255     virtual ~Finally() {}
256
257     virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
258       *stack_depth += kElementCount;
259       return previous_;
260     }
261   };
262
263   // The body of a for/in loop.
264   class ForIn : public Iteration {
265    public:
266     static const int kElementCount = 5;
267
268     ForIn(FullCodeGenerator* codegen, ForInStatement* statement)
269         : Iteration(codegen, statement) {
270     }
271     virtual ~ForIn() {}
272
273     virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
274       *stack_depth += kElementCount;
275       return previous_;
276     }
277   };
278
279
280   // The body of a with or catch.
281   class WithOrCatch : public NestedStatement {
282    public:
283     explicit WithOrCatch(FullCodeGenerator* codegen)
284         : NestedStatement(codegen) {
285     }
286     virtual ~WithOrCatch() {}
287
288     virtual NestedStatement* Exit(int* stack_depth, int* context_length) {
289       ++(*context_length);
290       return previous_;
291     }
292   };
293
294   // Type of a member function that generates inline code for a native function.
295   typedef void (FullCodeGenerator::*InlineFunctionGenerator)(CallRuntime* expr);
296
297   static const InlineFunctionGenerator kInlineFunctionGenerators[];
298
299   // A platform-specific utility to overwrite the accumulator register
300   // with a GC-safe value.
301   void ClearAccumulator();
302
303   // Determine whether or not to inline the smi case for the given
304   // operation.
305   bool ShouldInlineSmiCase(Token::Value op);
306
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,
311               Label* if_true,
312               Label* if_false,
313               Label* fall_through);
314   void DoTest(const TestContext* context);
315
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,
320              Register lhs,
321              const Operand&  rhs,
322              Label* if_true,
323              Label* if_false,
324              Label* fall_through);
325 #elif V8_TARGET_ARCH_MIPS64
326   void Split(Condition cc,
327              Register lhs,
328              const Operand&  rhs,
329              Label* if_true,
330              Label* if_false,
331              Label* fall_through);
332 #elif V8_TARGET_ARCH_PPC
333   void Split(Condition cc, Label* if_true, Label* if_false, Label* fall_through,
334              CRegister cr = cr7);
335 #else  // All other arch.
336   void Split(Condition cc,
337              Label* if_true,
338              Label* if_false,
339              Label* fall_through);
340 #endif
341
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);
346
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,
352               Register source,
353               Register scratch0,
354               Register scratch1);
355
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);
359
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);
365
366   void VisitForEffect(Expression* expr) {
367     EffectContext context(this);
368     Visit(expr);
369     PrepareForBailout(expr, NO_REGISTERS);
370   }
371
372   void VisitForAccumulatorValue(Expression* expr) {
373     AccumulatorValueContext context(this);
374     Visit(expr);
375     PrepareForBailout(expr, TOS_REG);
376   }
377
378   void VisitForStackValue(Expression* expr) {
379     StackValueContext context(this);
380     Visit(expr);
381     PrepareForBailout(expr, NO_REGISTERS);
382   }
383
384   void VisitForControl(Expression* expr,
385                        Label* if_true,
386                        Label* if_false,
387                        Label* fall_through) {
388     TestContext context(this, expr, if_true, if_false, fall_through);
389     Visit(expr);
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
392     // the expression.
393   }
394
395   void VisitInDuplicateContext(Expression* expr);
396
397   void VisitDeclarations(ZoneList<Declaration*>* declarations) OVERRIDE;
398   void DeclareModules(Handle<FixedArray> descriptions);
399   void DeclareGlobals(Handle<FixedArray> pairs);
400   int DeclareGlobalsFlags();
401
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);
406
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);
411
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);
416
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);
422
423   // Platform-specific code for equality comparison with a nil-like value.
424   void EmitLiteralCompareNil(CompareOperation* expr,
425                              Expression* sub_expr,
426                              NilValue nil);
427
428   // Bailout support.
429   void PrepareForBailout(Expression* node, State state);
430   void PrepareForBailoutForId(BailoutId id, State state);
431
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();
436   }
437   void EnsureSlotContainsAllocationSite(FeedbackVectorSlot slot);
438   void EnsureSlotContainsAllocationSite(FeedbackVectorICSlot slot);
439
440   // Returns a smi for the index into the FixedArray that backs the feedback
441   // vector
442   Smi* SmiFromSlot(FeedbackVectorSlot slot) const {
443     return Smi::FromInt(FeedbackVector()->GetIndex(slot));
444   }
445
446   Smi* SmiFromSlot(FeedbackVectorICSlot slot) const {
447     return Smi::FromInt(FeedbackVector()->GetIndex(slot));
448   }
449
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);
453
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,
461                                     Label* if_true,
462                                     Label* if_false);
463
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);
467
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();
478
479   void EmitProfilingCounterDecrement(int delta);
480   void EmitProfilingCounterReset();
481
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();
486
487   // Platform-specific return sequence
488   void EmitReturnSequence();
489
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);
497
498   // Platform-specific code for inline runtime calls.
499   InlineFunctionGenerator FindInlineFunctionGenerator(Runtime::FunctionId id);
500
501   void EmitInlineRuntimeCall(CallRuntime* expr);
502
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
507
508   // Platform-specific code for resuming generators.
509   void EmitGeneratorResume(Expression *generator,
510                            Expression *value,
511                            JSGeneratorObject::ResumeMode resume_mode);
512
513   // Platform-specific code for loading variables.
514   void EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
515                                      TypeofState typeof_state,
516                                      Label* slow);
517   MemOperand ContextSlotOperandCheckExtensions(Variable* var, Label* slow);
518   void EmitDynamicLookupFastCase(VariableProxy* proxy,
519                                  TypeofState typeof_state,
520                                  Label* slow,
521                                  Label* done);
522   void EmitVariableLoad(VariableProxy* proxy);
523
524   void EmitAccessor(Expression* expression);
525
526   // Expects the arguments and the function already pushed.
527   void EmitResolvePossiblyDirectEval(int arg_count);
528
529   // Platform-specific support for allocating a new closure based on
530   // the given function info.
531   void EmitNewClosure(Handle<SharedFunctionInfo> info, bool pretenure);
532
533   // Platform-specific support for compiling assignments.
534
535   // Left-hand side can only be a property, a global or a (parameter or local)
536   // slot.
537   enum LhsKind {
538     VARIABLE,
539     NAMED_PROPERTY,
540     KEYED_PROPERTY,
541     NAMED_SUPER_PROPERTY,
542     KEYED_SUPER_PROPERTY
543   };
544
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);
551   }
552
553   // Load a value from a named property.
554   // The receiver is left on the stack by the IC.
555   void EmitNamedPropertyLoad(Property* expr);
556
557   // Load a value from super.named property.
558   // Expect receiver ('this' value) and home_object on the stack.
559   void EmitNamedSuperPropertyLoad(Property* expr);
560
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);
564
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);
568
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);
573
574   // Pushes the property key as a Name on the stack.
575   void EmitPropertyKey(ObjectLiteralProperty* property, BailoutId bailout_id);
576
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);
580
581   // Helper functions for generating inlined smi code for certain
582   // binary operations.
583   void EmitInlineSmiBinaryOp(BinaryOperation* expr,
584                              Token::Value op,
585                              Expression* left,
586                              Expression* right);
587
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);
591
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;
597
598     if (var->mode() == CONST_LEGACY) {
599       return is_strict(language_mode) && op != Token::INIT_CONST_LEGACY;
600     }
601
602     return false;
603   }
604
605   // Complete a variable assignment.  The right-hand-side value is expected
606   // in the accumulator.
607   void EmitVariableAssignment(Variable* var,
608                               Token::Value op);
609
610   // Helper functions to EmitVariableAssignment
611   void EmitStoreToStackLocalOrContextSlot(Variable* var,
612                                           MemOperand location);
613
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);
617
618   // Complete a super named property assignment. The right-hand-side value
619   // is expected in accumulator.
620   void EmitNamedSuperPropertyStore(Property* prop);
621
622   // Complete a super named property assignment. The right-hand-side value
623   // is expected in accumulator.
624   void EmitKeyedSuperPropertyStore(Property* prop);
625
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
628   // accumulator.
629   void EmitKeyedPropertyAssignment(Assignment* expr);
630
631   void EmitLoadHomeObject(SuperReference* expr);
632
633   static bool NeedsHomeObject(Expression* expr) {
634     return FunctionLiteral::NeedsHomeObject(expr);
635   }
636
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);
641
642   void EmitLoadSuperConstructor();
643   bool ValidateSuperCall(Call* expr);
644
645   void CallIC(Handle<Code> code,
646               TypeFeedbackId id = TypeFeedbackId::None());
647
648   void CallLoadIC(ContextualMode mode,
649                   TypeFeedbackId id = TypeFeedbackId::None());
650   void CallStoreIC(TypeFeedbackId id = TypeFeedbackId::None());
651
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);
657
658   // Non-local control flow support.
659   void EnterFinallyBlock();
660   void ExitFinallyBlock();
661
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);
667     loop_depth_--;
668   }
669
670   MacroAssembler* masm() const { return masm_; }
671
672   class ExpressionContext;
673   const ExpressionContext* context() { return context_; }
674   void set_new_context(const ExpressionContext* context) { context_ = context; }
675
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_; }
683
684   static Register result_register();
685   static Register context_register();
686
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);
690
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);
694
695   // Push the function argument for the runtime functions PushWithContext
696   // and PushCatchContext.
697   void PushFunctionArgumentForContextAllocation();
698
699   // AST node visit functions.
700 #define DECLARE_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
701   AST_NODE_LIST(DECLARE_VISIT)
702 #undef DECLARE_VISIT
703
704   void VisitComma(BinaryOperation* expr);
705   void VisitLogicalExpression(BinaryOperation* expr);
706   void VisitArithmeticExpression(BinaryOperation* expr);
707
708   void VisitForTypeofValue(Expression* expr);
709
710   void Generate();
711   void PopulateDeoptimizationData(Handle<Code> code);
712   void PopulateTypeFeedbackInfo(Handle<Code> code);
713
714   bool MustCreateObjectLiteralWithRuntime(ObjectLiteral* expr) const;
715   bool MustCreateArrayLiteralWithRuntime(ArrayLiteral* expr) const;
716
717   Handle<FixedArray> handler_table() { return handler_table_; }
718
719   struct BailoutEntry {
720     BailoutId id;
721     unsigned pc_and_state;
722   };
723
724   struct BackEdgeEntry {
725     BailoutId id;
726     unsigned pc;
727     uint32_t loop_depth;
728   };
729
730   class ExpressionContext BASE_EMBEDDED {
731    public:
732     explicit ExpressionContext(FullCodeGenerator* codegen)
733         : masm_(codegen->masm()), old_(codegen->context()), codegen_(codegen) {
734       codegen->set_new_context(this);
735     }
736
737     virtual ~ExpressionContext() {
738       codegen_->set_new_context(old_);
739     }
740
741     Isolate* isolate() const { return codegen_->isolate(); }
742
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;
746
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;
755
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;
762
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
765     // context.
766     virtual void DropAndPlug(int count, Register reg) const = 0;
767
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,
772                              Label** if_true,
773                              Label** if_false,
774                              Label** fall_through) const = 0;
775
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; }
779
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; }
783
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; }
787
788    protected:
789     FullCodeGenerator* codegen() const { return codegen_; }
790     MacroAssembler* masm() const { return masm_; }
791     MacroAssembler* masm_;
792
793    private:
794     const ExpressionContext* old_;
795     FullCodeGenerator* codegen_;
796   };
797
798   class AccumulatorValueContext : public ExpressionContext {
799    public:
800     explicit AccumulatorValueContext(FullCodeGenerator* codegen)
801         : ExpressionContext(codegen) { }
802
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,
813                              Label** if_true,
814                              Label** if_false,
815                              Label** fall_through) const;
816     virtual bool IsAccumulatorValue() const { return true; }
817   };
818
819   class StackValueContext : public ExpressionContext {
820    public:
821     explicit StackValueContext(FullCodeGenerator* codegen)
822         : ExpressionContext(codegen) { }
823
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,
834                              Label** if_true,
835                              Label** if_false,
836                              Label** fall_through) const;
837     virtual bool IsStackValue() const { return true; }
838   };
839
840   class TestContext : public ExpressionContext {
841    public:
842     TestContext(FullCodeGenerator* codegen,
843                 Expression* condition,
844                 Label* true_label,
845                 Label* false_label,
846                 Label* fall_through)
847         : ExpressionContext(codegen),
848           condition_(condition),
849           true_label_(true_label),
850           false_label_(false_label),
851           fall_through_(fall_through) { }
852
853     static const TestContext* cast(const ExpressionContext* context) {
854       DCHECK(context->IsTest());
855       return reinterpret_cast<const TestContext*>(context);
856     }
857
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_; }
862
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,
873                              Label** if_true,
874                              Label** if_false,
875                              Label** fall_through) const;
876     virtual bool IsTest() const { return true; }
877
878    private:
879     Expression* condition_;
880     Label* true_label_;
881     Label* false_label_;
882     Label* fall_through_;
883   };
884
885   class EffectContext : public ExpressionContext {
886    public:
887     explicit EffectContext(FullCodeGenerator* codegen)
888         : ExpressionContext(codegen) { }
889
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,
900                              Label** if_true,
901                              Label** if_false,
902                              Label** fall_through) const;
903     virtual bool IsEffect() const { return true; }
904   };
905
906   class EnterBlockScopeIfNeeded {
907    public:
908     EnterBlockScopeIfNeeded(FullCodeGenerator* codegen, Scope* scope,
909                             BailoutId entry_id, BailoutId declarations_id,
910                             BailoutId exit_id);
911     ~EnterBlockScopeIfNeeded();
912
913    private:
914     MacroAssembler* masm() const { return codegen_->masm(); }
915
916     FullCodeGenerator* codegen_;
917     Scope* scope_;
918     Scope* saved_scope_;
919     BailoutId exit_id_;
920   };
921
922   MacroAssembler* masm_;
923   CompilationInfo* info_;
924   Scope* scope_;
925   Label return_label_;
926   NestedStatement* nesting_stack_;
927   int loop_depth_;
928   ZoneList<Handle<Object> >* globals_;
929   Handle<FixedArray> modules_;
930   int module_index_;
931   const ExpressionContext* context_;
932   ZoneList<BailoutEntry> bailout_entries_;
933   ZoneList<BackEdgeEntry> back_edges_;
934   int ic_total_count_;
935   Handle<FixedArray> handler_table_;
936   Handle<Cell> profiling_counter_;
937   bool generate_debug_code_;
938
939   friend class NestedStatement;
940
941   DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
942   DISALLOW_COPY_AND_ASSIGN(FullCodeGenerator);
943 };
944
945
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> {
950  public:
951   explicit AccessorTable(Zone* zone) :
952       TemplateHashMap<Literal, ObjectLiteral::Accessors,
953                       ZoneAllocationPolicy>(Literal::Match,
954                                             ZoneAllocationPolicy(zone)),
955       zone_(zone) { }
956
957   Iterator lookup(Literal* literal) {
958     Iterator it = find(literal, true, ZoneAllocationPolicy(zone_));
959     if (it->second == NULL) it->second = new(zone_) ObjectLiteral::Accessors();
960     return it;
961   }
962
963  private:
964   Zone* zone_;
965 };
966
967
968 class BackEdgeTable {
969  public:
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;
976   }
977
978   uint32_t length() { return length_; }
979
980   BailoutId ast_id(uint32_t index) {
981     return BailoutId(static_cast<int>(
982         Memory::uint32_at(entry_at(index) + kAstIdOffset)));
983   }
984
985   uint32_t loop_depth(uint32_t index) {
986     return Memory::uint32_at(entry_at(index) + kLoopDepthOffset);
987   }
988
989   uint32_t pc_offset(uint32_t index) {
990     return Memory::uint32_at(entry_at(index) + kPcOffsetOffset);
991   }
992
993   Address pc(uint32_t index) {
994     return instruction_start_ + pc_offset(index);
995   }
996
997   enum BackEdgeState {
998     INTERRUPT,
999     ON_STACK_REPLACEMENT,
1000     OSR_AFTER_STACK_CHECK
1001   };
1002
1003   // Increase allowed loop nesting level by one and patch those matching loops.
1004   static void Patch(Isolate* isolate, Code* unoptimized_code);
1005
1006   // Patch the back edge to the target state, provided the correct callee.
1007   static void PatchAt(Code* unoptimized_code,
1008                       Address pc,
1009                       BackEdgeState target_state,
1010                       Code* replacement_code);
1011
1012   // Change all patched back edges back to normal interrupts.
1013   static void Revert(Isolate* isolate,
1014                      Code* unoptimized_code);
1015
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);
1019
1020   // Revert the patch by AddStackCheck.
1021   static void RemoveStackCheck(Handle<Code> code, uint32_t pc_offset);
1022
1023   // Return the current patch state of the back edge.
1024   static BackEdgeState GetBackEdgeState(Isolate* isolate,
1025                                         Code* unoptimized_code,
1026                                         Address pc_after);
1027
1028 #ifdef DEBUG
1029   // Verify that all back edges of a certain loop depth are patched.
1030   static bool Verify(Isolate* isolate, Code* unoptimized_code);
1031 #endif  // DEBUG
1032
1033  private:
1034   Address entry_at(uint32_t index) {
1035     DCHECK(index < length_);
1036     return start_ + index * kEntrySize;
1037   }
1038
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;
1044
1045   Address start_;
1046   Address instruction_start_;
1047   uint32_t length_;
1048 };
1049
1050
1051 } }  // namespace v8::internal
1052
1053 #endif  // V8_FULL_CODEGEN_H_