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.
8 #include "src/ast-numbering.h"
9 #include "src/code-factory.h"
10 #include "src/codegen.h"
11 #include "src/compiler.h"
12 #include "src/debug.h"
13 #include "src/full-codegen.h"
14 #include "src/liveedit.h"
15 #include "src/macro-assembler.h"
16 #include "src/prettyprinter.h"
17 #include "src/scopeinfo.h"
18 #include "src/scopes.h"
19 #include "src/snapshot/snapshot.h"
24 void BreakableStatementChecker::Check(Statement* stmt) {
29 void BreakableStatementChecker::Check(Expression* expr) {
34 void BreakableStatementChecker::VisitVariableDeclaration(
35 VariableDeclaration* decl) {
39 void BreakableStatementChecker::VisitFunctionDeclaration(
40 FunctionDeclaration* decl) {
44 void BreakableStatementChecker::VisitModuleDeclaration(
45 ModuleDeclaration* decl) {
49 void BreakableStatementChecker::VisitImportDeclaration(
50 ImportDeclaration* decl) {
54 void BreakableStatementChecker::VisitExportDeclaration(
55 ExportDeclaration* decl) {
59 void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
63 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
67 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
71 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
75 void BreakableStatementChecker::VisitBlock(Block* stmt) {
79 void BreakableStatementChecker::VisitExpressionStatement(
80 ExpressionStatement* stmt) {
81 // Check if expression is breakable.
82 Visit(stmt->expression());
86 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
90 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
91 // If the condition is breakable the if statement is breakable.
92 Visit(stmt->condition());
96 void BreakableStatementChecker::VisitContinueStatement(
97 ContinueStatement* stmt) {
101 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
105 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
106 // Return is breakable if the expression is.
107 Visit(stmt->expression());
111 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
112 Visit(stmt->expression());
116 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
117 // Switch statements breakable if the tag expression is.
122 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
123 // Mark do while as breakable to avoid adding a break slot in front of it.
124 is_breakable_ = true;
128 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
129 // Mark while statements breakable if the condition expression is.
134 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
135 // We set positions for both init and condition, if they exist.
136 if (stmt->cond() != NULL || stmt->init() != NULL) is_breakable_ = true;
140 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
141 // For-in is breakable because we set the position for the enumerable.
142 is_breakable_ = true;
146 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
147 // For-of is breakable because we set the position for the next() call.
148 is_breakable_ = true;
152 void BreakableStatementChecker::VisitTryCatchStatement(
153 TryCatchStatement* stmt) {
154 // Mark try catch as breakable to avoid adding a break slot in front of it.
155 is_breakable_ = true;
159 void BreakableStatementChecker::VisitTryFinallyStatement(
160 TryFinallyStatement* stmt) {
161 // Mark try finally as breakable to avoid adding a break slot in front of it.
162 is_breakable_ = true;
166 void BreakableStatementChecker::VisitDebuggerStatement(
167 DebuggerStatement* stmt) {
168 // The debugger statement is breakable.
169 is_breakable_ = true;
173 void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
177 void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
181 void BreakableStatementChecker::VisitClassLiteral(ClassLiteral* expr) {
182 if (expr->extends() != NULL) {
183 Visit(expr->extends());
188 void BreakableStatementChecker::VisitNativeFunctionLiteral(
189 NativeFunctionLiteral* expr) {
193 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
197 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
201 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
205 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
209 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
213 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
217 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
218 // If assigning to a property (including a global property) the assignment is
220 VariableProxy* proxy = expr->target()->AsVariableProxy();
221 Property* prop = expr->target()->AsProperty();
222 if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
223 is_breakable_ = true;
227 // Otherwise the assignment is breakable if the assigned value is.
228 Visit(expr->value());
232 void BreakableStatementChecker::VisitYield(Yield* expr) {
233 // Yield is breakable if the expression is.
234 Visit(expr->expression());
238 void BreakableStatementChecker::VisitThrow(Throw* expr) {
239 // Throw is breakable if the expression is.
240 Visit(expr->exception());
244 void BreakableStatementChecker::VisitProperty(Property* expr) {
245 // Property load is breakable.
246 is_breakable_ = true;
250 void BreakableStatementChecker::VisitCall(Call* expr) {
251 // Function calls both through IC and call stub are breakable.
252 is_breakable_ = true;
256 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
257 // Function calls through new are breakable.
258 is_breakable_ = true;
262 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
266 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
267 Visit(expr->expression());
271 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
272 Visit(expr->expression());
276 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
278 if (expr->op() != Token::AND &&
279 expr->op() != Token::OR) {
280 Visit(expr->right());
285 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
287 Visit(expr->right());
291 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
295 void BreakableStatementChecker::VisitSuperReference(SuperReference* expr) {}
298 #define __ ACCESS_MASM(masm())
300 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
301 Isolate* isolate = info->isolate();
303 TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
305 // Ensure that the feedback vector is large enough.
306 info->EnsureFeedbackVector();
308 Handle<Script> script = info->script();
309 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
310 int len = String::cast(script->source())->length();
311 isolate->counters()->total_full_codegen_source_size()->Increment(len);
313 CodeGenerator::MakeCodePrologue(info, "full");
314 const int kInitialBufferSize = 4 * KB;
315 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
316 if (info->will_serialize()) masm.enable_serializer();
318 LOG_CODE_EVENT(isolate,
319 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
321 FullCodeGenerator cgen(&masm, info);
323 if (cgen.HasStackOverflow()) {
324 DCHECK(!isolate->has_pending_exception());
327 unsigned table_offset = cgen.EmitBackEdgeTable();
329 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
330 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
331 code->set_optimizable(info->IsOptimizable() &&
332 !info->function()->dont_optimize() &&
333 info->function()->scope()->AllowsLazyCompilation());
334 cgen.PopulateDeoptimizationData(code);
335 cgen.PopulateTypeFeedbackInfo(code);
336 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
337 code->set_has_reloc_info_for_serialization(info->will_serialize());
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);
345 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
346 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
349 // Check that no context-specific object has been embedded.
350 code->VerifyEmbeddedObjects(Code::kNoContextSpecificPointers);
356 unsigned FullCodeGenerator::EmitBackEdgeTable() {
357 // The back edge table consists of a length (in number of entries)
358 // field, and then a sequence of entries. Each entry is a pair of AST id
359 // and code-relative pc offset.
360 masm()->Align(kPointerSize);
361 unsigned offset = masm()->pc_offset();
362 unsigned length = back_edges_.length();
364 for (unsigned i = 0; i < length; ++i) {
365 __ dd(back_edges_[i].id.ToInt());
366 __ dd(back_edges_[i].pc);
367 __ dd(back_edges_[i].loop_depth);
373 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
374 FeedbackVectorSlot slot) {
375 Handle<TypeFeedbackVector> vector = FeedbackVector();
376 if (!vector->Get(slot)->IsAllocationSite()) {
377 Handle<AllocationSite> allocation_site =
378 isolate()->factory()->NewAllocationSite();
379 vector->Set(slot, *allocation_site);
384 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
385 FeedbackVectorICSlot slot) {
386 Handle<TypeFeedbackVector> vector = FeedbackVector();
387 if (!vector->Get(slot)->IsAllocationSite()) {
388 Handle<AllocationSite> allocation_site =
389 isolate()->factory()->NewAllocationSite();
390 vector->Set(slot, *allocation_site);
395 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
396 // Fill in the deoptimization information.
397 DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
398 if (!info_->HasDeoptimizationSupport()) return;
399 int length = bailout_entries_.length();
400 Handle<DeoptimizationOutputData> data =
401 DeoptimizationOutputData::New(isolate(), length, TENURED);
402 for (int i = 0; i < length; i++) {
403 data->SetAstId(i, bailout_entries_[i].id);
404 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
406 code->set_deoptimization_data(*data);
410 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
411 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
412 info->set_ic_total_count(ic_total_count_);
413 DCHECK(!isolate()->heap()->InNewSpace(*info));
414 code->set_type_feedback_info(*info);
418 bool FullCodeGenerator::MustCreateObjectLiteralWithRuntime(
419 ObjectLiteral* expr) const {
420 // FastCloneShallowObjectStub doesn't copy elements, and object literals don't
421 // support copy-on-write (COW) elements for now.
422 // TODO(mvstanton): make object literals support COW elements.
423 return expr->may_store_doubles() || expr->depth() > 1 ||
424 masm()->serializer_enabled() ||
425 expr->ComputeFlags() != ObjectLiteral::kFastElements ||
426 expr->has_elements() ||
427 expr->properties_count() >
428 FastCloneShallowObjectStub::kMaximumClonedProperties;
432 bool FullCodeGenerator::MustCreateArrayLiteralWithRuntime(
433 ArrayLiteral* expr) const {
434 return expr->depth() > 1 ||
435 expr->values()->length() > JSObject::kInitialMaxFastElementArray;
439 void FullCodeGenerator::Initialize() {
440 InitializeAstVisitor(info_->isolate(), info_->zone());
441 // The generation of debug code must match between the snapshot code and the
442 // code that is generated later. This is assumed by the debugger when it is
443 // calculating PC offsets after generating a debug version of code. Therefore
444 // we disable the production of debug code in the full compiler if we are
445 // either generating a snapshot or we booted from a snapshot.
446 generate_debug_code_ = FLAG_debug_code && !masm_->serializer_enabled() &&
447 !info_->isolate()->snapshot_available();
448 masm_->set_emit_debug_code(generate_debug_code_);
449 masm_->set_predictable_code_size(true);
453 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
454 PrepareForBailoutForId(node->id(), state);
458 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
460 Handle<Code> ic = CodeFactory::LoadIC(isolate(), contextual_mode).code();
465 void FullCodeGenerator::CallGlobalLoadIC(Handle<String> name) {
466 if (masm()->serializer_enabled() || FLAG_vector_ics) {
467 // Vector-ICs don't work with LoadGlobalIC.
468 return CallLoadIC(CONTEXTUAL);
470 Handle<Code> ic = CodeFactory::LoadGlobalIC(
471 isolate(), isolate()->global_object(), name).code();
472 CallIC(ic, TypeFeedbackId::None());
476 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
477 Handle<Code> ic = CodeFactory::StoreIC(isolate(), language_mode()).code();
482 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
483 // We record the offset of the function return so we can rebuild the frame
484 // if the function was inlined, i.e., this is the return address in the
485 // inlined function's frame.
487 // The state is ignored. We defensively set it to TOS_REG, which is the
488 // real state of the unoptimized code at the return site.
489 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
491 // In debug builds, mark the return so we can verify that this function
493 DCHECK(!call->return_is_recorded_);
494 call->return_is_recorded_ = true;
499 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
500 // There's no need to prepare this code for bailouts from already optimized
501 // code or code that can't be optimized.
502 if (!info_->HasDeoptimizationSupport()) return;
503 unsigned pc_and_state =
504 StateField::encode(state) | PcField::encode(masm_->pc_offset());
505 DCHECK(Smi::IsValid(pc_and_state));
507 for (int i = 0; i < bailout_entries_.length(); ++i) {
508 DCHECK(bailout_entries_[i].id != id);
511 BailoutEntry entry = { id, pc_and_state };
512 bailout_entries_.Add(entry, zone());
516 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
517 // The pc offset does not need to be encoded and packed together with a state.
518 DCHECK(masm_->pc_offset() > 0);
519 DCHECK(loop_depth() > 0);
520 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
521 BackEdgeEntry entry =
522 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
523 back_edges_.Add(entry, zone());
527 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
528 // Inline smi case inside loops, but not division and modulo which
529 // are too complicated and take up too much space.
530 if (op == Token::DIV ||op == Token::MOD) return false;
531 if (FLAG_always_inline_smi_code) return true;
532 return loop_depth_ > 0;
536 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
540 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
541 __ Move(result_register(), reg);
545 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
550 void FullCodeGenerator::TestContext::Plug(Register reg) const {
551 // For simplicity we always test the accumulator register.
552 __ Move(result_register(), reg);
553 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
554 codegen()->DoTest(this);
558 void FullCodeGenerator::EffectContext::PlugTOS() const {
563 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
564 __ Pop(result_register());
568 void FullCodeGenerator::StackValueContext::PlugTOS() const {
572 void FullCodeGenerator::TestContext::PlugTOS() const {
573 // For simplicity we always test the accumulator register.
574 __ Pop(result_register());
575 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
576 codegen()->DoTest(this);
580 void FullCodeGenerator::EffectContext::PrepareTest(
581 Label* materialize_true,
582 Label* materialize_false,
585 Label** fall_through) const {
586 // In an effect context, the true and the false case branch to the
588 *if_true = *if_false = *fall_through = materialize_true;
592 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
593 Label* materialize_true,
594 Label* materialize_false,
597 Label** fall_through) const {
598 *if_true = *fall_through = materialize_true;
599 *if_false = materialize_false;
603 void FullCodeGenerator::StackValueContext::PrepareTest(
604 Label* materialize_true,
605 Label* materialize_false,
608 Label** fall_through) const {
609 *if_true = *fall_through = materialize_true;
610 *if_false = materialize_false;
614 void FullCodeGenerator::TestContext::PrepareTest(
615 Label* materialize_true,
616 Label* materialize_false,
619 Label** fall_through) const {
620 *if_true = true_label_;
621 *if_false = false_label_;
622 *fall_through = fall_through_;
626 void FullCodeGenerator::DoTest(const TestContext* context) {
627 DoTest(context->condition(),
628 context->true_label(),
629 context->false_label(),
630 context->fall_through());
634 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
635 DCHECK(scope_->is_script_scope());
637 for (int i = 0; i < declarations->length(); i++) {
638 ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
639 if (declaration != NULL) {
640 ModuleLiteral* module = declaration->module()->AsModuleLiteral();
641 if (module != NULL) {
642 Comment cmnt(masm_, "[ Link nested modules");
643 Scope* scope = module->body()->scope();
644 DCHECK(scope->module()->IsFrozen());
646 scope->module()->Allocate(scope->module_var()->index());
648 // Set up module context.
649 DCHECK(scope->module()->Index() >= 0);
650 __ Push(Smi::FromInt(scope->module()->Index()));
651 __ Push(scope->GetScopeInfo(isolate()));
652 __ CallRuntime(Runtime::kPushModuleContext, 2);
653 StoreToFrameField(StandardFrameConstants::kContextOffset,
656 AllocateModules(scope->declarations());
658 // Pop module context.
659 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
660 // Update local stack frame context field.
661 StoreToFrameField(StandardFrameConstants::kContextOffset,
669 // Modules have their own local scope, represented by their own context.
670 // Module instance objects have an accessor for every export that forwards
671 // access to the respective slot from the module's context. (Exports that are
672 // modules themselves, however, are simple data properties.)
674 // All modules have a _hosting_ scope/context, which (currently) is the
675 // enclosing script scope. To deal with recursion, nested modules are hosted
676 // by the same scope as global ones.
678 // For every (global or nested) module literal, the hosting context has an
679 // internal slot that points directly to the respective module context. This
680 // enables quick access to (statically resolved) module members by 2-dimensional
681 // access through the hosting context. For example,
685 // module B { let y; }
687 // module C { let z; }
689 // allocates contexts as follows:
691 // [header| .A | .B | .C | A | C ] (global)
693 // | | +-- [header| z ] (module)
695 // | +------- [header| y ] (module)
697 // +------------ [header| x | B ] (module)
699 // Here, .A, .B, .C are the internal slots pointing to the hosted module
700 // contexts, whereas A, B, C hold the actual instance objects (note that every
701 // module context also points to the respective instance object through its
702 // extension slot in the header).
704 // To deal with arbitrary recursion and aliases between modules,
705 // they are created and initialized in several stages. Each stage applies to
706 // all modules in the hosting script scope, including nested ones.
708 // 1. Allocate: for each module _literal_, allocate the module contexts and
709 // respective instance object and wire them up. This happens in the
710 // PushModuleContext runtime function, as generated by AllocateModules
711 // (invoked by VisitDeclarations in the hosting scope).
713 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
714 // assign the respective instance object to respective local variables. This
715 // happens in VisitModuleDeclaration, and uses the instance objects created
716 // in the previous stage.
717 // For each module _literal_, this phase also constructs a module descriptor
718 // for the next stage. This happens in VisitModuleLiteral.
720 // 3. Populate: invoke the DeclareModules runtime function to populate each
721 // _instance_ object with accessors for it exports. This is generated by
722 // DeclareModules (invoked by VisitDeclarations in the hosting scope again),
723 // and uses the descriptors generated in the previous stage.
725 // 4. Initialize: execute the module bodies (and other code) in sequence. This
726 // happens by the separate statements generated for module bodies. To reenter
727 // the module scopes properly, the parser inserted ModuleStatements.
729 void FullCodeGenerator::VisitDeclarations(
730 ZoneList<Declaration*>* declarations) {
731 Handle<FixedArray> saved_modules = modules_;
732 int saved_module_index = module_index_;
733 ZoneList<Handle<Object> >* saved_globals = globals_;
734 ZoneList<Handle<Object> > inner_globals(10, zone());
735 globals_ = &inner_globals;
737 if (scope_->num_modules() != 0) {
738 // This is a scope hosting modules. Allocate a descriptor array to pass
739 // to the runtime for initialization.
740 Comment cmnt(masm_, "[ Allocate modules");
741 DCHECK(scope_->is_script_scope());
743 isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
746 // Generate code for allocating all modules, including nested ones.
747 // The allocated contexts are stored in internal variables in this scope.
748 AllocateModules(declarations);
751 AstVisitor::VisitDeclarations(declarations);
753 if (scope_->num_modules() != 0) {
754 // TODO(ES6): This step, which creates module instance objects,
755 // can probably be delayed until an "import *" declaration
756 // reifies a module instance. Until imports are implemented,
757 // we skip it altogether.
759 // Initialize modules from descriptor array.
760 // DCHECK(module_index_ == modules_->length());
761 // DeclareModules(modules_);
762 modules_ = saved_modules;
763 module_index_ = saved_module_index;
766 if (!globals_->is_empty()) {
767 // Invoke the platform-dependent code generator to do the actual
768 // declaration of the global functions and variables.
769 Handle<FixedArray> array =
770 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
771 for (int i = 0; i < globals_->length(); ++i)
772 array->set(i, *globals_->at(i));
773 DeclareGlobals(array);
776 globals_ = saved_globals;
780 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
781 Block* block = module->body();
782 Scope* saved_scope = scope();
783 scope_ = block->scope();
784 ModuleDescriptor* descriptor = scope_->module();
786 Comment cmnt(masm_, "[ ModuleLiteral");
787 SetStatementPosition(block);
789 DCHECK(!modules_.is_null());
790 DCHECK(module_index_ < modules_->length());
791 int index = module_index_++;
793 // Set up module context.
794 DCHECK(descriptor->Index() >= 0);
795 __ Push(Smi::FromInt(descriptor->Index()));
796 __ Push(Smi::FromInt(0));
797 __ CallRuntime(Runtime::kPushModuleContext, 2);
798 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
801 Comment cmnt(masm_, "[ Declarations");
802 VisitDeclarations(scope_->declarations());
805 // Populate the module description.
806 Handle<ModuleInfo> description =
807 ModuleInfo::Create(isolate(), descriptor, scope_);
808 modules_->set(index, *description);
810 scope_ = saved_scope;
811 // Pop module context.
812 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
813 // Update local stack frame context field.
814 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
818 // TODO(adamk): Delete ModulePath.
819 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
823 // TODO(adamk): Delete ModuleUrl.
824 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
828 int FullCodeGenerator::DeclareGlobalsFlags() {
829 DCHECK(DeclareGlobalsLanguageMode::is_valid(language_mode()));
830 return DeclareGlobalsEvalFlag::encode(is_eval()) |
831 DeclareGlobalsNativeFlag::encode(is_native()) |
832 DeclareGlobalsLanguageMode::encode(language_mode());
836 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
837 CodeGenerator::RecordPositions(masm_, fun->start_position());
841 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
842 CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
846 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
847 if (!info_->is_debug()) {
848 CodeGenerator::RecordPositions(masm_, stmt->position());
850 // Check if the statement will be breakable without adding a debug break
852 BreakableStatementChecker checker(info_->isolate(), zone());
854 // Record the statement position right here if the statement is not
855 // breakable. For breakable statements the actual recording of the
856 // position will be postponed to the breakable code (typically an IC).
857 bool position_recorded = CodeGenerator::RecordPositions(
858 masm_, stmt->position(), !checker.is_breakable());
859 // If the position recording did record a new position generate a debug
860 // break slot to make the statement breakable.
861 if (position_recorded) {
862 DebugCodegen::GenerateSlot(masm_);
868 void FullCodeGenerator::VisitSuperReference(SuperReference* super) {
869 __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
873 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
874 if (!info_->is_debug()) {
875 CodeGenerator::RecordPositions(masm_, expr->position());
877 // Check if the expression will be breakable without adding a debug break
879 BreakableStatementChecker checker(info_->isolate(), zone());
881 // Record a statement position right here if the expression is not
882 // breakable. For breakable expressions the actual recording of the
883 // position will be postponed to the breakable code (typically an IC).
884 // NOTE this will record a statement position for something which might
885 // not be a statement. As stepping in the debugger will only stop at
886 // statement positions this is used for e.g. the condition expression of
888 bool position_recorded = CodeGenerator::RecordPositions(
889 masm_, expr->position(), !checker.is_breakable());
890 // If the position recording did record a new position generate a debug
891 // break slot to make the statement breakable.
892 if (position_recorded) {
893 DebugCodegen::GenerateSlot(masm_);
899 void FullCodeGenerator::SetSourcePosition(int pos) {
900 if (pos != RelocInfo::kNoPosition) {
901 masm_->positions_recorder()->RecordPosition(pos);
906 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
907 ZoneList<Expression*>* args = expr->arguments();
908 DCHECK(args->length() == 2);
909 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
913 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
914 ZoneList<Expression*>* args = expr->arguments();
915 DCHECK(args->length() == 2);
916 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
920 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
921 context()->Plug(handle(Smi::FromInt(0), isolate()));
925 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
926 switch (expr->op()) {
928 return VisitComma(expr);
931 return VisitLogicalExpression(expr);
933 return VisitArithmeticExpression(expr);
938 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
939 if (context()->IsEffect()) {
940 VisitForEffect(expr);
941 } else if (context()->IsAccumulatorValue()) {
942 VisitForAccumulatorValue(expr);
943 } else if (context()->IsStackValue()) {
944 VisitForStackValue(expr);
945 } else if (context()->IsTest()) {
946 const TestContext* test = TestContext::cast(context());
947 VisitForControl(expr, test->true_label(), test->false_label(),
948 test->fall_through());
953 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
954 Comment cmnt(masm_, "[ Comma");
955 VisitForEffect(expr->left());
956 VisitInDuplicateContext(expr->right());
960 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
961 bool is_logical_and = expr->op() == Token::AND;
962 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
963 Expression* left = expr->left();
964 Expression* right = expr->right();
965 BailoutId right_id = expr->RightId();
968 if (context()->IsTest()) {
970 const TestContext* test = TestContext::cast(context());
971 if (is_logical_and) {
972 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
974 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
976 PrepareForBailoutForId(right_id, NO_REGISTERS);
977 __ bind(&eval_right);
979 } else if (context()->IsAccumulatorValue()) {
980 VisitForAccumulatorValue(left);
981 // We want the value in the accumulator for the test, and on the stack in
983 __ Push(result_register());
984 Label discard, restore;
985 if (is_logical_and) {
986 DoTest(left, &discard, &restore, &restore);
988 DoTest(left, &restore, &discard, &restore);
991 __ Pop(result_register());
995 PrepareForBailoutForId(right_id, NO_REGISTERS);
997 } else if (context()->IsStackValue()) {
998 VisitForAccumulatorValue(left);
999 // We want the value in the accumulator for the test, and on the stack in
1001 __ Push(result_register());
1003 if (is_logical_and) {
1004 DoTest(left, &discard, &done, &discard);
1006 DoTest(left, &done, &discard, &discard);
1010 PrepareForBailoutForId(right_id, NO_REGISTERS);
1013 DCHECK(context()->IsEffect());
1015 if (is_logical_and) {
1016 VisitForControl(left, &eval_right, &done, &eval_right);
1018 VisitForControl(left, &done, &eval_right, &eval_right);
1020 PrepareForBailoutForId(right_id, NO_REGISTERS);
1021 __ bind(&eval_right);
1024 VisitInDuplicateContext(right);
1029 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1030 Token::Value op = expr->op();
1031 Comment cmnt(masm_, "[ ArithmeticExpression");
1032 Expression* left = expr->left();
1033 Expression* right = expr->right();
1035 VisitForStackValue(left);
1036 VisitForAccumulatorValue(right);
1038 SetSourcePosition(expr->position());
1039 if (ShouldInlineSmiCase(op)) {
1040 EmitInlineSmiBinaryOp(expr, op, left, right);
1042 EmitBinaryOp(expr, op);
1047 void FullCodeGenerator::VisitBlock(Block* stmt) {
1048 Comment cmnt(masm_, "[ Block");
1049 NestedBlock nested_block(this, stmt);
1050 SetStatementPosition(stmt);
1053 EnterBlockScopeIfNeeded block_scope_state(
1054 this, stmt->scope(), stmt->EntryId(), stmt->DeclsId(), stmt->ExitId());
1055 VisitStatements(stmt->statements());
1056 __ bind(nested_block.break_label());
1061 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1062 Comment cmnt(masm_, "[ Module context");
1064 DCHECK(stmt->body()->scope()->is_module_scope());
1066 __ Push(Smi::FromInt(stmt->body()->scope()->module()->Index()));
1067 __ Push(Smi::FromInt(0));
1068 __ CallRuntime(Runtime::kPushModuleContext, 2);
1070 StandardFrameConstants::kContextOffset, context_register());
1072 Scope* saved_scope = scope_;
1073 scope_ = stmt->body()->scope();
1074 VisitStatements(stmt->body()->statements());
1075 scope_ = saved_scope;
1076 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1077 // Update local stack frame context field.
1078 StoreToFrameField(StandardFrameConstants::kContextOffset,
1079 context_register());
1083 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1084 Comment cmnt(masm_, "[ ExpressionStatement");
1085 SetStatementPosition(stmt);
1086 VisitForEffect(stmt->expression());
1090 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1091 Comment cmnt(masm_, "[ EmptyStatement");
1092 SetStatementPosition(stmt);
1096 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1097 Comment cmnt(masm_, "[ IfStatement");
1098 SetStatementPosition(stmt);
1099 Label then_part, else_part, done;
1101 if (stmt->HasElseStatement()) {
1102 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1103 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1104 __ bind(&then_part);
1105 Visit(stmt->then_statement());
1108 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1109 __ bind(&else_part);
1110 Visit(stmt->else_statement());
1112 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1113 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1114 __ bind(&then_part);
1115 Visit(stmt->then_statement());
1117 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1120 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1124 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1125 Comment cmnt(masm_, "[ ContinueStatement");
1126 SetStatementPosition(stmt);
1127 NestedStatement* current = nesting_stack_;
1128 int stack_depth = 0;
1129 int context_length = 0;
1130 // When continuing, we clobber the unpredictable value in the accumulator
1131 // with one that's safe for GC. If we hit an exit from the try block of
1132 // try...finally on our way out, we will unconditionally preserve the
1133 // accumulator on the stack.
1135 while (!current->IsContinueTarget(stmt->target())) {
1136 current = current->Exit(&stack_depth, &context_length);
1138 __ Drop(stack_depth);
1139 if (context_length > 0) {
1140 while (context_length > 0) {
1141 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1144 StoreToFrameField(StandardFrameConstants::kContextOffset,
1145 context_register());
1148 __ jmp(current->AsIteration()->continue_label());
1152 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1153 Comment cmnt(masm_, "[ BreakStatement");
1154 SetStatementPosition(stmt);
1155 NestedStatement* current = nesting_stack_;
1156 int stack_depth = 0;
1157 int context_length = 0;
1158 // When breaking, we clobber the unpredictable value in the accumulator
1159 // with one that's safe for GC. If we hit an exit from the try block of
1160 // try...finally on our way out, we will unconditionally preserve the
1161 // accumulator on the stack.
1163 while (!current->IsBreakTarget(stmt->target())) {
1164 current = current->Exit(&stack_depth, &context_length);
1166 __ Drop(stack_depth);
1167 if (context_length > 0) {
1168 while (context_length > 0) {
1169 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1172 StoreToFrameField(StandardFrameConstants::kContextOffset,
1173 context_register());
1176 __ jmp(current->AsBreakable()->break_label());
1180 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1181 NestedStatement* current = nesting_stack_;
1182 int stack_depth = 0;
1183 int context_length = 0;
1184 while (current != NULL) {
1185 current = current->Exit(&stack_depth, &context_length);
1187 __ Drop(stack_depth);
1191 void FullCodeGenerator::EmitPropertyKey(ObjectLiteralProperty* property,
1192 BailoutId bailout_id) {
1193 VisitForStackValue(property->key());
1194 __ InvokeBuiltin(Builtins::TO_NAME, CALL_FUNCTION);
1195 PrepareForBailoutForId(bailout_id, NO_REGISTERS);
1196 __ Push(result_register());
1200 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1201 Comment cmnt(masm_, "[ ReturnStatement");
1202 SetStatementPosition(stmt);
1203 Expression* expr = stmt->expression();
1204 VisitForAccumulatorValue(expr);
1205 EmitUnwindBeforeReturn();
1206 EmitReturnSequence();
1210 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1211 Comment cmnt(masm_, "[ WithStatement");
1212 SetStatementPosition(stmt);
1214 VisitForStackValue(stmt->expression());
1215 PushFunctionArgumentForContextAllocation();
1216 __ CallRuntime(Runtime::kPushWithContext, 2);
1217 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1218 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1220 Scope* saved_scope = scope();
1221 scope_ = stmt->scope();
1222 { WithOrCatch body(this);
1223 Visit(stmt->statement());
1225 scope_ = saved_scope;
1228 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1229 // Update local stack frame context field.
1230 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1234 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1235 Comment cmnt(masm_, "[ DoWhileStatement");
1236 SetStatementPosition(stmt);
1237 Label body, book_keeping;
1239 Iteration loop_statement(this, stmt);
1240 increment_loop_depth();
1243 Visit(stmt->body());
1245 // Record the position of the do while condition and make sure it is
1246 // possible to break on the condition.
1247 __ bind(loop_statement.continue_label());
1248 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1249 SetExpressionPosition(stmt->cond());
1250 VisitForControl(stmt->cond(),
1252 loop_statement.break_label(),
1255 // Check stack before looping.
1256 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1257 __ bind(&book_keeping);
1258 EmitBackEdgeBookkeeping(stmt, &body);
1261 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1262 __ bind(loop_statement.break_label());
1263 decrement_loop_depth();
1267 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1268 Comment cmnt(masm_, "[ WhileStatement");
1271 Iteration loop_statement(this, stmt);
1272 increment_loop_depth();
1276 SetExpressionPosition(stmt->cond());
1277 VisitForControl(stmt->cond(),
1279 loop_statement.break_label(),
1282 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1284 Visit(stmt->body());
1286 __ bind(loop_statement.continue_label());
1288 // Check stack before looping.
1289 EmitBackEdgeBookkeeping(stmt, &loop);
1292 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1293 __ bind(loop_statement.break_label());
1294 decrement_loop_depth();
1298 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1299 Comment cmnt(masm_, "[ ForStatement");
1302 Iteration loop_statement(this, stmt);
1304 // Set statement position for a break slot before entering the for-body.
1305 SetStatementPosition(stmt);
1307 if (stmt->init() != NULL) {
1308 SetStatementPosition(stmt->init());
1309 Visit(stmt->init());
1312 increment_loop_depth();
1313 // Emit the test at the bottom of the loop (even if empty).
1316 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1318 Visit(stmt->body());
1320 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1321 __ bind(loop_statement.continue_label());
1322 if (stmt->next() != NULL) {
1323 SetStatementPosition(stmt->next());
1324 Visit(stmt->next());
1327 // Emit the statement position here as this is where the for
1328 // statement code starts.
1329 SetStatementPosition(stmt);
1331 // Check stack before looping.
1332 EmitBackEdgeBookkeeping(stmt, &body);
1335 if (stmt->cond() != NULL) {
1336 SetExpressionPosition(stmt->cond());
1337 VisitForControl(stmt->cond(),
1339 loop_statement.break_label(),
1340 loop_statement.break_label());
1345 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1346 __ bind(loop_statement.break_label());
1347 decrement_loop_depth();
1351 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1352 Comment cmnt(masm_, "[ ForOfStatement");
1353 SetStatementPosition(stmt);
1355 Iteration loop_statement(this, stmt);
1356 increment_loop_depth();
1358 // var iterator = iterable[Symbol.iterator]();
1359 VisitForEffect(stmt->assign_iterator());
1362 __ bind(loop_statement.continue_label());
1364 // result = iterator.next()
1365 SetExpressionPosition(stmt->next_result());
1366 VisitForEffect(stmt->next_result());
1368 // if (result.done) break;
1369 Label result_not_done;
1370 VisitForControl(stmt->result_done(), loop_statement.break_label(),
1371 &result_not_done, &result_not_done);
1372 __ bind(&result_not_done);
1374 // each = result.value
1375 VisitForEffect(stmt->assign_each());
1377 // Generate code for the body of the loop.
1378 Visit(stmt->body());
1380 // Check stack before looping.
1381 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1382 EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1383 __ jmp(loop_statement.continue_label());
1385 // Exit and decrement the loop depth.
1386 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1387 __ bind(loop_statement.break_label());
1388 decrement_loop_depth();
1392 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1393 Comment cmnt(masm_, "[ TryCatchStatement");
1394 SetStatementPosition(stmt);
1395 // The try block adds a handler to the exception handler chain before
1396 // entering, and removes it again when exiting normally. If an exception
1397 // is thrown during execution of the try block, the handler is consumed
1398 // and control is passed to the catch block with the exception in the
1401 Label try_entry, handler_entry, exit;
1403 __ bind(&handler_entry);
1404 // Exception handler code, the exception is in the result register.
1405 // Extend the context before executing the catch block.
1406 { Comment cmnt(masm_, "[ Extend catch context");
1407 __ Push(stmt->variable()->name());
1408 __ Push(result_register());
1409 PushFunctionArgumentForContextAllocation();
1410 __ CallRuntime(Runtime::kPushCatchContext, 3);
1411 StoreToFrameField(StandardFrameConstants::kContextOffset,
1412 context_register());
1415 Scope* saved_scope = scope();
1416 scope_ = stmt->scope();
1417 DCHECK(scope_->declarations()->is_empty());
1418 { WithOrCatch catch_body(this);
1419 Visit(stmt->catch_block());
1421 // Restore the context.
1422 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1423 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1424 scope_ = saved_scope;
1427 // Try block code. Sets up the exception handler chain.
1428 __ bind(&try_entry);
1429 EnterTryBlock(stmt->index(), &handler_entry);
1430 { TryCatch try_body(this);
1431 Visit(stmt->try_block());
1433 ExitTryBlock(stmt->index());
1438 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1439 Comment cmnt(masm_, "[ TryFinallyStatement");
1440 SetStatementPosition(stmt);
1441 // Try finally is compiled by setting up a try-handler on the stack while
1442 // executing the try body, and removing it again afterwards.
1444 // The try-finally construct can enter the finally block in three ways:
1445 // 1. By exiting the try-block normally. This removes the try-handler and
1446 // calls the finally block code before continuing.
1447 // 2. By exiting the try-block with a function-local control flow transfer
1448 // (break/continue/return). The site of the, e.g., break removes the
1449 // try handler and calls the finally block code before continuing
1450 // its outward control transfer.
1451 // 3. By exiting the try-block with a thrown exception.
1452 // This can happen in nested function calls. It traverses the try-handler
1453 // chain and consumes the try-handler entry before jumping to the
1454 // handler code. The handler code then calls the finally-block before
1455 // rethrowing the exception.
1457 // The finally block must assume a return address on top of the stack
1458 // (or in the link register on ARM chips) and a value (return value or
1459 // exception) in the result register (rax/eax/r0), both of which must
1460 // be preserved. The return address isn't GC-safe, so it should be
1461 // cooked before GC.
1462 Label try_entry, handler_entry, finally_entry;
1464 // Jump to try-handler setup and try-block code.
1466 __ bind(&handler_entry);
1467 // Exception handler code. This code is only executed when an exception
1468 // is thrown. The exception is in the result register, and must be
1469 // preserved by the finally block. Call the finally block and then
1470 // rethrow the exception if it returns.
1471 __ Call(&finally_entry);
1472 __ Push(result_register());
1473 __ CallRuntime(Runtime::kReThrow, 1);
1475 // Finally block implementation.
1476 __ bind(&finally_entry);
1477 EnterFinallyBlock();
1478 { Finally finally_body(this);
1479 Visit(stmt->finally_block());
1481 ExitFinallyBlock(); // Return to the calling code.
1483 // Set up try handler.
1484 __ bind(&try_entry);
1485 EnterTryBlock(stmt->index(), &handler_entry);
1486 { TryFinally try_body(this, &finally_entry);
1487 Visit(stmt->try_block());
1489 ExitTryBlock(stmt->index());
1490 // Execute the finally block on the way out. Clobber the unpredictable
1491 // value in the result register with one that's safe for GC because the
1492 // finally block will unconditionally preserve the result register on the
1495 __ Call(&finally_entry);
1499 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1500 Comment cmnt(masm_, "[ DebuggerStatement");
1501 SetStatementPosition(stmt);
1504 // Ignore the return value.
1506 PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1510 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1515 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1516 Comment cmnt(masm_, "[ Conditional");
1517 Label true_case, false_case, done;
1518 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1520 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1521 __ bind(&true_case);
1522 SetExpressionPosition(expr->then_expression());
1523 if (context()->IsTest()) {
1524 const TestContext* for_test = TestContext::cast(context());
1525 VisitForControl(expr->then_expression(),
1526 for_test->true_label(),
1527 for_test->false_label(),
1530 VisitInDuplicateContext(expr->then_expression());
1534 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1535 __ bind(&false_case);
1536 SetExpressionPosition(expr->else_expression());
1537 VisitInDuplicateContext(expr->else_expression());
1538 // If control flow falls through Visit, merge it with true case here.
1539 if (!context()->IsTest()) {
1545 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1546 Comment cmnt(masm_, "[ Literal");
1547 context()->Plug(expr->value());
1551 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1552 Comment cmnt(masm_, "[ FunctionLiteral");
1554 // Build the function boilerplate and instantiate it.
1555 Handle<SharedFunctionInfo> function_info =
1556 Compiler::BuildFunctionInfo(expr, script(), info_);
1557 if (function_info.is_null()) {
1561 EmitNewClosure(function_info, expr->pretenure());
1565 void FullCodeGenerator::VisitClassLiteral(ClassLiteral* lit) {
1566 Comment cmnt(masm_, "[ ClassLiteral");
1569 EnterBlockScopeIfNeeded block_scope_state(
1570 this, lit->scope(), lit->EntryId(), lit->DeclsId(), lit->ExitId());
1572 if (lit->raw_name() != NULL) {
1573 __ Push(lit->name());
1575 __ Push(isolate()->factory()->undefined_value());
1578 if (lit->extends() != NULL) {
1579 VisitForStackValue(lit->extends());
1581 __ Push(isolate()->factory()->the_hole_value());
1584 VisitForStackValue(lit->constructor());
1587 __ Push(Smi::FromInt(lit->start_position()));
1588 __ Push(Smi::FromInt(lit->end_position()));
1590 __ CallRuntime(Runtime::kDefineClass, 6);
1591 EmitClassDefineProperties(lit);
1593 if (lit->scope() != NULL) {
1594 DCHECK_NOT_NULL(lit->class_variable_proxy());
1595 EmitVariableAssignment(lit->class_variable_proxy()->var(),
1600 context()->Plug(result_register());
1604 void FullCodeGenerator::VisitNativeFunctionLiteral(
1605 NativeFunctionLiteral* expr) {
1606 Comment cmnt(masm_, "[ NativeFunctionLiteral");
1608 // Compute the function template for the native function.
1609 Handle<String> name = expr->name();
1610 v8::Handle<v8::FunctionTemplate> fun_template =
1611 expr->extension()->GetNativeFunctionTemplate(
1612 reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1613 DCHECK(!fun_template.IsEmpty());
1615 // Instantiate the function and create a shared function info from it.
1616 Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1617 const int literals = fun->NumberOfLiterals();
1618 Handle<Code> code = Handle<Code>(fun->shared()->code());
1619 Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1620 Handle<SharedFunctionInfo> shared =
1621 isolate()->factory()->NewSharedFunctionInfo(
1622 name, literals, FunctionKind::kNormalFunction, code,
1623 Handle<ScopeInfo>(fun->shared()->scope_info()),
1624 Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1625 shared->set_construct_stub(*construct_stub);
1627 // Copy the function data to the shared function info.
1628 shared->set_function_data(fun->shared()->function_data());
1629 int parameters = fun->shared()->internal_formal_parameter_count();
1630 shared->set_internal_formal_parameter_count(parameters);
1632 EmitNewClosure(shared, false);
1636 void FullCodeGenerator::VisitThrow(Throw* expr) {
1637 Comment cmnt(masm_, "[ Throw");
1638 VisitForStackValue(expr->exception());
1639 __ CallRuntime(Runtime::kThrow, 1);
1640 // Never returns here.
1644 void FullCodeGenerator::EnterTryBlock(int index, Label* handler) {
1645 handler_table()->SetRangeStart(index, masm()->pc_offset());
1646 handler_table()->SetRangeHandler(index, handler->pos());
1648 // Determine expression stack depth of try statement.
1649 int stack_depth = info_->scope()->num_stack_slots(); // Include stack locals.
1650 for (NestedStatement* current = nesting_stack_; current != NULL; /*nop*/) {
1651 current = current->AccumulateDepth(&stack_depth);
1653 handler_table()->SetRangeDepth(index, stack_depth);
1655 // Push context onto operand stack.
1656 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1657 __ Push(context_register());
1661 void FullCodeGenerator::ExitTryBlock(int index) {
1662 handler_table()->SetRangeEnd(index, masm()->pc_offset());
1664 // Drop context from operand stack.
1665 __ Drop(TryBlockConstant::kElementCount);
1669 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
1670 int* stack_depth, int* context_length) {
1671 // The macros used here must preserve the result register.
1673 // Because the handler block contains the context of the finally
1674 // code, we can restore it directly from there for the finally code
1675 // rather than iteratively unwinding contexts via their previous
1677 if (*context_length > 0) {
1678 __ Drop(*stack_depth); // Down to the handler block.
1679 // Restore the context to its dedicated register and the stack.
1680 STATIC_ASSERT(TryFinally::kElementCount == 1);
1681 __ Pop(codegen_->context_register());
1682 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1683 codegen_->context_register());
1685 // Down to the handler block and also drop context.
1686 __ Drop(*stack_depth + kElementCount);
1688 __ Call(finally_entry_);
1691 *context_length = 0;
1696 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1697 Expression* sub_expr;
1698 Handle<String> check;
1699 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1700 EmitLiteralCompareTypeof(expr, sub_expr, check);
1704 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1705 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1709 if (expr->IsLiteralCompareNull(&sub_expr)) {
1710 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1718 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1719 DisallowHeapAllocation no_gc;
1720 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1722 // Increment loop nesting level by one and iterate over the back edge table
1723 // to find the matching loops to patch the interrupt
1724 // call to an unconditional call to the replacement code.
1725 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1726 if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1728 BackEdgeTable back_edges(unoptimized, &no_gc);
1729 for (uint32_t i = 0; i < back_edges.length(); i++) {
1730 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1731 DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1734 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1738 unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1739 DCHECK(Verify(isolate, unoptimized));
1743 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1744 DisallowHeapAllocation no_gc;
1745 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1747 // Iterate over the back edge table and revert the patched interrupt calls.
1748 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1750 BackEdgeTable back_edges(unoptimized, &no_gc);
1751 for (uint32_t i = 0; i < back_edges.length(); i++) {
1752 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1753 DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1756 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1760 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1761 // Assert that none of the back edges are patched anymore.
1762 DCHECK(Verify(isolate, unoptimized));
1766 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1767 DisallowHeapAllocation no_gc;
1768 Isolate* isolate = code->GetIsolate();
1769 Address pc = code->instruction_start() + pc_offset;
1770 Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1771 PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1775 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1776 DisallowHeapAllocation no_gc;
1777 Isolate* isolate = code->GetIsolate();
1778 Address pc = code->instruction_start() + pc_offset;
1780 if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1781 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1782 PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1788 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1789 DisallowHeapAllocation no_gc;
1790 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1791 BackEdgeTable back_edges(unoptimized, &no_gc);
1792 for (uint32_t i = 0; i < back_edges.length(); i++) {
1793 uint32_t loop_depth = back_edges.loop_depth(i);
1794 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1795 // Assert that all back edges for shallower loops (and only those)
1796 // have already been patched.
1797 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1798 GetBackEdgeState(isolate,
1800 back_edges.pc(i)) != INTERRUPT);
1807 FullCodeGenerator::EnterBlockScopeIfNeeded::EnterBlockScopeIfNeeded(
1808 FullCodeGenerator* codegen, Scope* scope, BailoutId entry_id,
1809 BailoutId declarations_id, BailoutId exit_id)
1810 : codegen_(codegen), scope_(scope), exit_id_(exit_id) {
1811 saved_scope_ = codegen_->scope();
1813 if (scope == NULL) {
1814 codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1816 codegen_->scope_ = scope;
1818 Comment cmnt(masm(), "[ Extend block context");
1819 __ Push(scope->GetScopeInfo(codegen->isolate()));
1820 codegen_->PushFunctionArgumentForContextAllocation();
1821 __ CallRuntime(Runtime::kPushBlockContext, 2);
1823 // Replace the context stored in the frame.
1824 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1825 codegen_->context_register());
1826 codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1829 Comment cmnt(masm(), "[ Declarations");
1830 codegen_->VisitDeclarations(scope->declarations());
1831 codegen_->PrepareForBailoutForId(declarations_id, NO_REGISTERS);
1837 FullCodeGenerator::EnterBlockScopeIfNeeded::~EnterBlockScopeIfNeeded() {
1838 if (scope_ != NULL) {
1839 codegen_->LoadContextField(codegen_->context_register(),
1840 Context::PREVIOUS_INDEX);
1841 // Update local stack frame context field.
1842 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1843 codegen_->context_register());
1845 codegen_->PrepareForBailoutForId(exit_id_, NO_REGISTERS);
1846 codegen_->scope_ = saved_scope_;
1853 } } // namespace v8::internal