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.
7 #include "src/codegen.h"
8 #include "src/compiler.h"
10 #include "src/full-codegen.h"
11 #include "src/liveedit.h"
12 #include "src/macro-assembler.h"
13 #include "src/prettyprinter.h"
14 #include "src/scopeinfo.h"
15 #include "src/scopes.h"
16 #include "src/snapshot.h"
17 #include "src/stub-cache.h"
22 void BreakableStatementChecker::Check(Statement* stmt) {
27 void BreakableStatementChecker::Check(Expression* expr) {
32 void BreakableStatementChecker::VisitVariableDeclaration(
33 VariableDeclaration* decl) {
36 void BreakableStatementChecker::VisitFunctionDeclaration(
37 FunctionDeclaration* decl) {
40 void BreakableStatementChecker::VisitModuleDeclaration(
41 ModuleDeclaration* decl) {
44 void BreakableStatementChecker::VisitImportDeclaration(
45 ImportDeclaration* decl) {
48 void BreakableStatementChecker::VisitExportDeclaration(
49 ExportDeclaration* decl) {
53 void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
57 void BreakableStatementChecker::VisitModuleVariable(ModuleVariable* module) {
61 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
65 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
69 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
73 void BreakableStatementChecker::VisitBlock(Block* stmt) {
77 void BreakableStatementChecker::VisitExpressionStatement(
78 ExpressionStatement* stmt) {
79 // Check if expression is breakable.
80 Visit(stmt->expression());
84 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
88 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
89 // If the condition is breakable the if statement is breakable.
90 Visit(stmt->condition());
94 void BreakableStatementChecker::VisitContinueStatement(
95 ContinueStatement* stmt) {
99 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
103 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
104 // Return is breakable if the expression is.
105 Visit(stmt->expression());
109 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
110 Visit(stmt->expression());
114 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
115 // Switch statements breakable if the tag expression is.
120 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
121 // Mark do while as breakable to avoid adding a break slot in front of it.
122 is_breakable_ = true;
126 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
127 // Mark while statements breakable if the condition expression is.
132 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
133 // Mark for statements breakable if the condition expression is.
134 if (stmt->cond() != NULL) {
140 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
141 // Mark for in statements breakable if the enumerable expression is.
142 Visit(stmt->enumerable());
146 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
147 // For-of is breakable because of 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::VisitNativeFunctionLiteral(
182 NativeFunctionLiteral* expr) {
186 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
190 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
194 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
198 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
202 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
206 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
210 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
211 // If assigning to a property (including a global property) the assignment is
213 VariableProxy* proxy = expr->target()->AsVariableProxy();
214 Property* prop = expr->target()->AsProperty();
215 if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
216 is_breakable_ = true;
220 // Otherwise the assignment is breakable if the assigned value is.
221 Visit(expr->value());
225 void BreakableStatementChecker::VisitYield(Yield* expr) {
226 // Yield is breakable if the expression is.
227 Visit(expr->expression());
231 void BreakableStatementChecker::VisitThrow(Throw* expr) {
232 // Throw is breakable if the expression is.
233 Visit(expr->exception());
237 void BreakableStatementChecker::VisitProperty(Property* expr) {
238 // Property load is breakable.
239 is_breakable_ = true;
243 void BreakableStatementChecker::VisitCall(Call* expr) {
244 // Function calls both through IC and call stub are breakable.
245 is_breakable_ = true;
249 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
250 // Function calls through new are breakable.
251 is_breakable_ = true;
255 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
259 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
260 Visit(expr->expression());
264 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
265 Visit(expr->expression());
269 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
271 if (expr->op() != Token::AND &&
272 expr->op() != Token::OR) {
273 Visit(expr->right());
278 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
280 Visit(expr->right());
284 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
288 #define __ ACCESS_MASM(masm())
290 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
291 Isolate* isolate = info->isolate();
293 TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
295 Handle<Script> script = info->script();
296 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
297 int len = String::cast(script->source())->length();
298 isolate->counters()->total_full_codegen_source_size()->Increment(len);
300 CodeGenerator::MakeCodePrologue(info, "full");
301 const int kInitialBufferSize = 4 * KB;
302 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
303 if (info->will_serialize()) masm.enable_serializer();
305 LOG_CODE_EVENT(isolate,
306 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
308 FullCodeGenerator cgen(&masm, info);
310 if (cgen.HasStackOverflow()) {
311 DCHECK(!isolate->has_pending_exception());
314 unsigned table_offset = cgen.EmitBackEdgeTable();
316 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
317 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
318 code->set_optimizable(info->IsOptimizable() &&
319 !info->function()->dont_optimize() &&
320 info->function()->scope()->AllowsLazyCompilation());
321 cgen.PopulateDeoptimizationData(code);
322 cgen.PopulateTypeFeedbackInfo(code);
323 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
324 code->set_handler_table(*cgen.handler_table());
325 code->set_compiled_optimizable(info->IsOptimizable());
326 code->set_allow_osr_at_loop_nesting_level(0);
327 code->set_profiler_ticks(0);
328 code->set_back_edge_table_offset(table_offset);
329 CodeGenerator::PrintCode(code, info);
331 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
332 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
337 unsigned FullCodeGenerator::EmitBackEdgeTable() {
338 // The back edge table consists of a length (in number of entries)
339 // field, and then a sequence of entries. Each entry is a pair of AST id
340 // and code-relative pc offset.
341 masm()->Align(kPointerSize);
342 unsigned offset = masm()->pc_offset();
343 unsigned length = back_edges_.length();
345 for (unsigned i = 0; i < length; ++i) {
346 __ dd(back_edges_[i].id.ToInt());
347 __ dd(back_edges_[i].pc);
348 __ dd(back_edges_[i].loop_depth);
354 void FullCodeGenerator::EnsureSlotContainsAllocationSite(int slot) {
355 Handle<FixedArray> vector = FeedbackVector();
356 if (!vector->get(slot)->IsAllocationSite()) {
357 Handle<AllocationSite> allocation_site =
358 isolate()->factory()->NewAllocationSite();
359 vector->set(slot, *allocation_site);
364 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
365 // Fill in the deoptimization information.
366 DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
367 if (!info_->HasDeoptimizationSupport()) return;
368 int length = bailout_entries_.length();
369 Handle<DeoptimizationOutputData> data =
370 DeoptimizationOutputData::New(isolate(), length, TENURED);
371 for (int i = 0; i < length; i++) {
372 data->SetAstId(i, bailout_entries_[i].id);
373 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
375 code->set_deoptimization_data(*data);
379 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
380 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
381 info->set_ic_total_count(ic_total_count_);
382 DCHECK(!isolate()->heap()->InNewSpace(*info));
383 code->set_type_feedback_info(*info);
387 void FullCodeGenerator::Initialize() {
388 InitializeAstVisitor(info_->zone());
389 // The generation of debug code must match between the snapshot code and the
390 // code that is generated later. This is assumed by the debugger when it is
391 // calculating PC offsets after generating a debug version of code. Therefore
392 // we disable the production of debug code in the full compiler if we are
393 // either generating a snapshot or we booted from a snapshot.
394 generate_debug_code_ = FLAG_debug_code &&
395 !masm_->serializer_enabled() &&
396 !Snapshot::HaveASnapshotToStartFrom();
397 masm_->set_emit_debug_code(generate_debug_code_);
398 masm_->set_predictable_code_size(true);
402 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
403 PrepareForBailoutForId(node->id(), state);
407 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
409 ExtraICState extra_state = LoadIC::ComputeExtraICState(contextual_mode);
410 Handle<Code> ic = LoadIC::initialize_stub(isolate(), extra_state);
415 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
416 Handle<Code> ic = StoreIC::initialize_stub(isolate(), strict_mode());
421 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
422 // We record the offset of the function return so we can rebuild the frame
423 // if the function was inlined, i.e., this is the return address in the
424 // inlined function's frame.
426 // The state is ignored. We defensively set it to TOS_REG, which is the
427 // real state of the unoptimized code at the return site.
428 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
430 // In debug builds, mark the return so we can verify that this function
432 DCHECK(!call->return_is_recorded_);
433 call->return_is_recorded_ = true;
438 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
439 // There's no need to prepare this code for bailouts from already optimized
440 // code or code that can't be optimized.
441 if (!info_->HasDeoptimizationSupport()) return;
442 unsigned pc_and_state =
443 StateField::encode(state) | PcField::encode(masm_->pc_offset());
444 DCHECK(Smi::IsValid(pc_and_state));
446 for (int i = 0; i < bailout_entries_.length(); ++i) {
447 DCHECK(bailout_entries_[i].id != id);
450 BailoutEntry entry = { id, pc_and_state };
451 bailout_entries_.Add(entry, zone());
455 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
456 // The pc offset does not need to be encoded and packed together with a state.
457 DCHECK(masm_->pc_offset() > 0);
458 DCHECK(loop_depth() > 0);
459 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
460 BackEdgeEntry entry =
461 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
462 back_edges_.Add(entry, zone());
466 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
467 // Inline smi case inside loops, but not division and modulo which
468 // are too complicated and take up too much space.
469 if (op == Token::DIV ||op == Token::MOD) return false;
470 if (FLAG_always_inline_smi_code) return true;
471 return loop_depth_ > 0;
475 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
479 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
480 __ Move(result_register(), reg);
484 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
489 void FullCodeGenerator::TestContext::Plug(Register reg) const {
490 // For simplicity we always test the accumulator register.
491 __ Move(result_register(), reg);
492 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
493 codegen()->DoTest(this);
497 void FullCodeGenerator::EffectContext::PlugTOS() const {
502 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
503 __ Pop(result_register());
507 void FullCodeGenerator::StackValueContext::PlugTOS() const {
511 void FullCodeGenerator::TestContext::PlugTOS() const {
512 // For simplicity we always test the accumulator register.
513 __ Pop(result_register());
514 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
515 codegen()->DoTest(this);
519 void FullCodeGenerator::EffectContext::PrepareTest(
520 Label* materialize_true,
521 Label* materialize_false,
524 Label** fall_through) const {
525 // In an effect context, the true and the false case branch to the
527 *if_true = *if_false = *fall_through = materialize_true;
531 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
532 Label* materialize_true,
533 Label* materialize_false,
536 Label** fall_through) const {
537 *if_true = *fall_through = materialize_true;
538 *if_false = materialize_false;
542 void FullCodeGenerator::StackValueContext::PrepareTest(
543 Label* materialize_true,
544 Label* materialize_false,
547 Label** fall_through) const {
548 *if_true = *fall_through = materialize_true;
549 *if_false = materialize_false;
553 void FullCodeGenerator::TestContext::PrepareTest(
554 Label* materialize_true,
555 Label* materialize_false,
558 Label** fall_through) const {
559 *if_true = true_label_;
560 *if_false = false_label_;
561 *fall_through = fall_through_;
565 void FullCodeGenerator::DoTest(const TestContext* context) {
566 DoTest(context->condition(),
567 context->true_label(),
568 context->false_label(),
569 context->fall_through());
573 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
574 DCHECK(scope_->is_global_scope());
576 for (int i = 0; i < declarations->length(); i++) {
577 ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
578 if (declaration != NULL) {
579 ModuleLiteral* module = declaration->module()->AsModuleLiteral();
580 if (module != NULL) {
581 Comment cmnt(masm_, "[ Link nested modules");
582 Scope* scope = module->body()->scope();
583 Interface* interface = scope->interface();
584 DCHECK(interface->IsModule() && interface->IsFrozen());
586 interface->Allocate(scope->module_var()->index());
588 // Set up module context.
589 DCHECK(scope->interface()->Index() >= 0);
590 __ Push(Smi::FromInt(scope->interface()->Index()));
591 __ Push(scope->GetScopeInfo());
592 __ CallRuntime(Runtime::kPushModuleContext, 2);
593 StoreToFrameField(StandardFrameConstants::kContextOffset,
596 AllocateModules(scope->declarations());
598 // Pop module context.
599 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
600 // Update local stack frame context field.
601 StoreToFrameField(StandardFrameConstants::kContextOffset,
609 // Modules have their own local scope, represented by their own context.
610 // Module instance objects have an accessor for every export that forwards
611 // access to the respective slot from the module's context. (Exports that are
612 // modules themselves, however, are simple data properties.)
614 // All modules have a _hosting_ scope/context, which (currently) is the
615 // (innermost) enclosing global scope. To deal with recursion, nested modules
616 // are hosted by the same scope as global ones.
618 // For every (global or nested) module literal, the hosting context has an
619 // internal slot that points directly to the respective module context. This
620 // enables quick access to (statically resolved) module members by 2-dimensional
621 // access through the hosting context. For example,
625 // module B { let y; }
627 // module C { let z; }
629 // allocates contexts as follows:
631 // [header| .A | .B | .C | A | C ] (global)
633 // | | +-- [header| z ] (module)
635 // | +------- [header| y ] (module)
637 // +------------ [header| x | B ] (module)
639 // Here, .A, .B, .C are the internal slots pointing to the hosted module
640 // contexts, whereas A, B, C hold the actual instance objects (note that every
641 // module context also points to the respective instance object through its
642 // extension slot in the header).
644 // To deal with arbitrary recursion and aliases between modules,
645 // they are created and initialized in several stages. Each stage applies to
646 // all modules in the hosting global scope, including nested ones.
648 // 1. Allocate: for each module _literal_, allocate the module contexts and
649 // respective instance object and wire them up. This happens in the
650 // PushModuleContext runtime function, as generated by AllocateModules
651 // (invoked by VisitDeclarations in the hosting scope).
653 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
654 // assign the respective instance object to respective local variables. This
655 // happens in VisitModuleDeclaration, and uses the instance objects created
656 // in the previous stage.
657 // For each module _literal_, this phase also constructs a module descriptor
658 // for the next stage. This happens in VisitModuleLiteral.
660 // 3. Populate: invoke the DeclareModules runtime function to populate each
661 // _instance_ object with accessors for it exports. This is generated by
662 // DeclareModules (invoked by VisitDeclarations in the hosting scope again),
663 // and uses the descriptors generated in the previous stage.
665 // 4. Initialize: execute the module bodies (and other code) in sequence. This
666 // happens by the separate statements generated for module bodies. To reenter
667 // the module scopes properly, the parser inserted ModuleStatements.
669 void FullCodeGenerator::VisitDeclarations(
670 ZoneList<Declaration*>* declarations) {
671 Handle<FixedArray> saved_modules = modules_;
672 int saved_module_index = module_index_;
673 ZoneList<Handle<Object> >* saved_globals = globals_;
674 ZoneList<Handle<Object> > inner_globals(10, zone());
675 globals_ = &inner_globals;
677 if (scope_->num_modules() != 0) {
678 // This is a scope hosting modules. Allocate a descriptor array to pass
679 // to the runtime for initialization.
680 Comment cmnt(masm_, "[ Allocate modules");
681 DCHECK(scope_->is_global_scope());
683 isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
686 // Generate code for allocating all modules, including nested ones.
687 // The allocated contexts are stored in internal variables in this scope.
688 AllocateModules(declarations);
691 AstVisitor::VisitDeclarations(declarations);
693 if (scope_->num_modules() != 0) {
694 // Initialize modules from descriptor array.
695 DCHECK(module_index_ == modules_->length());
696 DeclareModules(modules_);
697 modules_ = saved_modules;
698 module_index_ = saved_module_index;
701 if (!globals_->is_empty()) {
702 // Invoke the platform-dependent code generator to do the actual
703 // declaration of the global functions and variables.
704 Handle<FixedArray> array =
705 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
706 for (int i = 0; i < globals_->length(); ++i)
707 array->set(i, *globals_->at(i));
708 DeclareGlobals(array);
711 globals_ = saved_globals;
715 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
716 Block* block = module->body();
717 Scope* saved_scope = scope();
718 scope_ = block->scope();
719 Interface* interface = scope_->interface();
721 Comment cmnt(masm_, "[ ModuleLiteral");
722 SetStatementPosition(block);
724 DCHECK(!modules_.is_null());
725 DCHECK(module_index_ < modules_->length());
726 int index = module_index_++;
728 // Set up module context.
729 DCHECK(interface->Index() >= 0);
730 __ Push(Smi::FromInt(interface->Index()));
731 __ Push(Smi::FromInt(0));
732 __ CallRuntime(Runtime::kPushModuleContext, 2);
733 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
736 Comment cmnt(masm_, "[ Declarations");
737 VisitDeclarations(scope_->declarations());
740 // Populate the module description.
741 Handle<ModuleInfo> description =
742 ModuleInfo::Create(isolate(), interface, scope_);
743 modules_->set(index, *description);
745 scope_ = saved_scope;
746 // Pop module context.
747 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
748 // Update local stack frame context field.
749 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
753 void FullCodeGenerator::VisitModuleVariable(ModuleVariable* module) {
755 // The instance object is resolved statically through the module's interface.
759 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
761 // The instance object is resolved statically through the module's interface.
765 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
766 // TODO(rossberg): dummy allocation for now.
767 Scope* scope = module->body()->scope();
768 Interface* interface = scope_->interface();
770 DCHECK(interface->IsModule() && interface->IsFrozen());
771 DCHECK(!modules_.is_null());
772 DCHECK(module_index_ < modules_->length());
773 interface->Allocate(scope->module_var()->index());
774 int index = module_index_++;
776 Handle<ModuleInfo> description =
777 ModuleInfo::Create(isolate(), interface, scope_);
778 modules_->set(index, *description);
782 int FullCodeGenerator::DeclareGlobalsFlags() {
783 DCHECK(DeclareGlobalsStrictMode::is_valid(strict_mode()));
784 return DeclareGlobalsEvalFlag::encode(is_eval()) |
785 DeclareGlobalsNativeFlag::encode(is_native()) |
786 DeclareGlobalsStrictMode::encode(strict_mode());
790 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
791 CodeGenerator::RecordPositions(masm_, fun->start_position());
795 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
796 CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
800 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
801 if (!info_->is_debug()) {
802 CodeGenerator::RecordPositions(masm_, stmt->position());
804 // Check if the statement will be breakable without adding a debug break
806 BreakableStatementChecker checker(zone());
808 // Record the statement position right here if the statement is not
809 // breakable. For breakable statements the actual recording of the
810 // position will be postponed to the breakable code (typically an IC).
811 bool position_recorded = CodeGenerator::RecordPositions(
812 masm_, stmt->position(), !checker.is_breakable());
813 // If the position recording did record a new position generate a debug
814 // break slot to make the statement breakable.
815 if (position_recorded) {
816 DebugCodegen::GenerateSlot(masm_);
822 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
823 if (!info_->is_debug()) {
824 CodeGenerator::RecordPositions(masm_, expr->position());
826 // Check if the expression will be breakable without adding a debug break
828 BreakableStatementChecker checker(zone());
830 // Record a statement position right here if the expression is not
831 // breakable. For breakable expressions the actual recording of the
832 // position will be postponed to the breakable code (typically an IC).
833 // NOTE this will record a statement position for something which might
834 // not be a statement. As stepping in the debugger will only stop at
835 // statement positions this is used for e.g. the condition expression of
837 bool position_recorded = CodeGenerator::RecordPositions(
838 masm_, expr->position(), !checker.is_breakable());
839 // If the position recording did record a new position generate a debug
840 // break slot to make the statement breakable.
841 if (position_recorded) {
842 DebugCodegen::GenerateSlot(masm_);
848 void FullCodeGenerator::SetSourcePosition(int pos) {
849 if (pos != RelocInfo::kNoPosition) {
850 masm_->positions_recorder()->RecordPosition(pos);
851 masm_->positions_recorder()->WriteRecordedPositions();
856 // Lookup table for code generators for special runtime calls which are
858 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
859 &FullCodeGenerator::Emit##Name,
861 const FullCodeGenerator::InlineFunctionGenerator
862 FullCodeGenerator::kInlineFunctionGenerators[] = {
863 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
865 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
868 FullCodeGenerator::InlineFunctionGenerator
869 FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
871 static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
872 DCHECK(lookup_index >= 0);
873 DCHECK(static_cast<size_t>(lookup_index) <
874 ARRAY_SIZE(kInlineFunctionGenerators));
875 return kInlineFunctionGenerators[lookup_index];
879 void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
880 const Runtime::Function* function = expr->function();
881 DCHECK(function != NULL);
882 DCHECK(function->intrinsic_type == Runtime::INLINE);
883 InlineFunctionGenerator generator =
884 FindInlineFunctionGenerator(function->function_id);
885 ((*this).*(generator))(expr);
889 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
890 ZoneList<Expression*>* args = expr->arguments();
891 DCHECK(args->length() == 2);
892 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
896 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
897 ZoneList<Expression*>* args = expr->arguments();
898 DCHECK(args->length() == 2);
899 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
903 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
904 context()->Plug(handle(Smi::FromInt(0), isolate()));
908 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
909 switch (expr->op()) {
911 return VisitComma(expr);
914 return VisitLogicalExpression(expr);
916 return VisitArithmeticExpression(expr);
921 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
922 if (context()->IsEffect()) {
923 VisitForEffect(expr);
924 } else if (context()->IsAccumulatorValue()) {
925 VisitForAccumulatorValue(expr);
926 } else if (context()->IsStackValue()) {
927 VisitForStackValue(expr);
928 } else if (context()->IsTest()) {
929 const TestContext* test = TestContext::cast(context());
930 VisitForControl(expr, test->true_label(), test->false_label(),
931 test->fall_through());
936 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
937 Comment cmnt(masm_, "[ Comma");
938 VisitForEffect(expr->left());
939 VisitInDuplicateContext(expr->right());
943 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
944 bool is_logical_and = expr->op() == Token::AND;
945 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
946 Expression* left = expr->left();
947 Expression* right = expr->right();
948 BailoutId right_id = expr->RightId();
951 if (context()->IsTest()) {
953 const TestContext* test = TestContext::cast(context());
954 if (is_logical_and) {
955 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
957 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
959 PrepareForBailoutForId(right_id, NO_REGISTERS);
960 __ bind(&eval_right);
962 } else if (context()->IsAccumulatorValue()) {
963 VisitForAccumulatorValue(left);
964 // We want the value in the accumulator for the test, and on the stack in
966 __ Push(result_register());
967 Label discard, restore;
968 if (is_logical_and) {
969 DoTest(left, &discard, &restore, &restore);
971 DoTest(left, &restore, &discard, &restore);
974 __ Pop(result_register());
978 PrepareForBailoutForId(right_id, NO_REGISTERS);
980 } else if (context()->IsStackValue()) {
981 VisitForAccumulatorValue(left);
982 // We want the value in the accumulator for the test, and on the stack in
984 __ Push(result_register());
986 if (is_logical_and) {
987 DoTest(left, &discard, &done, &discard);
989 DoTest(left, &done, &discard, &discard);
993 PrepareForBailoutForId(right_id, NO_REGISTERS);
996 DCHECK(context()->IsEffect());
998 if (is_logical_and) {
999 VisitForControl(left, &eval_right, &done, &eval_right);
1001 VisitForControl(left, &done, &eval_right, &eval_right);
1003 PrepareForBailoutForId(right_id, NO_REGISTERS);
1004 __ bind(&eval_right);
1007 VisitInDuplicateContext(right);
1012 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1013 Token::Value op = expr->op();
1014 Comment cmnt(masm_, "[ ArithmeticExpression");
1015 Expression* left = expr->left();
1016 Expression* right = expr->right();
1017 OverwriteMode mode =
1018 left->ResultOverwriteAllowed()
1020 : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1022 VisitForStackValue(left);
1023 VisitForAccumulatorValue(right);
1025 SetSourcePosition(expr->position());
1026 if (ShouldInlineSmiCase(op)) {
1027 EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1029 EmitBinaryOp(expr, op, mode);
1034 void FullCodeGenerator::VisitBlock(Block* stmt) {
1035 Comment cmnt(masm_, "[ Block");
1036 NestedBlock nested_block(this, stmt);
1037 SetStatementPosition(stmt);
1039 Scope* saved_scope = scope();
1040 // Push a block context when entering a block with block scoped variables.
1041 if (stmt->scope() == NULL) {
1042 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1044 scope_ = stmt->scope();
1045 DCHECK(!scope_->is_module_scope());
1046 { Comment cmnt(masm_, "[ Extend block context");
1047 __ Push(scope_->GetScopeInfo());
1048 PushFunctionArgumentForContextAllocation();
1049 __ CallRuntime(Runtime::kPushBlockContext, 2);
1051 // Replace the context stored in the frame.
1052 StoreToFrameField(StandardFrameConstants::kContextOffset,
1053 context_register());
1054 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1056 { Comment cmnt(masm_, "[ Declarations");
1057 VisitDeclarations(scope_->declarations());
1058 PrepareForBailoutForId(stmt->DeclsId(), NO_REGISTERS);
1062 VisitStatements(stmt->statements());
1063 scope_ = saved_scope;
1064 __ bind(nested_block.break_label());
1066 // Pop block context if necessary.
1067 if (stmt->scope() != NULL) {
1068 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1069 // Update local stack frame context field.
1070 StoreToFrameField(StandardFrameConstants::kContextOffset,
1071 context_register());
1073 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1077 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1078 Comment cmnt(masm_, "[ Module context");
1080 __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
1081 __ Push(Smi::FromInt(0));
1082 __ CallRuntime(Runtime::kPushModuleContext, 2);
1084 StandardFrameConstants::kContextOffset, context_register());
1086 Scope* saved_scope = scope_;
1087 scope_ = stmt->body()->scope();
1088 VisitStatements(stmt->body()->statements());
1089 scope_ = saved_scope;
1090 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1091 // Update local stack frame context field.
1092 StoreToFrameField(StandardFrameConstants::kContextOffset,
1093 context_register());
1097 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1098 Comment cmnt(masm_, "[ ExpressionStatement");
1099 SetStatementPosition(stmt);
1100 VisitForEffect(stmt->expression());
1104 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1105 Comment cmnt(masm_, "[ EmptyStatement");
1106 SetStatementPosition(stmt);
1110 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1111 Comment cmnt(masm_, "[ IfStatement");
1112 SetStatementPosition(stmt);
1113 Label then_part, else_part, done;
1115 if (stmt->HasElseStatement()) {
1116 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1117 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1118 __ bind(&then_part);
1119 Visit(stmt->then_statement());
1122 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1123 __ bind(&else_part);
1124 Visit(stmt->else_statement());
1126 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1127 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1128 __ bind(&then_part);
1129 Visit(stmt->then_statement());
1131 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1134 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1138 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1139 Comment cmnt(masm_, "[ ContinueStatement");
1140 SetStatementPosition(stmt);
1141 NestedStatement* current = nesting_stack_;
1142 int stack_depth = 0;
1143 int context_length = 0;
1144 // When continuing, we clobber the unpredictable value in the accumulator
1145 // with one that's safe for GC. If we hit an exit from the try block of
1146 // try...finally on our way out, we will unconditionally preserve the
1147 // accumulator on the stack.
1149 while (!current->IsContinueTarget(stmt->target())) {
1150 current = current->Exit(&stack_depth, &context_length);
1152 __ Drop(stack_depth);
1153 if (context_length > 0) {
1154 while (context_length > 0) {
1155 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1158 StoreToFrameField(StandardFrameConstants::kContextOffset,
1159 context_register());
1162 __ jmp(current->AsIteration()->continue_label());
1166 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1167 Comment cmnt(masm_, "[ BreakStatement");
1168 SetStatementPosition(stmt);
1169 NestedStatement* current = nesting_stack_;
1170 int stack_depth = 0;
1171 int context_length = 0;
1172 // When breaking, we clobber the unpredictable value in the accumulator
1173 // with one that's safe for GC. If we hit an exit from the try block of
1174 // try...finally on our way out, we will unconditionally preserve the
1175 // accumulator on the stack.
1177 while (!current->IsBreakTarget(stmt->target())) {
1178 current = current->Exit(&stack_depth, &context_length);
1180 __ Drop(stack_depth);
1181 if (context_length > 0) {
1182 while (context_length > 0) {
1183 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1186 StoreToFrameField(StandardFrameConstants::kContextOffset,
1187 context_register());
1190 __ jmp(current->AsBreakable()->break_label());
1194 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1195 NestedStatement* current = nesting_stack_;
1196 int stack_depth = 0;
1197 int context_length = 0;
1198 while (current != NULL) {
1199 current = current->Exit(&stack_depth, &context_length);
1201 __ Drop(stack_depth);
1205 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1206 Comment cmnt(masm_, "[ ReturnStatement");
1207 SetStatementPosition(stmt);
1208 Expression* expr = stmt->expression();
1209 VisitForAccumulatorValue(expr);
1210 EmitUnwindBeforeReturn();
1211 EmitReturnSequence();
1215 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1216 Comment cmnt(masm_, "[ WithStatement");
1217 SetStatementPosition(stmt);
1219 VisitForStackValue(stmt->expression());
1220 PushFunctionArgumentForContextAllocation();
1221 __ CallRuntime(Runtime::kPushWithContext, 2);
1222 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1224 Scope* saved_scope = scope();
1225 scope_ = stmt->scope();
1226 { WithOrCatch body(this);
1227 Visit(stmt->statement());
1229 scope_ = saved_scope;
1232 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1233 // Update local stack frame context field.
1234 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1238 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1239 Comment cmnt(masm_, "[ DoWhileStatement");
1240 SetStatementPosition(stmt);
1241 Label body, book_keeping;
1243 Iteration loop_statement(this, stmt);
1244 increment_loop_depth();
1247 Visit(stmt->body());
1249 // Record the position of the do while condition and make sure it is
1250 // possible to break on the condition.
1251 __ bind(loop_statement.continue_label());
1252 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1253 SetExpressionPosition(stmt->cond());
1254 VisitForControl(stmt->cond(),
1256 loop_statement.break_label(),
1259 // Check stack before looping.
1260 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1261 __ bind(&book_keeping);
1262 EmitBackEdgeBookkeeping(stmt, &body);
1265 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1266 __ bind(loop_statement.break_label());
1267 decrement_loop_depth();
1271 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1272 Comment cmnt(masm_, "[ WhileStatement");
1275 Iteration loop_statement(this, stmt);
1276 increment_loop_depth();
1280 SetExpressionPosition(stmt->cond());
1281 VisitForControl(stmt->cond(),
1283 loop_statement.break_label(),
1286 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1288 Visit(stmt->body());
1290 __ bind(loop_statement.continue_label());
1292 // Check stack before looping.
1293 EmitBackEdgeBookkeeping(stmt, &loop);
1296 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1297 __ bind(loop_statement.break_label());
1298 decrement_loop_depth();
1302 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1303 Comment cmnt(masm_, "[ ForStatement");
1306 Iteration loop_statement(this, stmt);
1308 // Set statement position for a break slot before entering the for-body.
1309 SetStatementPosition(stmt);
1311 if (stmt->init() != NULL) {
1312 Visit(stmt->init());
1315 increment_loop_depth();
1316 // Emit the test at the bottom of the loop (even if empty).
1319 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1321 Visit(stmt->body());
1323 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1324 __ bind(loop_statement.continue_label());
1325 if (stmt->next() != NULL) {
1326 Visit(stmt->next());
1329 // Emit the statement position here as this is where the for
1330 // statement code starts.
1331 SetStatementPosition(stmt);
1333 // Check stack before looping.
1334 EmitBackEdgeBookkeeping(stmt, &body);
1337 if (stmt->cond() != NULL) {
1338 VisitForControl(stmt->cond(),
1340 loop_statement.break_label(),
1341 loop_statement.break_label());
1346 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1347 __ bind(loop_statement.break_label());
1348 decrement_loop_depth();
1352 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1353 Comment cmnt(masm_, "[ TryCatchStatement");
1354 SetStatementPosition(stmt);
1355 // The try block adds a handler to the exception handler chain before
1356 // entering, and removes it again when exiting normally. If an exception
1357 // is thrown during execution of the try block, the handler is consumed
1358 // and control is passed to the catch block with the exception in the
1361 Label try_entry, handler_entry, exit;
1363 __ bind(&handler_entry);
1364 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1365 // Exception handler code, the exception is in the result register.
1366 // Extend the context before executing the catch block.
1367 { Comment cmnt(masm_, "[ Extend catch context");
1368 __ Push(stmt->variable()->name());
1369 __ Push(result_register());
1370 PushFunctionArgumentForContextAllocation();
1371 __ CallRuntime(Runtime::kPushCatchContext, 3);
1372 StoreToFrameField(StandardFrameConstants::kContextOffset,
1373 context_register());
1376 Scope* saved_scope = scope();
1377 scope_ = stmt->scope();
1378 DCHECK(scope_->declarations()->is_empty());
1379 { WithOrCatch catch_body(this);
1380 Visit(stmt->catch_block());
1382 // Restore the context.
1383 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1384 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1385 scope_ = saved_scope;
1388 // Try block code. Sets up the exception handler chain.
1389 __ bind(&try_entry);
1390 __ PushTryHandler(StackHandler::CATCH, stmt->index());
1391 { TryCatch try_body(this);
1392 Visit(stmt->try_block());
1399 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1400 Comment cmnt(masm_, "[ TryFinallyStatement");
1401 SetStatementPosition(stmt);
1402 // Try finally is compiled by setting up a try-handler on the stack while
1403 // executing the try body, and removing it again afterwards.
1405 // The try-finally construct can enter the finally block in three ways:
1406 // 1. By exiting the try-block normally. This removes the try-handler and
1407 // calls the finally block code before continuing.
1408 // 2. By exiting the try-block with a function-local control flow transfer
1409 // (break/continue/return). The site of the, e.g., break removes the
1410 // try handler and calls the finally block code before continuing
1411 // its outward control transfer.
1412 // 3. By exiting the try-block with a thrown exception.
1413 // This can happen in nested function calls. It traverses the try-handler
1414 // chain and consumes the try-handler entry before jumping to the
1415 // handler code. The handler code then calls the finally-block before
1416 // rethrowing the exception.
1418 // The finally block must assume a return address on top of the stack
1419 // (or in the link register on ARM chips) and a value (return value or
1420 // exception) in the result register (rax/eax/r0), both of which must
1421 // be preserved. The return address isn't GC-safe, so it should be
1422 // cooked before GC.
1423 Label try_entry, handler_entry, finally_entry;
1425 // Jump to try-handler setup and try-block code.
1427 __ bind(&handler_entry);
1428 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1429 // Exception handler code. This code is only executed when an exception
1430 // is thrown. The exception is in the result register, and must be
1431 // preserved by the finally block. Call the finally block and then
1432 // rethrow the exception if it returns.
1433 __ Call(&finally_entry);
1434 __ Push(result_register());
1435 __ CallRuntime(Runtime::kReThrow, 1);
1437 // Finally block implementation.
1438 __ bind(&finally_entry);
1439 EnterFinallyBlock();
1440 { Finally finally_body(this);
1441 Visit(stmt->finally_block());
1443 ExitFinallyBlock(); // Return to the calling code.
1445 // Set up try handler.
1446 __ bind(&try_entry);
1447 __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1448 { TryFinally try_body(this, &finally_entry);
1449 Visit(stmt->try_block());
1452 // Execute the finally block on the way out. Clobber the unpredictable
1453 // value in the result register with one that's safe for GC because the
1454 // finally block will unconditionally preserve the result register on the
1457 __ Call(&finally_entry);
1461 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1462 Comment cmnt(masm_, "[ DebuggerStatement");
1463 SetStatementPosition(stmt);
1466 // Ignore the return value.
1470 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1475 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1476 Comment cmnt(masm_, "[ Conditional");
1477 Label true_case, false_case, done;
1478 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1480 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1481 __ bind(&true_case);
1482 SetExpressionPosition(expr->then_expression());
1483 if (context()->IsTest()) {
1484 const TestContext* for_test = TestContext::cast(context());
1485 VisitForControl(expr->then_expression(),
1486 for_test->true_label(),
1487 for_test->false_label(),
1490 VisitInDuplicateContext(expr->then_expression());
1494 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1495 __ bind(&false_case);
1496 SetExpressionPosition(expr->else_expression());
1497 VisitInDuplicateContext(expr->else_expression());
1498 // If control flow falls through Visit, merge it with true case here.
1499 if (!context()->IsTest()) {
1505 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1506 Comment cmnt(masm_, "[ Literal");
1507 context()->Plug(expr->value());
1511 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1512 Comment cmnt(masm_, "[ FunctionLiteral");
1514 // Build the function boilerplate and instantiate it.
1515 Handle<SharedFunctionInfo> function_info =
1516 Compiler::BuildFunctionInfo(expr, script(), info_);
1517 if (function_info.is_null()) {
1521 EmitNewClosure(function_info, expr->pretenure());
1525 void FullCodeGenerator::VisitNativeFunctionLiteral(
1526 NativeFunctionLiteral* expr) {
1527 Comment cmnt(masm_, "[ NativeFunctionLiteral");
1529 // Compute the function template for the native function.
1530 Handle<String> name = expr->name();
1531 v8::Handle<v8::FunctionTemplate> fun_template =
1532 expr->extension()->GetNativeFunctionTemplate(
1533 reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1534 DCHECK(!fun_template.IsEmpty());
1536 // Instantiate the function and create a shared function info from it.
1537 Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1538 const int literals = fun->NumberOfLiterals();
1539 Handle<Code> code = Handle<Code>(fun->shared()->code());
1540 Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1541 bool is_generator = false;
1542 bool is_arrow = false;
1543 Handle<SharedFunctionInfo> shared =
1544 isolate()->factory()->NewSharedFunctionInfo(
1545 name, literals, is_generator, is_arrow, code,
1546 Handle<ScopeInfo>(fun->shared()->scope_info()),
1547 Handle<FixedArray>(fun->shared()->feedback_vector()));
1548 shared->set_construct_stub(*construct_stub);
1550 // Copy the function data to the shared function info.
1551 shared->set_function_data(fun->shared()->function_data());
1552 int parameters = fun->shared()->formal_parameter_count();
1553 shared->set_formal_parameter_count(parameters);
1555 EmitNewClosure(shared, false);
1559 void FullCodeGenerator::VisitThrow(Throw* expr) {
1560 Comment cmnt(masm_, "[ Throw");
1561 VisitForStackValue(expr->exception());
1562 __ CallRuntime(Runtime::kThrow, 1);
1563 // Never returns here.
1567 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
1569 int* context_length) {
1570 // The macros used here must preserve the result register.
1571 __ Drop(*stack_depth);
1578 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1579 Expression* sub_expr;
1580 Handle<String> check;
1581 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1582 EmitLiteralCompareTypeof(expr, sub_expr, check);
1586 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1587 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1591 if (expr->IsLiteralCompareNull(&sub_expr)) {
1592 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1600 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1601 DisallowHeapAllocation no_gc;
1602 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1604 // Increment loop nesting level by one and iterate over the back edge table
1605 // to find the matching loops to patch the interrupt
1606 // call to an unconditional call to the replacement code.
1607 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1608 if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1610 BackEdgeTable back_edges(unoptimized, &no_gc);
1611 for (uint32_t i = 0; i < back_edges.length(); i++) {
1612 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1613 DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1616 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1620 unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1621 DCHECK(Verify(isolate, unoptimized));
1625 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1626 DisallowHeapAllocation no_gc;
1627 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1629 // Iterate over the back edge table and revert the patched interrupt calls.
1630 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1632 BackEdgeTable back_edges(unoptimized, &no_gc);
1633 for (uint32_t i = 0; i < back_edges.length(); i++) {
1634 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1635 DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1638 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1642 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1643 // Assert that none of the back edges are patched anymore.
1644 DCHECK(Verify(isolate, unoptimized));
1648 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1649 DisallowHeapAllocation no_gc;
1650 Isolate* isolate = code->GetIsolate();
1651 Address pc = code->instruction_start() + pc_offset;
1652 Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1653 PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1657 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1658 DisallowHeapAllocation no_gc;
1659 Isolate* isolate = code->GetIsolate();
1660 Address pc = code->instruction_start() + pc_offset;
1662 if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1663 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1664 PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1670 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1671 DisallowHeapAllocation no_gc;
1672 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1673 BackEdgeTable back_edges(unoptimized, &no_gc);
1674 for (uint32_t i = 0; i < back_edges.length(); i++) {
1675 uint32_t loop_depth = back_edges.loop_depth(i);
1676 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1677 // Assert that all back edges for shallower loops (and only those)
1678 // have already been patched.
1679 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1680 GetBackEdgeState(isolate,
1682 back_edges.pc(i)) != INTERRUPT);
1692 } } // namespace v8::internal