blob: af5dd41885c2f9a071cef82b9c447028f046eda5 [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/full-codegen/full-codegen.h"
6
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00007#include "src/ast/ast-numbering.h"
Ben Murdochda12d292016-06-02 14:46:10 +01008#include "src/ast/ast.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00009#include "src/ast/prettyprinter.h"
10#include "src/ast/scopeinfo.h"
11#include "src/ast/scopes.h"
12#include "src/code-factory.h"
13#include "src/codegen.h"
14#include "src/compiler.h"
15#include "src/debug/debug.h"
16#include "src/debug/liveedit.h"
Ben Murdochda12d292016-06-02 14:46:10 +010017#include "src/frames-inl.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000018#include "src/isolate-inl.h"
19#include "src/macro-assembler.h"
20#include "src/snapshot/snapshot.h"
Ben Murdoch097c5b22016-05-18 11:27:45 +010021#include "src/tracing/trace-event.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000022
23namespace v8 {
24namespace internal {
25
26#define __ ACCESS_MASM(masm())
27
28bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
29 Isolate* isolate = info->isolate();
30
31 TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
Ben Murdoch097c5b22016-05-18 11:27:45 +010032 TRACE_EVENT0("v8", "V8.CompileFullCode");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000033
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000034 Handle<Script> script = info->script();
35 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
36 int len = String::cast(script->source())->length();
37 isolate->counters()->total_full_codegen_source_size()->Increment(len);
38 }
39 CodeGenerator::MakeCodePrologue(info, "full");
40 const int kInitialBufferSize = 4 * KB;
41 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize,
42 CodeObjectRequired::kYes);
43 if (info->will_serialize()) masm.enable_serializer();
44
45 LOG_CODE_EVENT(isolate,
46 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
47
48 FullCodeGenerator cgen(&masm, info);
49 cgen.Generate();
50 if (cgen.HasStackOverflow()) {
51 DCHECK(!isolate->has_pending_exception());
52 return false;
53 }
54 unsigned table_offset = cgen.EmitBackEdgeTable();
55
56 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, info);
57 cgen.PopulateDeoptimizationData(code);
58 cgen.PopulateTypeFeedbackInfo(code);
59 cgen.PopulateHandlerTable(code);
60 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
61 code->set_has_reloc_info_for_serialization(info->will_serialize());
62 code->set_allow_osr_at_loop_nesting_level(0);
63 code->set_profiler_ticks(0);
64 code->set_back_edge_table_offset(table_offset);
65 CodeGenerator::PrintCode(code, info);
66 info->SetCode(code);
67 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
Ben Murdochda12d292016-06-02 14:46:10 +010068 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(
69 AbstractCode::cast(*code), line_info));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000070
71#ifdef DEBUG
72 // Check that no context-specific object has been embedded.
73 code->VerifyEmbeddedObjects(Code::kNoContextSpecificPointers);
74#endif // DEBUG
75 return true;
76}
77
78
79unsigned FullCodeGenerator::EmitBackEdgeTable() {
80 // The back edge table consists of a length (in number of entries)
81 // field, and then a sequence of entries. Each entry is a pair of AST id
82 // and code-relative pc offset.
83 masm()->Align(kPointerSize);
84 unsigned offset = masm()->pc_offset();
85 unsigned length = back_edges_.length();
86 __ dd(length);
87 for (unsigned i = 0; i < length; ++i) {
88 __ dd(back_edges_[i].id.ToInt());
89 __ dd(back_edges_[i].pc);
90 __ dd(back_edges_[i].loop_depth);
91 }
92 return offset;
93}
94
95
96void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
97 // Fill in the deoptimization information.
98 DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
99 if (!info_->HasDeoptimizationSupport()) return;
100 int length = bailout_entries_.length();
101 Handle<DeoptimizationOutputData> data =
102 DeoptimizationOutputData::New(isolate(), length, TENURED);
103 for (int i = 0; i < length; i++) {
104 data->SetAstId(i, bailout_entries_[i].id);
105 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
106 }
107 code->set_deoptimization_data(*data);
108}
109
110
111void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
112 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
113 info->set_ic_total_count(ic_total_count_);
114 DCHECK(!isolate()->heap()->InNewSpace(*info));
115 code->set_type_feedback_info(*info);
116}
117
118
119void FullCodeGenerator::PopulateHandlerTable(Handle<Code> code) {
120 int handler_table_size = static_cast<int>(handler_table_.size());
121 Handle<HandlerTable> table =
122 Handle<HandlerTable>::cast(isolate()->factory()->NewFixedArray(
123 HandlerTable::LengthForRange(handler_table_size), TENURED));
124 for (int i = 0; i < handler_table_size; ++i) {
125 HandlerTable::CatchPrediction prediction =
126 handler_table_[i].try_catch_depth > 0 ? HandlerTable::CAUGHT
127 : HandlerTable::UNCAUGHT;
128 table->SetRangeStart(i, handler_table_[i].range_start);
129 table->SetRangeEnd(i, handler_table_[i].range_end);
130 table->SetRangeHandler(i, handler_table_[i].handler_offset, prediction);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100131 table->SetRangeData(i, handler_table_[i].stack_depth);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000132 }
133 code->set_handler_table(*table);
134}
135
136
137int FullCodeGenerator::NewHandlerTableEntry() {
138 int index = static_cast<int>(handler_table_.size());
139 HandlerTableEntry entry = {0, 0, 0, 0, 0};
140 handler_table_.push_back(entry);
141 return index;
142}
143
144
145bool FullCodeGenerator::MustCreateObjectLiteralWithRuntime(
146 ObjectLiteral* expr) const {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000147 // FastCloneShallowObjectStub doesn't copy elements, and object literals don't
148 // support copy-on-write (COW) elements for now.
149 // TODO(mvstanton): make object literals support COW elements.
Ben Murdoch097c5b22016-05-18 11:27:45 +0100150 return masm()->serializer_enabled() || !expr->fast_elements() ||
151 !expr->has_shallow_properties() ||
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000152 expr->properties_count() >
153 FastCloneShallowObjectStub::kMaximumClonedProperties;
154}
155
156
157bool FullCodeGenerator::MustCreateArrayLiteralWithRuntime(
158 ArrayLiteral* expr) const {
Ben Murdochda12d292016-06-02 14:46:10 +0100159 return expr->depth() > 1 ||
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000160 expr->values()->length() > JSArray::kInitialMaxFastElementArray;
161}
162
163
164void FullCodeGenerator::Initialize() {
165 InitializeAstVisitor(info_->isolate());
Ben Murdoch097c5b22016-05-18 11:27:45 +0100166 masm_->set_emit_debug_code(FLAG_debug_code);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000167 masm_->set_predictable_code_size(true);
168}
169
170
171void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
172 PrepareForBailoutForId(node->id(), state);
173}
174
175
176void FullCodeGenerator::CallLoadIC(TypeofMode typeof_mode,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000177 TypeFeedbackId id) {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100178 Handle<Code> ic = CodeFactory::LoadIC(isolate(), typeof_mode).code();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000179 CallIC(ic, id);
180}
181
182
183void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
184 Handle<Code> ic = CodeFactory::StoreIC(isolate(), language_mode()).code();
185 CallIC(ic, id);
186}
187
188
189void FullCodeGenerator::RecordJSReturnSite(Call* call) {
190 // We record the offset of the function return so we can rebuild the frame
191 // if the function was inlined, i.e., this is the return address in the
192 // inlined function's frame.
193 //
194 // The state is ignored. We defensively set it to TOS_REG, which is the
195 // real state of the unoptimized code at the return site.
196 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
197#ifdef DEBUG
198 // In debug builds, mark the return so we can verify that this function
199 // was called.
200 DCHECK(!call->return_is_recorded_);
201 call->return_is_recorded_ = true;
202#endif
203}
204
205
206void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
207 // There's no need to prepare this code for bailouts from already optimized
208 // code or code that can't be optimized.
209 if (!info_->HasDeoptimizationSupport()) return;
210 unsigned pc_and_state =
211 StateField::encode(state) | PcField::encode(masm_->pc_offset());
212 DCHECK(Smi::IsValid(pc_and_state));
213#ifdef DEBUG
214 for (int i = 0; i < bailout_entries_.length(); ++i) {
215 DCHECK(bailout_entries_[i].id != id);
216 }
217#endif
218 BailoutEntry entry = { id, pc_and_state };
219 bailout_entries_.Add(entry, zone());
220}
221
222
223void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
224 // The pc offset does not need to be encoded and packed together with a state.
225 DCHECK(masm_->pc_offset() > 0);
226 DCHECK(loop_depth() > 0);
227 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
228 BackEdgeEntry entry =
229 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
230 back_edges_.Add(entry, zone());
231}
232
233
234bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
235 // Inline smi case inside loops, but not division and modulo which
236 // are too complicated and take up too much space.
237 if (op == Token::DIV ||op == Token::MOD) return false;
238 if (FLAG_always_inline_smi_code) return true;
239 return loop_depth_ > 0;
240}
241
242
243void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
244 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
245}
246
247
248void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
249 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
250 codegen()->GetVar(result_register(), var);
251}
252
253
254void FullCodeGenerator::TestContext::Plug(Variable* var) const {
255 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
256 // For simplicity we always test the accumulator register.
257 codegen()->GetVar(result_register(), var);
258 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
259 codegen()->DoTest(this);
260}
261
262
263void FullCodeGenerator::EffectContext::Plug(Register reg) const {
264}
265
266
267void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
268 __ Move(result_register(), reg);
269}
270
271
272void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100273 codegen()->PushOperand(reg);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000274}
275
276
277void FullCodeGenerator::TestContext::Plug(Register reg) const {
278 // For simplicity we always test the accumulator register.
279 __ Move(result_register(), reg);
280 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
281 codegen()->DoTest(this);
282}
283
284
285void FullCodeGenerator::EffectContext::Plug(bool flag) const {}
286
Ben Murdoch097c5b22016-05-18 11:27:45 +0100287void FullCodeGenerator::EffectContext::DropAndPlug(int count,
288 Register reg) const {
289 DCHECK(count > 0);
290 codegen()->DropOperands(count);
291}
292
293void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
294 int count, Register reg) const {
295 DCHECK(count > 0);
296 codegen()->DropOperands(count);
297 __ Move(result_register(), reg);
298}
299
300void FullCodeGenerator::TestContext::DropAndPlug(int count,
301 Register reg) const {
302 DCHECK(count > 0);
303 // For simplicity we always test the accumulator register.
304 codegen()->DropOperands(count);
305 __ Move(result_register(), reg);
306 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
307 codegen()->DoTest(this);
308}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000309
310void FullCodeGenerator::EffectContext::PlugTOS() const {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100311 codegen()->DropOperands(1);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000312}
313
314
315void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100316 codegen()->PopOperand(result_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000317}
318
319
320void FullCodeGenerator::StackValueContext::PlugTOS() const {
321}
322
323
324void FullCodeGenerator::TestContext::PlugTOS() const {
325 // For simplicity we always test the accumulator register.
Ben Murdoch097c5b22016-05-18 11:27:45 +0100326 codegen()->PopOperand(result_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000327 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
328 codegen()->DoTest(this);
329}
330
331
332void FullCodeGenerator::EffectContext::PrepareTest(
333 Label* materialize_true,
334 Label* materialize_false,
335 Label** if_true,
336 Label** if_false,
337 Label** fall_through) const {
338 // In an effect context, the true and the false case branch to the
339 // same label.
340 *if_true = *if_false = *fall_through = materialize_true;
341}
342
343
344void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
345 Label* materialize_true,
346 Label* materialize_false,
347 Label** if_true,
348 Label** if_false,
349 Label** fall_through) const {
350 *if_true = *fall_through = materialize_true;
351 *if_false = materialize_false;
352}
353
354
355void FullCodeGenerator::StackValueContext::PrepareTest(
356 Label* materialize_true,
357 Label* materialize_false,
358 Label** if_true,
359 Label** if_false,
360 Label** fall_through) const {
361 *if_true = *fall_through = materialize_true;
362 *if_false = materialize_false;
363}
364
365
366void FullCodeGenerator::TestContext::PrepareTest(
367 Label* materialize_true,
368 Label* materialize_false,
369 Label** if_true,
370 Label** if_false,
371 Label** fall_through) const {
372 *if_true = true_label_;
373 *if_false = false_label_;
374 *fall_through = fall_through_;
375}
376
377
378void FullCodeGenerator::DoTest(const TestContext* context) {
379 DoTest(context->condition(),
380 context->true_label(),
381 context->false_label(),
382 context->fall_through());
383}
384
385
386void FullCodeGenerator::VisitDeclarations(
387 ZoneList<Declaration*>* declarations) {
388 ZoneList<Handle<Object> >* saved_globals = globals_;
389 ZoneList<Handle<Object> > inner_globals(10, zone());
390 globals_ = &inner_globals;
391
392 AstVisitor::VisitDeclarations(declarations);
393
394 if (!globals_->is_empty()) {
395 // Invoke the platform-dependent code generator to do the actual
396 // declaration of the global functions and variables.
397 Handle<FixedArray> array =
398 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
399 for (int i = 0; i < globals_->length(); ++i)
400 array->set(i, *globals_->at(i));
401 DeclareGlobals(array);
402 }
403
404 globals_ = saved_globals;
405}
406
407
408void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
409 VariableProxy* proxy = declaration->proxy();
410 Variable* variable = proxy->var();
411 switch (variable->location()) {
412 case VariableLocation::GLOBAL:
413 case VariableLocation::UNALLOCATED:
414 // TODO(rossberg)
415 break;
416
417 case VariableLocation::CONTEXT: {
418 Comment cmnt(masm_, "[ ImportDeclaration");
419 EmitDebugCheckDeclarationContext(variable);
420 // TODO(rossberg)
421 break;
422 }
423
424 case VariableLocation::PARAMETER:
425 case VariableLocation::LOCAL:
426 case VariableLocation::LOOKUP:
427 UNREACHABLE();
428 }
429}
430
431
432void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
433 // TODO(rossberg)
434}
435
436
437void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
438 Comment cmnt(masm_, "[ VariableProxy");
439 EmitVariableLoad(expr);
440}
441
442
443void FullCodeGenerator::VisitSloppyBlockFunctionStatement(
444 SloppyBlockFunctionStatement* declaration) {
445 Visit(declaration->statement());
446}
447
448
449int FullCodeGenerator::DeclareGlobalsFlags() {
450 DCHECK(DeclareGlobalsLanguageMode::is_valid(language_mode()));
451 return DeclareGlobalsEvalFlag::encode(is_eval()) |
452 DeclareGlobalsNativeFlag::encode(is_native()) |
453 DeclareGlobalsLanguageMode::encode(language_mode());
454}
455
Ben Murdoch097c5b22016-05-18 11:27:45 +0100456void FullCodeGenerator::PushOperand(Handle<Object> handle) {
457 OperandStackDepthIncrement(1);
458 __ Push(handle);
459}
460
461void FullCodeGenerator::PushOperand(Smi* smi) {
462 OperandStackDepthIncrement(1);
463 __ Push(smi);
464}
465
466void FullCodeGenerator::PushOperand(Register reg) {
467 OperandStackDepthIncrement(1);
468 __ Push(reg);
469}
470
471void FullCodeGenerator::PopOperand(Register reg) {
472 OperandStackDepthDecrement(1);
473 __ Pop(reg);
474}
475
476void FullCodeGenerator::DropOperands(int count) {
477 OperandStackDepthDecrement(count);
478 __ Drop(count);
479}
480
481void FullCodeGenerator::CallRuntimeWithOperands(Runtime::FunctionId id) {
482 OperandStackDepthDecrement(Runtime::FunctionForId(id)->nargs);
483 __ CallRuntime(id);
484}
485
486void FullCodeGenerator::OperandStackDepthIncrement(int count) {
Ben Murdochda12d292016-06-02 14:46:10 +0100487 DCHECK_IMPLIES(!HasStackOverflow(), operand_stack_depth_ >= 0);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100488 DCHECK_GE(count, 0);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100489 operand_stack_depth_ += count;
490}
491
492void FullCodeGenerator::OperandStackDepthDecrement(int count) {
Ben Murdochda12d292016-06-02 14:46:10 +0100493 DCHECK_IMPLIES(!HasStackOverflow(), operand_stack_depth_ >= count);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100494 DCHECK_GE(count, 0);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100495 operand_stack_depth_ -= count;
496}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000497
498void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
499 // Load the arguments on the stack and call the stub.
500 SubStringStub stub(isolate());
501 ZoneList<Expression*>* args = expr->arguments();
502 DCHECK(args->length() == 3);
503 VisitForStackValue(args->at(0));
504 VisitForStackValue(args->at(1));
505 VisitForStackValue(args->at(2));
506 __ CallStub(&stub);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100507 OperandStackDepthDecrement(3);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000508 context()->Plug(result_register());
509}
510
511
512void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
513 // Load the arguments on the stack and call the stub.
514 RegExpExecStub stub(isolate());
515 ZoneList<Expression*>* args = expr->arguments();
516 DCHECK(args->length() == 4);
517 VisitForStackValue(args->at(0));
518 VisitForStackValue(args->at(1));
519 VisitForStackValue(args->at(2));
520 VisitForStackValue(args->at(3));
521 __ CallStub(&stub);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100522 OperandStackDepthDecrement(4);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000523 context()->Plug(result_register());
524}
525
526
527void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
528 // Load the arguments on the stack and call the runtime function.
Ben Murdoch097c5b22016-05-18 11:27:45 +0100529 MathPowStub stub(isolate(), MathPowStub::ON_STACK);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000530 ZoneList<Expression*>* args = expr->arguments();
531 DCHECK(args->length() == 2);
532 VisitForStackValue(args->at(0));
533 VisitForStackValue(args->at(1));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000534 __ CallStub(&stub);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100535 OperandStackDepthDecrement(2);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000536 context()->Plug(result_register());
537}
538
539
540void FullCodeGenerator::EmitIntrinsicAsStubCall(CallRuntime* expr,
541 const Callable& callable) {
542 ZoneList<Expression*>* args = expr->arguments();
543 int param_count = callable.descriptor().GetRegisterParameterCount();
544 DCHECK_EQ(args->length(), param_count);
545
546 if (param_count > 0) {
547 int last = param_count - 1;
548 // Put all but last arguments on stack.
549 for (int i = 0; i < last; i++) {
550 VisitForStackValue(args->at(i));
551 }
552 // The last argument goes to the accumulator.
553 VisitForAccumulatorValue(args->at(last));
554
555 // Move the arguments to the registers, as required by the stub.
556 __ Move(callable.descriptor().GetRegisterParameter(last),
557 result_register());
558 for (int i = last; i-- > 0;) {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100559 PopOperand(callable.descriptor().GetRegisterParameter(i));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000560 }
561 }
562 __ Call(callable.code(), RelocInfo::CODE_TARGET);
Ben Murdochda12d292016-06-02 14:46:10 +0100563
564 // Reload the context register after the call as i.e. TurboFan code stubs
565 // won't preserve the context register.
566 LoadFromFrameField(StandardFrameConstants::kContextOffset,
567 context_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000568 context()->Plug(result_register());
569}
570
Ben Murdochda12d292016-06-02 14:46:10 +0100571void FullCodeGenerator::EmitNewObject(CallRuntime* expr) {
572 EmitIntrinsicAsStubCall(expr, CodeFactory::FastNewObject(isolate()));
573}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000574
575void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
576 EmitIntrinsicAsStubCall(expr, CodeFactory::NumberToString(isolate()));
577}
578
579
580void FullCodeGenerator::EmitToString(CallRuntime* expr) {
581 EmitIntrinsicAsStubCall(expr, CodeFactory::ToString(isolate()));
582}
583
584
Ben Murdoch097c5b22016-05-18 11:27:45 +0100585void FullCodeGenerator::EmitToName(CallRuntime* expr) {
586 EmitIntrinsicAsStubCall(expr, CodeFactory::ToName(isolate()));
587}
588
589
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000590void FullCodeGenerator::EmitToLength(CallRuntime* expr) {
591 EmitIntrinsicAsStubCall(expr, CodeFactory::ToLength(isolate()));
592}
593
Ben Murdochda12d292016-06-02 14:46:10 +0100594void FullCodeGenerator::EmitToInteger(CallRuntime* expr) {
595 EmitIntrinsicAsStubCall(expr, CodeFactory::ToInteger(isolate()));
596}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000597
598void FullCodeGenerator::EmitToNumber(CallRuntime* expr) {
599 EmitIntrinsicAsStubCall(expr, CodeFactory::ToNumber(isolate()));
600}
601
602
603void FullCodeGenerator::EmitToObject(CallRuntime* expr) {
604 EmitIntrinsicAsStubCall(expr, CodeFactory::ToObject(isolate()));
605}
606
607
608void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
609 EmitIntrinsicAsStubCall(expr, CodeFactory::RegExpConstructResult(isolate()));
610}
611
612
613bool RecordStatementPosition(MacroAssembler* masm, int pos) {
614 if (pos == RelocInfo::kNoPosition) return false;
615 masm->positions_recorder()->RecordStatementPosition(pos);
616 masm->positions_recorder()->RecordPosition(pos);
617 return masm->positions_recorder()->WriteRecordedPositions();
618}
619
620
621bool RecordPosition(MacroAssembler* masm, int pos) {
622 if (pos == RelocInfo::kNoPosition) return false;
623 masm->positions_recorder()->RecordPosition(pos);
624 return masm->positions_recorder()->WriteRecordedPositions();
625}
626
627
628void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
629 RecordPosition(masm_, fun->start_position());
630}
631
632
633void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
634 // For default constructors, start position equals end position, and there
635 // is no source code besides the class literal.
636 int pos = std::max(fun->start_position(), fun->end_position() - 1);
637 RecordStatementPosition(masm_, pos);
638 if (info_->is_debug()) {
639 // Always emit a debug break slot before a return.
640 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_RETURN);
641 }
642}
643
644
645void FullCodeGenerator::SetStatementPosition(
646 Statement* stmt, FullCodeGenerator::InsertBreak insert_break) {
647 if (stmt->position() == RelocInfo::kNoPosition) return;
648 bool recorded = RecordStatementPosition(masm_, stmt->position());
649 if (recorded && insert_break == INSERT_BREAK && info_->is_debug() &&
650 !stmt->IsDebuggerStatement()) {
651 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
652 }
653}
654
655
656void FullCodeGenerator::SetExpressionPosition(
657 Expression* expr, FullCodeGenerator::InsertBreak insert_break) {
658 if (expr->position() == RelocInfo::kNoPosition) return;
659 bool recorded = RecordPosition(masm_, expr->position());
660 if (recorded && insert_break == INSERT_BREAK && info_->is_debug()) {
661 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
662 }
663}
664
665
666void FullCodeGenerator::SetExpressionAsStatementPosition(Expression* expr) {
667 if (expr->position() == RelocInfo::kNoPosition) return;
668 bool recorded = RecordStatementPosition(masm_, expr->position());
669 if (recorded && info_->is_debug()) {
670 DebugCodegen::GenerateSlot(masm_, RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
671 }
672}
673
Ben Murdochda12d292016-06-02 14:46:10 +0100674void FullCodeGenerator::SetCallPosition(Expression* expr,
675 TailCallMode tail_call_mode) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000676 if (expr->position() == RelocInfo::kNoPosition) return;
677 RecordPosition(masm_, expr->position());
678 if (info_->is_debug()) {
Ben Murdochda12d292016-06-02 14:46:10 +0100679 RelocInfo::Mode mode = (tail_call_mode == TailCallMode::kAllow)
680 ? RelocInfo::DEBUG_BREAK_SLOT_AT_TAIL_CALL
681 : RelocInfo::DEBUG_BREAK_SLOT_AT_CALL;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000682 // Always emit a debug break slot before a call.
Ben Murdochda12d292016-06-02 14:46:10 +0100683 DebugCodegen::GenerateSlot(masm_, mode);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000684 }
685}
686
687
688void FullCodeGenerator::VisitSuperPropertyReference(
689 SuperPropertyReference* super) {
690 __ CallRuntime(Runtime::kThrowUnsupportedSuperError);
691}
692
693
694void FullCodeGenerator::VisitSuperCallReference(SuperCallReference* super) {
695 __ CallRuntime(Runtime::kThrowUnsupportedSuperError);
696}
697
698
699void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
700 ZoneList<Expression*>* args = expr->arguments();
701 DCHECK(args->length() == 2);
702 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
703}
704
705
Ben Murdoch097c5b22016-05-18 11:27:45 +0100706void FullCodeGenerator::EmitGeneratorReturn(CallRuntime* expr) {
707 ZoneList<Expression*>* args = expr->arguments();
708 DCHECK(args->length() == 2);
709 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::RETURN);
710}
711
712
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000713void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
714 ZoneList<Expression*>* args = expr->arguments();
715 DCHECK(args->length() == 2);
716 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
717}
718
719
720void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
721 context()->Plug(handle(Smi::FromInt(0), isolate()));
722}
723
724
725void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
726 switch (expr->op()) {
727 case Token::COMMA:
728 return VisitComma(expr);
729 case Token::OR:
730 case Token::AND:
731 return VisitLogicalExpression(expr);
732 default:
733 return VisitArithmeticExpression(expr);
734 }
735}
736
737
738void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
739 if (context()->IsEffect()) {
740 VisitForEffect(expr);
741 } else if (context()->IsAccumulatorValue()) {
742 VisitForAccumulatorValue(expr);
743 } else if (context()->IsStackValue()) {
744 VisitForStackValue(expr);
745 } else if (context()->IsTest()) {
746 const TestContext* test = TestContext::cast(context());
747 VisitForControl(expr, test->true_label(), test->false_label(),
748 test->fall_through());
749 }
750}
751
752
753void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
754 Comment cmnt(masm_, "[ Comma");
755 VisitForEffect(expr->left());
756 VisitInDuplicateContext(expr->right());
757}
758
759
760void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
761 bool is_logical_and = expr->op() == Token::AND;
762 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
763 Expression* left = expr->left();
764 Expression* right = expr->right();
765 BailoutId right_id = expr->RightId();
766 Label done;
767
768 if (context()->IsTest()) {
769 Label eval_right;
770 const TestContext* test = TestContext::cast(context());
771 if (is_logical_and) {
772 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
773 } else {
774 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
775 }
776 PrepareForBailoutForId(right_id, NO_REGISTERS);
777 __ bind(&eval_right);
778
779 } else if (context()->IsAccumulatorValue()) {
780 VisitForAccumulatorValue(left);
781 // We want the value in the accumulator for the test, and on the stack in
782 // case we need it.
783 __ Push(result_register());
784 Label discard, restore;
785 if (is_logical_and) {
786 DoTest(left, &discard, &restore, &restore);
787 } else {
788 DoTest(left, &restore, &discard, &restore);
789 }
790 __ bind(&restore);
791 __ Pop(result_register());
792 __ jmp(&done);
793 __ bind(&discard);
794 __ Drop(1);
795 PrepareForBailoutForId(right_id, NO_REGISTERS);
796
797 } else if (context()->IsStackValue()) {
798 VisitForAccumulatorValue(left);
799 // We want the value in the accumulator for the test, and on the stack in
800 // case we need it.
801 __ Push(result_register());
802 Label discard;
803 if (is_logical_and) {
804 DoTest(left, &discard, &done, &discard);
805 } else {
806 DoTest(left, &done, &discard, &discard);
807 }
808 __ bind(&discard);
809 __ Drop(1);
810 PrepareForBailoutForId(right_id, NO_REGISTERS);
811
812 } else {
813 DCHECK(context()->IsEffect());
814 Label eval_right;
815 if (is_logical_and) {
816 VisitForControl(left, &eval_right, &done, &eval_right);
817 } else {
818 VisitForControl(left, &done, &eval_right, &eval_right);
819 }
820 PrepareForBailoutForId(right_id, NO_REGISTERS);
821 __ bind(&eval_right);
822 }
823
824 VisitInDuplicateContext(right);
825 __ bind(&done);
826}
827
828
829void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
830 Token::Value op = expr->op();
831 Comment cmnt(masm_, "[ ArithmeticExpression");
832 Expression* left = expr->left();
833 Expression* right = expr->right();
834
835 VisitForStackValue(left);
836 VisitForAccumulatorValue(right);
837
838 SetExpressionPosition(expr);
839 if (ShouldInlineSmiCase(op)) {
840 EmitInlineSmiBinaryOp(expr, op, left, right);
841 } else {
842 EmitBinaryOp(expr, op);
843 }
844}
845
846
847void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
848 VariableProxy* proxy = expr->AsVariableProxy();
849 DCHECK(!context()->IsEffect());
850 DCHECK(!context()->IsTest());
851
852 if (proxy != NULL && (proxy->var()->IsUnallocatedOrGlobalSlot() ||
853 proxy->var()->IsLookupSlot())) {
854 EmitVariableLoad(proxy, INSIDE_TYPEOF);
855 PrepareForBailout(proxy, TOS_REG);
856 } else {
857 // This expression cannot throw a reference error at the top level.
858 VisitInDuplicateContext(expr);
859 }
860}
861
862
863void FullCodeGenerator::VisitBlock(Block* stmt) {
864 Comment cmnt(masm_, "[ Block");
865 NestedBlock nested_block(this, stmt);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000866
867 {
868 EnterBlockScopeIfNeeded block_scope_state(
869 this, stmt->scope(), stmt->EntryId(), stmt->DeclsId(), stmt->ExitId());
870 VisitStatements(stmt->statements());
871 __ bind(nested_block.break_label());
872 }
873}
874
875
876void FullCodeGenerator::VisitDoExpression(DoExpression* expr) {
877 Comment cmnt(masm_, "[ Do Expression");
878 NestedStatement nested_block(this);
879 SetExpressionPosition(expr);
880 VisitBlock(expr->block());
881 EmitVariableLoad(expr->result());
882}
883
884
885void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
886 Comment cmnt(masm_, "[ ExpressionStatement");
887 SetStatementPosition(stmt);
888 VisitForEffect(stmt->expression());
889}
890
891
892void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
893 Comment cmnt(masm_, "[ EmptyStatement");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000894}
895
896
897void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
898 Comment cmnt(masm_, "[ IfStatement");
899 SetStatementPosition(stmt);
900 Label then_part, else_part, done;
901
902 if (stmt->HasElseStatement()) {
903 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
904 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
905 __ bind(&then_part);
906 Visit(stmt->then_statement());
907 __ jmp(&done);
908
909 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
910 __ bind(&else_part);
911 Visit(stmt->else_statement());
912 } else {
913 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
914 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
915 __ bind(&then_part);
916 Visit(stmt->then_statement());
917
918 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
919 }
920 __ bind(&done);
921 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
922}
923
Ben Murdoch097c5b22016-05-18 11:27:45 +0100924void FullCodeGenerator::EmitContinue(Statement* target) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000925 NestedStatement* current = nesting_stack_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000926 int context_length = 0;
927 // When continuing, we clobber the unpredictable value in the accumulator
928 // with one that's safe for GC. If we hit an exit from the try block of
929 // try...finally on our way out, we will unconditionally preserve the
930 // accumulator on the stack.
931 ClearAccumulator();
Ben Murdoch097c5b22016-05-18 11:27:45 +0100932 while (!current->IsContinueTarget(target)) {
933 if (current->IsTryFinally()) {
934 Comment cmnt(masm(), "[ Deferred continue through finally");
Ben Murdochda12d292016-06-02 14:46:10 +0100935 current->Exit(&context_length);
936 DCHECK_EQ(-1, context_length);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100937 current->AsTryFinally()->deferred_commands()->RecordContinue(target);
938 return;
939 }
Ben Murdochda12d292016-06-02 14:46:10 +0100940 current = current->Exit(&context_length);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000941 }
Ben Murdochda12d292016-06-02 14:46:10 +0100942 int stack_depth = current->GetStackDepthAtTarget();
943 int stack_drop = operand_stack_depth_ - stack_depth;
944 DCHECK_GE(stack_drop, 0);
945 __ Drop(stack_drop);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000946 if (context_length > 0) {
947 while (context_length > 0) {
948 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
949 --context_length;
950 }
951 StoreToFrameField(StandardFrameConstants::kContextOffset,
952 context_register());
953 }
954
955 __ jmp(current->AsIteration()->continue_label());
956}
957
Ben Murdoch097c5b22016-05-18 11:27:45 +0100958void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
959 Comment cmnt(masm_, "[ ContinueStatement");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000960 SetStatementPosition(stmt);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100961 EmitContinue(stmt->target());
962}
963
964void FullCodeGenerator::EmitBreak(Statement* target) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000965 NestedStatement* current = nesting_stack_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000966 int context_length = 0;
967 // When breaking, we clobber the unpredictable value in the accumulator
968 // with one that's safe for GC. If we hit an exit from the try block of
969 // try...finally on our way out, we will unconditionally preserve the
970 // accumulator on the stack.
971 ClearAccumulator();
Ben Murdoch097c5b22016-05-18 11:27:45 +0100972 while (!current->IsBreakTarget(target)) {
973 if (current->IsTryFinally()) {
974 Comment cmnt(masm(), "[ Deferred break through finally");
Ben Murdochda12d292016-06-02 14:46:10 +0100975 current->Exit(&context_length);
976 DCHECK_EQ(-1, context_length);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100977 current->AsTryFinally()->deferred_commands()->RecordBreak(target);
978 return;
979 }
Ben Murdochda12d292016-06-02 14:46:10 +0100980 current = current->Exit(&context_length);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000981 }
Ben Murdochda12d292016-06-02 14:46:10 +0100982 int stack_depth = current->GetStackDepthAtTarget();
983 int stack_drop = operand_stack_depth_ - stack_depth;
984 DCHECK_GE(stack_drop, 0);
985 __ Drop(stack_drop);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000986 if (context_length > 0) {
987 while (context_length > 0) {
988 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
989 --context_length;
990 }
991 StoreToFrameField(StandardFrameConstants::kContextOffset,
992 context_register());
993 }
994
995 __ jmp(current->AsBreakable()->break_label());
996}
997
Ben Murdoch097c5b22016-05-18 11:27:45 +0100998void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
999 Comment cmnt(masm_, "[ BreakStatement");
1000 SetStatementPosition(stmt);
1001 EmitBreak(stmt->target());
1002}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001003
Ben Murdoch097c5b22016-05-18 11:27:45 +01001004void FullCodeGenerator::EmitUnwindAndReturn() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001005 NestedStatement* current = nesting_stack_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001006 int context_length = 0;
1007 while (current != NULL) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01001008 if (current->IsTryFinally()) {
1009 Comment cmnt(masm(), "[ Deferred return through finally");
Ben Murdochda12d292016-06-02 14:46:10 +01001010 current->Exit(&context_length);
1011 DCHECK_EQ(-1, context_length);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001012 current->AsTryFinally()->deferred_commands()->RecordReturn();
1013 return;
1014 }
Ben Murdochda12d292016-06-02 14:46:10 +01001015 current = current->Exit(&context_length);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001016 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01001017 EmitReturnSequence();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001018}
1019
Ben Murdochda12d292016-06-02 14:46:10 +01001020void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1021 bool pretenure) {
1022 // Use the fast case closure allocation code that allocates in new
1023 // space for nested functions that don't need literals cloning. If
1024 // we're running with the --always-opt or the --prepare-always-opt
1025 // flag, we need to use the runtime function so that the new function
1026 // we are creating here gets a chance to have its code optimized and
1027 // doesn't just get a copy of the existing unoptimized code.
1028 if (!FLAG_always_opt &&
1029 !FLAG_prepare_always_opt &&
1030 !pretenure &&
1031 scope()->is_function_scope() &&
1032 info->num_literals() == 0) {
1033 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1034 __ Move(stub.GetCallInterfaceDescriptor().GetRegisterParameter(0), info);
1035 __ CallStub(&stub);
1036 } else {
1037 __ Push(info);
1038 __ CallRuntime(pretenure ? Runtime::kNewClosure_Tenured
1039 : Runtime::kNewClosure);
1040 }
1041 context()->Plug(result_register());
1042}
1043
1044void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
1045 SetExpressionPosition(prop);
1046 Literal* key = prop->key()->AsLiteral();
1047 DCHECK(!key->value()->IsSmi());
1048 DCHECK(!prop->IsSuperAccess());
1049
1050 __ Move(LoadDescriptor::NameRegister(), key->value());
1051 __ Move(LoadDescriptor::SlotRegister(),
1052 SmiFromSlot(prop->PropertyFeedbackSlot()));
1053 CallLoadIC(NOT_INSIDE_TYPEOF);
1054}
1055
Ben Murdoch097c5b22016-05-18 11:27:45 +01001056void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
1057 // Stack: receiver, home_object
1058 SetExpressionPosition(prop);
1059 Literal* key = prop->key()->AsLiteral();
1060 DCHECK(!key->value()->IsSmi());
1061 DCHECK(prop->IsSuperAccess());
1062
1063 PushOperand(key->value());
1064 CallRuntimeWithOperands(Runtime::kLoadFromSuper);
1065}
1066
1067void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
1068 SetExpressionPosition(prop);
1069 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
1070 __ Move(LoadDescriptor::SlotRegister(),
1071 SmiFromSlot(prop->PropertyFeedbackSlot()));
1072 CallIC(ic);
1073}
1074
1075void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
1076 // Stack: receiver, home_object, key.
1077 SetExpressionPosition(prop);
1078 CallRuntimeWithOperands(Runtime::kLoadKeyedFromSuper);
1079}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001080
1081void FullCodeGenerator::EmitPropertyKey(ObjectLiteralProperty* property,
1082 BailoutId bailout_id) {
1083 VisitForStackValue(property->key());
Ben Murdoch097c5b22016-05-18 11:27:45 +01001084 CallRuntimeWithOperands(Runtime::kToName);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001085 PrepareForBailoutForId(bailout_id, NO_REGISTERS);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001086 PushOperand(result_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001087}
1088
Ben Murdochda12d292016-06-02 14:46:10 +01001089void FullCodeGenerator::EmitLoadStoreICSlot(FeedbackVectorSlot slot) {
1090 DCHECK(!slot.IsInvalid());
1091 __ Move(VectorStoreICTrampolineDescriptor::SlotRegister(), SmiFromSlot(slot));
1092}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001093
1094void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1095 Comment cmnt(masm_, "[ ReturnStatement");
1096 SetStatementPosition(stmt);
1097 Expression* expr = stmt->expression();
1098 VisitForAccumulatorValue(expr);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001099 EmitUnwindAndReturn();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001100}
1101
1102
1103void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1104 Comment cmnt(masm_, "[ WithStatement");
1105 SetStatementPosition(stmt);
1106
1107 VisitForAccumulatorValue(stmt->expression());
1108 Callable callable = CodeFactory::ToObject(isolate());
1109 __ Move(callable.descriptor().GetRegisterParameter(0), result_register());
1110 __ Call(callable.code(), RelocInfo::CODE_TARGET);
1111 PrepareForBailoutForId(stmt->ToObjectId(), NO_REGISTERS);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001112 PushOperand(result_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001113 PushFunctionArgumentForContextAllocation();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001114 CallRuntimeWithOperands(Runtime::kPushWithContext);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001115 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1116 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1117
1118 Scope* saved_scope = scope();
1119 scope_ = stmt->scope();
1120 { WithOrCatch body(this);
1121 Visit(stmt->statement());
1122 }
1123 scope_ = saved_scope;
1124
1125 // Pop context.
1126 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1127 // Update local stack frame context field.
1128 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1129}
1130
1131
1132void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1133 Comment cmnt(masm_, "[ DoWhileStatement");
1134 // Do not insert break location as we do that below.
1135 SetStatementPosition(stmt, SKIP_BREAK);
1136
1137 Label body, book_keeping;
1138
1139 Iteration loop_statement(this, stmt);
1140 increment_loop_depth();
1141
1142 __ bind(&body);
1143 Visit(stmt->body());
1144
1145 // Record the position of the do while condition and make sure it is
1146 // possible to break on the condition.
1147 __ bind(loop_statement.continue_label());
1148 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1149
1150 // Here is the actual 'while' keyword.
1151 SetExpressionAsStatementPosition(stmt->cond());
1152 VisitForControl(stmt->cond(),
1153 &book_keeping,
1154 loop_statement.break_label(),
1155 &book_keeping);
1156
1157 // Check stack before looping.
1158 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1159 __ bind(&book_keeping);
1160 EmitBackEdgeBookkeeping(stmt, &body);
1161 __ jmp(&body);
1162
1163 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1164 __ bind(loop_statement.break_label());
1165 decrement_loop_depth();
1166}
1167
1168
1169void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1170 Comment cmnt(masm_, "[ WhileStatement");
1171 Label loop, body;
1172
1173 Iteration loop_statement(this, stmt);
1174 increment_loop_depth();
1175
1176 __ bind(&loop);
1177
1178 SetExpressionAsStatementPosition(stmt->cond());
1179 VisitForControl(stmt->cond(),
1180 &body,
1181 loop_statement.break_label(),
1182 &body);
1183
1184 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1185 __ bind(&body);
1186 Visit(stmt->body());
1187
1188 __ bind(loop_statement.continue_label());
1189
1190 // Check stack before looping.
1191 EmitBackEdgeBookkeeping(stmt, &loop);
1192 __ jmp(&loop);
1193
1194 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1195 __ bind(loop_statement.break_label());
1196 decrement_loop_depth();
1197}
1198
1199
1200void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1201 Comment cmnt(masm_, "[ ForStatement");
1202 // Do not insert break location as we do it below.
1203 SetStatementPosition(stmt, SKIP_BREAK);
1204
1205 Label test, body;
1206
1207 Iteration loop_statement(this, stmt);
1208
1209 if (stmt->init() != NULL) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001210 Visit(stmt->init());
1211 }
1212
1213 increment_loop_depth();
1214 // Emit the test at the bottom of the loop (even if empty).
1215 __ jmp(&test);
1216
1217 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1218 __ bind(&body);
1219 Visit(stmt->body());
1220
1221 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1222 __ bind(loop_statement.continue_label());
1223 if (stmt->next() != NULL) {
1224 SetStatementPosition(stmt->next());
1225 Visit(stmt->next());
1226 }
1227
1228 // Check stack before looping.
1229 EmitBackEdgeBookkeeping(stmt, &body);
1230
1231 __ bind(&test);
1232 if (stmt->cond() != NULL) {
1233 SetExpressionAsStatementPosition(stmt->cond());
1234 VisitForControl(stmt->cond(),
1235 &body,
1236 loop_statement.break_label(),
1237 loop_statement.break_label());
1238 } else {
1239 __ jmp(&body);
1240 }
1241
1242 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1243 __ bind(loop_statement.break_label());
1244 decrement_loop_depth();
1245}
1246
1247
1248void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1249 Comment cmnt(masm_, "[ ForOfStatement");
1250
1251 Iteration loop_statement(this, stmt);
1252 increment_loop_depth();
1253
1254 // var iterator = iterable[Symbol.iterator]();
1255 VisitForEffect(stmt->assign_iterator());
1256
1257 // Loop entry.
1258 __ bind(loop_statement.continue_label());
1259
1260 // result = iterator.next()
1261 SetExpressionAsStatementPosition(stmt->next_result());
1262 VisitForEffect(stmt->next_result());
1263
1264 // if (result.done) break;
1265 Label result_not_done;
1266 VisitForControl(stmt->result_done(), loop_statement.break_label(),
1267 &result_not_done, &result_not_done);
1268 __ bind(&result_not_done);
1269
1270 // each = result.value
1271 VisitForEffect(stmt->assign_each());
1272
1273 // Generate code for the body of the loop.
1274 Visit(stmt->body());
1275
1276 // Check stack before looping.
1277 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1278 EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1279 __ jmp(loop_statement.continue_label());
1280
1281 // Exit and decrement the loop depth.
1282 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1283 __ bind(loop_statement.break_label());
1284 decrement_loop_depth();
1285}
1286
Ben Murdochda12d292016-06-02 14:46:10 +01001287void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
1288 LoadFromFrameField(JavaScriptFrameConstants::kFunctionOffset,
1289 result_register());
1290 context()->Plug(result_register());
1291}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001292
1293void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1294 Comment cmnt(masm_, "[ TryCatchStatement");
1295 SetStatementPosition(stmt, SKIP_BREAK);
1296
1297 // The try block adds a handler to the exception handler chain before
1298 // entering, and removes it again when exiting normally. If an exception
1299 // is thrown during execution of the try block, the handler is consumed
1300 // and control is passed to the catch block with the exception in the
1301 // result register.
1302
1303 Label try_entry, handler_entry, exit;
1304 __ jmp(&try_entry);
1305 __ bind(&handler_entry);
Ben Murdochda12d292016-06-02 14:46:10 +01001306 if (stmt->clear_pending_message()) ClearPendingMessage();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001307
1308 // Exception handler code, the exception is in the result register.
1309 // Extend the context before executing the catch block.
1310 { Comment cmnt(masm_, "[ Extend catch context");
Ben Murdoch097c5b22016-05-18 11:27:45 +01001311 PushOperand(stmt->variable()->name());
1312 PushOperand(result_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001313 PushFunctionArgumentForContextAllocation();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001314 CallRuntimeWithOperands(Runtime::kPushCatchContext);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001315 StoreToFrameField(StandardFrameConstants::kContextOffset,
1316 context_register());
1317 }
1318
1319 Scope* saved_scope = scope();
1320 scope_ = stmt->scope();
1321 DCHECK(scope_->declarations()->is_empty());
1322 { WithOrCatch catch_body(this);
1323 Visit(stmt->catch_block());
1324 }
1325 // Restore the context.
1326 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1327 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1328 scope_ = saved_scope;
1329 __ jmp(&exit);
1330
1331 // Try block code. Sets up the exception handler chain.
1332 __ bind(&try_entry);
1333
1334 try_catch_depth_++;
1335 int handler_index = NewHandlerTableEntry();
1336 EnterTryBlock(handler_index, &handler_entry);
Ben Murdochda12d292016-06-02 14:46:10 +01001337 {
1338 Comment cmnt_try(masm(), "[ Try block");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001339 Visit(stmt->try_block());
1340 }
1341 ExitTryBlock(handler_index);
1342 try_catch_depth_--;
1343 __ bind(&exit);
1344}
1345
1346
1347void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1348 Comment cmnt(masm_, "[ TryFinallyStatement");
1349 SetStatementPosition(stmt, SKIP_BREAK);
1350
1351 // Try finally is compiled by setting up a try-handler on the stack while
1352 // executing the try body, and removing it again afterwards.
1353 //
1354 // The try-finally construct can enter the finally block in three ways:
Ben Murdoch097c5b22016-05-18 11:27:45 +01001355 // 1. By exiting the try-block normally. This exits the try block,
1356 // pushes the continuation token and falls through to the finally
1357 // block.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001358 // 2. By exiting the try-block with a function-local control flow transfer
Ben Murdoch097c5b22016-05-18 11:27:45 +01001359 // (break/continue/return). The site of the, e.g., break exits the
1360 // try block, pushes the continuation token and jumps to the
1361 // finally block. After the finally block executes, the execution
1362 // continues based on the continuation token to a block that
1363 // continues with the control flow transfer.
1364 // 3. By exiting the try-block with a thrown exception. In the handler,
1365 // we push the exception and continuation token and jump to the
1366 // finally block (which will again dispatch based on the token once
1367 // it is finished).
1368
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001369 Label try_entry, handler_entry, finally_entry;
Ben Murdoch097c5b22016-05-18 11:27:45 +01001370 DeferredCommands deferred(this, &finally_entry);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001371
1372 // Jump to try-handler setup and try-block code.
1373 __ jmp(&try_entry);
1374 __ bind(&handler_entry);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001375
1376 // Exception handler code. This code is only executed when an exception
Ben Murdoch097c5b22016-05-18 11:27:45 +01001377 // is thrown. Record the continuation and jump to the finally block.
1378 {
Ben Murdochda12d292016-06-02 14:46:10 +01001379 Comment cmnt_handler(masm(), "[ Finally handler");
Ben Murdoch097c5b22016-05-18 11:27:45 +01001380 deferred.RecordThrow();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001381 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001382
1383 // Set up try handler.
1384 __ bind(&try_entry);
1385 int handler_index = NewHandlerTableEntry();
1386 EnterTryBlock(handler_index, &handler_entry);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001387 {
Ben Murdochda12d292016-06-02 14:46:10 +01001388 Comment cmnt_try(masm(), "[ Try block");
Ben Murdoch097c5b22016-05-18 11:27:45 +01001389 TryFinally try_body(this, &deferred);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001390 Visit(stmt->try_block());
1391 }
1392 ExitTryBlock(handler_index);
1393 // Execute the finally block on the way out. Clobber the unpredictable
1394 // value in the result register with one that's safe for GC because the
1395 // finally block will unconditionally preserve the result register on the
1396 // stack.
1397 ClearAccumulator();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001398 deferred.EmitFallThrough();
1399 // Fall through to the finally block.
1400
1401 // Finally block implementation.
1402 __ bind(&finally_entry);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001403 {
Ben Murdochda12d292016-06-02 14:46:10 +01001404 Comment cmnt_finally(masm(), "[ Finally block");
1405 OperandStackDepthIncrement(2); // Token and accumulator are on stack.
1406 EnterFinallyBlock();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001407 Visit(stmt->finally_block());
Ben Murdochda12d292016-06-02 14:46:10 +01001408 ExitFinallyBlock();
1409 OperandStackDepthDecrement(2); // Token and accumulator were on stack.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001410 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01001411
1412 {
1413 Comment cmnt_deferred(masm(), "[ Post-finally dispatch");
1414 deferred.EmitCommands(); // Return to the calling code.
1415 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001416}
1417
1418
1419void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1420 Comment cmnt(masm_, "[ DebuggerStatement");
1421 SetStatementPosition(stmt);
1422
1423 __ DebugBreak();
1424 // Ignore the return value.
1425
1426 PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1427}
1428
1429
1430void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1431 UNREACHABLE();
1432}
1433
1434
1435void FullCodeGenerator::VisitConditional(Conditional* expr) {
1436 Comment cmnt(masm_, "[ Conditional");
1437 Label true_case, false_case, done;
1438 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1439
Ben Murdoch097c5b22016-05-18 11:27:45 +01001440 int original_stack_depth = operand_stack_depth_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001441 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1442 __ bind(&true_case);
1443 SetExpressionPosition(expr->then_expression());
1444 if (context()->IsTest()) {
1445 const TestContext* for_test = TestContext::cast(context());
1446 VisitForControl(expr->then_expression(),
1447 for_test->true_label(),
1448 for_test->false_label(),
1449 NULL);
1450 } else {
1451 VisitInDuplicateContext(expr->then_expression());
1452 __ jmp(&done);
1453 }
1454
Ben Murdoch097c5b22016-05-18 11:27:45 +01001455 operand_stack_depth_ = original_stack_depth;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001456 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1457 __ bind(&false_case);
1458 SetExpressionPosition(expr->else_expression());
1459 VisitInDuplicateContext(expr->else_expression());
1460 // If control flow falls through Visit, merge it with true case here.
1461 if (!context()->IsTest()) {
1462 __ bind(&done);
1463 }
1464}
1465
1466
1467void FullCodeGenerator::VisitLiteral(Literal* expr) {
1468 Comment cmnt(masm_, "[ Literal");
1469 context()->Plug(expr->value());
1470}
1471
1472
1473void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1474 Comment cmnt(masm_, "[ FunctionLiteral");
1475
1476 // Build the function boilerplate and instantiate it.
1477 Handle<SharedFunctionInfo> function_info =
1478 Compiler::GetSharedFunctionInfo(expr, script(), info_);
1479 if (function_info.is_null()) {
1480 SetStackOverflow();
1481 return;
1482 }
1483 EmitNewClosure(function_info, expr->pretenure());
1484}
1485
1486
1487void FullCodeGenerator::VisitClassLiteral(ClassLiteral* lit) {
1488 Comment cmnt(masm_, "[ ClassLiteral");
1489
1490 {
Ben Murdochda12d292016-06-02 14:46:10 +01001491 NestedClassLiteral nested_class_literal(this, lit);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001492 EnterBlockScopeIfNeeded block_scope_state(
1493 this, lit->scope(), lit->EntryId(), lit->DeclsId(), lit->ExitId());
1494
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001495 if (lit->extends() != NULL) {
1496 VisitForStackValue(lit->extends());
1497 } else {
Ben Murdoch097c5b22016-05-18 11:27:45 +01001498 PushOperand(isolate()->factory()->the_hole_value());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001499 }
1500
1501 VisitForStackValue(lit->constructor());
1502
Ben Murdoch097c5b22016-05-18 11:27:45 +01001503 PushOperand(Smi::FromInt(lit->start_position()));
1504 PushOperand(Smi::FromInt(lit->end_position()));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001505
Ben Murdoch097c5b22016-05-18 11:27:45 +01001506 CallRuntimeWithOperands(Runtime::kDefineClass);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001507 PrepareForBailoutForId(lit->CreateLiteralId(), TOS_REG);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001508 PushOperand(result_register());
1509
1510 // Load the "prototype" from the constructor.
1511 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
1512 __ LoadRoot(LoadDescriptor::NameRegister(),
1513 Heap::kprototype_stringRootIndex);
1514 __ Move(LoadDescriptor::SlotRegister(), SmiFromSlot(lit->PrototypeSlot()));
1515 CallLoadIC(NOT_INSIDE_TYPEOF);
1516 PrepareForBailoutForId(lit->PrototypeId(), TOS_REG);
1517 PushOperand(result_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001518
1519 EmitClassDefineProperties(lit);
1520
Ben Murdochda12d292016-06-02 14:46:10 +01001521 // Set both the prototype and constructor to have fast properties.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001522 CallRuntimeWithOperands(Runtime::kFinalizeClassDefinition);
1523
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001524 if (lit->class_variable_proxy() != nullptr) {
1525 EmitVariableAssignment(lit->class_variable_proxy()->var(), Token::INIT,
1526 lit->ProxySlot());
1527 }
1528 }
1529
1530 context()->Plug(result_register());
1531}
1532
1533
1534void FullCodeGenerator::VisitNativeFunctionLiteral(
1535 NativeFunctionLiteral* expr) {
1536 Comment cmnt(masm_, "[ NativeFunctionLiteral");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001537 Handle<SharedFunctionInfo> shared =
Ben Murdoch097c5b22016-05-18 11:27:45 +01001538 Compiler::GetSharedFunctionInfoForNative(expr->extension(), expr->name());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001539 EmitNewClosure(shared, false);
1540}
1541
1542
1543void FullCodeGenerator::VisitThrow(Throw* expr) {
1544 Comment cmnt(masm_, "[ Throw");
1545 VisitForStackValue(expr->exception());
1546 SetExpressionPosition(expr);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001547 CallRuntimeWithOperands(Runtime::kThrow);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001548 // Never returns here.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001549
1550 // Even though this expression doesn't produce a value, we need to simulate
1551 // plugging of the value context to ensure stack depth tracking is in sync.
1552 if (context()->IsStackValue()) OperandStackDepthIncrement(1);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001553}
1554
1555
1556void FullCodeGenerator::EnterTryBlock(int handler_index, Label* handler) {
1557 HandlerTableEntry* entry = &handler_table_[handler_index];
1558 entry->range_start = masm()->pc_offset();
1559 entry->handler_offset = handler->pos();
1560 entry->try_catch_depth = try_catch_depth_;
Ben Murdoch097c5b22016-05-18 11:27:45 +01001561 entry->stack_depth = operand_stack_depth_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001562
Ben Murdoch097c5b22016-05-18 11:27:45 +01001563 // We are using the operand stack depth, check for accuracy.
1564 EmitOperandStackDepthCheck();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001565
1566 // Push context onto operand stack.
1567 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001568 PushOperand(context_register());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001569}
1570
1571
1572void FullCodeGenerator::ExitTryBlock(int handler_index) {
1573 HandlerTableEntry* entry = &handler_table_[handler_index];
1574 entry->range_end = masm()->pc_offset();
1575
1576 // Drop context from operand stack.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001577 DropOperands(TryBlockConstant::kElementCount);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001578}
1579
1580
1581void FullCodeGenerator::VisitCall(Call* expr) {
1582#ifdef DEBUG
1583 // We want to verify that RecordJSReturnSite gets called on all paths
1584 // through this function. Avoid early returns.
1585 expr->return_is_recorded_ = false;
1586#endif
1587
Ben Murdoch097c5b22016-05-18 11:27:45 +01001588 Comment cmnt(masm_, (expr->tail_call_mode() == TailCallMode::kAllow)
1589 ? "[ TailCall"
1590 : "[ Call");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001591 Expression* callee = expr->expression();
1592 Call::CallType call_type = expr->GetCallType(isolate());
1593
1594 switch (call_type) {
1595 case Call::POSSIBLY_EVAL_CALL:
1596 EmitPossiblyEvalCall(expr);
1597 break;
1598 case Call::GLOBAL_CALL:
1599 EmitCallWithLoadIC(expr);
1600 break;
1601 case Call::LOOKUP_SLOT_CALL:
1602 // Call to a lookup slot (dynamically introduced variable).
1603 PushCalleeAndWithBaseObject(expr);
1604 EmitCall(expr);
1605 break;
1606 case Call::NAMED_PROPERTY_CALL: {
1607 Property* property = callee->AsProperty();
1608 VisitForStackValue(property->obj());
1609 EmitCallWithLoadIC(expr);
1610 break;
1611 }
1612 case Call::KEYED_PROPERTY_CALL: {
1613 Property* property = callee->AsProperty();
1614 VisitForStackValue(property->obj());
1615 EmitKeyedCallWithLoadIC(expr, property->key());
1616 break;
1617 }
1618 case Call::NAMED_SUPER_PROPERTY_CALL:
1619 EmitSuperCallWithLoadIC(expr);
1620 break;
1621 case Call::KEYED_SUPER_PROPERTY_CALL:
1622 EmitKeyedSuperCallWithLoadIC(expr);
1623 break;
1624 case Call::SUPER_CALL:
1625 EmitSuperConstructorCall(expr);
1626 break;
1627 case Call::OTHER_CALL:
1628 // Call to an arbitrary expression not handled specially above.
1629 VisitForStackValue(callee);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001630 OperandStackDepthIncrement(1);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001631 __ PushRoot(Heap::kUndefinedValueRootIndex);
1632 // Emit function call.
1633 EmitCall(expr);
1634 break;
1635 }
1636
1637#ifdef DEBUG
1638 // RecordJSReturnSite should have been called.
1639 DCHECK(expr->return_is_recorded_);
1640#endif
1641}
1642
Ben Murdochda12d292016-06-02 14:46:10 +01001643void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
1644 ZoneList<Expression*>* args = expr->arguments();
1645 int arg_count = args->length();
1646
1647 if (expr->is_jsruntime()) {
1648 Comment cmnt(masm_, "[ CallRuntime");
1649 EmitLoadJSRuntimeFunction(expr);
1650
1651 // Push the arguments ("left-to-right").
1652 for (int i = 0; i < arg_count; i++) {
1653 VisitForStackValue(args->at(i));
1654 }
1655
1656 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
1657 EmitCallJSRuntimeFunction(expr);
1658 context()->DropAndPlug(1, result_register());
1659
1660 } else {
1661 const Runtime::Function* function = expr->function();
1662 switch (function->function_id) {
1663#define CALL_INTRINSIC_GENERATOR(Name) \
1664 case Runtime::kInline##Name: { \
1665 Comment cmnt(masm_, "[ Inline" #Name); \
1666 return Emit##Name(expr); \
1667 }
1668 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
1669#undef CALL_INTRINSIC_GENERATOR
1670 default: {
1671 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
1672 // Push the arguments ("left-to-right").
1673 for (int i = 0; i < arg_count; i++) {
1674 VisitForStackValue(args->at(i));
1675 }
1676
1677 // Call the C runtime function.
1678 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
1679 __ CallRuntime(expr->function(), arg_count);
1680 OperandStackDepthDecrement(arg_count);
1681 context()->Plug(result_register());
1682 }
1683 }
1684 }
1685}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001686
1687void FullCodeGenerator::VisitSpread(Spread* expr) { UNREACHABLE(); }
1688
1689
1690void FullCodeGenerator::VisitEmptyParentheses(EmptyParentheses* expr) {
1691 UNREACHABLE();
1692}
1693
1694
Ben Murdoch097c5b22016-05-18 11:27:45 +01001695void FullCodeGenerator::VisitRewritableExpression(RewritableExpression* expr) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001696 Visit(expr->expression());
1697}
1698
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001699FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
Ben Murdochda12d292016-06-02 14:46:10 +01001700 int* context_length) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001701 // The macros used here must preserve the result register.
1702
Ben Murdochda12d292016-06-02 14:46:10 +01001703 // Calculate how many operands to drop to get down to handler block.
1704 int stack_drop = codegen_->operand_stack_depth_ - GetStackDepthAtTarget();
1705 DCHECK_GE(stack_drop, 0);
1706
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001707 // Because the handler block contains the context of the finally
1708 // code, we can restore it directly from there for the finally code
1709 // rather than iteratively unwinding contexts via their previous
1710 // links.
1711 if (*context_length > 0) {
Ben Murdochda12d292016-06-02 14:46:10 +01001712 __ Drop(stack_drop); // Down to the handler block.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001713 // Restore the context to its dedicated register and the stack.
Ben Murdochda12d292016-06-02 14:46:10 +01001714 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001715 __ Pop(codegen_->context_register());
1716 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1717 codegen_->context_register());
1718 } else {
1719 // Down to the handler block and also drop context.
Ben Murdochda12d292016-06-02 14:46:10 +01001720 __ Drop(stack_drop + TryBlockConstant::kElementCount);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001721 }
Ben Murdochda12d292016-06-02 14:46:10 +01001722
1723 // The caller will ignore outputs.
1724 *context_length = -1;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001725 return previous_;
1726}
1727
Ben Murdoch097c5b22016-05-18 11:27:45 +01001728void FullCodeGenerator::DeferredCommands::RecordBreak(Statement* target) {
1729 TokenId token = dispenser_.GetBreakContinueToken();
1730 commands_.push_back({kBreak, token, target});
1731 EmitJumpToFinally(token);
1732}
1733
1734void FullCodeGenerator::DeferredCommands::RecordContinue(Statement* target) {
1735 TokenId token = dispenser_.GetBreakContinueToken();
1736 commands_.push_back({kContinue, token, target});
1737 EmitJumpToFinally(token);
1738}
1739
1740void FullCodeGenerator::DeferredCommands::RecordReturn() {
1741 if (return_token_ == TokenDispenserForFinally::kInvalidToken) {
1742 return_token_ = TokenDispenserForFinally::kReturnToken;
1743 commands_.push_back({kReturn, return_token_, nullptr});
1744 }
1745 EmitJumpToFinally(return_token_);
1746}
1747
1748void FullCodeGenerator::DeferredCommands::RecordThrow() {
1749 if (throw_token_ == TokenDispenserForFinally::kInvalidToken) {
1750 throw_token_ = TokenDispenserForFinally::kThrowToken;
1751 commands_.push_back({kThrow, throw_token_, nullptr});
1752 }
1753 EmitJumpToFinally(throw_token_);
1754}
1755
1756void FullCodeGenerator::DeferredCommands::EmitFallThrough() {
1757 __ Push(Smi::FromInt(TokenDispenserForFinally::kFallThroughToken));
1758 __ Push(result_register());
1759}
1760
1761void FullCodeGenerator::DeferredCommands::EmitJumpToFinally(TokenId token) {
1762 __ Push(Smi::FromInt(token));
1763 __ Push(result_register());
1764 __ jmp(finally_entry_);
1765}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001766
1767bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1768 Expression* sub_expr;
1769 Handle<String> check;
1770 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1771 EmitLiteralCompareTypeof(expr, sub_expr, check);
1772 return true;
1773 }
1774
Ben Murdochda12d292016-06-02 14:46:10 +01001775 if (expr->IsLiteralCompareUndefined(&sub_expr)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001776 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1777 return true;
1778 }
1779
1780 if (expr->IsLiteralCompareNull(&sub_expr)) {
1781 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1782 return true;
1783 }
1784
1785 return false;
1786}
1787
1788
1789void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1790 DisallowHeapAllocation no_gc;
1791 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1792
1793 // Increment loop nesting level by one and iterate over the back edge table
1794 // to find the matching loops to patch the interrupt
1795 // call to an unconditional call to the replacement code.
1796 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1797 if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1798
1799 BackEdgeTable back_edges(unoptimized, &no_gc);
1800 for (uint32_t i = 0; i < back_edges.length(); i++) {
1801 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1802 DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1803 unoptimized,
1804 back_edges.pc(i)));
1805 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1806 }
1807 }
1808
1809 unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1810 DCHECK(Verify(isolate, unoptimized));
1811}
1812
1813
1814void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1815 DisallowHeapAllocation no_gc;
1816 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1817
1818 // Iterate over the back edge table and revert the patched interrupt calls.
1819 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1820
1821 BackEdgeTable back_edges(unoptimized, &no_gc);
1822 for (uint32_t i = 0; i < back_edges.length(); i++) {
1823 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1824 DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1825 unoptimized,
1826 back_edges.pc(i)));
1827 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1828 }
1829 }
1830
1831 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1832 // Assert that none of the back edges are patched anymore.
1833 DCHECK(Verify(isolate, unoptimized));
1834}
1835
1836
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001837#ifdef DEBUG
1838bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1839 DisallowHeapAllocation no_gc;
1840 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1841 BackEdgeTable back_edges(unoptimized, &no_gc);
1842 for (uint32_t i = 0; i < back_edges.length(); i++) {
1843 uint32_t loop_depth = back_edges.loop_depth(i);
1844 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1845 // Assert that all back edges for shallower loops (and only those)
1846 // have already been patched.
1847 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1848 GetBackEdgeState(isolate,
1849 unoptimized,
1850 back_edges.pc(i)) != INTERRUPT);
1851 }
1852 return true;
1853}
1854#endif // DEBUG
1855
1856
1857FullCodeGenerator::EnterBlockScopeIfNeeded::EnterBlockScopeIfNeeded(
1858 FullCodeGenerator* codegen, Scope* scope, BailoutId entry_id,
1859 BailoutId declarations_id, BailoutId exit_id)
1860 : codegen_(codegen), exit_id_(exit_id) {
1861 saved_scope_ = codegen_->scope();
1862
1863 if (scope == NULL) {
1864 codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1865 needs_block_context_ = false;
1866 } else {
1867 needs_block_context_ = scope->NeedsContext();
1868 codegen_->scope_ = scope;
1869 {
1870 if (needs_block_context_) {
1871 Comment cmnt(masm(), "[ Extend block context");
Ben Murdoch097c5b22016-05-18 11:27:45 +01001872 codegen_->PushOperand(scope->GetScopeInfo(codegen->isolate()));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001873 codegen_->PushFunctionArgumentForContextAllocation();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001874 codegen_->CallRuntimeWithOperands(Runtime::kPushBlockContext);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001875
1876 // Replace the context stored in the frame.
1877 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1878 codegen_->context_register());
1879 }
1880 CHECK_EQ(0, scope->num_stack_slots());
1881 codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1882 }
1883 {
1884 Comment cmnt(masm(), "[ Declarations");
1885 codegen_->VisitDeclarations(scope->declarations());
1886 codegen_->PrepareForBailoutForId(declarations_id, NO_REGISTERS);
1887 }
1888 }
1889}
1890
1891
1892FullCodeGenerator::EnterBlockScopeIfNeeded::~EnterBlockScopeIfNeeded() {
1893 if (needs_block_context_) {
1894 codegen_->LoadContextField(codegen_->context_register(),
1895 Context::PREVIOUS_INDEX);
1896 // Update local stack frame context field.
1897 codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1898 codegen_->context_register());
1899 }
1900 codegen_->PrepareForBailoutForId(exit_id_, NO_REGISTERS);
1901 codegen_->scope_ = saved_scope_;
1902}
1903
1904
1905bool FullCodeGenerator::NeedsHoleCheckForLoad(VariableProxy* proxy) {
1906 Variable* var = proxy->var();
1907
1908 if (!var->binding_needs_init()) {
1909 return false;
1910 }
1911
1912 // var->scope() may be NULL when the proxy is located in eval code and
1913 // refers to a potential outside binding. Currently those bindings are
1914 // always looked up dynamically, i.e. in that case
1915 // var->location() == LOOKUP.
1916 // always holds.
1917 DCHECK(var->scope() != NULL);
1918 DCHECK(var->location() == VariableLocation::PARAMETER ||
1919 var->location() == VariableLocation::LOCAL ||
1920 var->location() == VariableLocation::CONTEXT);
1921
1922 // Check if the binding really needs an initialization check. The check
1923 // can be skipped in the following situation: we have a LET or CONST
1924 // binding in harmony mode, both the Variable and the VariableProxy have
1925 // the same declaration scope (i.e. they are both in global code, in the
1926 // same function or in the same eval code), the VariableProxy is in
1927 // the source physically located after the initializer of the variable,
1928 // and that the initializer cannot be skipped due to a nonlinear scope.
1929 //
1930 // We cannot skip any initialization checks for CONST in non-harmony
1931 // mode because const variables may be declared but never initialized:
1932 // if (false) { const x; }; var y = x;
1933 //
1934 // The condition on the declaration scopes is a conservative check for
1935 // nested functions that access a binding and are called before the
1936 // binding is initialized:
1937 // function() { f(); let x = 1; function f() { x = 2; } }
1938 //
1939 // The check cannot be skipped on non-linear scopes, namely switch
1940 // scopes, to ensure tests are done in cases like the following:
1941 // switch (1) { case 0: let x = 2; case 1: f(x); }
1942 // The scope of the variable needs to be checked, in case the use is
1943 // in a sub-block which may be linear.
1944 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1945 return true;
1946 }
1947
1948 if (var->is_this()) {
1949 DCHECK(literal() != nullptr &&
1950 (literal()->kind() & kSubclassConstructor) != 0);
1951 // TODO(littledan): implement 'this' hole check elimination.
1952 return true;
1953 }
1954
1955 // Check that we always have valid source position.
1956 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1957 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1958
1959 return var->mode() == CONST_LEGACY || var->scope()->is_nonlinear() ||
1960 var->initializer_position() >= proxy->position();
1961}
1962
1963
1964#undef __
1965
1966
1967} // namespace internal
1968} // namespace v8