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.
6 #include "src/ast-numbering.h"
7 #include "src/code-factory.h"
8 #include "src/codegen.h"
9 #include "src/compiler.h"
10 #include "src/debug/debug.h"
11 #include "src/debug/liveedit.h"
12 #include "src/full-codegen/full-codegen.h"
13 #include "src/macro-assembler.h"
14 #include "src/prettyprinter.h"
15 #include "src/scopeinfo.h"
16 #include "src/scopes.h"
17 #include "src/snapshot/snapshot.h"
22 #define __ ACCESS_MASM(masm())
24 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
25 Isolate* isolate = info->isolate();
27 TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
29 // Ensure that the feedback vector is large enough.
30 info->EnsureFeedbackVector();
32 Handle<Script> script = info->script();
33 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
34 int len = String::cast(script->source())->length();
35 isolate->counters()->total_full_codegen_source_size()->Increment(len);
37 CodeGenerator::MakeCodePrologue(info, "full");
38 const int kInitialBufferSize = 4 * KB;
39 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
40 if (info->will_serialize()) masm.enable_serializer();
42 LOG_CODE_EVENT(isolate,
43 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
45 FullCodeGenerator cgen(&masm, info);
47 if (cgen.HasStackOverflow()) {
48 DCHECK(!isolate->has_pending_exception());
51 unsigned table_offset = cgen.EmitBackEdgeTable();
53 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, info);
54 cgen.PopulateDeoptimizationData(code);
55 cgen.PopulateTypeFeedbackInfo(code);
56 cgen.PopulateHandlerTable(code);
57 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
58 code->set_has_reloc_info_for_serialization(info->will_serialize());
59 code->set_allow_osr_at_loop_nesting_level(0);
60 code->set_profiler_ticks(0);
61 code->set_back_edge_table_offset(table_offset);
62 CodeGenerator::PrintCode(code, info);
64 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
65 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
68 // Check that no context-specific object has been embedded.
69 code->VerifyEmbeddedObjects(Code::kNoContextSpecificPointers);
75 unsigned FullCodeGenerator::EmitBackEdgeTable() {
76 // The back edge table consists of a length (in number of entries)
77 // field, and then a sequence of entries. Each entry is a pair of AST id
78 // and code-relative pc offset.
79 masm()->Align(kPointerSize);
80 unsigned offset = masm()->pc_offset();
81 unsigned length = back_edges_.length();
83 for (unsigned i = 0; i < length; ++i) {
84 __ dd(back_edges_[i].id.ToInt());
85 __ dd(back_edges_[i].pc);
86 __ dd(back_edges_[i].loop_depth);
92 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
93 FeedbackVectorSlot slot) {
94 Handle<TypeFeedbackVector> vector = FeedbackVector();
95 if (!vector->Get(slot)->IsAllocationSite()) {
96 Handle<AllocationSite> allocation_site =
97 isolate()->factory()->NewAllocationSite();
98 vector->Set(slot, *allocation_site);
103 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
104 FeedbackVectorICSlot slot) {
105 Handle<TypeFeedbackVector> vector = FeedbackVector();
106 if (!vector->Get(slot)->IsAllocationSite()) {
107 Handle<AllocationSite> allocation_site =
108 isolate()->factory()->NewAllocationSite();
109 vector->Set(slot, *allocation_site);
114 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
115 // Fill in the deoptimization information.
116 DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
117 if (!info_->HasDeoptimizationSupport()) return;
118 int length = bailout_entries_.length();
119 Handle<DeoptimizationOutputData> data =
120 DeoptimizationOutputData::New(isolate(), length, TENURED);
121 for (int i = 0; i < length; i++) {
122 data->SetAstId(i, bailout_entries_[i].id);
123 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
125 code->set_deoptimization_data(*data);
129 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
130 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
131 info->set_ic_total_count(ic_total_count_);
132 DCHECK(!isolate()->heap()->InNewSpace(*info));
133 code->set_type_feedback_info(*info);
137 void FullCodeGenerator::PopulateHandlerTable(Handle<Code> code) {
138 int handler_table_size = static_cast<int>(handler_table_.size());
139 Handle<HandlerTable> table =
140 Handle<HandlerTable>::cast(isolate()->factory()->NewFixedArray(
141 HandlerTable::LengthForRange(handler_table_size), TENURED));
142 for (int i = 0; i < handler_table_size; ++i) {
143 HandlerTable::CatchPrediction prediction =
144 handler_table_[i].try_catch_depth > 0 ? HandlerTable::CAUGHT
145 : HandlerTable::UNCAUGHT;
146 table->SetRangeStart(i, handler_table_[i].range_start);
147 table->SetRangeEnd(i, handler_table_[i].range_end);
148 table->SetRangeHandler(i, handler_table_[i].handler_offset, prediction);
149 table->SetRangeDepth(i, handler_table_[i].stack_depth);
151 code->set_handler_table(*table);
155 int FullCodeGenerator::NewHandlerTableEntry() {
156 int index = static_cast<int>(handler_table_.size());
157 HandlerTableEntry entry = {0, 0, 0, 0, 0};
158 handler_table_.push_back(entry);
163 bool FullCodeGenerator::MustCreateObjectLiteralWithRuntime(
164 ObjectLiteral* expr) const {
165 int literal_flags = expr->ComputeFlags();
166 // FastCloneShallowObjectStub doesn't copy elements, and object literals don't
167 // support copy-on-write (COW) elements for now.
168 // TODO(mvstanton): make object literals support COW elements.
169 return masm()->serializer_enabled() ||
170 literal_flags != ObjectLiteral::kShallowProperties ||
171 literal_flags != ObjectLiteral::kFastElements ||
172 expr->properties_count() >
173 FastCloneShallowObjectStub::kMaximumClonedProperties;
177 bool FullCodeGenerator::MustCreateArrayLiteralWithRuntime(
178 ArrayLiteral* expr) const {
179 // TODO(rossberg): Teach strong mode to FastCloneShallowArrayStub.
180 return expr->depth() > 1 || expr->is_strong() ||
181 expr->values()->length() > JSObject::kInitialMaxFastElementArray;
185 void FullCodeGenerator::Initialize() {
186 InitializeAstVisitor(info_->isolate(), info_->zone());
187 // The generation of debug code must match between the snapshot code and the
188 // code that is generated later. This is assumed by the debugger when it is
189 // calculating PC offsets after generating a debug version of code. Therefore
190 // we disable the production of debug code in the full compiler if we are
191 // either generating a snapshot or we booted from a snapshot.
192 generate_debug_code_ = FLAG_debug_code && !masm_->serializer_enabled() &&
193 !info_->isolate()->snapshot_available();
194 masm_->set_emit_debug_code(generate_debug_code_);
195 masm_->set_predictable_code_size(true);
199 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
200 PrepareForBailoutForId(node->id(), state);
204 void FullCodeGenerator::CallLoadIC(TypeofMode typeof_mode,
205 LanguageMode language_mode,
208 CodeFactory::LoadIC(isolate(), typeof_mode, language_mode).code();
213 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
214 Handle<Code> ic = CodeFactory::StoreIC(isolate(), language_mode()).code();
219 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
220 // We record the offset of the function return so we can rebuild the frame
221 // if the function was inlined, i.e., this is the return address in the
222 // inlined function's frame.
224 // The state is ignored. We defensively set it to TOS_REG, which is the
225 // real state of the unoptimized code at the return site.
226 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
228 // In debug builds, mark the return so we can verify that this function
230 DCHECK(!call->return_is_recorded_);
231 call->return_is_recorded_ = true;
236 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
237 // There's no need to prepare this code for bailouts from already optimized
238 // code or code that can't be optimized.
239 if (!info_->HasDeoptimizationSupport()) return;
240 unsigned pc_and_state =
241 StateField::encode(state) | PcField::encode(masm_->pc_offset());
242 DCHECK(Smi::IsValid(pc_and_state));
244 for (int i = 0; i < bailout_entries_.length(); ++i) {
245 DCHECK(bailout_entries_[i].id != id);
248 BailoutEntry entry = { id, pc_and_state };
249 bailout_entries_.Add(entry, zone());
253 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
254 // The pc offset does not need to be encoded and packed together with a state.
255 DCHECK(masm_->pc_offset() > 0);
256 DCHECK(loop_depth() > 0);
257 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
258 BackEdgeEntry entry =
259 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
260 back_edges_.Add(entry, zone());
264 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
265 // Inline smi case inside loops, but not division and modulo which
266 // are too complicated and take up too much space.
267 if (op == Token::DIV ||op == Token::MOD) return false;
268 if (FLAG_always_inline_smi_code) return true;
269 return loop_depth_ > 0;
273 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
274 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
278 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
279 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
280 codegen()->GetVar(result_register(), var);
284 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
285 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
286 // For simplicity we always test the accumulator register.
287 codegen()->GetVar(result_register(), var);
288 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
289 codegen()->DoTest(this);
293 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
297 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
298 __ Move(result_register(), reg);
302 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
307 void FullCodeGenerator::TestContext::Plug(Register reg) const {
308 // For simplicity we always test the accumulator register.
309 __ Move(result_register(), reg);
310 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
311 codegen()->DoTest(this);
315 void FullCodeGenerator::EffectContext::Plug(bool flag) const {}
318 void FullCodeGenerator::EffectContext::PlugTOS() const {
323 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
324 __ Pop(result_register());
328 void FullCodeGenerator::StackValueContext::PlugTOS() const {
332 void FullCodeGenerator::TestContext::PlugTOS() const {
333 // For simplicity we always test the accumulator register.
334 __ Pop(result_register());
335 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
336 codegen()->DoTest(this);
340 void FullCodeGenerator::EffectContext::PrepareTest(
341 Label* materialize_true,
342 Label* materialize_false,
345 Label** fall_through) const {
346 // In an effect context, the true and the false case branch to the
348 *if_true = *if_false = *fall_through = materialize_true;
352 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
353 Label* materialize_true,
354 Label* materialize_false,
357 Label** fall_through) const {
358 *if_true = *fall_through = materialize_true;
359 *if_false = materialize_false;
363 void FullCodeGenerator::StackValueContext::PrepareTest(
364 Label* materialize_true,
365 Label* materialize_false,
368 Label** fall_through) const {
369 *if_true = *fall_through = materialize_true;
370 *if_false = materialize_false;
374 void FullCodeGenerator::TestContext::PrepareTest(
375 Label* materialize_true,
376 Label* materialize_false,
379 Label** fall_through) const {
380 *if_true = true_label_;
381 *if_false = false_label_;
382 *fall_through = fall_through_;
386 void FullCodeGenerator::DoTest(const TestContext* context) {
387 DoTest(context->condition(),
388 context->true_label(),
389 context->false_label(),
390 context->fall_through());
394 void FullCodeGenerator::VisitDeclarations(
395 ZoneList<Declaration*>* declarations) {
396 ZoneList<Handle<Object> >* saved_globals = globals_;
397 ZoneList<Handle<Object> > inner_globals(10, zone());
398 globals_ = &inner_globals;
400 AstVisitor::VisitDeclarations(declarations);
402 if (!globals_->is_empty()) {
403 // Invoke the platform-dependent code generator to do the actual
404 // declaration of the global functions and variables.
405 Handle<FixedArray> array =
406 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
407 for (int i = 0; i < globals_->length(); ++i)
408 array->set(i, *globals_->at(i));
409 DeclareGlobals(array);
412 globals_ = saved_globals;
416 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
417 VariableProxy* proxy = declaration->proxy();
418 Variable* variable = proxy->var();
419 switch (variable->location()) {
420 case VariableLocation::GLOBAL:
421 case VariableLocation::UNALLOCATED:
425 case VariableLocation::CONTEXT: {
426 Comment cmnt(masm_, "[ ImportDeclaration");
427 EmitDebugCheckDeclarationContext(variable);
432 case VariableLocation::PARAMETER:
433 case VariableLocation::LOCAL:
434 case VariableLocation::LOOKUP:
440 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
445 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
446 Comment cmnt(masm_, "[ VariableProxy");
447 EmitVariableLoad(expr);
451 int FullCodeGenerator::DeclareGlobalsFlags() {
452 DCHECK(DeclareGlobalsLanguageMode::is_valid(language_mode()));
453 return DeclareGlobalsEvalFlag::encode(is_eval()) |
454 DeclareGlobalsNativeFlag::encode(is_native()) |
455 DeclareGlobalsLanguageMode::encode(language_mode());
459 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
460 // Load the arguments on the stack and call the stub.
461 SubStringStub stub(isolate());
462 ZoneList<Expression*>* args = expr->arguments();
463 DCHECK(args->length() == 3);
464 VisitForStackValue(args->at(0));
465 VisitForStackValue(args->at(1));
466 VisitForStackValue(args->at(2));
468 context()->Plug(result_register());
472 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
473 // Load the arguments on the stack and call the stub.
474 RegExpExecStub stub(isolate());
475 ZoneList<Expression*>* args = expr->arguments();
476 DCHECK(args->length() == 4);
477 VisitForStackValue(args->at(0));
478 VisitForStackValue(args->at(1));
479 VisitForStackValue(args->at(2));
480 VisitForStackValue(args->at(3));
482 context()->Plug(result_register());
486 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
487 // Load the arguments on the stack and call the runtime function.
488 ZoneList<Expression*>* args = expr->arguments();
489 DCHECK(args->length() == 2);
490 VisitForStackValue(args->at(0));
491 VisitForStackValue(args->at(1));
493 MathPowStub stub(isolate(), MathPowStub::ON_STACK);
495 context()->Plug(result_register());
499 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
500 ZoneList<Expression*>* args = expr->arguments();
501 DCHECK_EQ(2, args->length());
503 VisitForStackValue(args->at(0));
504 VisitForStackValue(args->at(1));
506 StringCompareStub stub(isolate());
508 context()->Plug(result_register());
512 bool RecordStatementPosition(MacroAssembler* masm, int pos) {
513 if (pos == RelocInfo::kNoPosition) return false;
514 masm->positions_recorder()->RecordStatementPosition(pos);
515 masm->positions_recorder()->RecordPosition(pos);
516 return masm->positions_recorder()->WriteRecordedPositions();
520 bool RecordPosition(MacroAssembler* masm, int pos) {
521 if (pos == RelocInfo::kNoPosition) return false;
522 masm->positions_recorder()->RecordPosition(pos);
523 return masm->positions_recorder()->WriteRecordedPositions();
527 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
528 RecordPosition(masm_, fun->start_position());
532 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
533 RecordStatementPosition(masm_, fun->end_position() - 1);
534 if (info_->is_debug()) {
535 // Always emit a debug break slot before a return.
536 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_RETURN);
541 void FullCodeGenerator::SetStatementPosition(
542 Statement* stmt, FullCodeGenerator::InsertBreak insert_break) {
543 if (stmt->position() == RelocInfo::kNoPosition) return;
544 bool recorded = RecordStatementPosition(masm_, stmt->position());
545 if (recorded && insert_break == INSERT_BREAK && info_->is_debug() &&
546 !stmt->IsDebuggerStatement()) {
547 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
552 void FullCodeGenerator::SetExpressionPosition(
553 Expression* expr, FullCodeGenerator::InsertBreak insert_break) {
554 if (expr->position() == RelocInfo::kNoPosition) return;
555 bool recorded = RecordPosition(masm_, expr->position());
556 if (recorded && insert_break == INSERT_BREAK && info_->is_debug()) {
557 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
562 void FullCodeGenerator::SetExpressionAsStatementPosition(Expression* expr) {
563 if (expr->position() == RelocInfo::kNoPosition) return;
564 bool recorded = RecordStatementPosition(masm_, expr->position());
565 if (recorded && info_->is_debug()) {
566 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
571 void FullCodeGenerator::SetCallPosition(Expression* expr, int argc) {
572 if (expr->position() == RelocInfo::kNoPosition) return;
573 RecordPosition(masm_, expr->position());
574 if (info_->is_debug()) {
575 // Always emit a debug break slot before a call.
576 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_CALL,
582 void FullCodeGenerator::SetConstructCallPosition(Expression* expr) {
583 if (expr->position() == RelocInfo::kNoPosition) return;
584 RecordPosition(masm_, expr->position());
585 if (info_->is_debug()) {
586 // Always emit a debug break slot before a construct call.
587 DebugCodegen::GenerateSlot(masm_,
588 RelocInfo::DEBUG_BREAK_SLOT_AT_CONSTRUCT_CALL);
593 void FullCodeGenerator::VisitSuperPropertyReference(
594 SuperPropertyReference* super) {
595 __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
599 void FullCodeGenerator::VisitSuperCallReference(SuperCallReference* super) {
600 __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
604 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
605 ZoneList<Expression*>* args = expr->arguments();
606 DCHECK(args->length() == 2);
607 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
611 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
612 ZoneList<Expression*>* args = expr->arguments();
613 DCHECK(args->length() == 2);
614 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
618 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
619 context()->Plug(handle(Smi::FromInt(0), isolate()));
623 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
624 switch (expr->op()) {
626 return VisitComma(expr);
629 return VisitLogicalExpression(expr);
631 return VisitArithmeticExpression(expr);
636 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
637 if (context()->IsEffect()) {
638 VisitForEffect(expr);
639 } else if (context()->IsAccumulatorValue()) {
640 VisitForAccumulatorValue(expr);
641 } else if (context()->IsStackValue()) {
642 VisitForStackValue(expr);
643 } else if (context()->IsTest()) {
644 const TestContext* test = TestContext::cast(context());
645 VisitForControl(expr, test->true_label(), test->false_label(),
646 test->fall_through());
651 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
652 Comment cmnt(masm_, "[ Comma");
653 VisitForEffect(expr->left());
654 VisitInDuplicateContext(expr->right());
658 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
659 bool is_logical_and = expr->op() == Token::AND;
660 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
661 Expression* left = expr->left();
662 Expression* right = expr->right();
663 BailoutId right_id = expr->RightId();
666 if (context()->IsTest()) {
668 const TestContext* test = TestContext::cast(context());
669 if (is_logical_and) {
670 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
672 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
674 PrepareForBailoutForId(right_id, NO_REGISTERS);
675 __ bind(&eval_right);
677 } else if (context()->IsAccumulatorValue()) {
678 VisitForAccumulatorValue(left);
679 // We want the value in the accumulator for the test, and on the stack in
681 __ Push(result_register());
682 Label discard, restore;
683 if (is_logical_and) {
684 DoTest(left, &discard, &restore, &restore);
686 DoTest(left, &restore, &discard, &restore);
689 __ Pop(result_register());
693 PrepareForBailoutForId(right_id, NO_REGISTERS);
695 } else if (context()->IsStackValue()) {
696 VisitForAccumulatorValue(left);
697 // We want the value in the accumulator for the test, and on the stack in
699 __ Push(result_register());
701 if (is_logical_and) {
702 DoTest(left, &discard, &done, &discard);
704 DoTest(left, &done, &discard, &discard);
708 PrepareForBailoutForId(right_id, NO_REGISTERS);
711 DCHECK(context()->IsEffect());
713 if (is_logical_and) {
714 VisitForControl(left, &eval_right, &done, &eval_right);
716 VisitForControl(left, &done, &eval_right, &eval_right);
718 PrepareForBailoutForId(right_id, NO_REGISTERS);
719 __ bind(&eval_right);
722 VisitInDuplicateContext(right);
727 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
728 Token::Value op = expr->op();
729 Comment cmnt(masm_, "[ ArithmeticExpression");
730 Expression* left = expr->left();
731 Expression* right = expr->right();
733 VisitForStackValue(left);
734 VisitForAccumulatorValue(right);
736 SetExpressionPosition(expr);
737 if (ShouldInlineSmiCase(op)) {
738 EmitInlineSmiBinaryOp(expr, op, left, right);
740 EmitBinaryOp(expr, op);
745 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
746 VariableProxy* proxy = expr->AsVariableProxy();
747 DCHECK(!context()->IsEffect());
748 DCHECK(!context()->IsTest());
750 if (proxy != NULL && (proxy->var()->IsUnallocatedOrGlobalSlot() ||
751 proxy->var()->IsLookupSlot())) {
752 EmitVariableLoad(proxy, INSIDE_TYPEOF);
753 PrepareForBailout(proxy, TOS_REG);
755 // This expression cannot throw a reference error at the top level.
756 VisitInDuplicateContext(expr);
761 void FullCodeGenerator::VisitBlock(Block* stmt) {
762 Comment cmnt(masm_, "[ Block");
763 NestedBlock nested_block(this, stmt);
764 SetStatementPosition(stmt);
767 EnterBlockScopeIfNeeded block_scope_state(
768 this, stmt->scope(), stmt->EntryId(), stmt->DeclsId(), stmt->ExitId());
769 VisitStatements(stmt->statements());
770 __ bind(nested_block.break_label());
775 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
776 Comment cmnt(masm_, "[ ExpressionStatement");
777 SetStatementPosition(stmt);
778 VisitForEffect(stmt->expression());
782 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
783 Comment cmnt(masm_, "[ EmptyStatement");
784 SetStatementPosition(stmt);
788 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
789 Comment cmnt(masm_, "[ IfStatement");
790 SetStatementPosition(stmt);
791 Label then_part, else_part, done;
793 if (stmt->HasElseStatement()) {
794 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
795 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
797 Visit(stmt->then_statement());
800 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
802 Visit(stmt->else_statement());
804 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
805 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
807 Visit(stmt->then_statement());
809 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
812 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
816 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
817 Comment cmnt(masm_, "[ ContinueStatement");
818 SetStatementPosition(stmt);
819 NestedStatement* current = nesting_stack_;
821 int context_length = 0;
822 // When continuing, we clobber the unpredictable value in the accumulator
823 // with one that's safe for GC. If we hit an exit from the try block of
824 // try...finally on our way out, we will unconditionally preserve the
825 // accumulator on the stack.
827 while (!current->IsContinueTarget(stmt->target())) {
828 current = current->Exit(&stack_depth, &context_length);
830 __ Drop(stack_depth);
831 if (context_length > 0) {
832 while (context_length > 0) {
833 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
836 StoreToFrameField(StandardFrameConstants::kContextOffset,
840 __ jmp(current->AsIteration()->continue_label());
844 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
845 Comment cmnt(masm_, "[ BreakStatement");
846 SetStatementPosition(stmt);
847 NestedStatement* current = nesting_stack_;
849 int context_length = 0;
850 // When breaking, we clobber the unpredictable value in the accumulator
851 // with one that's safe for GC. If we hit an exit from the try block of
852 // try...finally on our way out, we will unconditionally preserve the
853 // accumulator on the stack.
855 while (!current->IsBreakTarget(stmt->target())) {
856 current = current->Exit(&stack_depth, &context_length);
858 __ Drop(stack_depth);
859 if (context_length > 0) {
860 while (context_length > 0) {
861 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
864 StoreToFrameField(StandardFrameConstants::kContextOffset,
868 __ jmp(current->AsBreakable()->break_label());
872 void FullCodeGenerator::EmitUnwindBeforeReturn() {
873 NestedStatement* current = nesting_stack_;
875 int context_length = 0;
876 while (current != NULL) {
877 current = current->Exit(&stack_depth, &context_length);
879 __ Drop(stack_depth);
883 void FullCodeGenerator::EmitPropertyKey(ObjectLiteralProperty* property,
884 BailoutId bailout_id) {
885 VisitForStackValue(property->key());
886 __ InvokeBuiltin(Context::TO_NAME_BUILTIN_INDEX, CALL_FUNCTION);
887 PrepareForBailoutForId(bailout_id, NO_REGISTERS);
888 __ Push(result_register());
892 void FullCodeGenerator::EmitLoadSuperConstructor(SuperCallReference* ref) {
893 VisitForStackValue(ref->this_function_var());
894 __ CallRuntime(Runtime::kGetPrototype, 1);
898 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
899 Comment cmnt(masm_, "[ ReturnStatement");
900 SetStatementPosition(stmt);
901 Expression* expr = stmt->expression();
902 VisitForAccumulatorValue(expr);
903 EmitUnwindBeforeReturn();
904 EmitReturnSequence();
908 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
909 Comment cmnt(masm_, "[ WithStatement");
910 SetStatementPosition(stmt);
912 VisitForStackValue(stmt->expression());
913 PushFunctionArgumentForContextAllocation();
914 __ CallRuntime(Runtime::kPushWithContext, 2);
915 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
916 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
918 Scope* saved_scope = scope();
919 scope_ = stmt->scope();
920 { WithOrCatch body(this);
921 Visit(stmt->statement());
923 scope_ = saved_scope;
926 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
927 // Update local stack frame context field.
928 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
932 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
933 Comment cmnt(masm_, "[ DoWhileStatement");
934 // Do not insert break location as we do that below.
935 SetStatementPosition(stmt, SKIP_BREAK);
937 Label body, book_keeping;
939 Iteration loop_statement(this, stmt);
940 increment_loop_depth();
945 // Record the position of the do while condition and make sure it is
946 // possible to break on the condition.
947 __ bind(loop_statement.continue_label());
948 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
950 // Here is the actual 'while' keyword.
951 SetExpressionAsStatementPosition(stmt->cond());
952 VisitForControl(stmt->cond(),
954 loop_statement.break_label(),
957 // Check stack before looping.
958 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
959 __ bind(&book_keeping);
960 EmitBackEdgeBookkeeping(stmt, &body);
963 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
964 __ bind(loop_statement.break_label());
965 decrement_loop_depth();
969 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
970 Comment cmnt(masm_, "[ WhileStatement");
973 Iteration loop_statement(this, stmt);
974 increment_loop_depth();
978 SetExpressionAsStatementPosition(stmt->cond());
979 VisitForControl(stmt->cond(),
981 loop_statement.break_label(),
984 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
988 __ bind(loop_statement.continue_label());
990 // Check stack before looping.
991 EmitBackEdgeBookkeeping(stmt, &loop);
994 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
995 __ bind(loop_statement.break_label());
996 decrement_loop_depth();
1000 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1001 Comment cmnt(masm_, "[ ForStatement");
1002 // Do not insert break location as we do it below.
1003 SetStatementPosition(stmt, SKIP_BREAK);
1007 Iteration loop_statement(this, stmt);
1009 if (stmt->init() != NULL) {
1010 SetStatementPosition(stmt->init());
1011 Visit(stmt->init());
1014 increment_loop_depth();
1015 // Emit the test at the bottom of the loop (even if empty).
1018 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1020 Visit(stmt->body());
1022 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1023 __ bind(loop_statement.continue_label());
1024 if (stmt->next() != NULL) {
1025 SetStatementPosition(stmt->next());
1026 Visit(stmt->next());
1029 // Check stack before looping.
1030 EmitBackEdgeBookkeeping(stmt, &body);
1033 if (stmt->cond() != NULL) {
1034 SetExpressionAsStatementPosition(stmt->cond());
1035 VisitForControl(stmt->cond(),
1037 loop_statement.break_label(),
1038 loop_statement.break_label());
1043 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1044 __ bind(loop_statement.break_label());
1045 decrement_loop_depth();
1049 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1050 Comment cmnt(masm_, "[ ForOfStatement");
1052 Iteration loop_statement(this, stmt);
1053 increment_loop_depth();
1055 // var iterator = iterable[Symbol.iterator]();
1056 VisitForEffect(stmt->assign_iterator());
1059 __ bind(loop_statement.continue_label());
1061 // result = iterator.next()
1062 SetExpressionAsStatementPosition(stmt->next_result());
1063 VisitForEffect(stmt->next_result());
1065 // if (result.done) break;
1066 Label result_not_done;
1067 VisitForControl(stmt->result_done(), loop_statement.break_label(),
1068 &result_not_done, &result_not_done);
1069 __ bind(&result_not_done);
1071 // each = result.value
1072 VisitForEffect(stmt->assign_each());
1074 // Generate code for the body of the loop.
1075 Visit(stmt->body());
1077 // Check stack before looping.
1078 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1079 EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1080 __ jmp(loop_statement.continue_label());
1082 // Exit and decrement the loop depth.
1083 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1084 __ bind(loop_statement.break_label());
1085 decrement_loop_depth();
1089 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1090 Comment cmnt(masm_, "[ TryCatchStatement");
1091 SetStatementPosition(stmt, SKIP_BREAK);
1093 // The try block adds a handler to the exception handler chain before
1094 // entering, and removes it again when exiting normally. If an exception
1095 // is thrown during execution of the try block, the handler is consumed
1096 // and control is passed to the catch block with the exception in the
1099 Label try_entry, handler_entry, exit;
1101 __ bind(&handler_entry);
1102 PrepareForBailoutForId(stmt->HandlerId(), NO_REGISTERS);
1103 ClearPendingMessage();
1105 // Exception handler code, the exception is in the result register.
1106 // Extend the context before executing the catch block.
1107 { Comment cmnt(masm_, "[ Extend catch context");
1108 __ Push(stmt->variable()->name());
1109 __ Push(result_register());
1110 PushFunctionArgumentForContextAllocation();
1111 __ CallRuntime(Runtime::kPushCatchContext, 3);
1112 StoreToFrameField(StandardFrameConstants::kContextOffset,
1113 context_register());
1116 Scope* saved_scope = scope();
1117 scope_ = stmt->scope();
1118 DCHECK(scope_->declarations()->is_empty());
1119 { WithOrCatch catch_body(this);
1120 Visit(stmt->catch_block());
1122 // Restore the context.
1123 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1124 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1125 scope_ = saved_scope;
1128 // Try block code. Sets up the exception handler chain.
1129 __ bind(&try_entry);
1132 int handler_index = NewHandlerTableEntry();
1133 EnterTryBlock(handler_index, &handler_entry);
1134 { TryCatch try_body(this);
1135 Visit(stmt->try_block());
1137 ExitTryBlock(handler_index);
1143 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1144 Comment cmnt(masm_, "[ TryFinallyStatement");
1145 SetStatementPosition(stmt, SKIP_BREAK);
1147 // Try finally is compiled by setting up a try-handler on the stack while
1148 // executing the try body, and removing it again afterwards.
1150 // The try-finally construct can enter the finally block in three ways:
1151 // 1. By exiting the try-block normally. This removes the try-handler and
1152 // calls the finally block code before continuing.
1153 // 2. By exiting the try-block with a function-local control flow transfer
1154 // (break/continue/return). The site of the, e.g., break removes the
1155 // try handler and calls the finally block code before continuing
1156 // its outward control transfer.
1157 // 3. By exiting the try-block with a thrown exception.
1158 // This can happen in nested function calls. It traverses the try-handler
1159 // chain and consumes the try-handler entry before jumping to the
1160 // handler code. The handler code then calls the finally-block before
1161 // rethrowing the exception.
1163 // The finally block must assume a return address on top of the stack
1164 // (or in the link register on ARM chips) and a value (return value or
1165 // exception) in the result register (rax/eax/r0), both of which must
1166 // be preserved. The return address isn't GC-safe, so it should be
1167 // cooked before GC.
1168 Label try_entry, handler_entry, finally_entry;
1170 // Jump to try-handler setup and try-block code.
1172 __ bind(&handler_entry);
1173 PrepareForBailoutForId(stmt->HandlerId(), NO_REGISTERS);
1175 // Exception handler code. This code is only executed when an exception
1176 // is thrown. The exception is in the result register, and must be
1177 // preserved by the finally block. Call the finally block and then
1178 // rethrow the exception if it returns.
1179 __ Call(&finally_entry);
1180 __ Push(result_register());
1181 __ CallRuntime(Runtime::kReThrow, 1);
1183 // Finally block implementation.
1184 __ bind(&finally_entry);
1185 EnterFinallyBlock();
1186 { Finally finally_body(this);
1187 Visit(stmt->finally_block());
1189 ExitFinallyBlock(); // Return to the calling code.
1191 // Set up try handler.
1192 __ bind(&try_entry);
1193 int handler_index = NewHandlerTableEntry();
1194 EnterTryBlock(handler_index, &handler_entry);
1195 { TryFinally try_body(this, &finally_entry);
1196 Visit(stmt->try_block());
1198 ExitTryBlock(handler_index);
1199 // Execute the finally block on the way out. Clobber the unpredictable
1200 // value in the result register with one that's safe for GC because the
1201 // finally block will unconditionally preserve the result register on the
1204 __ Call(&finally_entry);
1208 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1209 Comment cmnt(masm_, "[ DebuggerStatement");
1210 SetStatementPosition(stmt);
1213 // Ignore the return value.
1215 PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1219 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1224 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1225 Comment cmnt(masm_, "[ Conditional");
1226 Label true_case, false_case, done;
1227 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1229 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1230 __ bind(&true_case);
1231 SetExpressionPosition(expr->then_expression());
1232 if (context()->IsTest()) {
1233 const TestContext* for_test = TestContext::cast(context());
1234 VisitForControl(expr->then_expression(),
1235 for_test->true_label(),
1236 for_test->false_label(),
1239 VisitInDuplicateContext(expr->then_expression());
1243 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1244 __ bind(&false_case);
1245 SetExpressionPosition(expr->else_expression());
1246 VisitInDuplicateContext(expr->else_expression());
1247 // If control flow falls through Visit, merge it with true case here.
1248 if (!context()->IsTest()) {
1254 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1255 Comment cmnt(masm_, "[ Literal");
1256 context()->Plug(expr->value());
1260 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1261 Comment cmnt(masm_, "[ FunctionLiteral");
1263 // Build the function boilerplate and instantiate it.
1264 Handle<SharedFunctionInfo> function_info =
1265 Compiler::GetSharedFunctionInfo(expr, script(), info_);
1266 if (function_info.is_null()) {
1270 EmitNewClosure(function_info, expr->pretenure());
1274 void FullCodeGenerator::VisitClassLiteral(ClassLiteral* lit) {
1275 Comment cmnt(masm_, "[ ClassLiteral");
1278 EnterBlockScopeIfNeeded block_scope_state(
1279 this, lit->scope(), lit->EntryId(), lit->DeclsId(), lit->ExitId());
1281 if (lit->raw_name() != NULL) {
1282 __ Push(lit->name());
1284 __ Push(isolate()->factory()->undefined_value());
1287 if (lit->extends() != NULL) {
1288 VisitForStackValue(lit->extends());
1290 __ Push(isolate()->factory()->the_hole_value());
1293 VisitForStackValue(lit->constructor());
1295 __ Push(Smi::FromInt(lit->start_position()));
1296 __ Push(Smi::FromInt(lit->end_position()));
1298 __ CallRuntime(is_strong(language_mode()) ? Runtime::kDefineClassStrong
1299 : Runtime::kDefineClass,
1301 PrepareForBailoutForId(lit->CreateLiteralId(), TOS_REG);
1303 int store_slot_index = 0;
1304 EmitClassDefineProperties(lit, &store_slot_index);
1306 if (lit->scope() != NULL) {
1307 DCHECK_NOT_NULL(lit->class_variable_proxy());
1308 FeedbackVectorICSlot slot =
1309 FLAG_vector_stores &&
1310 lit->class_variable_proxy()->var()->IsUnallocated()
1311 ? lit->GetNthSlot(store_slot_index++)
1312 : FeedbackVectorICSlot::Invalid();
1313 EmitVariableAssignment(lit->class_variable_proxy()->var(),
1314 Token::INIT_CONST, slot);
1317 // Verify that compilation exactly consumed the number of store ic slots
1318 // that the ClassLiteral node had to offer.
1319 DCHECK(!FLAG_vector_stores || store_slot_index == lit->slot_count());
1322 context()->Plug(result_register());
1326 void FullCodeGenerator::VisitNativeFunctionLiteral(
1327 NativeFunctionLiteral* expr) {
1328 Comment cmnt(masm_, "[ NativeFunctionLiteral");
1330 v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate());
1332 // Compute the function template for the native function.
1333 Handle<String> name = expr->name();
1334 v8::Local<v8::FunctionTemplate> fun_template =
1335 expr->extension()->GetNativeFunctionTemplate(v8_isolate,
1336 v8::Utils::ToLocal(name));
1337 DCHECK(!fun_template.IsEmpty());
1339 // Instantiate the function and create a shared function info from it.
1340 Handle<JSFunction> fun = Utils::OpenHandle(
1341 *fun_template->GetFunction(v8_isolate->GetCurrentContext())
1343 const int literals = fun->NumberOfLiterals();
1344 Handle<Code> code = Handle<Code>(fun->shared()->code());
1345 Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1346 Handle<SharedFunctionInfo> shared =
1347 isolate()->factory()->NewSharedFunctionInfo(
1348 name, literals, FunctionKind::kNormalFunction, code,
1349 Handle<ScopeInfo>(fun->shared()->scope_info()),
1350 Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1351 shared->set_construct_stub(*construct_stub);
1353 // Copy the function data to the shared function info.
1354 shared->set_function_data(fun->shared()->function_data());
1355 int parameters = fun->shared()->internal_formal_parameter_count();
1356 shared->set_internal_formal_parameter_count(parameters);
1358 EmitNewClosure(shared, false);
1362 void FullCodeGenerator::VisitThrow(Throw* expr) {
1363 Comment cmnt(masm_, "[ Throw");
1364 VisitForStackValue(expr->exception());
1365 SetExpressionPosition(expr);
1366 __ CallRuntime(Runtime::kThrow, 1);
1367 // Never returns here.
1371 void FullCodeGenerator::EnterTryBlock(int handler_index, Label* handler) {
1372 HandlerTableEntry* entry = &handler_table_[handler_index];
1373 entry->range_start = masm()->pc_offset();
1374 entry->handler_offset = handler->pos();
1375 entry->try_catch_depth = try_catch_depth_;
1377 // Determine expression stack depth of try statement.
1378 int stack_depth = info_->scope()->num_stack_slots(); // Include stack locals.
1379 for (NestedStatement* current = nesting_stack_; current != NULL; /*nop*/) {
1380 current = current->AccumulateDepth(&stack_depth);
1382 entry->stack_depth = stack_depth;
1384 // Push context onto operand stack.
1385 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1386 __ Push(context_register());
1390 void FullCodeGenerator::ExitTryBlock(int handler_index) {
1391 HandlerTableEntry* entry = &handler_table_[handler_index];
1392 entry->range_end = masm()->pc_offset();
1394 // Drop context from operand stack.
1395 __ Drop(TryBlockConstant::kElementCount);
1399 void FullCodeGenerator::VisitSpread(Spread* expr) { UNREACHABLE(); }
1402 void FullCodeGenerator::VisitEmptyParentheses(EmptyParentheses* expr) {
1407 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
1408 int* stack_depth, int* context_length) {
1409 // The macros used here must preserve the result register.
1411 // Because the handler block contains the context of the finally
1412 // code, we can restore it directly from there for the finally code
1413 // rather than iteratively unwinding contexts via their previous
1415 if (*context_length > 0) {
1416 __ Drop(*stack_depth); // Down to the handler block.
1417 // Restore the context to its dedicated register and the stack.
1418 STATIC_ASSERT(TryFinally::kElementCount == 1);
1419 __ Pop(codegen_->context_register());
1420 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1421 codegen_->context_register());
1423 // Down to the handler block and also drop context.
1424 __ Drop(*stack_depth + kElementCount);
1426 __ Call(finally_entry_);
1429 *context_length = 0;
1434 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1435 Expression* sub_expr;
1436 Handle<String> check;
1437 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1438 EmitLiteralCompareTypeof(expr, sub_expr, check);
1442 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1443 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1447 if (expr->IsLiteralCompareNull(&sub_expr)) {
1448 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1456 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1457 DisallowHeapAllocation no_gc;
1458 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1460 // Increment loop nesting level by one and iterate over the back edge table
1461 // to find the matching loops to patch the interrupt
1462 // call to an unconditional call to the replacement code.
1463 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1464 if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1466 BackEdgeTable back_edges(unoptimized, &no_gc);
1467 for (uint32_t i = 0; i < back_edges.length(); i++) {
1468 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1469 DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1472 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1476 unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1477 DCHECK(Verify(isolate, unoptimized));
1481 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1482 DisallowHeapAllocation no_gc;
1483 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1485 // Iterate over the back edge table and revert the patched interrupt calls.
1486 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1488 BackEdgeTable back_edges(unoptimized, &no_gc);
1489 for (uint32_t i = 0; i < back_edges.length(); i++) {
1490 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1491 DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1494 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1498 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1499 // Assert that none of the back edges are patched anymore.
1500 DCHECK(Verify(isolate, unoptimized));
1504 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1505 DisallowHeapAllocation no_gc;
1506 Isolate* isolate = code->GetIsolate();
1507 Address pc = code->instruction_start() + pc_offset;
1508 Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1509 PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1513 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1514 DisallowHeapAllocation no_gc;
1515 Isolate* isolate = code->GetIsolate();
1516 Address pc = code->instruction_start() + pc_offset;
1518 if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1519 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1520 PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1526 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1527 DisallowHeapAllocation no_gc;
1528 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1529 BackEdgeTable back_edges(unoptimized, &no_gc);
1530 for (uint32_t i = 0; i < back_edges.length(); i++) {
1531 uint32_t loop_depth = back_edges.loop_depth(i);
1532 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1533 // Assert that all back edges for shallower loops (and only those)
1534 // have already been patched.
1535 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1536 GetBackEdgeState(isolate,
1538 back_edges.pc(i)) != INTERRUPT);
1545 FullCodeGenerator::EnterBlockScopeIfNeeded::EnterBlockScopeIfNeeded(
1546 FullCodeGenerator* codegen, Scope* scope, BailoutId entry_id,
1547 BailoutId declarations_id, BailoutId exit_id)
1548 : codegen_(codegen), exit_id_(exit_id) {
1549 saved_scope_ = codegen_->scope();
1551 if (scope == NULL) {
1552 codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1553 needs_block_context_ = false;
1555 needs_block_context_ = scope->NeedsContext();
1556 codegen_->scope_ = scope;
1558 if (needs_block_context_) {
1559 Comment cmnt(masm(), "[ Extend block context");
1560 __ Push(scope->GetScopeInfo(codegen->isolate()));
1561 codegen_->PushFunctionArgumentForContextAllocation();
1562 __ CallRuntime(Runtime::kPushBlockContext, 2);
1564 // Replace the context stored in the frame.
1565 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1566 codegen_->context_register());
1568 CHECK_EQ(0, scope->num_stack_slots());
1569 codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1572 Comment cmnt(masm(), "[ Declarations");
1573 codegen_->VisitDeclarations(scope->declarations());
1574 codegen_->PrepareForBailoutForId(declarations_id, NO_REGISTERS);
1580 FullCodeGenerator::EnterBlockScopeIfNeeded::~EnterBlockScopeIfNeeded() {
1581 if (needs_block_context_) {
1582 codegen_->LoadContextField(codegen_->context_register(),
1583 Context::PREVIOUS_INDEX);
1584 // Update local stack frame context field.
1585 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1586 codegen_->context_register());
1588 codegen_->PrepareForBailoutForId(exit_id_, NO_REGISTERS);
1589 codegen_->scope_ = saved_scope_;
1596 } // namespace internal