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.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::VisitModuleVariable(ModuleVariable* module) {
67 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
71 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
75 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
79 void BreakableStatementChecker::VisitBlock(Block* stmt) {
83 void BreakableStatementChecker::VisitExpressionStatement(
84 ExpressionStatement* stmt) {
85 // Check if expression is breakable.
86 Visit(stmt->expression());
90 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
94 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
95 // If the condition is breakable the if statement is breakable.
96 Visit(stmt->condition());
100 void BreakableStatementChecker::VisitContinueStatement(
101 ContinueStatement* stmt) {
105 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
109 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
110 // Return is breakable if the expression is.
111 Visit(stmt->expression());
115 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
116 Visit(stmt->expression());
120 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
121 // Switch statements breakable if the tag expression is.
126 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
127 // Mark do while as breakable to avoid adding a break slot in front of it.
128 is_breakable_ = true;
132 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
133 // Mark while statements breakable if the condition expression is.
138 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
139 // Mark for statements breakable if the condition expression is.
140 if (stmt->cond() != NULL) {
146 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
147 // Mark for in statements breakable if the enumerable expression is.
148 Visit(stmt->enumerable());
152 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
153 // For-of is breakable because of the next() call.
154 is_breakable_ = true;
158 void BreakableStatementChecker::VisitTryCatchStatement(
159 TryCatchStatement* stmt) {
160 // Mark try catch as breakable to avoid adding a break slot in front of it.
161 is_breakable_ = true;
165 void BreakableStatementChecker::VisitTryFinallyStatement(
166 TryFinallyStatement* stmt) {
167 // Mark try finally as breakable to avoid adding a break slot in front of it.
168 is_breakable_ = true;
172 void BreakableStatementChecker::VisitDebuggerStatement(
173 DebuggerStatement* stmt) {
174 // The debugger statement is breakable.
175 is_breakable_ = true;
179 void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
183 void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
187 void BreakableStatementChecker::VisitClassLiteral(ClassLiteral* expr) {
188 if (expr->extends() != NULL) {
189 Visit(expr->extends());
194 void BreakableStatementChecker::VisitNativeFunctionLiteral(
195 NativeFunctionLiteral* expr) {
199 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
203 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
207 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
211 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
215 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
219 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
223 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
224 // If assigning to a property (including a global property) the assignment is
226 VariableProxy* proxy = expr->target()->AsVariableProxy();
227 Property* prop = expr->target()->AsProperty();
228 if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
229 is_breakable_ = true;
233 // Otherwise the assignment is breakable if the assigned value is.
234 Visit(expr->value());
238 void BreakableStatementChecker::VisitYield(Yield* expr) {
239 // Yield is breakable if the expression is.
240 Visit(expr->expression());
244 void BreakableStatementChecker::VisitThrow(Throw* expr) {
245 // Throw is breakable if the expression is.
246 Visit(expr->exception());
250 void BreakableStatementChecker::VisitProperty(Property* expr) {
251 // Property load is breakable.
252 is_breakable_ = true;
256 void BreakableStatementChecker::VisitCall(Call* expr) {
257 // Function calls both through IC and call stub are breakable.
258 is_breakable_ = true;
262 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
263 // Function calls through new are breakable.
264 is_breakable_ = true;
268 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
272 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
273 Visit(expr->expression());
277 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
278 Visit(expr->expression());
282 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
284 if (expr->op() != Token::AND &&
285 expr->op() != Token::OR) {
286 Visit(expr->right());
291 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
293 Visit(expr->right());
297 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
301 void BreakableStatementChecker::VisitSuperReference(SuperReference* expr) {}
304 #define __ ACCESS_MASM(masm())
306 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
307 Isolate* isolate = info->isolate();
309 TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
311 Handle<Script> script = info->script();
312 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
313 int len = String::cast(script->source())->length();
314 isolate->counters()->total_full_codegen_source_size()->Increment(len);
316 CodeGenerator::MakeCodePrologue(info, "full");
317 const int kInitialBufferSize = 4 * KB;
318 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
319 if (info->will_serialize()) masm.enable_serializer();
321 LOG_CODE_EVENT(isolate,
322 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
324 FullCodeGenerator cgen(&masm, info);
326 if (cgen.HasStackOverflow()) {
327 DCHECK(!isolate->has_pending_exception());
330 unsigned table_offset = cgen.EmitBackEdgeTable();
332 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
333 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
334 code->set_optimizable(info->IsOptimizable() &&
335 !info->function()->dont_optimize() &&
336 info->function()->scope()->AllowsLazyCompilation());
337 cgen.PopulateDeoptimizationData(code);
338 cgen.PopulateTypeFeedbackInfo(code);
339 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
340 code->set_handler_table(*cgen.handler_table());
341 code->set_compiled_optimizable(info->IsOptimizable());
342 code->set_allow_osr_at_loop_nesting_level(0);
343 code->set_profiler_ticks(0);
344 code->set_back_edge_table_offset(table_offset);
345 CodeGenerator::PrintCode(code, info);
347 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
348 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
351 // Check that no context-specific object has been embedded.
352 code->VerifyEmbeddedObjectsInFullCode();
358 unsigned FullCodeGenerator::EmitBackEdgeTable() {
359 // The back edge table consists of a length (in number of entries)
360 // field, and then a sequence of entries. Each entry is a pair of AST id
361 // and code-relative pc offset.
362 masm()->Align(kPointerSize);
363 unsigned offset = masm()->pc_offset();
364 unsigned length = back_edges_.length();
366 for (unsigned i = 0; i < length; ++i) {
367 __ dd(back_edges_[i].id.ToInt());
368 __ dd(back_edges_[i].pc);
369 __ dd(back_edges_[i].loop_depth);
375 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
376 FeedbackVectorSlot slot) {
377 Handle<TypeFeedbackVector> vector = FeedbackVector();
378 if (!vector->Get(slot)->IsAllocationSite()) {
379 Handle<AllocationSite> allocation_site =
380 isolate()->factory()->NewAllocationSite();
381 vector->Set(slot, *allocation_site);
386 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
387 FeedbackVectorICSlot slot) {
388 Handle<TypeFeedbackVector> vector = FeedbackVector();
389 if (!vector->Get(slot)->IsAllocationSite()) {
390 Handle<AllocationSite> allocation_site =
391 isolate()->factory()->NewAllocationSite();
392 vector->Set(slot, *allocation_site);
397 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
398 // Fill in the deoptimization information.
399 DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
400 if (!info_->HasDeoptimizationSupport()) return;
401 int length = bailout_entries_.length();
402 Handle<DeoptimizationOutputData> data =
403 DeoptimizationOutputData::New(isolate(), length, TENURED);
404 for (int i = 0; i < length; i++) {
405 data->SetAstId(i, bailout_entries_[i].id);
406 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
408 code->set_deoptimization_data(*data);
412 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
413 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
414 info->set_ic_total_count(ic_total_count_);
415 DCHECK(!isolate()->heap()->InNewSpace(*info));
416 code->set_type_feedback_info(*info);
420 void FullCodeGenerator::Initialize() {
421 InitializeAstVisitor(info_->zone());
422 // The generation of debug code must match between the snapshot code and the
423 // code that is generated later. This is assumed by the debugger when it is
424 // calculating PC offsets after generating a debug version of code. Therefore
425 // we disable the production of debug code in the full compiler if we are
426 // either generating a snapshot or we booted from a snapshot.
427 generate_debug_code_ = FLAG_debug_code &&
428 !masm_->serializer_enabled() &&
429 !Snapshot::HaveASnapshotToStartFrom();
430 masm_->set_emit_debug_code(generate_debug_code_);
431 masm_->set_predictable_code_size(true);
435 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
436 PrepareForBailoutForId(node->id(), state);
440 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
442 Handle<Code> ic = CodeFactory::LoadIC(isolate(), contextual_mode).code();
447 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
448 Handle<Code> ic = CodeFactory::StoreIC(isolate(), strict_mode()).code();
453 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
454 // We record the offset of the function return so we can rebuild the frame
455 // if the function was inlined, i.e., this is the return address in the
456 // inlined function's frame.
458 // The state is ignored. We defensively set it to TOS_REG, which is the
459 // real state of the unoptimized code at the return site.
460 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
462 // In debug builds, mark the return so we can verify that this function
464 DCHECK(!call->return_is_recorded_);
465 call->return_is_recorded_ = true;
470 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
471 // There's no need to prepare this code for bailouts from already optimized
472 // code or code that can't be optimized.
473 if (!info_->HasDeoptimizationSupport()) return;
474 unsigned pc_and_state =
475 StateField::encode(state) | PcField::encode(masm_->pc_offset());
476 DCHECK(Smi::IsValid(pc_and_state));
478 for (int i = 0; i < bailout_entries_.length(); ++i) {
479 DCHECK(bailout_entries_[i].id != id);
482 BailoutEntry entry = { id, pc_and_state };
483 bailout_entries_.Add(entry, zone());
487 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
488 // The pc offset does not need to be encoded and packed together with a state.
489 DCHECK(masm_->pc_offset() > 0);
490 DCHECK(loop_depth() > 0);
491 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
492 BackEdgeEntry entry =
493 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
494 back_edges_.Add(entry, zone());
498 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
499 // Inline smi case inside loops, but not division and modulo which
500 // are too complicated and take up too much space.
501 if (op == Token::DIV ||op == Token::MOD) return false;
502 if (FLAG_always_inline_smi_code) return true;
503 return loop_depth_ > 0;
507 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
511 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
512 __ Move(result_register(), reg);
516 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
521 void FullCodeGenerator::TestContext::Plug(Register reg) const {
522 // For simplicity we always test the accumulator register.
523 __ Move(result_register(), reg);
524 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
525 codegen()->DoTest(this);
529 void FullCodeGenerator::EffectContext::PlugTOS() const {
534 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
535 __ Pop(result_register());
539 void FullCodeGenerator::StackValueContext::PlugTOS() const {
543 void FullCodeGenerator::TestContext::PlugTOS() const {
544 // For simplicity we always test the accumulator register.
545 __ Pop(result_register());
546 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
547 codegen()->DoTest(this);
551 void FullCodeGenerator::EffectContext::PrepareTest(
552 Label* materialize_true,
553 Label* materialize_false,
556 Label** fall_through) const {
557 // In an effect context, the true and the false case branch to the
559 *if_true = *if_false = *fall_through = materialize_true;
563 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
564 Label* materialize_true,
565 Label* materialize_false,
568 Label** fall_through) const {
569 *if_true = *fall_through = materialize_true;
570 *if_false = materialize_false;
574 void FullCodeGenerator::StackValueContext::PrepareTest(
575 Label* materialize_true,
576 Label* materialize_false,
579 Label** fall_through) const {
580 *if_true = *fall_through = materialize_true;
581 *if_false = materialize_false;
585 void FullCodeGenerator::TestContext::PrepareTest(
586 Label* materialize_true,
587 Label* materialize_false,
590 Label** fall_through) const {
591 *if_true = true_label_;
592 *if_false = false_label_;
593 *fall_through = fall_through_;
597 void FullCodeGenerator::DoTest(const TestContext* context) {
598 DoTest(context->condition(),
599 context->true_label(),
600 context->false_label(),
601 context->fall_through());
605 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
606 DCHECK(scope_->is_global_scope());
608 for (int i = 0; i < declarations->length(); i++) {
609 ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
610 if (declaration != NULL) {
611 ModuleLiteral* module = declaration->module()->AsModuleLiteral();
612 if (module != NULL) {
613 Comment cmnt(masm_, "[ Link nested modules");
614 Scope* scope = module->body()->scope();
615 Interface* interface = scope->interface();
616 DCHECK(interface->IsModule() && interface->IsFrozen());
618 interface->Allocate(scope->module_var()->index());
620 // Set up module context.
621 DCHECK(scope->interface()->Index() >= 0);
622 __ Push(Smi::FromInt(scope->interface()->Index()));
623 __ Push(scope->GetScopeInfo());
624 __ CallRuntime(Runtime::kPushModuleContext, 2);
625 StoreToFrameField(StandardFrameConstants::kContextOffset,
628 AllocateModules(scope->declarations());
630 // Pop module context.
631 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
632 // Update local stack frame context field.
633 StoreToFrameField(StandardFrameConstants::kContextOffset,
641 // Modules have their own local scope, represented by their own context.
642 // Module instance objects have an accessor for every export that forwards
643 // access to the respective slot from the module's context. (Exports that are
644 // modules themselves, however, are simple data properties.)
646 // All modules have a _hosting_ scope/context, which (currently) is the
647 // (innermost) enclosing global scope. To deal with recursion, nested modules
648 // are hosted by the same scope as global ones.
650 // For every (global or nested) module literal, the hosting context has an
651 // internal slot that points directly to the respective module context. This
652 // enables quick access to (statically resolved) module members by 2-dimensional
653 // access through the hosting context. For example,
657 // module B { let y; }
659 // module C { let z; }
661 // allocates contexts as follows:
663 // [header| .A | .B | .C | A | C ] (global)
665 // | | +-- [header| z ] (module)
667 // | +------- [header| y ] (module)
669 // +------------ [header| x | B ] (module)
671 // Here, .A, .B, .C are the internal slots pointing to the hosted module
672 // contexts, whereas A, B, C hold the actual instance objects (note that every
673 // module context also points to the respective instance object through its
674 // extension slot in the header).
676 // To deal with arbitrary recursion and aliases between modules,
677 // they are created and initialized in several stages. Each stage applies to
678 // all modules in the hosting global scope, including nested ones.
680 // 1. Allocate: for each module _literal_, allocate the module contexts and
681 // respective instance object and wire them up. This happens in the
682 // PushModuleContext runtime function, as generated by AllocateModules
683 // (invoked by VisitDeclarations in the hosting scope).
685 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
686 // assign the respective instance object to respective local variables. This
687 // happens in VisitModuleDeclaration, and uses the instance objects created
688 // in the previous stage.
689 // For each module _literal_, this phase also constructs a module descriptor
690 // for the next stage. This happens in VisitModuleLiteral.
692 // 3. Populate: invoke the DeclareModules runtime function to populate each
693 // _instance_ object with accessors for it exports. This is generated by
694 // DeclareModules (invoked by VisitDeclarations in the hosting scope again),
695 // and uses the descriptors generated in the previous stage.
697 // 4. Initialize: execute the module bodies (and other code) in sequence. This
698 // happens by the separate statements generated for module bodies. To reenter
699 // the module scopes properly, the parser inserted ModuleStatements.
701 void FullCodeGenerator::VisitDeclarations(
702 ZoneList<Declaration*>* declarations) {
703 Handle<FixedArray> saved_modules = modules_;
704 int saved_module_index = module_index_;
705 ZoneList<Handle<Object> >* saved_globals = globals_;
706 ZoneList<Handle<Object> > inner_globals(10, zone());
707 globals_ = &inner_globals;
709 if (scope_->num_modules() != 0) {
710 // This is a scope hosting modules. Allocate a descriptor array to pass
711 // to the runtime for initialization.
712 Comment cmnt(masm_, "[ Allocate modules");
713 DCHECK(scope_->is_global_scope());
715 isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
718 // Generate code for allocating all modules, including nested ones.
719 // The allocated contexts are stored in internal variables in this scope.
720 AllocateModules(declarations);
723 AstVisitor::VisitDeclarations(declarations);
725 if (scope_->num_modules() != 0) {
726 // Initialize modules from descriptor array.
727 DCHECK(module_index_ == modules_->length());
728 DeclareModules(modules_);
729 modules_ = saved_modules;
730 module_index_ = saved_module_index;
733 if (!globals_->is_empty()) {
734 // Invoke the platform-dependent code generator to do the actual
735 // declaration of the global functions and variables.
736 Handle<FixedArray> array =
737 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
738 for (int i = 0; i < globals_->length(); ++i)
739 array->set(i, *globals_->at(i));
740 DeclareGlobals(array);
743 globals_ = saved_globals;
747 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
748 Block* block = module->body();
749 Scope* saved_scope = scope();
750 scope_ = block->scope();
751 Interface* interface = scope_->interface();
753 Comment cmnt(masm_, "[ ModuleLiteral");
754 SetStatementPosition(block);
756 DCHECK(!modules_.is_null());
757 DCHECK(module_index_ < modules_->length());
758 int index = module_index_++;
760 // Set up module context.
761 DCHECK(interface->Index() >= 0);
762 __ Push(Smi::FromInt(interface->Index()));
763 __ Push(Smi::FromInt(0));
764 __ CallRuntime(Runtime::kPushModuleContext, 2);
765 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
768 Comment cmnt(masm_, "[ Declarations");
769 VisitDeclarations(scope_->declarations());
772 // Populate the module description.
773 Handle<ModuleInfo> description =
774 ModuleInfo::Create(isolate(), interface, scope_);
775 modules_->set(index, *description);
777 scope_ = saved_scope;
778 // Pop module context.
779 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
780 // Update local stack frame context field.
781 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
785 void FullCodeGenerator::VisitModuleVariable(ModuleVariable* module) {
787 // The instance object is resolved statically through the module's interface.
791 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
793 // The instance object is resolved statically through the module's interface.
797 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
798 // TODO(rossberg): dummy allocation for now.
799 Scope* scope = module->body()->scope();
800 Interface* interface = scope_->interface();
802 DCHECK(interface->IsModule() && interface->IsFrozen());
803 DCHECK(!modules_.is_null());
804 DCHECK(module_index_ < modules_->length());
805 interface->Allocate(scope->module_var()->index());
806 int index = module_index_++;
808 Handle<ModuleInfo> description =
809 ModuleInfo::Create(isolate(), interface, scope_);
810 modules_->set(index, *description);
814 int FullCodeGenerator::DeclareGlobalsFlags() {
815 DCHECK(DeclareGlobalsStrictMode::is_valid(strict_mode()));
816 return DeclareGlobalsEvalFlag::encode(is_eval()) |
817 DeclareGlobalsNativeFlag::encode(is_native()) |
818 DeclareGlobalsStrictMode::encode(strict_mode());
822 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
823 CodeGenerator::RecordPositions(masm_, fun->start_position());
827 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
828 CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
832 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
833 if (!info_->is_debug()) {
834 CodeGenerator::RecordPositions(masm_, stmt->position());
836 // Check if the statement will be breakable without adding a debug break
838 BreakableStatementChecker checker(zone());
840 // Record the statement position right here if the statement is not
841 // breakable. For breakable statements the actual recording of the
842 // position will be postponed to the breakable code (typically an IC).
843 bool position_recorded = CodeGenerator::RecordPositions(
844 masm_, stmt->position(), !checker.is_breakable());
845 // If the position recording did record a new position generate a debug
846 // break slot to make the statement breakable.
847 if (position_recorded) {
848 DebugCodegen::GenerateSlot(masm_);
854 void FullCodeGenerator::VisitSuperReference(SuperReference* super) {
855 __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
859 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
860 if (!info_->is_debug()) {
861 CodeGenerator::RecordPositions(masm_, expr->position());
863 // Check if the expression will be breakable without adding a debug break
865 BreakableStatementChecker checker(zone());
867 // Record a statement position right here if the expression is not
868 // breakable. For breakable expressions the actual recording of the
869 // position will be postponed to the breakable code (typically an IC).
870 // NOTE this will record a statement position for something which might
871 // not be a statement. As stepping in the debugger will only stop at
872 // statement positions this is used for e.g. the condition expression of
874 bool position_recorded = CodeGenerator::RecordPositions(
875 masm_, expr->position(), !checker.is_breakable());
876 // If the position recording did record a new position generate a debug
877 // break slot to make the statement breakable.
878 if (position_recorded) {
879 DebugCodegen::GenerateSlot(masm_);
885 void FullCodeGenerator::SetSourcePosition(int pos) {
886 if (pos != RelocInfo::kNoPosition) {
887 masm_->positions_recorder()->RecordPosition(pos);
888 masm_->positions_recorder()->WriteRecordedPositions();
893 // Lookup table for code generators for special runtime calls which are
895 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
896 &FullCodeGenerator::Emit##Name,
898 const FullCodeGenerator::InlineFunctionGenerator
899 FullCodeGenerator::kInlineFunctionGenerators[] = {
900 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
902 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
905 FullCodeGenerator::InlineFunctionGenerator
906 FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
908 static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
909 DCHECK(lookup_index >= 0);
910 DCHECK(static_cast<size_t>(lookup_index) <
911 arraysize(kInlineFunctionGenerators));
912 return kInlineFunctionGenerators[lookup_index];
916 void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
917 const Runtime::Function* function = expr->function();
918 DCHECK(function != NULL);
919 DCHECK(function->intrinsic_type == Runtime::INLINE);
920 InlineFunctionGenerator generator =
921 FindInlineFunctionGenerator(function->function_id);
922 ((*this).*(generator))(expr);
926 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
927 ZoneList<Expression*>* args = expr->arguments();
928 DCHECK(args->length() == 2);
929 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
933 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
934 ZoneList<Expression*>* args = expr->arguments();
935 DCHECK(args->length() == 2);
936 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
940 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
941 context()->Plug(handle(Smi::FromInt(0), isolate()));
945 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
946 switch (expr->op()) {
948 return VisitComma(expr);
951 return VisitLogicalExpression(expr);
953 return VisitArithmeticExpression(expr);
958 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
959 if (context()->IsEffect()) {
960 VisitForEffect(expr);
961 } else if (context()->IsAccumulatorValue()) {
962 VisitForAccumulatorValue(expr);
963 } else if (context()->IsStackValue()) {
964 VisitForStackValue(expr);
965 } else if (context()->IsTest()) {
966 const TestContext* test = TestContext::cast(context());
967 VisitForControl(expr, test->true_label(), test->false_label(),
968 test->fall_through());
973 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
974 Comment cmnt(masm_, "[ Comma");
975 VisitForEffect(expr->left());
976 VisitInDuplicateContext(expr->right());
980 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
981 bool is_logical_and = expr->op() == Token::AND;
982 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
983 Expression* left = expr->left();
984 Expression* right = expr->right();
985 BailoutId right_id = expr->RightId();
988 if (context()->IsTest()) {
990 const TestContext* test = TestContext::cast(context());
991 if (is_logical_and) {
992 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
994 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
996 PrepareForBailoutForId(right_id, NO_REGISTERS);
997 __ bind(&eval_right);
999 } else if (context()->IsAccumulatorValue()) {
1000 VisitForAccumulatorValue(left);
1001 // We want the value in the accumulator for the test, and on the stack in
1003 __ Push(result_register());
1004 Label discard, restore;
1005 if (is_logical_and) {
1006 DoTest(left, &discard, &restore, &restore);
1008 DoTest(left, &restore, &discard, &restore);
1011 __ Pop(result_register());
1015 PrepareForBailoutForId(right_id, NO_REGISTERS);
1017 } else if (context()->IsStackValue()) {
1018 VisitForAccumulatorValue(left);
1019 // We want the value in the accumulator for the test, and on the stack in
1021 __ Push(result_register());
1023 if (is_logical_and) {
1024 DoTest(left, &discard, &done, &discard);
1026 DoTest(left, &done, &discard, &discard);
1030 PrepareForBailoutForId(right_id, NO_REGISTERS);
1033 DCHECK(context()->IsEffect());
1035 if (is_logical_and) {
1036 VisitForControl(left, &eval_right, &done, &eval_right);
1038 VisitForControl(left, &done, &eval_right, &eval_right);
1040 PrepareForBailoutForId(right_id, NO_REGISTERS);
1041 __ bind(&eval_right);
1044 VisitInDuplicateContext(right);
1049 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1050 Token::Value op = expr->op();
1051 Comment cmnt(masm_, "[ ArithmeticExpression");
1052 Expression* left = expr->left();
1053 Expression* right = expr->right();
1054 OverwriteMode mode =
1055 left->ResultOverwriteAllowed()
1057 : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1059 VisitForStackValue(left);
1060 VisitForAccumulatorValue(right);
1062 SetSourcePosition(expr->position());
1063 if (ShouldInlineSmiCase(op)) {
1064 EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1066 EmitBinaryOp(expr, op, mode);
1071 void FullCodeGenerator::VisitBlock(Block* stmt) {
1072 Comment cmnt(masm_, "[ Block");
1073 NestedBlock nested_block(this, stmt);
1074 SetStatementPosition(stmt);
1076 Scope* saved_scope = scope();
1077 // Push a block context when entering a block with block scoped variables.
1078 if (stmt->scope() == NULL) {
1079 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1081 scope_ = stmt->scope();
1082 DCHECK(!scope_->is_module_scope());
1083 { Comment cmnt(masm_, "[ Extend block context");
1084 __ Push(scope_->GetScopeInfo());
1085 PushFunctionArgumentForContextAllocation();
1086 __ CallRuntime(Runtime::kPushBlockContext, 2);
1088 // Replace the context stored in the frame.
1089 StoreToFrameField(StandardFrameConstants::kContextOffset,
1090 context_register());
1091 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1093 { Comment cmnt(masm_, "[ Declarations");
1094 VisitDeclarations(scope_->declarations());
1095 PrepareForBailoutForId(stmt->DeclsId(), NO_REGISTERS);
1099 VisitStatements(stmt->statements());
1100 scope_ = saved_scope;
1101 __ bind(nested_block.break_label());
1103 // Pop block context if necessary.
1104 if (stmt->scope() != NULL) {
1105 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1106 // Update local stack frame context field.
1107 StoreToFrameField(StandardFrameConstants::kContextOffset,
1108 context_register());
1110 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1114 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1115 Comment cmnt(masm_, "[ Module context");
1117 __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
1118 __ Push(Smi::FromInt(0));
1119 __ CallRuntime(Runtime::kPushModuleContext, 2);
1121 StandardFrameConstants::kContextOffset, context_register());
1123 Scope* saved_scope = scope_;
1124 scope_ = stmt->body()->scope();
1125 VisitStatements(stmt->body()->statements());
1126 scope_ = saved_scope;
1127 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1128 // Update local stack frame context field.
1129 StoreToFrameField(StandardFrameConstants::kContextOffset,
1130 context_register());
1134 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1135 Comment cmnt(masm_, "[ ExpressionStatement");
1136 SetStatementPosition(stmt);
1137 VisitForEffect(stmt->expression());
1141 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1142 Comment cmnt(masm_, "[ EmptyStatement");
1143 SetStatementPosition(stmt);
1147 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1148 Comment cmnt(masm_, "[ IfStatement");
1149 SetStatementPosition(stmt);
1150 Label then_part, else_part, done;
1152 if (stmt->HasElseStatement()) {
1153 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1154 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1155 __ bind(&then_part);
1156 Visit(stmt->then_statement());
1159 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1160 __ bind(&else_part);
1161 Visit(stmt->else_statement());
1163 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1164 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1165 __ bind(&then_part);
1166 Visit(stmt->then_statement());
1168 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1171 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1175 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1176 Comment cmnt(masm_, "[ ContinueStatement");
1177 SetStatementPosition(stmt);
1178 NestedStatement* current = nesting_stack_;
1179 int stack_depth = 0;
1180 int context_length = 0;
1181 // When continuing, we clobber the unpredictable value in the accumulator
1182 // with one that's safe for GC. If we hit an exit from the try block of
1183 // try...finally on our way out, we will unconditionally preserve the
1184 // accumulator on the stack.
1186 while (!current->IsContinueTarget(stmt->target())) {
1187 current = current->Exit(&stack_depth, &context_length);
1189 __ Drop(stack_depth);
1190 if (context_length > 0) {
1191 while (context_length > 0) {
1192 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1195 StoreToFrameField(StandardFrameConstants::kContextOffset,
1196 context_register());
1199 __ jmp(current->AsIteration()->continue_label());
1203 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1204 Comment cmnt(masm_, "[ BreakStatement");
1205 SetStatementPosition(stmt);
1206 NestedStatement* current = nesting_stack_;
1207 int stack_depth = 0;
1208 int context_length = 0;
1209 // When breaking, we clobber the unpredictable value in the accumulator
1210 // with one that's safe for GC. If we hit an exit from the try block of
1211 // try...finally on our way out, we will unconditionally preserve the
1212 // accumulator on the stack.
1214 while (!current->IsBreakTarget(stmt->target())) {
1215 current = current->Exit(&stack_depth, &context_length);
1217 __ Drop(stack_depth);
1218 if (context_length > 0) {
1219 while (context_length > 0) {
1220 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1223 StoreToFrameField(StandardFrameConstants::kContextOffset,
1224 context_register());
1227 __ jmp(current->AsBreakable()->break_label());
1231 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1232 NestedStatement* current = nesting_stack_;
1233 int stack_depth = 0;
1234 int context_length = 0;
1235 while (current != NULL) {
1236 current = current->Exit(&stack_depth, &context_length);
1238 __ Drop(stack_depth);
1242 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1243 Comment cmnt(masm_, "[ ReturnStatement");
1244 SetStatementPosition(stmt);
1245 Expression* expr = stmt->expression();
1246 VisitForAccumulatorValue(expr);
1247 EmitUnwindBeforeReturn();
1248 EmitReturnSequence();
1252 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1253 Comment cmnt(masm_, "[ WithStatement");
1254 SetStatementPosition(stmt);
1256 VisitForStackValue(stmt->expression());
1257 PushFunctionArgumentForContextAllocation();
1258 __ CallRuntime(Runtime::kPushWithContext, 2);
1259 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1261 Scope* saved_scope = scope();
1262 scope_ = stmt->scope();
1263 { WithOrCatch body(this);
1264 Visit(stmt->statement());
1266 scope_ = saved_scope;
1269 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1270 // Update local stack frame context field.
1271 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1275 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1276 Comment cmnt(masm_, "[ DoWhileStatement");
1277 SetStatementPosition(stmt);
1278 Label body, book_keeping;
1280 Iteration loop_statement(this, stmt);
1281 increment_loop_depth();
1284 Visit(stmt->body());
1286 // Record the position of the do while condition and make sure it is
1287 // possible to break on the condition.
1288 __ bind(loop_statement.continue_label());
1289 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1290 SetExpressionPosition(stmt->cond());
1291 VisitForControl(stmt->cond(),
1293 loop_statement.break_label(),
1296 // Check stack before looping.
1297 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1298 __ bind(&book_keeping);
1299 EmitBackEdgeBookkeeping(stmt, &body);
1302 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1303 __ bind(loop_statement.break_label());
1304 decrement_loop_depth();
1308 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1309 Comment cmnt(masm_, "[ WhileStatement");
1312 Iteration loop_statement(this, stmt);
1313 increment_loop_depth();
1317 SetExpressionPosition(stmt->cond());
1318 VisitForControl(stmt->cond(),
1320 loop_statement.break_label(),
1323 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1325 Visit(stmt->body());
1327 __ bind(loop_statement.continue_label());
1329 // Check stack before looping.
1330 EmitBackEdgeBookkeeping(stmt, &loop);
1333 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1334 __ bind(loop_statement.break_label());
1335 decrement_loop_depth();
1339 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1340 Comment cmnt(masm_, "[ ForStatement");
1343 Iteration loop_statement(this, stmt);
1345 // Set statement position for a break slot before entering the for-body.
1346 SetStatementPosition(stmt);
1348 if (stmt->init() != NULL) {
1349 Visit(stmt->init());
1352 increment_loop_depth();
1353 // Emit the test at the bottom of the loop (even if empty).
1356 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1358 Visit(stmt->body());
1360 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1361 __ bind(loop_statement.continue_label());
1362 if (stmt->next() != NULL) {
1363 Visit(stmt->next());
1366 // Emit the statement position here as this is where the for
1367 // statement code starts.
1368 SetStatementPosition(stmt);
1370 // Check stack before looping.
1371 EmitBackEdgeBookkeeping(stmt, &body);
1374 if (stmt->cond() != NULL) {
1375 VisitForControl(stmt->cond(),
1377 loop_statement.break_label(),
1378 loop_statement.break_label());
1383 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1384 __ bind(loop_statement.break_label());
1385 decrement_loop_depth();
1389 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1390 Comment cmnt(masm_, "[ TryCatchStatement");
1391 SetStatementPosition(stmt);
1392 // The try block adds a handler to the exception handler chain before
1393 // entering, and removes it again when exiting normally. If an exception
1394 // is thrown during execution of the try block, the handler is consumed
1395 // and control is passed to the catch block with the exception in the
1398 Label try_entry, handler_entry, exit;
1400 __ bind(&handler_entry);
1401 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1402 // Exception handler code, the exception is in the result register.
1403 // Extend the context before executing the catch block.
1404 { Comment cmnt(masm_, "[ Extend catch context");
1405 __ Push(stmt->variable()->name());
1406 __ Push(result_register());
1407 PushFunctionArgumentForContextAllocation();
1408 __ CallRuntime(Runtime::kPushCatchContext, 3);
1409 StoreToFrameField(StandardFrameConstants::kContextOffset,
1410 context_register());
1413 Scope* saved_scope = scope();
1414 scope_ = stmt->scope();
1415 DCHECK(scope_->declarations()->is_empty());
1416 { WithOrCatch catch_body(this);
1417 Visit(stmt->catch_block());
1419 // Restore the context.
1420 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1421 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1422 scope_ = saved_scope;
1425 // Try block code. Sets up the exception handler chain.
1426 __ bind(&try_entry);
1427 __ PushTryHandler(StackHandler::CATCH, stmt->index());
1428 { TryCatch try_body(this);
1429 Visit(stmt->try_block());
1436 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1437 Comment cmnt(masm_, "[ TryFinallyStatement");
1438 SetStatementPosition(stmt);
1439 // Try finally is compiled by setting up a try-handler on the stack while
1440 // executing the try body, and removing it again afterwards.
1442 // The try-finally construct can enter the finally block in three ways:
1443 // 1. By exiting the try-block normally. This removes the try-handler and
1444 // calls the finally block code before continuing.
1445 // 2. By exiting the try-block with a function-local control flow transfer
1446 // (break/continue/return). The site of the, e.g., break removes the
1447 // try handler and calls the finally block code before continuing
1448 // its outward control transfer.
1449 // 3. By exiting the try-block with a thrown exception.
1450 // This can happen in nested function calls. It traverses the try-handler
1451 // chain and consumes the try-handler entry before jumping to the
1452 // handler code. The handler code then calls the finally-block before
1453 // rethrowing the exception.
1455 // The finally block must assume a return address on top of the stack
1456 // (or in the link register on ARM chips) and a value (return value or
1457 // exception) in the result register (rax/eax/r0), both of which must
1458 // be preserved. The return address isn't GC-safe, so it should be
1459 // cooked before GC.
1460 Label try_entry, handler_entry, finally_entry;
1462 // Jump to try-handler setup and try-block code.
1464 __ bind(&handler_entry);
1465 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1466 // Exception handler code. This code is only executed when an exception
1467 // is thrown. The exception is in the result register, and must be
1468 // preserved by the finally block. Call the finally block and then
1469 // rethrow the exception if it returns.
1470 __ Call(&finally_entry);
1471 __ Push(result_register());
1472 __ CallRuntime(Runtime::kReThrow, 1);
1474 // Finally block implementation.
1475 __ bind(&finally_entry);
1476 EnterFinallyBlock();
1477 { Finally finally_body(this);
1478 Visit(stmt->finally_block());
1480 ExitFinallyBlock(); // Return to the calling code.
1482 // Set up try handler.
1483 __ bind(&try_entry);
1484 __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1485 { TryFinally try_body(this, &finally_entry);
1486 Visit(stmt->try_block());
1489 // Execute the finally block on the way out. Clobber the unpredictable
1490 // value in the result register with one that's safe for GC because the
1491 // finally block will unconditionally preserve the result register on the
1494 __ Call(&finally_entry);
1498 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1499 Comment cmnt(masm_, "[ DebuggerStatement");
1500 SetStatementPosition(stmt);
1503 // Ignore the return value.
1505 PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1509 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1514 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1515 Comment cmnt(masm_, "[ Conditional");
1516 Label true_case, false_case, done;
1517 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1519 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1520 __ bind(&true_case);
1521 SetExpressionPosition(expr->then_expression());
1522 if (context()->IsTest()) {
1523 const TestContext* for_test = TestContext::cast(context());
1524 VisitForControl(expr->then_expression(),
1525 for_test->true_label(),
1526 for_test->false_label(),
1529 VisitInDuplicateContext(expr->then_expression());
1533 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1534 __ bind(&false_case);
1535 SetExpressionPosition(expr->else_expression());
1536 VisitInDuplicateContext(expr->else_expression());
1537 // If control flow falls through Visit, merge it with true case here.
1538 if (!context()->IsTest()) {
1544 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1545 Comment cmnt(masm_, "[ Literal");
1546 context()->Plug(expr->value());
1550 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1551 Comment cmnt(masm_, "[ FunctionLiteral");
1553 // Build the function boilerplate and instantiate it.
1554 Handle<SharedFunctionInfo> function_info =
1555 Compiler::BuildFunctionInfo(expr, script(), info_);
1556 if (function_info.is_null()) {
1560 EmitNewClosure(function_info, expr->pretenure());
1564 void FullCodeGenerator::VisitClassLiteral(ClassLiteral* lit) {
1565 Comment cmnt(masm_, "[ ClassLiteral");
1567 if (lit->raw_name() != NULL) {
1568 __ Push(lit->name());
1570 __ Push(isolate()->factory()->undefined_value());
1573 if (lit->extends() != NULL) {
1574 VisitForStackValue(lit->extends());
1576 __ Push(isolate()->factory()->the_hole_value());
1579 if (lit->constructor() != NULL) {
1580 VisitForStackValue(lit->constructor());
1582 __ Push(isolate()->factory()->undefined_value());
1586 __ Push(Smi::FromInt(lit->start_position()));
1587 __ Push(Smi::FromInt(lit->end_position()));
1589 __ CallRuntime(Runtime::kDefineClass, 6);
1590 EmitClassDefineProperties(lit);
1592 context()->Plug(result_register());
1596 void FullCodeGenerator::VisitNativeFunctionLiteral(
1597 NativeFunctionLiteral* expr) {
1598 Comment cmnt(masm_, "[ NativeFunctionLiteral");
1600 // Compute the function template for the native function.
1601 Handle<String> name = expr->name();
1602 v8::Handle<v8::FunctionTemplate> fun_template =
1603 expr->extension()->GetNativeFunctionTemplate(
1604 reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1605 DCHECK(!fun_template.IsEmpty());
1607 // Instantiate the function and create a shared function info from it.
1608 Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1609 const int literals = fun->NumberOfLiterals();
1610 Handle<Code> code = Handle<Code>(fun->shared()->code());
1611 Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1612 Handle<SharedFunctionInfo> shared =
1613 isolate()->factory()->NewSharedFunctionInfo(
1614 name, literals, FunctionKind::kNormalFunction, code,
1615 Handle<ScopeInfo>(fun->shared()->scope_info()),
1616 Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1617 shared->set_construct_stub(*construct_stub);
1619 // Copy the function data to the shared function info.
1620 shared->set_function_data(fun->shared()->function_data());
1621 int parameters = fun->shared()->formal_parameter_count();
1622 shared->set_formal_parameter_count(parameters);
1624 EmitNewClosure(shared, false);
1628 void FullCodeGenerator::VisitThrow(Throw* expr) {
1629 Comment cmnt(masm_, "[ Throw");
1630 VisitForStackValue(expr->exception());
1631 __ CallRuntime(Runtime::kThrow, 1);
1632 // Never returns here.
1636 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
1638 int* context_length) {
1639 // The macros used here must preserve the result register.
1640 __ Drop(*stack_depth);
1647 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1648 Expression* sub_expr;
1649 Handle<String> check;
1650 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1651 EmitLiteralCompareTypeof(expr, sub_expr, check);
1655 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1656 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1660 if (expr->IsLiteralCompareNull(&sub_expr)) {
1661 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1669 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1670 DisallowHeapAllocation no_gc;
1671 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1673 // Increment loop nesting level by one and iterate over the back edge table
1674 // to find the matching loops to patch the interrupt
1675 // call to an unconditional call to the replacement code.
1676 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1677 if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1679 BackEdgeTable back_edges(unoptimized, &no_gc);
1680 for (uint32_t i = 0; i < back_edges.length(); i++) {
1681 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1682 DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1685 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1689 unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1690 DCHECK(Verify(isolate, unoptimized));
1694 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1695 DisallowHeapAllocation no_gc;
1696 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1698 // Iterate over the back edge table and revert the patched interrupt calls.
1699 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1701 BackEdgeTable back_edges(unoptimized, &no_gc);
1702 for (uint32_t i = 0; i < back_edges.length(); i++) {
1703 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1704 DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1707 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1711 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1712 // Assert that none of the back edges are patched anymore.
1713 DCHECK(Verify(isolate, unoptimized));
1717 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1718 DisallowHeapAllocation no_gc;
1719 Isolate* isolate = code->GetIsolate();
1720 Address pc = code->instruction_start() + pc_offset;
1721 Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1722 PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1726 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1727 DisallowHeapAllocation no_gc;
1728 Isolate* isolate = code->GetIsolate();
1729 Address pc = code->instruction_start() + pc_offset;
1731 if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1732 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1733 PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1739 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1740 DisallowHeapAllocation no_gc;
1741 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1742 BackEdgeTable back_edges(unoptimized, &no_gc);
1743 for (uint32_t i = 0; i < back_edges.length(); i++) {
1744 uint32_t loop_depth = back_edges.loop_depth(i);
1745 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1746 // Assert that all back edges for shallower loops (and only those)
1747 // have already been patched.
1748 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1749 GetBackEdgeState(isolate,
1751 back_edges.pc(i)) != INTERRUPT);
1761 } } // namespace v8::internal