Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / v8 / src / full-codegen.cc
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 #include "src/v8.h"
6
7 #include "src/code-factory.h"
8 #include "src/codegen.h"
9 #include "src/compiler.h"
10 #include "src/debug.h"
11 #include "src/full-codegen.h"
12 #include "src/liveedit.h"
13 #include "src/macro-assembler.h"
14 #include "src/prettyprinter.h"
15 #include "src/scopeinfo.h"
16 #include "src/scopes.h"
17 #include "src/snapshot.h"
18
19 namespace v8 {
20 namespace internal {
21
22 void BreakableStatementChecker::Check(Statement* stmt) {
23   Visit(stmt);
24 }
25
26
27 void BreakableStatementChecker::Check(Expression* expr) {
28   Visit(expr);
29 }
30
31
32 void BreakableStatementChecker::VisitVariableDeclaration(
33     VariableDeclaration* decl) {
34 }
35
36
37 void BreakableStatementChecker::VisitFunctionDeclaration(
38     FunctionDeclaration* decl) {
39 }
40
41
42 void BreakableStatementChecker::VisitModuleDeclaration(
43     ModuleDeclaration* decl) {
44 }
45
46
47 void BreakableStatementChecker::VisitImportDeclaration(
48     ImportDeclaration* decl) {
49 }
50
51
52 void BreakableStatementChecker::VisitExportDeclaration(
53     ExportDeclaration* decl) {
54 }
55
56
57 void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
58 }
59
60
61 void BreakableStatementChecker::VisitModuleVariable(ModuleVariable* module) {
62 }
63
64
65 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
66 }
67
68
69 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
70 }
71
72
73 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
74 }
75
76
77 void BreakableStatementChecker::VisitBlock(Block* stmt) {
78 }
79
80
81 void BreakableStatementChecker::VisitExpressionStatement(
82     ExpressionStatement* stmt) {
83   // Check if expression is breakable.
84   Visit(stmt->expression());
85 }
86
87
88 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
89 }
90
91
92 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
93   // If the condition is breakable the if statement is breakable.
94   Visit(stmt->condition());
95 }
96
97
98 void BreakableStatementChecker::VisitContinueStatement(
99     ContinueStatement* stmt) {
100 }
101
102
103 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
104 }
105
106
107 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
108   // Return is breakable if the expression is.
109   Visit(stmt->expression());
110 }
111
112
113 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
114   Visit(stmt->expression());
115 }
116
117
118 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
119   // Switch statements breakable if the tag expression is.
120   Visit(stmt->tag());
121 }
122
123
124 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
125   // Mark do while as breakable to avoid adding a break slot in front of it.
126   is_breakable_ = true;
127 }
128
129
130 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
131   // Mark while statements breakable if the condition expression is.
132   Visit(stmt->cond());
133 }
134
135
136 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
137   // Mark for statements breakable if the condition expression is.
138   if (stmt->cond() != NULL) {
139     Visit(stmt->cond());
140   }
141 }
142
143
144 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
145   // Mark for in statements breakable if the enumerable expression is.
146   Visit(stmt->enumerable());
147 }
148
149
150 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
151   // For-of is breakable because of the next() call.
152   is_breakable_ = true;
153 }
154
155
156 void BreakableStatementChecker::VisitTryCatchStatement(
157     TryCatchStatement* stmt) {
158   // Mark try catch as breakable to avoid adding a break slot in front of it.
159   is_breakable_ = true;
160 }
161
162
163 void BreakableStatementChecker::VisitTryFinallyStatement(
164     TryFinallyStatement* stmt) {
165   // Mark try finally as breakable to avoid adding a break slot in front of it.
166   is_breakable_ = true;
167 }
168
169
170 void BreakableStatementChecker::VisitDebuggerStatement(
171     DebuggerStatement* stmt) {
172   // The debugger statement is breakable.
173   is_breakable_ = true;
174 }
175
176
177 void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
178 }
179
180
181 void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
182 }
183
184
185 void BreakableStatementChecker::VisitClassLiteral(ClassLiteral* expr) {
186   if (expr->extends() != NULL) {
187     Visit(expr->extends());
188   }
189 }
190
191
192 void BreakableStatementChecker::VisitNativeFunctionLiteral(
193     NativeFunctionLiteral* expr) {
194 }
195
196
197 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
198 }
199
200
201 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
202 }
203
204
205 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
206 }
207
208
209 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
210 }
211
212
213 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
214 }
215
216
217 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
218 }
219
220
221 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
222   // If assigning to a property (including a global property) the assignment is
223   // breakable.
224   VariableProxy* proxy = expr->target()->AsVariableProxy();
225   Property* prop = expr->target()->AsProperty();
226   if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
227     is_breakable_ = true;
228     return;
229   }
230
231   // Otherwise the assignment is breakable if the assigned value is.
232   Visit(expr->value());
233 }
234
235
236 void BreakableStatementChecker::VisitYield(Yield* expr) {
237   // Yield is breakable if the expression is.
238   Visit(expr->expression());
239 }
240
241
242 void BreakableStatementChecker::VisitThrow(Throw* expr) {
243   // Throw is breakable if the expression is.
244   Visit(expr->exception());
245 }
246
247
248 void BreakableStatementChecker::VisitProperty(Property* expr) {
249   // Property load is breakable.
250   is_breakable_ = true;
251 }
252
253
254 void BreakableStatementChecker::VisitCall(Call* expr) {
255   // Function calls both through IC and call stub are breakable.
256   is_breakable_ = true;
257 }
258
259
260 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
261   // Function calls through new are breakable.
262   is_breakable_ = true;
263 }
264
265
266 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
267 }
268
269
270 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
271   Visit(expr->expression());
272 }
273
274
275 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
276   Visit(expr->expression());
277 }
278
279
280 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
281   Visit(expr->left());
282   if (expr->op() != Token::AND &&
283       expr->op() != Token::OR) {
284     Visit(expr->right());
285   }
286 }
287
288
289 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
290   Visit(expr->left());
291   Visit(expr->right());
292 }
293
294
295 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
296 }
297
298
299 void BreakableStatementChecker::VisitSuperReference(SuperReference* expr) {}
300
301
302 #define __ ACCESS_MASM(masm())
303
304 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
305   Isolate* isolate = info->isolate();
306
307   TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
308
309   Handle<Script> script = info->script();
310   if (!script->IsUndefined() && !script->source()->IsUndefined()) {
311     int len = String::cast(script->source())->length();
312     isolate->counters()->total_full_codegen_source_size()->Increment(len);
313   }
314   CodeGenerator::MakeCodePrologue(info, "full");
315   const int kInitialBufferSize = 4 * KB;
316   MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
317   if (info->will_serialize()) masm.enable_serializer();
318
319   LOG_CODE_EVENT(isolate,
320                  CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
321
322   FullCodeGenerator cgen(&masm, info);
323   cgen.Generate();
324   if (cgen.HasStackOverflow()) {
325     DCHECK(!isolate->has_pending_exception());
326     return false;
327   }
328   unsigned table_offset = cgen.EmitBackEdgeTable();
329
330   Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
331   Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
332   code->set_optimizable(info->IsOptimizable() &&
333                         !info->function()->dont_optimize() &&
334                         info->function()->scope()->AllowsLazyCompilation());
335   cgen.PopulateDeoptimizationData(code);
336   cgen.PopulateTypeFeedbackInfo(code);
337   code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
338   code->set_handler_table(*cgen.handler_table());
339   code->set_compiled_optimizable(info->IsOptimizable());
340   code->set_allow_osr_at_loop_nesting_level(0);
341   code->set_profiler_ticks(0);
342   code->set_back_edge_table_offset(table_offset);
343   CodeGenerator::PrintCode(code, info);
344   info->SetCode(code);
345   void* line_info = masm.positions_recorder()->DetachJITHandlerData();
346   LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
347   return true;
348 }
349
350
351 unsigned FullCodeGenerator::EmitBackEdgeTable() {
352   // The back edge table consists of a length (in number of entries)
353   // field, and then a sequence of entries.  Each entry is a pair of AST id
354   // and code-relative pc offset.
355   masm()->Align(kPointerSize);
356   unsigned offset = masm()->pc_offset();
357   unsigned length = back_edges_.length();
358   __ dd(length);
359   for (unsigned i = 0; i < length; ++i) {
360     __ dd(back_edges_[i].id.ToInt());
361     __ dd(back_edges_[i].pc);
362     __ dd(back_edges_[i].loop_depth);
363   }
364   return offset;
365 }
366
367
368 void FullCodeGenerator::EnsureSlotContainsAllocationSite(int slot) {
369   Handle<FixedArray> vector = FeedbackVector();
370   if (!vector->get(slot)->IsAllocationSite()) {
371     Handle<AllocationSite> allocation_site =
372         isolate()->factory()->NewAllocationSite();
373     vector->set(slot, *allocation_site);
374   }
375 }
376
377
378 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
379   // Fill in the deoptimization information.
380   DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
381   if (!info_->HasDeoptimizationSupport()) return;
382   int length = bailout_entries_.length();
383   Handle<DeoptimizationOutputData> data =
384       DeoptimizationOutputData::New(isolate(), length, TENURED);
385   for (int i = 0; i < length; i++) {
386     data->SetAstId(i, bailout_entries_[i].id);
387     data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
388   }
389   code->set_deoptimization_data(*data);
390 }
391
392
393 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
394   Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
395   info->set_ic_total_count(ic_total_count_);
396   DCHECK(!isolate()->heap()->InNewSpace(*info));
397   code->set_type_feedback_info(*info);
398 }
399
400
401 void FullCodeGenerator::Initialize() {
402   InitializeAstVisitor(info_->zone());
403   // The generation of debug code must match between the snapshot code and the
404   // code that is generated later.  This is assumed by the debugger when it is
405   // calculating PC offsets after generating a debug version of code.  Therefore
406   // we disable the production of debug code in the full compiler if we are
407   // either generating a snapshot or we booted from a snapshot.
408   generate_debug_code_ = FLAG_debug_code &&
409                          !masm_->serializer_enabled() &&
410                          !Snapshot::HaveASnapshotToStartFrom();
411   masm_->set_emit_debug_code(generate_debug_code_);
412   masm_->set_predictable_code_size(true);
413 }
414
415
416 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
417   PrepareForBailoutForId(node->id(), state);
418 }
419
420
421 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
422                                    TypeFeedbackId id) {
423   Handle<Code> ic = CodeFactory::LoadIC(isolate(), contextual_mode).code();
424   CallIC(ic, id);
425 }
426
427
428 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
429   Handle<Code> ic = CodeFactory::StoreIC(isolate(), strict_mode()).code();
430   CallIC(ic, id);
431 }
432
433
434 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
435   // We record the offset of the function return so we can rebuild the frame
436   // if the function was inlined, i.e., this is the return address in the
437   // inlined function's frame.
438   //
439   // The state is ignored.  We defensively set it to TOS_REG, which is the
440   // real state of the unoptimized code at the return site.
441   PrepareForBailoutForId(call->ReturnId(), TOS_REG);
442 #ifdef DEBUG
443   // In debug builds, mark the return so we can verify that this function
444   // was called.
445   DCHECK(!call->return_is_recorded_);
446   call->return_is_recorded_ = true;
447 #endif
448 }
449
450
451 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
452   // There's no need to prepare this code for bailouts from already optimized
453   // code or code that can't be optimized.
454   if (!info_->HasDeoptimizationSupport()) return;
455   unsigned pc_and_state =
456       StateField::encode(state) | PcField::encode(masm_->pc_offset());
457   DCHECK(Smi::IsValid(pc_and_state));
458 #ifdef DEBUG
459   for (int i = 0; i < bailout_entries_.length(); ++i) {
460     DCHECK(bailout_entries_[i].id != id);
461   }
462 #endif
463   BailoutEntry entry = { id, pc_and_state };
464   bailout_entries_.Add(entry, zone());
465 }
466
467
468 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
469   // The pc offset does not need to be encoded and packed together with a state.
470   DCHECK(masm_->pc_offset() > 0);
471   DCHECK(loop_depth() > 0);
472   uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
473   BackEdgeEntry entry =
474       { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
475   back_edges_.Add(entry, zone());
476 }
477
478
479 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
480   // Inline smi case inside loops, but not division and modulo which
481   // are too complicated and take up too much space.
482   if (op == Token::DIV ||op == Token::MOD) return false;
483   if (FLAG_always_inline_smi_code) return true;
484   return loop_depth_ > 0;
485 }
486
487
488 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
489 }
490
491
492 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
493   __ Move(result_register(), reg);
494 }
495
496
497 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
498   __ Push(reg);
499 }
500
501
502 void FullCodeGenerator::TestContext::Plug(Register reg) const {
503   // For simplicity we always test the accumulator register.
504   __ Move(result_register(), reg);
505   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
506   codegen()->DoTest(this);
507 }
508
509
510 void FullCodeGenerator::EffectContext::PlugTOS() const {
511   __ Drop(1);
512 }
513
514
515 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
516   __ Pop(result_register());
517 }
518
519
520 void FullCodeGenerator::StackValueContext::PlugTOS() const {
521 }
522
523
524 void FullCodeGenerator::TestContext::PlugTOS() const {
525   // For simplicity we always test the accumulator register.
526   __ Pop(result_register());
527   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
528   codegen()->DoTest(this);
529 }
530
531
532 void FullCodeGenerator::EffectContext::PrepareTest(
533     Label* materialize_true,
534     Label* materialize_false,
535     Label** if_true,
536     Label** if_false,
537     Label** fall_through) const {
538   // In an effect context, the true and the false case branch to the
539   // same label.
540   *if_true = *if_false = *fall_through = materialize_true;
541 }
542
543
544 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
545     Label* materialize_true,
546     Label* materialize_false,
547     Label** if_true,
548     Label** if_false,
549     Label** fall_through) const {
550   *if_true = *fall_through = materialize_true;
551   *if_false = materialize_false;
552 }
553
554
555 void FullCodeGenerator::StackValueContext::PrepareTest(
556     Label* materialize_true,
557     Label* materialize_false,
558     Label** if_true,
559     Label** if_false,
560     Label** fall_through) const {
561   *if_true = *fall_through = materialize_true;
562   *if_false = materialize_false;
563 }
564
565
566 void FullCodeGenerator::TestContext::PrepareTest(
567     Label* materialize_true,
568     Label* materialize_false,
569     Label** if_true,
570     Label** if_false,
571     Label** fall_through) const {
572   *if_true = true_label_;
573   *if_false = false_label_;
574   *fall_through = fall_through_;
575 }
576
577
578 void FullCodeGenerator::DoTest(const TestContext* context) {
579   DoTest(context->condition(),
580          context->true_label(),
581          context->false_label(),
582          context->fall_through());
583 }
584
585
586 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
587   DCHECK(scope_->is_global_scope());
588
589   for (int i = 0; i < declarations->length(); i++) {
590     ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
591     if (declaration != NULL) {
592       ModuleLiteral* module = declaration->module()->AsModuleLiteral();
593       if (module != NULL) {
594         Comment cmnt(masm_, "[ Link nested modules");
595         Scope* scope = module->body()->scope();
596         Interface* interface = scope->interface();
597         DCHECK(interface->IsModule() && interface->IsFrozen());
598
599         interface->Allocate(scope->module_var()->index());
600
601         // Set up module context.
602         DCHECK(scope->interface()->Index() >= 0);
603         __ Push(Smi::FromInt(scope->interface()->Index()));
604         __ Push(scope->GetScopeInfo());
605         __ CallRuntime(Runtime::kPushModuleContext, 2);
606         StoreToFrameField(StandardFrameConstants::kContextOffset,
607                           context_register());
608
609         AllocateModules(scope->declarations());
610
611         // Pop module context.
612         LoadContextField(context_register(), Context::PREVIOUS_INDEX);
613         // Update local stack frame context field.
614         StoreToFrameField(StandardFrameConstants::kContextOffset,
615                           context_register());
616       }
617     }
618   }
619 }
620
621
622 // Modules have their own local scope, represented by their own context.
623 // Module instance objects have an accessor for every export that forwards
624 // access to the respective slot from the module's context. (Exports that are
625 // modules themselves, however, are simple data properties.)
626 //
627 // All modules have a _hosting_ scope/context, which (currently) is the
628 // (innermost) enclosing global scope. To deal with recursion, nested modules
629 // are hosted by the same scope as global ones.
630 //
631 // For every (global or nested) module literal, the hosting context has an
632 // internal slot that points directly to the respective module context. This
633 // enables quick access to (statically resolved) module members by 2-dimensional
634 // access through the hosting context. For example,
635 //
636 //   module A {
637 //     let x;
638 //     module B { let y; }
639 //   }
640 //   module C { let z; }
641 //
642 // allocates contexts as follows:
643 //
644 // [header| .A | .B | .C | A | C ]  (global)
645 //           |    |    |
646 //           |    |    +-- [header| z ]  (module)
647 //           |    |
648 //           |    +------- [header| y ]  (module)
649 //           |
650 //           +------------ [header| x | B ]  (module)
651 //
652 // Here, .A, .B, .C are the internal slots pointing to the hosted module
653 // contexts, whereas A, B, C hold the actual instance objects (note that every
654 // module context also points to the respective instance object through its
655 // extension slot in the header).
656 //
657 // To deal with arbitrary recursion and aliases between modules,
658 // they are created and initialized in several stages. Each stage applies to
659 // all modules in the hosting global scope, including nested ones.
660 //
661 // 1. Allocate: for each module _literal_, allocate the module contexts and
662 //    respective instance object and wire them up. This happens in the
663 //    PushModuleContext runtime function, as generated by AllocateModules
664 //    (invoked by VisitDeclarations in the hosting scope).
665 //
666 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
667 //    assign the respective instance object to respective local variables. This
668 //    happens in VisitModuleDeclaration, and uses the instance objects created
669 //    in the previous stage.
670 //    For each module _literal_, this phase also constructs a module descriptor
671 //    for the next stage. This happens in VisitModuleLiteral.
672 //
673 // 3. Populate: invoke the DeclareModules runtime function to populate each
674 //    _instance_ object with accessors for it exports. This is generated by
675 //    DeclareModules (invoked by VisitDeclarations in the hosting scope again),
676 //    and uses the descriptors generated in the previous stage.
677 //
678 // 4. Initialize: execute the module bodies (and other code) in sequence. This
679 //    happens by the separate statements generated for module bodies. To reenter
680 //    the module scopes properly, the parser inserted ModuleStatements.
681
682 void FullCodeGenerator::VisitDeclarations(
683     ZoneList<Declaration*>* declarations) {
684   Handle<FixedArray> saved_modules = modules_;
685   int saved_module_index = module_index_;
686   ZoneList<Handle<Object> >* saved_globals = globals_;
687   ZoneList<Handle<Object> > inner_globals(10, zone());
688   globals_ = &inner_globals;
689
690   if (scope_->num_modules() != 0) {
691     // This is a scope hosting modules. Allocate a descriptor array to pass
692     // to the runtime for initialization.
693     Comment cmnt(masm_, "[ Allocate modules");
694     DCHECK(scope_->is_global_scope());
695     modules_ =
696         isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
697     module_index_ = 0;
698
699     // Generate code for allocating all modules, including nested ones.
700     // The allocated contexts are stored in internal variables in this scope.
701     AllocateModules(declarations);
702   }
703
704   AstVisitor::VisitDeclarations(declarations);
705
706   if (scope_->num_modules() != 0) {
707     // Initialize modules from descriptor array.
708     DCHECK(module_index_ == modules_->length());
709     DeclareModules(modules_);
710     modules_ = saved_modules;
711     module_index_ = saved_module_index;
712   }
713
714   if (!globals_->is_empty()) {
715     // Invoke the platform-dependent code generator to do the actual
716     // declaration of the global functions and variables.
717     Handle<FixedArray> array =
718        isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
719     for (int i = 0; i < globals_->length(); ++i)
720       array->set(i, *globals_->at(i));
721     DeclareGlobals(array);
722   }
723
724   globals_ = saved_globals;
725 }
726
727
728 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
729   Block* block = module->body();
730   Scope* saved_scope = scope();
731   scope_ = block->scope();
732   Interface* interface = scope_->interface();
733
734   Comment cmnt(masm_, "[ ModuleLiteral");
735   SetStatementPosition(block);
736
737   DCHECK(!modules_.is_null());
738   DCHECK(module_index_ < modules_->length());
739   int index = module_index_++;
740
741   // Set up module context.
742   DCHECK(interface->Index() >= 0);
743   __ Push(Smi::FromInt(interface->Index()));
744   __ Push(Smi::FromInt(0));
745   __ CallRuntime(Runtime::kPushModuleContext, 2);
746   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
747
748   {
749     Comment cmnt(masm_, "[ Declarations");
750     VisitDeclarations(scope_->declarations());
751   }
752
753   // Populate the module description.
754   Handle<ModuleInfo> description =
755       ModuleInfo::Create(isolate(), interface, scope_);
756   modules_->set(index, *description);
757
758   scope_ = saved_scope;
759   // Pop module context.
760   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
761   // Update local stack frame context field.
762   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
763 }
764
765
766 void FullCodeGenerator::VisitModuleVariable(ModuleVariable* module) {
767   // Nothing to do.
768   // The instance object is resolved statically through the module's interface.
769 }
770
771
772 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
773   // Nothing to do.
774   // The instance object is resolved statically through the module's interface.
775 }
776
777
778 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
779   // TODO(rossberg): dummy allocation for now.
780   Scope* scope = module->body()->scope();
781   Interface* interface = scope_->interface();
782
783   DCHECK(interface->IsModule() && interface->IsFrozen());
784   DCHECK(!modules_.is_null());
785   DCHECK(module_index_ < modules_->length());
786   interface->Allocate(scope->module_var()->index());
787   int index = module_index_++;
788
789   Handle<ModuleInfo> description =
790       ModuleInfo::Create(isolate(), interface, scope_);
791   modules_->set(index, *description);
792 }
793
794
795 int FullCodeGenerator::DeclareGlobalsFlags() {
796   DCHECK(DeclareGlobalsStrictMode::is_valid(strict_mode()));
797   return DeclareGlobalsEvalFlag::encode(is_eval()) |
798       DeclareGlobalsNativeFlag::encode(is_native()) |
799       DeclareGlobalsStrictMode::encode(strict_mode());
800 }
801
802
803 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
804   CodeGenerator::RecordPositions(masm_, fun->start_position());
805 }
806
807
808 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
809   CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
810 }
811
812
813 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
814   if (!info_->is_debug()) {
815     CodeGenerator::RecordPositions(masm_, stmt->position());
816   } else {
817     // Check if the statement will be breakable without adding a debug break
818     // slot.
819     BreakableStatementChecker checker(zone());
820     checker.Check(stmt);
821     // Record the statement position right here if the statement is not
822     // breakable. For breakable statements the actual recording of the
823     // position will be postponed to the breakable code (typically an IC).
824     bool position_recorded = CodeGenerator::RecordPositions(
825         masm_, stmt->position(), !checker.is_breakable());
826     // If the position recording did record a new position generate a debug
827     // break slot to make the statement breakable.
828     if (position_recorded) {
829       DebugCodegen::GenerateSlot(masm_);
830     }
831   }
832 }
833
834
835 void FullCodeGenerator::VisitSuperReference(SuperReference* super) {
836   __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
837 }
838
839
840 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
841   if (!info_->is_debug()) {
842     CodeGenerator::RecordPositions(masm_, expr->position());
843   } else {
844     // Check if the expression will be breakable without adding a debug break
845     // slot.
846     BreakableStatementChecker checker(zone());
847     checker.Check(expr);
848     // Record a statement position right here if the expression is not
849     // breakable. For breakable expressions the actual recording of the
850     // position will be postponed to the breakable code (typically an IC).
851     // NOTE this will record a statement position for something which might
852     // not be a statement. As stepping in the debugger will only stop at
853     // statement positions this is used for e.g. the condition expression of
854     // a do while loop.
855     bool position_recorded = CodeGenerator::RecordPositions(
856         masm_, expr->position(), !checker.is_breakable());
857     // If the position recording did record a new position generate a debug
858     // break slot to make the statement breakable.
859     if (position_recorded) {
860       DebugCodegen::GenerateSlot(masm_);
861     }
862   }
863 }
864
865
866 void FullCodeGenerator::SetSourcePosition(int pos) {
867   if (pos != RelocInfo::kNoPosition) {
868     masm_->positions_recorder()->RecordPosition(pos);
869     masm_->positions_recorder()->WriteRecordedPositions();
870   }
871 }
872
873
874 // Lookup table for code generators for  special runtime calls which are
875 // generated inline.
876 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize)          \
877     &FullCodeGenerator::Emit##Name,
878
879 const FullCodeGenerator::InlineFunctionGenerator
880   FullCodeGenerator::kInlineFunctionGenerators[] = {
881     INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
882   };
883 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
884
885
886 FullCodeGenerator::InlineFunctionGenerator
887   FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
888     int lookup_index =
889         static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
890     DCHECK(lookup_index >= 0);
891     DCHECK(static_cast<size_t>(lookup_index) <
892            arraysize(kInlineFunctionGenerators));
893     return kInlineFunctionGenerators[lookup_index];
894 }
895
896
897 void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
898   const Runtime::Function* function = expr->function();
899   DCHECK(function != NULL);
900   DCHECK(function->intrinsic_type == Runtime::INLINE);
901   InlineFunctionGenerator generator =
902       FindInlineFunctionGenerator(function->function_id);
903   ((*this).*(generator))(expr);
904 }
905
906
907 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
908   ZoneList<Expression*>* args = expr->arguments();
909   DCHECK(args->length() == 2);
910   EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
911 }
912
913
914 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
915   ZoneList<Expression*>* args = expr->arguments();
916   DCHECK(args->length() == 2);
917   EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
918 }
919
920
921 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
922   context()->Plug(handle(Smi::FromInt(0), isolate()));
923 }
924
925
926 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
927   switch (expr->op()) {
928     case Token::COMMA:
929       return VisitComma(expr);
930     case Token::OR:
931     case Token::AND:
932       return VisitLogicalExpression(expr);
933     default:
934       return VisitArithmeticExpression(expr);
935   }
936 }
937
938
939 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
940   if (context()->IsEffect()) {
941     VisitForEffect(expr);
942   } else if (context()->IsAccumulatorValue()) {
943     VisitForAccumulatorValue(expr);
944   } else if (context()->IsStackValue()) {
945     VisitForStackValue(expr);
946   } else if (context()->IsTest()) {
947     const TestContext* test = TestContext::cast(context());
948     VisitForControl(expr, test->true_label(), test->false_label(),
949                     test->fall_through());
950   }
951 }
952
953
954 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
955   Comment cmnt(masm_, "[ Comma");
956   VisitForEffect(expr->left());
957   VisitInDuplicateContext(expr->right());
958 }
959
960
961 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
962   bool is_logical_and = expr->op() == Token::AND;
963   Comment cmnt(masm_, is_logical_and ? "[ Logical AND" :  "[ Logical OR");
964   Expression* left = expr->left();
965   Expression* right = expr->right();
966   BailoutId right_id = expr->RightId();
967   Label done;
968
969   if (context()->IsTest()) {
970     Label eval_right;
971     const TestContext* test = TestContext::cast(context());
972     if (is_logical_and) {
973       VisitForControl(left, &eval_right, test->false_label(), &eval_right);
974     } else {
975       VisitForControl(left, test->true_label(), &eval_right, &eval_right);
976     }
977     PrepareForBailoutForId(right_id, NO_REGISTERS);
978     __ bind(&eval_right);
979
980   } else if (context()->IsAccumulatorValue()) {
981     VisitForAccumulatorValue(left);
982     // We want the value in the accumulator for the test, and on the stack in
983     // case we need it.
984     __ Push(result_register());
985     Label discard, restore;
986     if (is_logical_and) {
987       DoTest(left, &discard, &restore, &restore);
988     } else {
989       DoTest(left, &restore, &discard, &restore);
990     }
991     __ bind(&restore);
992     __ Pop(result_register());
993     __ jmp(&done);
994     __ bind(&discard);
995     __ Drop(1);
996     PrepareForBailoutForId(right_id, NO_REGISTERS);
997
998   } else if (context()->IsStackValue()) {
999     VisitForAccumulatorValue(left);
1000     // We want the value in the accumulator for the test, and on the stack in
1001     // case we need it.
1002     __ Push(result_register());
1003     Label discard;
1004     if (is_logical_and) {
1005       DoTest(left, &discard, &done, &discard);
1006     } else {
1007       DoTest(left, &done, &discard, &discard);
1008     }
1009     __ bind(&discard);
1010     __ Drop(1);
1011     PrepareForBailoutForId(right_id, NO_REGISTERS);
1012
1013   } else {
1014     DCHECK(context()->IsEffect());
1015     Label eval_right;
1016     if (is_logical_and) {
1017       VisitForControl(left, &eval_right, &done, &eval_right);
1018     } else {
1019       VisitForControl(left, &done, &eval_right, &eval_right);
1020     }
1021     PrepareForBailoutForId(right_id, NO_REGISTERS);
1022     __ bind(&eval_right);
1023   }
1024
1025   VisitInDuplicateContext(right);
1026   __ bind(&done);
1027 }
1028
1029
1030 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1031   Token::Value op = expr->op();
1032   Comment cmnt(masm_, "[ ArithmeticExpression");
1033   Expression* left = expr->left();
1034   Expression* right = expr->right();
1035   OverwriteMode mode =
1036       left->ResultOverwriteAllowed()
1037       ? OVERWRITE_LEFT
1038       : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1039
1040   VisitForStackValue(left);
1041   VisitForAccumulatorValue(right);
1042
1043   SetSourcePosition(expr->position());
1044   if (ShouldInlineSmiCase(op)) {
1045     EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1046   } else {
1047     EmitBinaryOp(expr, op, mode);
1048   }
1049 }
1050
1051
1052 void FullCodeGenerator::VisitBlock(Block* stmt) {
1053   Comment cmnt(masm_, "[ Block");
1054   NestedBlock nested_block(this, stmt);
1055   SetStatementPosition(stmt);
1056
1057   Scope* saved_scope = scope();
1058   // Push a block context when entering a block with block scoped variables.
1059   if (stmt->scope() == NULL) {
1060     PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1061   } else {
1062     scope_ = stmt->scope();
1063     DCHECK(!scope_->is_module_scope());
1064     { Comment cmnt(masm_, "[ Extend block context");
1065       __ Push(scope_->GetScopeInfo());
1066       PushFunctionArgumentForContextAllocation();
1067       __ CallRuntime(Runtime::kPushBlockContext, 2);
1068
1069       // Replace the context stored in the frame.
1070       StoreToFrameField(StandardFrameConstants::kContextOffset,
1071                         context_register());
1072       PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1073     }
1074     { Comment cmnt(masm_, "[ Declarations");
1075       VisitDeclarations(scope_->declarations());
1076       PrepareForBailoutForId(stmt->DeclsId(), NO_REGISTERS);
1077     }
1078   }
1079
1080   VisitStatements(stmt->statements());
1081   scope_ = saved_scope;
1082   __ bind(nested_block.break_label());
1083
1084   // Pop block context if necessary.
1085   if (stmt->scope() != NULL) {
1086     LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1087     // Update local stack frame context field.
1088     StoreToFrameField(StandardFrameConstants::kContextOffset,
1089                       context_register());
1090   }
1091   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1092 }
1093
1094
1095 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1096   Comment cmnt(masm_, "[ Module context");
1097
1098   __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
1099   __ Push(Smi::FromInt(0));
1100   __ CallRuntime(Runtime::kPushModuleContext, 2);
1101   StoreToFrameField(
1102       StandardFrameConstants::kContextOffset, context_register());
1103
1104   Scope* saved_scope = scope_;
1105   scope_ = stmt->body()->scope();
1106   VisitStatements(stmt->body()->statements());
1107   scope_ = saved_scope;
1108   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1109   // Update local stack frame context field.
1110   StoreToFrameField(StandardFrameConstants::kContextOffset,
1111                     context_register());
1112 }
1113
1114
1115 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1116   Comment cmnt(masm_, "[ ExpressionStatement");
1117   SetStatementPosition(stmt);
1118   VisitForEffect(stmt->expression());
1119 }
1120
1121
1122 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1123   Comment cmnt(masm_, "[ EmptyStatement");
1124   SetStatementPosition(stmt);
1125 }
1126
1127
1128 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1129   Comment cmnt(masm_, "[ IfStatement");
1130   SetStatementPosition(stmt);
1131   Label then_part, else_part, done;
1132
1133   if (stmt->HasElseStatement()) {
1134     VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1135     PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1136     __ bind(&then_part);
1137     Visit(stmt->then_statement());
1138     __ jmp(&done);
1139
1140     PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1141     __ bind(&else_part);
1142     Visit(stmt->else_statement());
1143   } else {
1144     VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1145     PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1146     __ bind(&then_part);
1147     Visit(stmt->then_statement());
1148
1149     PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1150   }
1151   __ bind(&done);
1152   PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1153 }
1154
1155
1156 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1157   Comment cmnt(masm_,  "[ ContinueStatement");
1158   SetStatementPosition(stmt);
1159   NestedStatement* current = nesting_stack_;
1160   int stack_depth = 0;
1161   int context_length = 0;
1162   // When continuing, we clobber the unpredictable value in the accumulator
1163   // with one that's safe for GC.  If we hit an exit from the try block of
1164   // try...finally on our way out, we will unconditionally preserve the
1165   // accumulator on the stack.
1166   ClearAccumulator();
1167   while (!current->IsContinueTarget(stmt->target())) {
1168     current = current->Exit(&stack_depth, &context_length);
1169   }
1170   __ Drop(stack_depth);
1171   if (context_length > 0) {
1172     while (context_length > 0) {
1173       LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1174       --context_length;
1175     }
1176     StoreToFrameField(StandardFrameConstants::kContextOffset,
1177                       context_register());
1178   }
1179
1180   __ jmp(current->AsIteration()->continue_label());
1181 }
1182
1183
1184 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1185   Comment cmnt(masm_,  "[ BreakStatement");
1186   SetStatementPosition(stmt);
1187   NestedStatement* current = nesting_stack_;
1188   int stack_depth = 0;
1189   int context_length = 0;
1190   // When breaking, we clobber the unpredictable value in the accumulator
1191   // with one that's safe for GC.  If we hit an exit from the try block of
1192   // try...finally on our way out, we will unconditionally preserve the
1193   // accumulator on the stack.
1194   ClearAccumulator();
1195   while (!current->IsBreakTarget(stmt->target())) {
1196     current = current->Exit(&stack_depth, &context_length);
1197   }
1198   __ Drop(stack_depth);
1199   if (context_length > 0) {
1200     while (context_length > 0) {
1201       LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1202       --context_length;
1203     }
1204     StoreToFrameField(StandardFrameConstants::kContextOffset,
1205                       context_register());
1206   }
1207
1208   __ jmp(current->AsBreakable()->break_label());
1209 }
1210
1211
1212 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1213   NestedStatement* current = nesting_stack_;
1214   int stack_depth = 0;
1215   int context_length = 0;
1216   while (current != NULL) {
1217     current = current->Exit(&stack_depth, &context_length);
1218   }
1219   __ Drop(stack_depth);
1220 }
1221
1222
1223 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1224   Comment cmnt(masm_, "[ ReturnStatement");
1225   SetStatementPosition(stmt);
1226   Expression* expr = stmt->expression();
1227   VisitForAccumulatorValue(expr);
1228   EmitUnwindBeforeReturn();
1229   EmitReturnSequence();
1230 }
1231
1232
1233 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1234   Comment cmnt(masm_, "[ WithStatement");
1235   SetStatementPosition(stmt);
1236
1237   VisitForStackValue(stmt->expression());
1238   PushFunctionArgumentForContextAllocation();
1239   __ CallRuntime(Runtime::kPushWithContext, 2);
1240   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1241
1242   Scope* saved_scope = scope();
1243   scope_ = stmt->scope();
1244   { WithOrCatch body(this);
1245     Visit(stmt->statement());
1246   }
1247   scope_ = saved_scope;
1248
1249   // Pop context.
1250   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1251   // Update local stack frame context field.
1252   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1253 }
1254
1255
1256 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1257   Comment cmnt(masm_, "[ DoWhileStatement");
1258   SetStatementPosition(stmt);
1259   Label body, book_keeping;
1260
1261   Iteration loop_statement(this, stmt);
1262   increment_loop_depth();
1263
1264   __ bind(&body);
1265   Visit(stmt->body());
1266
1267   // Record the position of the do while condition and make sure it is
1268   // possible to break on the condition.
1269   __ bind(loop_statement.continue_label());
1270   PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1271   SetExpressionPosition(stmt->cond());
1272   VisitForControl(stmt->cond(),
1273                   &book_keeping,
1274                   loop_statement.break_label(),
1275                   &book_keeping);
1276
1277   // Check stack before looping.
1278   PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1279   __ bind(&book_keeping);
1280   EmitBackEdgeBookkeeping(stmt, &body);
1281   __ jmp(&body);
1282
1283   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1284   __ bind(loop_statement.break_label());
1285   decrement_loop_depth();
1286 }
1287
1288
1289 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1290   Comment cmnt(masm_, "[ WhileStatement");
1291   Label loop, body;
1292
1293   Iteration loop_statement(this, stmt);
1294   increment_loop_depth();
1295
1296   __ bind(&loop);
1297
1298   SetExpressionPosition(stmt->cond());
1299   VisitForControl(stmt->cond(),
1300                   &body,
1301                   loop_statement.break_label(),
1302                   &body);
1303
1304   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1305   __ bind(&body);
1306   Visit(stmt->body());
1307
1308   __ bind(loop_statement.continue_label());
1309
1310   // Check stack before looping.
1311   EmitBackEdgeBookkeeping(stmt, &loop);
1312   __ jmp(&loop);
1313
1314   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1315   __ bind(loop_statement.break_label());
1316   decrement_loop_depth();
1317 }
1318
1319
1320 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1321   Comment cmnt(masm_, "[ ForStatement");
1322   Label test, body;
1323
1324   Iteration loop_statement(this, stmt);
1325
1326   // Set statement position for a break slot before entering the for-body.
1327   SetStatementPosition(stmt);
1328
1329   if (stmt->init() != NULL) {
1330     Visit(stmt->init());
1331   }
1332
1333   increment_loop_depth();
1334   // Emit the test at the bottom of the loop (even if empty).
1335   __ jmp(&test);
1336
1337   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1338   __ bind(&body);
1339   Visit(stmt->body());
1340
1341   PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1342   __ bind(loop_statement.continue_label());
1343   if (stmt->next() != NULL) {
1344     Visit(stmt->next());
1345   }
1346
1347   // Emit the statement position here as this is where the for
1348   // statement code starts.
1349   SetStatementPosition(stmt);
1350
1351   // Check stack before looping.
1352   EmitBackEdgeBookkeeping(stmt, &body);
1353
1354   __ bind(&test);
1355   if (stmt->cond() != NULL) {
1356     VisitForControl(stmt->cond(),
1357                     &body,
1358                     loop_statement.break_label(),
1359                     loop_statement.break_label());
1360   } else {
1361     __ jmp(&body);
1362   }
1363
1364   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1365   __ bind(loop_statement.break_label());
1366   decrement_loop_depth();
1367 }
1368
1369
1370 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1371   Comment cmnt(masm_, "[ TryCatchStatement");
1372   SetStatementPosition(stmt);
1373   // The try block adds a handler to the exception handler chain before
1374   // entering, and removes it again when exiting normally.  If an exception
1375   // is thrown during execution of the try block, the handler is consumed
1376   // and control is passed to the catch block with the exception in the
1377   // result register.
1378
1379   Label try_entry, handler_entry, exit;
1380   __ jmp(&try_entry);
1381   __ bind(&handler_entry);
1382   handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1383   // Exception handler code, the exception is in the result register.
1384   // Extend the context before executing the catch block.
1385   { Comment cmnt(masm_, "[ Extend catch context");
1386     __ Push(stmt->variable()->name());
1387     __ Push(result_register());
1388     PushFunctionArgumentForContextAllocation();
1389     __ CallRuntime(Runtime::kPushCatchContext, 3);
1390     StoreToFrameField(StandardFrameConstants::kContextOffset,
1391                       context_register());
1392   }
1393
1394   Scope* saved_scope = scope();
1395   scope_ = stmt->scope();
1396   DCHECK(scope_->declarations()->is_empty());
1397   { WithOrCatch catch_body(this);
1398     Visit(stmt->catch_block());
1399   }
1400   // Restore the context.
1401   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1402   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1403   scope_ = saved_scope;
1404   __ jmp(&exit);
1405
1406   // Try block code. Sets up the exception handler chain.
1407   __ bind(&try_entry);
1408   __ PushTryHandler(StackHandler::CATCH, stmt->index());
1409   { TryCatch try_body(this);
1410     Visit(stmt->try_block());
1411   }
1412   __ PopTryHandler();
1413   __ bind(&exit);
1414 }
1415
1416
1417 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1418   Comment cmnt(masm_, "[ TryFinallyStatement");
1419   SetStatementPosition(stmt);
1420   // Try finally is compiled by setting up a try-handler on the stack while
1421   // executing the try body, and removing it again afterwards.
1422   //
1423   // The try-finally construct can enter the finally block in three ways:
1424   // 1. By exiting the try-block normally. This removes the try-handler and
1425   //    calls the finally block code before continuing.
1426   // 2. By exiting the try-block with a function-local control flow transfer
1427   //    (break/continue/return). The site of the, e.g., break removes the
1428   //    try handler and calls the finally block code before continuing
1429   //    its outward control transfer.
1430   // 3. By exiting the try-block with a thrown exception.
1431   //    This can happen in nested function calls. It traverses the try-handler
1432   //    chain and consumes the try-handler entry before jumping to the
1433   //    handler code. The handler code then calls the finally-block before
1434   //    rethrowing the exception.
1435   //
1436   // The finally block must assume a return address on top of the stack
1437   // (or in the link register on ARM chips) and a value (return value or
1438   // exception) in the result register (rax/eax/r0), both of which must
1439   // be preserved. The return address isn't GC-safe, so it should be
1440   // cooked before GC.
1441   Label try_entry, handler_entry, finally_entry;
1442
1443   // Jump to try-handler setup and try-block code.
1444   __ jmp(&try_entry);
1445   __ bind(&handler_entry);
1446   handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1447   // Exception handler code.  This code is only executed when an exception
1448   // is thrown.  The exception is in the result register, and must be
1449   // preserved by the finally block.  Call the finally block and then
1450   // rethrow the exception if it returns.
1451   __ Call(&finally_entry);
1452   __ Push(result_register());
1453   __ CallRuntime(Runtime::kReThrow, 1);
1454
1455   // Finally block implementation.
1456   __ bind(&finally_entry);
1457   EnterFinallyBlock();
1458   { Finally finally_body(this);
1459     Visit(stmt->finally_block());
1460   }
1461   ExitFinallyBlock();  // Return to the calling code.
1462
1463   // Set up try handler.
1464   __ bind(&try_entry);
1465   __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1466   { TryFinally try_body(this, &finally_entry);
1467     Visit(stmt->try_block());
1468   }
1469   __ PopTryHandler();
1470   // Execute the finally block on the way out.  Clobber the unpredictable
1471   // value in the result register with one that's safe for GC because the
1472   // finally block will unconditionally preserve the result register on the
1473   // stack.
1474   ClearAccumulator();
1475   __ Call(&finally_entry);
1476 }
1477
1478
1479 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1480   Comment cmnt(masm_, "[ DebuggerStatement");
1481   SetStatementPosition(stmt);
1482
1483   __ DebugBreak();
1484   // Ignore the return value.
1485
1486   PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1487 }
1488
1489
1490 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1491   UNREACHABLE();
1492 }
1493
1494
1495 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1496   Comment cmnt(masm_, "[ Conditional");
1497   Label true_case, false_case, done;
1498   VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1499
1500   PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1501   __ bind(&true_case);
1502   SetExpressionPosition(expr->then_expression());
1503   if (context()->IsTest()) {
1504     const TestContext* for_test = TestContext::cast(context());
1505     VisitForControl(expr->then_expression(),
1506                     for_test->true_label(),
1507                     for_test->false_label(),
1508                     NULL);
1509   } else {
1510     VisitInDuplicateContext(expr->then_expression());
1511     __ jmp(&done);
1512   }
1513
1514   PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1515   __ bind(&false_case);
1516   SetExpressionPosition(expr->else_expression());
1517   VisitInDuplicateContext(expr->else_expression());
1518   // If control flow falls through Visit, merge it with true case here.
1519   if (!context()->IsTest()) {
1520     __ bind(&done);
1521   }
1522 }
1523
1524
1525 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1526   Comment cmnt(masm_, "[ Literal");
1527   context()->Plug(expr->value());
1528 }
1529
1530
1531 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1532   Comment cmnt(masm_, "[ FunctionLiteral");
1533
1534   // Build the function boilerplate and instantiate it.
1535   Handle<SharedFunctionInfo> function_info =
1536       Compiler::BuildFunctionInfo(expr, script(), info_);
1537   if (function_info.is_null()) {
1538     SetStackOverflow();
1539     return;
1540   }
1541   EmitNewClosure(function_info, expr->pretenure());
1542 }
1543
1544
1545 void FullCodeGenerator::VisitClassLiteral(ClassLiteral* expr) {
1546   // TODO(arv): Implement
1547   Comment cmnt(masm_, "[ ClassLiteral");
1548   if (expr->extends() != NULL) {
1549     VisitForEffect(expr->extends());
1550   }
1551   context()->Plug(isolate()->factory()->undefined_value());
1552 }
1553
1554
1555 void FullCodeGenerator::VisitNativeFunctionLiteral(
1556     NativeFunctionLiteral* expr) {
1557   Comment cmnt(masm_, "[ NativeFunctionLiteral");
1558
1559   // Compute the function template for the native function.
1560   Handle<String> name = expr->name();
1561   v8::Handle<v8::FunctionTemplate> fun_template =
1562       expr->extension()->GetNativeFunctionTemplate(
1563           reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1564   DCHECK(!fun_template.IsEmpty());
1565
1566   // Instantiate the function and create a shared function info from it.
1567   Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1568   const int literals = fun->NumberOfLiterals();
1569   Handle<Code> code = Handle<Code>(fun->shared()->code());
1570   Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1571   Handle<SharedFunctionInfo> shared =
1572       isolate()->factory()->NewSharedFunctionInfo(
1573           name, literals, FunctionKind::kNormalFunction, code,
1574           Handle<ScopeInfo>(fun->shared()->scope_info()),
1575           Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1576   shared->set_construct_stub(*construct_stub);
1577
1578   // Copy the function data to the shared function info.
1579   shared->set_function_data(fun->shared()->function_data());
1580   int parameters = fun->shared()->formal_parameter_count();
1581   shared->set_formal_parameter_count(parameters);
1582
1583   EmitNewClosure(shared, false);
1584 }
1585
1586
1587 void FullCodeGenerator::VisitThrow(Throw* expr) {
1588   Comment cmnt(masm_, "[ Throw");
1589   VisitForStackValue(expr->exception());
1590   __ CallRuntime(Runtime::kThrow, 1);
1591   // Never returns here.
1592 }
1593
1594
1595 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
1596     int* stack_depth,
1597     int* context_length) {
1598   // The macros used here must preserve the result register.
1599   __ Drop(*stack_depth);
1600   __ PopTryHandler();
1601   *stack_depth = 0;
1602   return previous_;
1603 }
1604
1605
1606 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1607   Expression* sub_expr;
1608   Handle<String> check;
1609   if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1610     EmitLiteralCompareTypeof(expr, sub_expr, check);
1611     return true;
1612   }
1613
1614   if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1615     EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1616     return true;
1617   }
1618
1619   if (expr->IsLiteralCompareNull(&sub_expr)) {
1620     EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1621     return true;
1622   }
1623
1624   return false;
1625 }
1626
1627
1628 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1629   DisallowHeapAllocation no_gc;
1630   Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1631
1632   // Increment loop nesting level by one and iterate over the back edge table
1633   // to find the matching loops to patch the interrupt
1634   // call to an unconditional call to the replacement code.
1635   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1636   if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1637
1638   BackEdgeTable back_edges(unoptimized, &no_gc);
1639   for (uint32_t i = 0; i < back_edges.length(); i++) {
1640     if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1641       DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1642                                             unoptimized,
1643                                             back_edges.pc(i)));
1644       PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1645     }
1646   }
1647
1648   unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1649   DCHECK(Verify(isolate, unoptimized));
1650 }
1651
1652
1653 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1654   DisallowHeapAllocation no_gc;
1655   Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1656
1657   // Iterate over the back edge table and revert the patched interrupt calls.
1658   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1659
1660   BackEdgeTable back_edges(unoptimized, &no_gc);
1661   for (uint32_t i = 0; i < back_edges.length(); i++) {
1662     if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1663       DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1664                                             unoptimized,
1665                                             back_edges.pc(i)));
1666       PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1667     }
1668   }
1669
1670   unoptimized->set_allow_osr_at_loop_nesting_level(0);
1671   // Assert that none of the back edges are patched anymore.
1672   DCHECK(Verify(isolate, unoptimized));
1673 }
1674
1675
1676 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1677   DisallowHeapAllocation no_gc;
1678   Isolate* isolate = code->GetIsolate();
1679   Address pc = code->instruction_start() + pc_offset;
1680   Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1681   PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1682 }
1683
1684
1685 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1686   DisallowHeapAllocation no_gc;
1687   Isolate* isolate = code->GetIsolate();
1688   Address pc = code->instruction_start() + pc_offset;
1689
1690   if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1691     Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1692     PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1693   }
1694 }
1695
1696
1697 #ifdef DEBUG
1698 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1699   DisallowHeapAllocation no_gc;
1700   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1701   BackEdgeTable back_edges(unoptimized, &no_gc);
1702   for (uint32_t i = 0; i < back_edges.length(); i++) {
1703     uint32_t loop_depth = back_edges.loop_depth(i);
1704     CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1705     // Assert that all back edges for shallower loops (and only those)
1706     // have already been patched.
1707     CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1708              GetBackEdgeState(isolate,
1709                               unoptimized,
1710                               back_edges.pc(i)) != INTERRUPT);
1711   }
1712   return true;
1713 }
1714 #endif  // DEBUG
1715
1716
1717 #undef __
1718
1719
1720 } }  // namespace v8::internal