1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/code-factory.h"
8 #include "src/code-stubs.h"
9 #include "src/codegen.h"
10 #include "src/compiler.h"
11 #include "src/debug/debug.h"
12 #include "src/full-codegen/full-codegen.h"
13 #include "src/ic/ic.h"
14 #include "src/parser.h"
15 #include "src/scopes.h"
20 #define __ ACCESS_MASM(masm_)
23 class JumpPatchSite BASE_EMBEDDED {
25 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
27 info_emitted_ = false;
32 DCHECK(patch_site_.is_bound() == info_emitted_);
35 void EmitJumpIfNotSmi(Register reg,
37 Label::Distance near_jump = Label::kFar) {
38 __ testb(reg, Immediate(kSmiTagMask));
39 EmitJump(not_carry, target, near_jump); // Always taken before patched.
42 void EmitJumpIfSmi(Register reg,
44 Label::Distance near_jump = Label::kFar) {
45 __ testb(reg, Immediate(kSmiTagMask));
46 EmitJump(carry, target, near_jump); // Never taken before patched.
49 void EmitPatchInfo() {
50 if (patch_site_.is_bound()) {
51 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
52 DCHECK(is_uint8(delta_to_patch_site));
53 __ testl(rax, Immediate(delta_to_patch_site));
58 __ nop(); // Signals no inlined code.
63 // jc will be patched with jz, jnc will become jnz.
64 void EmitJump(Condition cc, Label* target, Label::Distance near_jump) {
65 DCHECK(!patch_site_.is_bound() && !info_emitted_);
66 DCHECK(cc == carry || cc == not_carry);
67 __ bind(&patch_site_);
68 __ j(cc, target, near_jump);
71 MacroAssembler* masm_;
79 // Generate code for a JS function. On entry to the function the receiver
80 // and arguments have been pushed on the stack left to right, with the
81 // return address on top of them. The actual argument count matches the
82 // formal parameter count expected by the function.
84 // The live registers are:
85 // o rdi: the JS function object being called (i.e. ourselves)
87 // o rbp: our caller's frame pointer
88 // o rsp: stack pointer (pointing to return address)
90 // The function builds a JS frame. Please see JavaScriptFrameConstants in
91 // frames-x64.h for its layout.
92 void FullCodeGenerator::Generate() {
93 CompilationInfo* info = info_;
94 profiling_counter_ = isolate()->factory()->NewCell(
95 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
96 SetFunctionPosition(literal());
97 Comment cmnt(masm_, "[ function compiled by full code generator");
99 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
102 if (strlen(FLAG_stop_at) > 0 &&
103 info->literal()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
108 // Sloppy mode functions and builtins need to replace the receiver with the
109 // global proxy when called as functions (without an explicit receiver
111 if (info->MustReplaceUndefinedReceiverWithGlobalProxy()) {
113 // +1 for return address.
114 StackArgumentsAccessor args(rsp, info->scope()->num_parameters());
115 __ movp(rcx, args.GetReceiverOperand());
117 __ CompareRoot(rcx, Heap::kUndefinedValueRootIndex);
118 __ j(not_equal, &ok, Label::kNear);
120 __ movp(rcx, GlobalObjectOperand());
121 __ movp(rcx, FieldOperand(rcx, GlobalObject::kGlobalProxyOffset));
123 __ movp(args.GetReceiverOperand(), rcx);
128 // Open a frame scope to indicate that there is a frame on the stack. The
129 // MANUAL indicates that the scope shouldn't actually generate code to set up
130 // the frame (that is done below).
131 FrameScope frame_scope(masm_, StackFrame::MANUAL);
133 info->set_prologue_offset(masm_->pc_offset());
134 __ Prologue(info->IsCodePreAgingActive());
135 info->AddNoFrameRange(0, masm_->pc_offset());
137 { Comment cmnt(masm_, "[ Allocate locals");
138 int locals_count = info->scope()->num_stack_slots();
139 // Generators allocate locals, if any, in context slots.
140 DCHECK(!IsGeneratorFunction(info->literal()->kind()) || locals_count == 0);
141 if (locals_count == 1) {
142 __ PushRoot(Heap::kUndefinedValueRootIndex);
143 } else if (locals_count > 1) {
144 if (locals_count >= 128) {
147 __ subp(rcx, Immediate(locals_count * kPointerSize));
148 __ CompareRoot(rcx, Heap::kRealStackLimitRootIndex);
149 __ j(above_equal, &ok, Label::kNear);
150 __ CallRuntime(Runtime::kThrowStackOverflow, 0);
153 __ LoadRoot(rdx, Heap::kUndefinedValueRootIndex);
154 const int kMaxPushes = 32;
155 if (locals_count >= kMaxPushes) {
156 int loop_iterations = locals_count / kMaxPushes;
157 __ movp(rcx, Immediate(loop_iterations));
159 __ bind(&loop_header);
161 for (int i = 0; i < kMaxPushes; i++) {
164 // Continue loop if not done.
166 __ j(not_zero, &loop_header, Label::kNear);
168 int remaining = locals_count % kMaxPushes;
169 // Emit the remaining pushes.
170 for (int i = 0; i < remaining; i++) {
176 bool function_in_register = true;
178 // Possibly allocate a local context.
179 if (info->scope()->num_heap_slots() > 0) {
180 Comment cmnt(masm_, "[ Allocate context");
181 bool need_write_barrier = true;
182 int slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
183 // Argument to NewContext is the function, which is still in rdi.
184 if (info->scope()->is_script_scope()) {
186 __ Push(info->scope()->GetScopeInfo(info->isolate()));
187 __ CallRuntime(Runtime::kNewScriptContext, 2);
188 } else if (slots <= FastNewContextStub::kMaximumSlots) {
189 FastNewContextStub stub(isolate(), slots);
191 // Result of FastNewContextStub is always in new space.
192 need_write_barrier = false;
195 __ CallRuntime(Runtime::kNewFunctionContext, 1);
197 function_in_register = false;
198 // Context is returned in rax. It replaces the context passed to us.
199 // It's saved in the stack and kept live in rsi.
201 __ movp(Operand(rbp, StandardFrameConstants::kContextOffset), rax);
203 // Copy any necessary parameters into the context.
204 int num_parameters = info->scope()->num_parameters();
205 int first_parameter = info->scope()->has_this_declaration() ? -1 : 0;
206 for (int i = first_parameter; i < num_parameters; i++) {
207 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
208 if (var->IsContextSlot()) {
209 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
210 (num_parameters - 1 - i) * kPointerSize;
211 // Load parameter from stack.
212 __ movp(rax, Operand(rbp, parameter_offset));
213 // Store it in the context.
214 int context_offset = Context::SlotOffset(var->index());
215 __ movp(Operand(rsi, context_offset), rax);
216 // Update the write barrier. This clobbers rax and rbx.
217 if (need_write_barrier) {
218 __ RecordWriteContextSlot(
219 rsi, context_offset, rax, rbx, kDontSaveFPRegs);
220 } else if (FLAG_debug_code) {
222 __ JumpIfInNewSpace(rsi, rax, &done, Label::kNear);
223 __ Abort(kExpectedNewSpaceObject);
230 PrepareForBailoutForId(BailoutId::Prologue(), NO_REGISTERS);
231 // Function register is trashed in case we bailout here. But since that
232 // could happen only when we allocate a context the value of
233 // |function_in_register| is correct.
235 // Possibly set up a local binding to the this function which is used in
236 // derived constructors with super calls.
237 Variable* this_function_var = scope()->this_function_var();
238 if (this_function_var != nullptr) {
239 Comment cmnt(masm_, "[ This function");
240 if (!function_in_register) {
241 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
242 // The write barrier clobbers register again, keep it marked as such.
244 SetVar(this_function_var, rdi, rbx, rdx);
247 Variable* new_target_var = scope()->new_target_var();
248 if (new_target_var != nullptr) {
249 Comment cmnt(masm_, "[ new.target");
251 __ movp(rax, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
252 Label non_adaptor_frame;
253 __ Cmp(Operand(rax, StandardFrameConstants::kContextOffset),
254 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
255 __ j(not_equal, &non_adaptor_frame);
256 __ movp(rax, Operand(rax, StandardFrameConstants::kCallerFPOffset));
258 __ bind(&non_adaptor_frame);
259 __ Cmp(Operand(rax, StandardFrameConstants::kMarkerOffset),
260 Smi::FromInt(StackFrame::CONSTRUCT));
262 Label non_construct_frame, done;
263 __ j(not_equal, &non_construct_frame);
267 Operand(rax, ConstructFrameConstants::kOriginalConstructorOffset));
270 // Non-construct frame
271 __ bind(&non_construct_frame);
272 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
275 SetVar(new_target_var, rax, rbx, rdx);
278 // Possibly allocate an arguments object.
279 Variable* arguments = scope()->arguments();
280 if (arguments != NULL) {
281 // Arguments object must be allocated after the context object, in
282 // case the "arguments" or ".arguments" variables are in the context.
283 Comment cmnt(masm_, "[ Allocate arguments object");
284 if (function_in_register) {
287 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
289 // The receiver is just before the parameters on the caller's stack.
290 int num_parameters = info->scope()->num_parameters();
291 int offset = num_parameters * kPointerSize;
293 Operand(rbp, StandardFrameConstants::kCallerSPOffset + offset));
295 __ Push(Smi::FromInt(num_parameters));
296 // Arguments to ArgumentsAccessStub:
297 // function, receiver address, parameter count.
298 // The stub will rewrite receiver and parameter count if the previous
299 // stack frame was an arguments adapter frame.
301 ArgumentsAccessStub::Type type;
302 if (is_strict(language_mode()) || !has_simple_parameters()) {
303 type = ArgumentsAccessStub::NEW_STRICT;
304 } else if (literal()->has_duplicate_parameters()) {
305 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
307 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
309 ArgumentsAccessStub stub(isolate(), type);
312 SetVar(arguments, rax, rbx, rdx);
316 __ CallRuntime(Runtime::kTraceEnter, 0);
319 // Visit the declarations and body unless there is an illegal
321 if (scope()->HasIllegalRedeclaration()) {
322 Comment cmnt(masm_, "[ Declarations");
323 VisitForEffect(scope()->GetIllegalRedeclaration());
326 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
327 { Comment cmnt(masm_, "[ Declarations");
328 VisitDeclarations(scope()->declarations());
331 // Assert that the declarations do not use ICs. Otherwise the debugger
332 // won't be able to redirect a PC at an IC to the correct IC in newly
334 DCHECK_EQ(0, ic_total_count_);
336 { Comment cmnt(masm_, "[ Stack check");
337 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
339 __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
340 __ j(above_equal, &ok, Label::kNear);
341 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
345 { Comment cmnt(masm_, "[ Body");
346 DCHECK(loop_depth() == 0);
347 VisitStatements(literal()->body());
348 DCHECK(loop_depth() == 0);
352 // Always emit a 'return undefined' in case control fell off the end of
354 { Comment cmnt(masm_, "[ return <undefined>;");
355 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
356 EmitReturnSequence();
361 void FullCodeGenerator::ClearAccumulator() {
366 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
367 __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
368 __ SmiAddConstant(FieldOperand(rbx, Cell::kValueOffset),
369 Smi::FromInt(-delta));
373 void FullCodeGenerator::EmitProfilingCounterReset() {
374 int reset_value = FLAG_interrupt_budget;
375 __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
376 __ Move(kScratchRegister, Smi::FromInt(reset_value));
377 __ movp(FieldOperand(rbx, Cell::kValueOffset), kScratchRegister);
381 static const byte kJnsOffset = kPointerSize == kInt64Size ? 0x1d : 0x14;
384 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
385 Label* back_edge_target) {
386 Comment cmnt(masm_, "[ Back edge bookkeeping");
389 DCHECK(back_edge_target->is_bound());
390 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
391 int weight = Min(kMaxBackEdgeWeight,
392 Max(1, distance / kCodeSizeMultiplier));
393 EmitProfilingCounterDecrement(weight);
395 __ j(positive, &ok, Label::kNear);
397 PredictableCodeSizeScope predictible_code_size_scope(masm_, kJnsOffset);
398 DontEmitDebugCodeScope dont_emit_debug_code_scope(masm_);
399 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
401 // Record a mapping of this PC offset to the OSR id. This is used to find
402 // the AST id from the unoptimized code in order to use it as a key into
403 // the deoptimization input data found in the optimized code.
404 RecordBackEdge(stmt->OsrEntryId());
406 EmitProfilingCounterReset();
410 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
411 // Record a mapping of the OSR id to this PC. This is used if the OSR
412 // entry becomes the target of a bailout. We don't expect it to be, but
413 // we want it to work if it is.
414 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
418 void FullCodeGenerator::EmitReturnSequence() {
419 Comment cmnt(masm_, "[ Return sequence");
420 if (return_label_.is_bound()) {
421 __ jmp(&return_label_);
423 __ bind(&return_label_);
426 __ CallRuntime(Runtime::kTraceExit, 1);
428 // Pretend that the exit is a backwards jump to the entry.
430 if (info_->ShouldSelfOptimize()) {
431 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
433 int distance = masm_->pc_offset();
434 weight = Min(kMaxBackEdgeWeight,
435 Max(1, distance / kCodeSizeMultiplier));
437 EmitProfilingCounterDecrement(weight);
439 __ j(positive, &ok, Label::kNear);
441 __ call(isolate()->builtins()->InterruptCheck(),
442 RelocInfo::CODE_TARGET);
444 EmitProfilingCounterReset();
447 SetReturnPosition(literal());
448 int no_frame_start = masm_->pc_offset();
451 int arg_count = info_->scope()->num_parameters() + 1;
452 int arguments_bytes = arg_count * kPointerSize;
453 __ Ret(arguments_bytes, rcx);
455 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
460 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
461 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
462 MemOperand operand = codegen()->VarOperand(var, result_register());
467 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
471 void FullCodeGenerator::AccumulatorValueContext::Plug(
472 Heap::RootListIndex index) const {
473 __ LoadRoot(result_register(), index);
477 void FullCodeGenerator::StackValueContext::Plug(
478 Heap::RootListIndex index) const {
483 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
484 codegen()->PrepareForBailoutBeforeSplit(condition(),
488 if (index == Heap::kUndefinedValueRootIndex ||
489 index == Heap::kNullValueRootIndex ||
490 index == Heap::kFalseValueRootIndex) {
491 if (false_label_ != fall_through_) __ jmp(false_label_);
492 } else if (index == Heap::kTrueValueRootIndex) {
493 if (true_label_ != fall_through_) __ jmp(true_label_);
495 __ LoadRoot(result_register(), index);
496 codegen()->DoTest(this);
501 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
505 void FullCodeGenerator::AccumulatorValueContext::Plug(
506 Handle<Object> lit) const {
508 __ SafeMove(result_register(), Smi::cast(*lit));
510 __ Move(result_register(), lit);
515 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
517 __ SafePush(Smi::cast(*lit));
524 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
525 codegen()->PrepareForBailoutBeforeSplit(condition(),
529 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
530 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
531 if (false_label_ != fall_through_) __ jmp(false_label_);
532 } else if (lit->IsTrue() || lit->IsJSObject()) {
533 if (true_label_ != fall_through_) __ jmp(true_label_);
534 } else if (lit->IsString()) {
535 if (String::cast(*lit)->length() == 0) {
536 if (false_label_ != fall_through_) __ jmp(false_label_);
538 if (true_label_ != fall_through_) __ jmp(true_label_);
540 } else if (lit->IsSmi()) {
541 if (Smi::cast(*lit)->value() == 0) {
542 if (false_label_ != fall_through_) __ jmp(false_label_);
544 if (true_label_ != fall_through_) __ jmp(true_label_);
547 // For simplicity we always test the accumulator register.
548 __ Move(result_register(), lit);
549 codegen()->DoTest(this);
554 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
555 Register reg) const {
561 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
563 Register reg) const {
566 __ Move(result_register(), reg);
570 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
571 Register reg) const {
573 if (count > 1) __ Drop(count - 1);
574 __ movp(Operand(rsp, 0), reg);
578 void FullCodeGenerator::TestContext::DropAndPlug(int count,
579 Register reg) const {
581 // For simplicity we always test the accumulator register.
583 __ Move(result_register(), reg);
584 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
585 codegen()->DoTest(this);
589 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
590 Label* materialize_false) const {
591 DCHECK(materialize_true == materialize_false);
592 __ bind(materialize_true);
596 void FullCodeGenerator::AccumulatorValueContext::Plug(
597 Label* materialize_true,
598 Label* materialize_false) const {
600 __ bind(materialize_true);
601 __ Move(result_register(), isolate()->factory()->true_value());
602 __ jmp(&done, Label::kNear);
603 __ bind(materialize_false);
604 __ Move(result_register(), isolate()->factory()->false_value());
609 void FullCodeGenerator::StackValueContext::Plug(
610 Label* materialize_true,
611 Label* materialize_false) const {
613 __ bind(materialize_true);
614 __ Push(isolate()->factory()->true_value());
615 __ jmp(&done, Label::kNear);
616 __ bind(materialize_false);
617 __ Push(isolate()->factory()->false_value());
622 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
623 Label* materialize_false) const {
624 DCHECK(materialize_true == true_label_);
625 DCHECK(materialize_false == false_label_);
629 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
630 Heap::RootListIndex value_root_index =
631 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
632 __ LoadRoot(result_register(), value_root_index);
636 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
637 Heap::RootListIndex value_root_index =
638 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
639 __ PushRoot(value_root_index);
643 void FullCodeGenerator::TestContext::Plug(bool flag) const {
644 codegen()->PrepareForBailoutBeforeSplit(condition(),
649 if (true_label_ != fall_through_) __ jmp(true_label_);
651 if (false_label_ != fall_through_) __ jmp(false_label_);
656 void FullCodeGenerator::DoTest(Expression* condition,
659 Label* fall_through) {
660 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
661 CallIC(ic, condition->test_id());
662 __ testp(result_register(), result_register());
663 // The stub returns nonzero for true.
664 Split(not_zero, if_true, if_false, fall_through);
668 void FullCodeGenerator::Split(Condition cc,
671 Label* fall_through) {
672 if (if_false == fall_through) {
674 } else if (if_true == fall_through) {
675 __ j(NegateCondition(cc), if_false);
683 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
684 DCHECK(var->IsStackAllocated());
685 // Offset is negative because higher indexes are at lower addresses.
686 int offset = -var->index() * kPointerSize;
687 // Adjust by a (parameter or local) base offset.
688 if (var->IsParameter()) {
689 offset += kFPOnStackSize + kPCOnStackSize +
690 (info_->scope()->num_parameters() - 1) * kPointerSize;
692 offset += JavaScriptFrameConstants::kLocal0Offset;
694 return Operand(rbp, offset);
698 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
699 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
700 if (var->IsContextSlot()) {
701 int context_chain_length = scope()->ContextChainLength(var->scope());
702 __ LoadContext(scratch, context_chain_length);
703 return ContextOperand(scratch, var->index());
705 return StackOperand(var);
710 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
711 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
712 MemOperand location = VarOperand(var, dest);
713 __ movp(dest, location);
717 void FullCodeGenerator::SetVar(Variable* var,
721 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
722 DCHECK(!scratch0.is(src));
723 DCHECK(!scratch0.is(scratch1));
724 DCHECK(!scratch1.is(src));
725 MemOperand location = VarOperand(var, scratch0);
726 __ movp(location, src);
728 // Emit the write barrier code if the location is in the heap.
729 if (var->IsContextSlot()) {
730 int offset = Context::SlotOffset(var->index());
731 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
736 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
737 bool should_normalize,
740 // Only prepare for bailouts before splits if we're in a test
741 // context. Otherwise, we let the Visit function deal with the
742 // preparation to avoid preparing with the same AST id twice.
743 if (!context()->IsTest()) return;
746 if (should_normalize) __ jmp(&skip, Label::kNear);
747 PrepareForBailout(expr, TOS_REG);
748 if (should_normalize) {
749 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
750 Split(equal, if_true, if_false, NULL);
756 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
757 // The variable in the declaration always resides in the current context.
758 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
759 if (generate_debug_code_) {
760 // Check that we're not inside a with or catch context.
761 __ movp(rbx, FieldOperand(rsi, HeapObject::kMapOffset));
762 __ CompareRoot(rbx, Heap::kWithContextMapRootIndex);
763 __ Check(not_equal, kDeclarationInWithContext);
764 __ CompareRoot(rbx, Heap::kCatchContextMapRootIndex);
765 __ Check(not_equal, kDeclarationInCatchContext);
770 void FullCodeGenerator::VisitVariableDeclaration(
771 VariableDeclaration* declaration) {
772 // If it was not possible to allocate the variable at compile time, we
773 // need to "declare" it at runtime to make sure it actually exists in the
775 VariableProxy* proxy = declaration->proxy();
776 VariableMode mode = declaration->mode();
777 Variable* variable = proxy->var();
778 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
779 switch (variable->location()) {
780 case VariableLocation::GLOBAL:
781 case VariableLocation::UNALLOCATED:
782 globals_->Add(variable->name(), zone());
783 globals_->Add(variable->binding_needs_init()
784 ? isolate()->factory()->the_hole_value()
785 : isolate()->factory()->undefined_value(),
789 case VariableLocation::PARAMETER:
790 case VariableLocation::LOCAL:
792 Comment cmnt(masm_, "[ VariableDeclaration");
793 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
794 __ movp(StackOperand(variable), kScratchRegister);
798 case VariableLocation::CONTEXT:
800 Comment cmnt(masm_, "[ VariableDeclaration");
801 EmitDebugCheckDeclarationContext(variable);
802 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
803 __ movp(ContextOperand(rsi, variable->index()), kScratchRegister);
804 // No write barrier since the hole value is in old space.
805 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
809 case VariableLocation::LOOKUP: {
810 Comment cmnt(masm_, "[ VariableDeclaration");
811 __ Push(variable->name());
812 // Declaration nodes are always introduced in one of four modes.
813 DCHECK(IsDeclaredVariableMode(mode));
814 // Push initial value, if any.
815 // Note: For variables we must not push an initial value (such as
816 // 'undefined') because we may have a (legal) redeclaration and we
817 // must not destroy the current value.
819 __ PushRoot(Heap::kTheHoleValueRootIndex);
821 __ Push(Smi::FromInt(0)); // Indicates no initial value.
823 __ CallRuntime(IsImmutableVariableMode(mode)
824 ? Runtime::kDeclareReadOnlyLookupSlot
825 : Runtime::kDeclareLookupSlot,
833 void FullCodeGenerator::VisitFunctionDeclaration(
834 FunctionDeclaration* declaration) {
835 VariableProxy* proxy = declaration->proxy();
836 Variable* variable = proxy->var();
837 switch (variable->location()) {
838 case VariableLocation::GLOBAL:
839 case VariableLocation::UNALLOCATED: {
840 globals_->Add(variable->name(), zone());
841 Handle<SharedFunctionInfo> function =
842 Compiler::GetSharedFunctionInfo(declaration->fun(), script(), info_);
843 // Check for stack-overflow exception.
844 if (function.is_null()) return SetStackOverflow();
845 globals_->Add(function, zone());
849 case VariableLocation::PARAMETER:
850 case VariableLocation::LOCAL: {
851 Comment cmnt(masm_, "[ FunctionDeclaration");
852 VisitForAccumulatorValue(declaration->fun());
853 __ movp(StackOperand(variable), result_register());
857 case VariableLocation::CONTEXT: {
858 Comment cmnt(masm_, "[ FunctionDeclaration");
859 EmitDebugCheckDeclarationContext(variable);
860 VisitForAccumulatorValue(declaration->fun());
861 __ movp(ContextOperand(rsi, variable->index()), result_register());
862 int offset = Context::SlotOffset(variable->index());
863 // We know that we have written a function, which is not a smi.
864 __ RecordWriteContextSlot(rsi,
871 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
875 case VariableLocation::LOOKUP: {
876 Comment cmnt(masm_, "[ FunctionDeclaration");
877 __ Push(variable->name());
878 VisitForStackValue(declaration->fun());
879 __ CallRuntime(Runtime::kDeclareLookupSlot, 2);
886 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
887 // Call the runtime to declare the globals.
889 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
890 __ CallRuntime(Runtime::kDeclareGlobals, 2);
891 // Return value is ignored.
895 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
896 // Call the runtime to declare the modules.
897 __ Push(descriptions);
898 __ CallRuntime(Runtime::kDeclareModules, 1);
899 // Return value is ignored.
903 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
904 Comment cmnt(masm_, "[ SwitchStatement");
905 Breakable nested_statement(this, stmt);
906 SetStatementPosition(stmt);
908 // Keep the switch value on the stack until a case matches.
909 VisitForStackValue(stmt->tag());
910 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
912 ZoneList<CaseClause*>* clauses = stmt->cases();
913 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
915 Label next_test; // Recycled for each test.
916 // Compile all the tests with branches to their bodies.
917 for (int i = 0; i < clauses->length(); i++) {
918 CaseClause* clause = clauses->at(i);
919 clause->body_target()->Unuse();
921 // The default is not a test, but remember it as final fall through.
922 if (clause->is_default()) {
923 default_clause = clause;
927 Comment cmnt(masm_, "[ Case comparison");
931 // Compile the label expression.
932 VisitForAccumulatorValue(clause->label());
934 // Perform the comparison as if via '==='.
935 __ movp(rdx, Operand(rsp, 0)); // Switch value.
936 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
937 JumpPatchSite patch_site(masm_);
938 if (inline_smi_code) {
942 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
945 __ j(not_equal, &next_test);
946 __ Drop(1); // Switch value is no longer needed.
947 __ jmp(clause->body_target());
951 // Record position before stub call for type feedback.
952 SetExpressionPosition(clause);
953 Handle<Code> ic = CodeFactory::CompareIC(isolate(), Token::EQ_STRICT,
954 strength(language_mode())).code();
955 CallIC(ic, clause->CompareId());
956 patch_site.EmitPatchInfo();
959 __ jmp(&skip, Label::kNear);
960 PrepareForBailout(clause, TOS_REG);
961 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
962 __ j(not_equal, &next_test);
964 __ jmp(clause->body_target());
968 __ j(not_equal, &next_test);
969 __ Drop(1); // Switch value is no longer needed.
970 __ jmp(clause->body_target());
973 // Discard the test value and jump to the default if present, otherwise to
974 // the end of the statement.
976 __ Drop(1); // Switch value is no longer needed.
977 if (default_clause == NULL) {
978 __ jmp(nested_statement.break_label());
980 __ jmp(default_clause->body_target());
983 // Compile all the case bodies.
984 for (int i = 0; i < clauses->length(); i++) {
985 Comment cmnt(masm_, "[ Case body");
986 CaseClause* clause = clauses->at(i);
987 __ bind(clause->body_target());
988 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
989 VisitStatements(clause->statements());
992 __ bind(nested_statement.break_label());
993 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
997 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
998 Comment cmnt(masm_, "[ ForInStatement");
999 SetStatementPosition(stmt, SKIP_BREAK);
1001 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1004 ForIn loop_statement(this, stmt);
1005 increment_loop_depth();
1007 // Get the object to enumerate over. If the object is null or undefined, skip
1008 // over the loop. See ECMA-262 version 5, section 12.6.4.
1009 SetExpressionAsStatementPosition(stmt->enumerable());
1010 VisitForAccumulatorValue(stmt->enumerable());
1011 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1013 Register null_value = rdi;
1014 __ LoadRoot(null_value, Heap::kNullValueRootIndex);
1015 __ cmpp(rax, null_value);
1018 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1020 // Convert the object to a JS object.
1021 Label convert, done_convert;
1022 __ JumpIfSmi(rax, &convert, Label::kNear);
1023 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rcx);
1024 __ j(above_equal, &done_convert, Label::kNear);
1026 ToObjectStub stub(isolate());
1028 __ bind(&done_convert);
1029 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1032 // Check for proxies.
1034 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1035 __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx);
1036 __ j(below_equal, &call_runtime);
1038 // Check cache validity in generated code. This is a fast case for
1039 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1040 // guarantee cache validity, call the runtime system to check cache
1041 // validity or get the property names in a fixed array.
1042 __ CheckEnumCache(null_value, &call_runtime);
1044 // The enum cache is valid. Load the map of the object being
1045 // iterated over and use the cache for the iteration.
1047 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
1048 __ jmp(&use_cache, Label::kNear);
1050 // Get the set of properties to enumerate.
1051 __ bind(&call_runtime);
1052 __ Push(rax); // Duplicate the enumerable object on the stack.
1053 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1054 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1056 // If we got a map from the runtime call, we can do a fast
1057 // modification check. Otherwise, we got a fixed array, and we have
1058 // to do a slow check.
1060 __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
1061 Heap::kMetaMapRootIndex);
1062 __ j(not_equal, &fixed_array);
1064 // We got a map in register rax. Get the enumeration cache from it.
1065 __ bind(&use_cache);
1067 Label no_descriptors;
1069 __ EnumLength(rdx, rax);
1070 __ Cmp(rdx, Smi::FromInt(0));
1071 __ j(equal, &no_descriptors);
1073 __ LoadInstanceDescriptors(rax, rcx);
1074 __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheOffset));
1075 __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1077 // Set up the four remaining stack slots.
1078 __ Push(rax); // Map.
1079 __ Push(rcx); // Enumeration cache.
1080 __ Push(rdx); // Number of valid entries for the map in the enum cache.
1081 __ Push(Smi::FromInt(0)); // Initial index.
1084 __ bind(&no_descriptors);
1085 __ addp(rsp, Immediate(kPointerSize));
1088 // We got a fixed array in register rax. Iterate through that.
1090 __ bind(&fixed_array);
1092 // No need for a write barrier, we are storing a Smi in the feedback vector.
1093 __ Move(rbx, FeedbackVector());
1094 int vector_index = FeedbackVector()->GetIndex(slot);
1095 __ Move(FieldOperand(rbx, FixedArray::OffsetOfElementAt(vector_index)),
1096 TypeFeedbackVector::MegamorphicSentinel(isolate()));
1097 __ Move(rbx, Smi::FromInt(1)); // Smi indicates slow check
1098 __ movp(rcx, Operand(rsp, 0 * kPointerSize)); // Get enumerated object
1099 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1100 __ CmpObjectType(rcx, LAST_JS_PROXY_TYPE, rcx);
1101 __ j(above, &non_proxy);
1102 __ Move(rbx, Smi::FromInt(0)); // Zero indicates proxy
1103 __ bind(&non_proxy);
1104 __ Push(rbx); // Smi
1105 __ Push(rax); // Array
1106 __ movp(rax, FieldOperand(rax, FixedArray::kLengthOffset));
1107 __ Push(rax); // Fixed array length (as smi).
1108 __ Push(Smi::FromInt(0)); // Initial index.
1110 // Generate code for doing the condition check.
1111 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1113 SetExpressionAsStatementPosition(stmt->each());
1115 __ movp(rax, Operand(rsp, 0 * kPointerSize)); // Get the current index.
1116 __ cmpp(rax, Operand(rsp, 1 * kPointerSize)); // Compare to the array length.
1117 __ j(above_equal, loop_statement.break_label());
1119 // Get the current entry of the array into register rbx.
1120 __ movp(rbx, Operand(rsp, 2 * kPointerSize));
1121 SmiIndex index = masm()->SmiToIndex(rax, rax, kPointerSizeLog2);
1122 __ movp(rbx, FieldOperand(rbx,
1125 FixedArray::kHeaderSize));
1127 // Get the expected map from the stack or a smi in the
1128 // permanent slow case into register rdx.
1129 __ movp(rdx, Operand(rsp, 3 * kPointerSize));
1131 // Check if the expected map still matches that of the enumerable.
1132 // If not, we may have to filter the key.
1134 __ movp(rcx, Operand(rsp, 4 * kPointerSize));
1135 __ cmpp(rdx, FieldOperand(rcx, HeapObject::kMapOffset));
1136 __ j(equal, &update_each, Label::kNear);
1138 // For proxies, no filtering is done.
1139 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1140 __ Cmp(rdx, Smi::FromInt(0));
1141 __ j(equal, &update_each, Label::kNear);
1143 // Convert the entry to a string or null if it isn't a property
1144 // anymore. If the property has been removed while iterating, we
1146 __ Push(rcx); // Enumerable.
1147 __ Push(rbx); // Current entry.
1148 __ CallRuntime(Runtime::kForInFilter, 2);
1149 PrepareForBailoutForId(stmt->FilterId(), TOS_REG);
1150 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1151 __ j(equal, loop_statement.continue_label());
1154 // Update the 'each' property or variable from the possibly filtered
1155 // entry in register rbx.
1156 __ bind(&update_each);
1157 __ movp(result_register(), rbx);
1158 // Perform the assignment as if via '='.
1159 { EffectContext context(this);
1160 EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1161 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1164 // Generate code for the body of the loop.
1165 Visit(stmt->body());
1167 // Generate code for going to the next element by incrementing the
1168 // index (smi) stored on top of the stack.
1169 __ bind(loop_statement.continue_label());
1170 __ SmiAddConstant(Operand(rsp, 0 * kPointerSize), Smi::FromInt(1));
1172 EmitBackEdgeBookkeeping(stmt, &loop);
1175 // Remove the pointers stored on the stack.
1176 __ bind(loop_statement.break_label());
1177 __ addp(rsp, Immediate(5 * kPointerSize));
1179 // Exit and decrement the loop depth.
1180 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1182 decrement_loop_depth();
1186 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1188 // Use the fast case closure allocation code that allocates in new
1189 // space for nested functions that don't need literals cloning. If
1190 // we're running with the --always-opt or the --prepare-always-opt
1191 // flag, we need to use the runtime function so that the new function
1192 // we are creating here gets a chance to have its code optimized and
1193 // doesn't just get a copy of the existing unoptimized code.
1194 if (!FLAG_always_opt &&
1195 !FLAG_prepare_always_opt &&
1197 scope()->is_function_scope() &&
1198 info->num_literals() == 0) {
1199 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1205 pretenure ? Runtime::kNewClosure_Tenured : Runtime::kNewClosure, 1);
1207 context()->Plug(rax);
1211 void FullCodeGenerator::EmitSetHomeObject(Expression* initializer, int offset,
1212 FeedbackVectorICSlot slot) {
1213 DCHECK(NeedsHomeObject(initializer));
1214 __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1215 __ Move(StoreDescriptor::NameRegister(),
1216 isolate()->factory()->home_object_symbol());
1217 __ movp(StoreDescriptor::ValueRegister(),
1218 Operand(rsp, offset * kPointerSize));
1219 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
1224 void FullCodeGenerator::EmitSetHomeObjectAccumulator(
1225 Expression* initializer, int offset, FeedbackVectorICSlot slot) {
1226 DCHECK(NeedsHomeObject(initializer));
1227 __ movp(StoreDescriptor::ReceiverRegister(), rax);
1228 __ Move(StoreDescriptor::NameRegister(),
1229 isolate()->factory()->home_object_symbol());
1230 __ movp(StoreDescriptor::ValueRegister(),
1231 Operand(rsp, offset * kPointerSize));
1232 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
1237 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1238 TypeofMode typeof_mode,
1240 Register context = rsi;
1241 Register temp = rdx;
1245 if (s->num_heap_slots() > 0) {
1246 if (s->calls_sloppy_eval()) {
1247 // Check that extension is NULL.
1248 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX),
1250 __ j(not_equal, slow);
1252 // Load next context in chain.
1253 __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1254 // Walk the rest of the chain without clobbering rsi.
1257 // If no outer scope calls eval, we do not need to check more
1258 // context extensions. If we have reached an eval scope, we check
1259 // all extensions from this point.
1260 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1261 s = s->outer_scope();
1264 if (s != NULL && s->is_eval_scope()) {
1265 // Loop up the context chain. There is no frame effect so it is
1266 // safe to use raw labels here.
1268 if (!context.is(temp)) {
1269 __ movp(temp, context);
1271 // Load map for comparison into register, outside loop.
1272 __ LoadRoot(kScratchRegister, Heap::kNativeContextMapRootIndex);
1274 // Terminate at native context.
1275 __ cmpp(kScratchRegister, FieldOperand(temp, HeapObject::kMapOffset));
1276 __ j(equal, &fast, Label::kNear);
1277 // Check that extension is NULL.
1278 __ cmpp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1279 __ j(not_equal, slow);
1280 // Load next context in chain.
1281 __ movp(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1286 // All extension objects were empty and it is safe to use a normal global
1288 EmitGlobalVariableLoad(proxy, typeof_mode);
1292 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1294 DCHECK(var->IsContextSlot());
1295 Register context = rsi;
1296 Register temp = rbx;
1298 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1299 if (s->num_heap_slots() > 0) {
1300 if (s->calls_sloppy_eval()) {
1301 // Check that extension is NULL.
1302 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX),
1304 __ j(not_equal, slow);
1306 __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1307 // Walk the rest of the chain without clobbering rsi.
1311 // Check that last extension is NULL.
1312 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1313 __ j(not_equal, slow);
1315 // This function is used only for loads, not stores, so it's safe to
1316 // return an rsi-based operand (the write barrier cannot be allowed to
1317 // destroy the rsi register).
1318 return ContextOperand(context, var->index());
1322 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1323 TypeofMode typeof_mode,
1324 Label* slow, Label* done) {
1325 // Generate fast-case code for variables that might be shadowed by
1326 // eval-introduced variables. Eval is used a lot without
1327 // introducing variables. In those cases, we do not want to
1328 // perform a runtime call for all variables in the scope
1329 // containing the eval.
1330 Variable* var = proxy->var();
1331 if (var->mode() == DYNAMIC_GLOBAL) {
1332 EmitLoadGlobalCheckExtensions(proxy, typeof_mode, slow);
1334 } else if (var->mode() == DYNAMIC_LOCAL) {
1335 Variable* local = var->local_if_not_shadowed();
1336 __ movp(rax, ContextSlotOperandCheckExtensions(local, slow));
1337 if (local->mode() == LET || local->mode() == CONST ||
1338 local->mode() == CONST_LEGACY) {
1339 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
1340 __ j(not_equal, done);
1341 if (local->mode() == CONST_LEGACY) {
1342 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
1343 } else { // LET || CONST
1344 __ Push(var->name());
1345 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1353 void FullCodeGenerator::EmitGlobalVariableLoad(VariableProxy* proxy,
1354 TypeofMode typeof_mode) {
1355 Variable* var = proxy->var();
1356 DCHECK(var->IsUnallocatedOrGlobalSlot() ||
1357 (var->IsLookupSlot() && var->mode() == DYNAMIC_GLOBAL));
1358 if (var->IsGlobalSlot()) {
1359 DCHECK(var->index() > 0);
1360 DCHECK(var->IsStaticGlobalObjectProperty());
1361 int const slot = var->index();
1362 int const depth = scope()->ContextChainLength(var->scope());
1363 if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
1364 __ Set(LoadGlobalViaContextDescriptor::SlotRegister(), slot);
1365 LoadGlobalViaContextStub stub(isolate(), depth);
1368 __ Push(Smi::FromInt(slot));
1369 __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
1373 __ Move(LoadDescriptor::NameRegister(), var->name());
1374 __ movp(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1375 __ Move(LoadDescriptor::SlotRegister(),
1376 SmiFromSlot(proxy->VariableFeedbackSlot()));
1377 CallLoadIC(typeof_mode);
1382 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy,
1383 TypeofMode typeof_mode) {
1384 // Record position before possible IC call.
1385 SetExpressionPosition(proxy);
1386 PrepareForBailoutForId(proxy->BeforeId(), NO_REGISTERS);
1387 Variable* var = proxy->var();
1389 // Three cases: global variables, lookup variables, and all other types of
1391 switch (var->location()) {
1392 case VariableLocation::GLOBAL:
1393 case VariableLocation::UNALLOCATED: {
1394 Comment cmnt(masm_, "[ Global variable");
1395 EmitGlobalVariableLoad(proxy, typeof_mode);
1396 context()->Plug(rax);
1400 case VariableLocation::PARAMETER:
1401 case VariableLocation::LOCAL:
1402 case VariableLocation::CONTEXT: {
1403 DCHECK_EQ(NOT_INSIDE_TYPEOF, typeof_mode);
1404 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context slot"
1406 if (NeedsHoleCheckForLoad(proxy)) {
1407 // Let and const need a read barrier.
1410 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
1411 __ j(not_equal, &done, Label::kNear);
1412 if (var->mode() == LET || var->mode() == CONST) {
1413 // Throw a reference error when using an uninitialized let/const
1414 // binding in harmony mode.
1415 __ Push(var->name());
1416 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1418 // Uninitialized legacy const bindings are unholed.
1419 DCHECK(var->mode() == CONST_LEGACY);
1420 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
1423 context()->Plug(rax);
1426 context()->Plug(var);
1430 case VariableLocation::LOOKUP: {
1431 Comment cmnt(masm_, "[ Lookup slot");
1433 // Generate code for loading from variables potentially shadowed
1434 // by eval-introduced variables.
1435 EmitDynamicLookupFastCase(proxy, typeof_mode, &slow, &done);
1437 __ Push(rsi); // Context.
1438 __ Push(var->name());
1439 Runtime::FunctionId function_id =
1440 typeof_mode == NOT_INSIDE_TYPEOF
1441 ? Runtime::kLoadLookupSlot
1442 : Runtime::kLoadLookupSlotNoReferenceError;
1443 __ CallRuntime(function_id, 2);
1445 context()->Plug(rax);
1452 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1453 Comment cmnt(masm_, "[ RegExpLiteral");
1455 // Registers will be used as follows:
1456 // rdi = JS function.
1457 // rcx = literals array.
1458 // rbx = regexp literal.
1459 // rax = regexp literal clone.
1460 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1461 __ movp(rcx, FieldOperand(rdi, JSFunction::kLiteralsOffset));
1462 int literal_offset =
1463 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1464 __ movp(rbx, FieldOperand(rcx, literal_offset));
1465 __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex);
1466 __ j(not_equal, &materialized, Label::kNear);
1468 // Create regexp literal using runtime function
1469 // Result will be in rax.
1471 __ Push(Smi::FromInt(expr->literal_index()));
1472 __ Push(expr->pattern());
1473 __ Push(expr->flags());
1474 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1477 __ bind(&materialized);
1478 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1479 Label allocated, runtime_allocate;
1480 __ Allocate(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
1483 __ bind(&runtime_allocate);
1485 __ Push(Smi::FromInt(size));
1486 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1489 __ bind(&allocated);
1490 // Copy the content into the newly allocated memory.
1491 // (Unroll copy loop once for better throughput).
1492 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1493 __ movp(rdx, FieldOperand(rbx, i));
1494 __ movp(rcx, FieldOperand(rbx, i + kPointerSize));
1495 __ movp(FieldOperand(rax, i), rdx);
1496 __ movp(FieldOperand(rax, i + kPointerSize), rcx);
1498 if ((size % (2 * kPointerSize)) != 0) {
1499 __ movp(rdx, FieldOperand(rbx, size - kPointerSize));
1500 __ movp(FieldOperand(rax, size - kPointerSize), rdx);
1502 context()->Plug(rax);
1506 void FullCodeGenerator::EmitAccessor(ObjectLiteralProperty* property) {
1507 Expression* expression = (property == NULL) ? NULL : property->value();
1508 if (expression == NULL) {
1509 __ PushRoot(Heap::kNullValueRootIndex);
1511 VisitForStackValue(expression);
1512 if (NeedsHomeObject(expression)) {
1513 DCHECK(property->kind() == ObjectLiteral::Property::GETTER ||
1514 property->kind() == ObjectLiteral::Property::SETTER);
1515 int offset = property->kind() == ObjectLiteral::Property::GETTER ? 2 : 3;
1516 EmitSetHomeObject(expression, offset, property->GetSlot());
1522 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1523 Comment cmnt(masm_, "[ ObjectLiteral");
1525 Handle<FixedArray> constant_properties = expr->constant_properties();
1526 int flags = expr->ComputeFlags();
1527 if (MustCreateObjectLiteralWithRuntime(expr)) {
1528 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1529 __ Push(FieldOperand(rdi, JSFunction::kLiteralsOffset));
1530 __ Push(Smi::FromInt(expr->literal_index()));
1531 __ Push(constant_properties);
1532 __ Push(Smi::FromInt(flags));
1533 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1535 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1536 __ movp(rax, FieldOperand(rdi, JSFunction::kLiteralsOffset));
1537 __ Move(rbx, Smi::FromInt(expr->literal_index()));
1538 __ Move(rcx, constant_properties);
1539 __ Move(rdx, Smi::FromInt(flags));
1540 FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
1543 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1545 // If result_saved is true the result is on top of the stack. If
1546 // result_saved is false the result is in rax.
1547 bool result_saved = false;
1549 AccessorTable accessor_table(zone());
1550 int property_index = 0;
1551 for (; property_index < expr->properties()->length(); property_index++) {
1552 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1553 if (property->is_computed_name()) break;
1554 if (property->IsCompileTimeValue()) continue;
1556 Literal* key = property->key()->AsLiteral();
1557 Expression* value = property->value();
1558 if (!result_saved) {
1559 __ Push(rax); // Save result on the stack
1560 result_saved = true;
1562 switch (property->kind()) {
1563 case ObjectLiteral::Property::CONSTANT:
1565 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1566 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1568 case ObjectLiteral::Property::COMPUTED:
1569 // It is safe to use [[Put]] here because the boilerplate already
1570 // contains computed properties with an uninitialized value.
1571 if (key->value()->IsInternalizedString()) {
1572 if (property->emit_store()) {
1573 VisitForAccumulatorValue(value);
1574 DCHECK(StoreDescriptor::ValueRegister().is(rax));
1575 __ Move(StoreDescriptor::NameRegister(), key->value());
1576 __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1577 if (FLAG_vector_stores) {
1578 EmitLoadStoreICSlot(property->GetSlot(0));
1581 CallStoreIC(key->LiteralFeedbackId());
1583 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1585 if (NeedsHomeObject(value)) {
1586 EmitSetHomeObjectAccumulator(value, 0, property->GetSlot(1));
1589 VisitForEffect(value);
1593 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1594 VisitForStackValue(key);
1595 VisitForStackValue(value);
1596 if (property->emit_store()) {
1597 if (NeedsHomeObject(value)) {
1598 EmitSetHomeObject(value, 2, property->GetSlot());
1600 __ Push(Smi::FromInt(SLOPPY)); // Language mode
1601 __ CallRuntime(Runtime::kSetProperty, 4);
1606 case ObjectLiteral::Property::PROTOTYPE:
1607 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1608 VisitForStackValue(value);
1609 DCHECK(property->emit_store());
1610 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1612 case ObjectLiteral::Property::GETTER:
1613 if (property->emit_store()) {
1614 accessor_table.lookup(key)->second->getter = property;
1617 case ObjectLiteral::Property::SETTER:
1618 if (property->emit_store()) {
1619 accessor_table.lookup(key)->second->setter = property;
1625 // Emit code to define accessors, using only a single call to the runtime for
1626 // each pair of corresponding getters and setters.
1627 for (AccessorTable::Iterator it = accessor_table.begin();
1628 it != accessor_table.end();
1630 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1631 VisitForStackValue(it->first);
1632 EmitAccessor(it->second->getter);
1633 EmitAccessor(it->second->setter);
1634 __ Push(Smi::FromInt(NONE));
1635 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1638 // Object literals have two parts. The "static" part on the left contains no
1639 // computed property names, and so we can compute its map ahead of time; see
1640 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1641 // starts with the first computed property name, and continues with all
1642 // properties to its right. All the code from above initializes the static
1643 // component of the object literal, and arranges for the map of the result to
1644 // reflect the static order in which the keys appear. For the dynamic
1645 // properties, we compile them into a series of "SetOwnProperty" runtime
1646 // calls. This will preserve insertion order.
1647 for (; property_index < expr->properties()->length(); property_index++) {
1648 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1650 Expression* value = property->value();
1651 if (!result_saved) {
1652 __ Push(rax); // Save result on the stack
1653 result_saved = true;
1656 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1658 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1659 DCHECK(!property->is_computed_name());
1660 VisitForStackValue(value);
1661 DCHECK(property->emit_store());
1662 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1664 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1665 VisitForStackValue(value);
1666 if (NeedsHomeObject(value)) {
1667 EmitSetHomeObject(value, 2, property->GetSlot());
1670 switch (property->kind()) {
1671 case ObjectLiteral::Property::CONSTANT:
1672 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1673 case ObjectLiteral::Property::COMPUTED:
1674 if (property->emit_store()) {
1675 __ Push(Smi::FromInt(NONE));
1676 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1682 case ObjectLiteral::Property::PROTOTYPE:
1686 case ObjectLiteral::Property::GETTER:
1687 __ Push(Smi::FromInt(NONE));
1688 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1691 case ObjectLiteral::Property::SETTER:
1692 __ Push(Smi::FromInt(NONE));
1693 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1699 if (expr->has_function()) {
1700 DCHECK(result_saved);
1701 __ Push(Operand(rsp, 0));
1702 __ CallRuntime(Runtime::kToFastProperties, 1);
1706 context()->PlugTOS();
1708 context()->Plug(rax);
1713 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1714 Comment cmnt(masm_, "[ ArrayLiteral");
1716 expr->BuildConstantElements(isolate());
1717 Handle<FixedArray> constant_elements = expr->constant_elements();
1718 bool has_constant_fast_elements =
1719 IsFastObjectElementsKind(expr->constant_elements_kind());
1721 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1722 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1723 // If the only customer of allocation sites is transitioning, then
1724 // we can turn it off if we don't have anywhere else to transition to.
1725 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1728 if (MustCreateArrayLiteralWithRuntime(expr)) {
1729 __ movp(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1730 __ Push(FieldOperand(rbx, JSFunction::kLiteralsOffset));
1731 __ Push(Smi::FromInt(expr->literal_index()));
1732 __ Push(constant_elements);
1733 __ Push(Smi::FromInt(expr->ComputeFlags()));
1734 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1736 __ movp(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1737 __ movp(rax, FieldOperand(rbx, JSFunction::kLiteralsOffset));
1738 __ Move(rbx, Smi::FromInt(expr->literal_index()));
1739 __ Move(rcx, constant_elements);
1740 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1743 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1745 bool result_saved = false; // Is the result saved to the stack?
1746 ZoneList<Expression*>* subexprs = expr->values();
1747 int length = subexprs->length();
1749 // Emit code to evaluate all the non-constant subexpressions and to store
1750 // them into the newly cloned array.
1751 int array_index = 0;
1752 for (; array_index < length; array_index++) {
1753 Expression* subexpr = subexprs->at(array_index);
1754 if (subexpr->IsSpread()) break;
1756 // If the subexpression is a literal or a simple materialized literal it
1757 // is already set in the cloned array.
1758 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1760 if (!result_saved) {
1761 __ Push(rax); // array literal
1762 __ Push(Smi::FromInt(expr->literal_index()));
1763 result_saved = true;
1765 VisitForAccumulatorValue(subexpr);
1767 if (has_constant_fast_elements) {
1768 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1769 // cannot transition and don't need to call the runtime stub.
1770 int offset = FixedArray::kHeaderSize + (array_index * kPointerSize);
1771 __ movp(rbx, Operand(rsp, kPointerSize)); // Copy of array literal.
1772 __ movp(rbx, FieldOperand(rbx, JSObject::kElementsOffset));
1773 // Store the subexpression value in the array's elements.
1774 __ movp(FieldOperand(rbx, offset), result_register());
1775 // Update the write barrier for the array store.
1776 __ RecordWriteField(rbx, offset, result_register(), rcx,
1778 EMIT_REMEMBERED_SET,
1781 // Store the subexpression value in the array's elements.
1782 __ Move(rcx, Smi::FromInt(array_index));
1783 StoreArrayLiteralElementStub stub(isolate());
1787 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1790 // In case the array literal contains spread expressions it has two parts. The
1791 // first part is the "static" array which has a literal index is handled
1792 // above. The second part is the part after the first spread expression
1793 // (inclusive) and these elements gets appended to the array. Note that the
1794 // number elements an iterable produces is unknown ahead of time.
1795 if (array_index < length && result_saved) {
1796 __ Drop(1); // literal index
1798 result_saved = false;
1800 for (; array_index < length; array_index++) {
1801 Expression* subexpr = subexprs->at(array_index);
1804 if (subexpr->IsSpread()) {
1805 VisitForStackValue(subexpr->AsSpread()->expression());
1806 __ InvokeBuiltin(Context::CONCAT_ITERABLE_TO_ARRAY_BUILTIN_INDEX,
1809 VisitForStackValue(subexpr);
1810 __ CallRuntime(Runtime::kAppendElement, 2);
1813 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1817 __ Drop(1); // literal index
1818 context()->PlugTOS();
1820 context()->Plug(rax);
1825 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1826 DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
1828 Comment cmnt(masm_, "[ Assignment");
1829 SetExpressionPosition(expr, INSERT_BREAK);
1831 Property* property = expr->target()->AsProperty();
1832 LhsKind assign_type = Property::GetAssignType(property);
1834 // Evaluate LHS expression.
1835 switch (assign_type) {
1837 // Nothing to do here.
1839 case NAMED_PROPERTY:
1840 if (expr->is_compound()) {
1841 // We need the receiver both on the stack and in the register.
1842 VisitForStackValue(property->obj());
1843 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
1845 VisitForStackValue(property->obj());
1848 case NAMED_SUPER_PROPERTY:
1850 property->obj()->AsSuperPropertyReference()->this_var());
1851 VisitForAccumulatorValue(
1852 property->obj()->AsSuperPropertyReference()->home_object());
1853 __ Push(result_register());
1854 if (expr->is_compound()) {
1855 __ Push(MemOperand(rsp, kPointerSize));
1856 __ Push(result_register());
1859 case KEYED_SUPER_PROPERTY:
1861 property->obj()->AsSuperPropertyReference()->this_var());
1863 property->obj()->AsSuperPropertyReference()->home_object());
1864 VisitForAccumulatorValue(property->key());
1865 __ Push(result_register());
1866 if (expr->is_compound()) {
1867 __ Push(MemOperand(rsp, 2 * kPointerSize));
1868 __ Push(MemOperand(rsp, 2 * kPointerSize));
1869 __ Push(result_register());
1872 case KEYED_PROPERTY: {
1873 if (expr->is_compound()) {
1874 VisitForStackValue(property->obj());
1875 VisitForStackValue(property->key());
1876 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
1877 __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
1879 VisitForStackValue(property->obj());
1880 VisitForStackValue(property->key());
1886 // For compound assignments we need another deoptimization point after the
1887 // variable/property load.
1888 if (expr->is_compound()) {
1889 { AccumulatorValueContext context(this);
1890 switch (assign_type) {
1892 EmitVariableLoad(expr->target()->AsVariableProxy());
1893 PrepareForBailout(expr->target(), TOS_REG);
1895 case NAMED_PROPERTY:
1896 EmitNamedPropertyLoad(property);
1897 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1899 case NAMED_SUPER_PROPERTY:
1900 EmitNamedSuperPropertyLoad(property);
1901 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1903 case KEYED_SUPER_PROPERTY:
1904 EmitKeyedSuperPropertyLoad(property);
1905 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1907 case KEYED_PROPERTY:
1908 EmitKeyedPropertyLoad(property);
1909 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1914 Token::Value op = expr->binary_op();
1915 __ Push(rax); // Left operand goes on the stack.
1916 VisitForAccumulatorValue(expr->value());
1918 AccumulatorValueContext context(this);
1919 if (ShouldInlineSmiCase(op)) {
1920 EmitInlineSmiBinaryOp(expr->binary_operation(),
1925 EmitBinaryOp(expr->binary_operation(), op);
1927 // Deoptimization point in case the binary operation may have side effects.
1928 PrepareForBailout(expr->binary_operation(), TOS_REG);
1930 VisitForAccumulatorValue(expr->value());
1933 SetExpressionPosition(expr);
1936 switch (assign_type) {
1938 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1939 expr->op(), expr->AssignmentSlot());
1940 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
1941 context()->Plug(rax);
1943 case NAMED_PROPERTY:
1944 EmitNamedPropertyAssignment(expr);
1946 case NAMED_SUPER_PROPERTY:
1947 EmitNamedSuperPropertyStore(property);
1948 context()->Plug(rax);
1950 case KEYED_SUPER_PROPERTY:
1951 EmitKeyedSuperPropertyStore(property);
1952 context()->Plug(rax);
1954 case KEYED_PROPERTY:
1955 EmitKeyedPropertyAssignment(expr);
1961 void FullCodeGenerator::VisitYield(Yield* expr) {
1962 Comment cmnt(masm_, "[ Yield");
1963 SetExpressionPosition(expr);
1965 // Evaluate yielded value first; the initial iterator definition depends on
1966 // this. It stays on the stack while we update the iterator.
1967 VisitForStackValue(expr->expression());
1969 switch (expr->yield_kind()) {
1970 case Yield::kSuspend:
1971 // Pop value from top-of-stack slot; box result into result register.
1972 EmitCreateIteratorResult(false);
1973 __ Push(result_register());
1975 case Yield::kInitial: {
1976 Label suspend, continuation, post_runtime, resume;
1979 __ bind(&continuation);
1980 __ RecordGeneratorContinuation();
1984 VisitForAccumulatorValue(expr->generator_object());
1985 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
1986 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
1987 Smi::FromInt(continuation.pos()));
1988 __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
1990 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
1992 __ leap(rbx, Operand(rbp, StandardFrameConstants::kExpressionsOffset));
1994 __ j(equal, &post_runtime);
1995 __ Push(rax); // generator object
1996 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
1997 __ movp(context_register(),
1998 Operand(rbp, StandardFrameConstants::kContextOffset));
1999 __ bind(&post_runtime);
2001 __ Pop(result_register());
2002 EmitReturnSequence();
2005 context()->Plug(result_register());
2009 case Yield::kFinal: {
2010 VisitForAccumulatorValue(expr->generator_object());
2011 __ Move(FieldOperand(result_register(),
2012 JSGeneratorObject::kContinuationOffset),
2013 Smi::FromInt(JSGeneratorObject::kGeneratorClosed));
2014 // Pop value from top-of-stack slot, box result into result register.
2015 EmitCreateIteratorResult(true);
2016 EmitUnwindBeforeReturn();
2017 EmitReturnSequence();
2021 case Yield::kDelegating: {
2022 VisitForStackValue(expr->generator_object());
2024 // Initial stack layout is as follows:
2025 // [sp + 1 * kPointerSize] iter
2026 // [sp + 0 * kPointerSize] g
2028 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2029 Label l_next, l_call, l_loop;
2030 Register load_receiver = LoadDescriptor::ReceiverRegister();
2031 Register load_name = LoadDescriptor::NameRegister();
2033 // Initial send value is undefined.
2034 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
2037 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2039 __ LoadRoot(load_name, Heap::kthrow_stringRootIndex); // "throw"
2041 __ Push(Operand(rsp, 2 * kPointerSize)); // iter
2042 __ Push(rax); // exception
2045 // try { received = %yield result }
2046 // Shuffle the received result above a try handler and yield it without
2049 __ Pop(rax); // result
2050 int handler_index = NewHandlerTableEntry();
2051 EnterTryBlock(handler_index, &l_catch);
2052 const int try_block_size = TryCatch::kElementCount * kPointerSize;
2053 __ Push(rax); // result
2056 __ bind(&l_continuation);
2057 __ RecordGeneratorContinuation();
2060 __ bind(&l_suspend);
2061 const int generator_object_depth = kPointerSize + try_block_size;
2062 __ movp(rax, Operand(rsp, generator_object_depth));
2064 __ Push(Smi::FromInt(handler_index)); // handler-index
2065 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2066 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
2067 Smi::FromInt(l_continuation.pos()));
2068 __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
2070 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
2072 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
2073 __ movp(context_register(),
2074 Operand(rbp, StandardFrameConstants::kContextOffset));
2075 __ Pop(rax); // result
2076 EmitReturnSequence();
2077 __ bind(&l_resume); // received in rax
2078 ExitTryBlock(handler_index);
2080 // receiver = iter; f = 'next'; arg = received;
2083 __ LoadRoot(load_name, Heap::knext_stringRootIndex);
2084 __ Push(load_name); // "next"
2085 __ Push(Operand(rsp, 2 * kPointerSize)); // iter
2086 __ Push(rax); // received
2088 // result = receiver[f](arg);
2090 __ movp(load_receiver, Operand(rsp, kPointerSize));
2091 __ Move(LoadDescriptor::SlotRegister(),
2092 SmiFromSlot(expr->KeyedLoadFeedbackSlot()));
2093 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), SLOPPY).code();
2094 CallIC(ic, TypeFeedbackId::None());
2096 __ movp(Operand(rsp, 2 * kPointerSize), rdi);
2098 SetCallPosition(expr, 1);
2099 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2102 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2103 __ Drop(1); // The function is still on the stack; drop it.
2105 // if (!result.done) goto l_try;
2107 __ Move(load_receiver, rax);
2108 __ Push(load_receiver); // save result
2109 __ LoadRoot(load_name, Heap::kdone_stringRootIndex); // "done"
2110 __ Move(LoadDescriptor::SlotRegister(),
2111 SmiFromSlot(expr->DoneFeedbackSlot()));
2112 CallLoadIC(NOT_INSIDE_TYPEOF); // rax=result.done
2113 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2115 __ testp(result_register(), result_register());
2119 __ Pop(load_receiver); // result
2120 __ LoadRoot(load_name, Heap::kvalue_stringRootIndex); // "value"
2121 __ Move(LoadDescriptor::SlotRegister(),
2122 SmiFromSlot(expr->ValueFeedbackSlot()));
2123 CallLoadIC(NOT_INSIDE_TYPEOF); // result.value in rax
2124 context()->DropAndPlug(2, rax); // drop iter and g
2131 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2133 JSGeneratorObject::ResumeMode resume_mode) {
2134 // The value stays in rax, and is ultimately read by the resumed generator, as
2135 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2136 // is read to throw the value when the resumed generator is already closed.
2137 // rbx will hold the generator object until the activation has been resumed.
2138 VisitForStackValue(generator);
2139 VisitForAccumulatorValue(value);
2142 // Load suspended function and context.
2143 __ movp(rsi, FieldOperand(rbx, JSGeneratorObject::kContextOffset));
2144 __ movp(rdi, FieldOperand(rbx, JSGeneratorObject::kFunctionOffset));
2147 __ Push(FieldOperand(rbx, JSGeneratorObject::kReceiverOffset));
2149 // Push holes for arguments to generator function.
2150 __ movp(rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
2151 __ LoadSharedFunctionInfoSpecialField(rdx, rdx,
2152 SharedFunctionInfo::kFormalParameterCountOffset);
2153 __ LoadRoot(rcx, Heap::kTheHoleValueRootIndex);
2154 Label push_argument_holes, push_frame;
2155 __ bind(&push_argument_holes);
2156 __ subp(rdx, Immediate(1));
2157 __ j(carry, &push_frame);
2159 __ jmp(&push_argument_holes);
2161 // Enter a new JavaScript frame, and initialize its slots as they were when
2162 // the generator was suspended.
2163 Label resume_frame, done;
2164 __ bind(&push_frame);
2165 __ call(&resume_frame);
2167 __ bind(&resume_frame);
2168 __ pushq(rbp); // Caller's frame pointer.
2170 __ Push(rsi); // Callee's context.
2171 __ Push(rdi); // Callee's JS Function.
2173 // Load the operand stack size.
2174 __ movp(rdx, FieldOperand(rbx, JSGeneratorObject::kOperandStackOffset));
2175 __ movp(rdx, FieldOperand(rdx, FixedArray::kLengthOffset));
2176 __ SmiToInteger32(rdx, rdx);
2178 // If we are sending a value and there is no operand stack, we can jump back
2180 if (resume_mode == JSGeneratorObject::NEXT) {
2182 __ cmpp(rdx, Immediate(0));
2183 __ j(not_zero, &slow_resume);
2184 __ movp(rdx, FieldOperand(rdi, JSFunction::kCodeEntryOffset));
2185 __ SmiToInteger64(rcx,
2186 FieldOperand(rbx, JSGeneratorObject::kContinuationOffset));
2188 __ Move(FieldOperand(rbx, JSGeneratorObject::kContinuationOffset),
2189 Smi::FromInt(JSGeneratorObject::kGeneratorExecuting));
2191 __ bind(&slow_resume);
2194 // Otherwise, we push holes for the operand stack and call the runtime to fix
2195 // up the stack and the handlers.
2196 Label push_operand_holes, call_resume;
2197 __ bind(&push_operand_holes);
2198 __ subp(rdx, Immediate(1));
2199 __ j(carry, &call_resume);
2201 __ jmp(&push_operand_holes);
2202 __ bind(&call_resume);
2204 __ Push(result_register());
2205 __ Push(Smi::FromInt(resume_mode));
2206 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2207 // Not reached: the runtime call returns elsewhere.
2208 __ Abort(kGeneratorFailedToResume);
2211 context()->Plug(result_register());
2215 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2216 Label allocate, done_allocate;
2218 __ Allocate(JSIteratorResult::kSize, rax, rcx, rdx, &allocate, TAG_OBJECT);
2219 __ jmp(&done_allocate, Label::kNear);
2222 __ Push(Smi::FromInt(JSIteratorResult::kSize));
2223 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2225 __ bind(&done_allocate);
2226 __ movp(rbx, GlobalObjectOperand());
2227 __ movp(rbx, FieldOperand(rbx, GlobalObject::kNativeContextOffset));
2228 __ movp(rbx, ContextOperand(rbx, Context::ITERATOR_RESULT_MAP_INDEX));
2229 __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
2230 __ LoadRoot(rbx, Heap::kEmptyFixedArrayRootIndex);
2231 __ movp(FieldOperand(rax, JSObject::kPropertiesOffset), rbx);
2232 __ movp(FieldOperand(rax, JSObject::kElementsOffset), rbx);
2233 __ Pop(FieldOperand(rax, JSIteratorResult::kValueOffset));
2234 __ LoadRoot(FieldOperand(rax, JSIteratorResult::kDoneOffset),
2235 done ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex);
2236 STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
2240 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2241 SetExpressionPosition(prop);
2242 Literal* key = prop->key()->AsLiteral();
2243 DCHECK(!prop->IsSuperAccess());
2245 // See comment below.
2246 if (FeedbackVector()->GetIndex(prop->PropertyFeedbackSlot()) == 6) {
2247 __ Push(LoadDescriptor::ReceiverRegister());
2250 __ Move(LoadDescriptor::NameRegister(), key->value());
2251 __ Move(LoadDescriptor::SlotRegister(),
2252 SmiFromSlot(prop->PropertyFeedbackSlot()));
2253 CallLoadIC(NOT_INSIDE_TYPEOF, language_mode());
2255 // Sanity check: The loaded value must be a JS-exposed kind of object,
2256 // not something internal (like a Map, or FixedArray). Check this here
2257 // to chase after a rare but recurring crash bug. It seems to always
2258 // occur for functions beginning with "this.foo.bar()", so be selective
2259 // and only insert the check for the first LoadIC (identified by slot).
2260 // TODO(jkummerow): Remove this when it has generated a few crash reports.
2261 // Don't forget to remove the Push() above as well!
2262 if (FeedbackVector()->GetIndex(prop->PropertyFeedbackSlot()) == 6) {
2263 __ Pop(LoadDescriptor::ReceiverRegister());
2266 __ JumpIfSmi(rax, &ok, Label::kNear);
2267 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
2268 __ CmpInstanceType(rbx, LAST_PRIMITIVE_TYPE);
2269 __ j(below_equal, &ok, Label::kNear);
2270 __ CmpInstanceType(rbx, FIRST_JS_RECEIVER_TYPE);
2271 __ j(above_equal, &ok, Label::kNear);
2273 __ Push(Smi::FromInt(0xaabbccdd));
2274 __ Push(LoadDescriptor::ReceiverRegister());
2275 __ movp(rbx, FieldOperand(LoadDescriptor::ReceiverRegister(),
2276 HeapObject::kMapOffset));
2278 __ movp(rbx, FieldOperand(LoadDescriptor::ReceiverRegister(),
2279 JSObject::kPropertiesOffset));
2288 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2289 // Stack: receiver, home_object
2290 SetExpressionPosition(prop);
2291 Literal* key = prop->key()->AsLiteral();
2292 DCHECK(!key->value()->IsSmi());
2293 DCHECK(prop->IsSuperAccess());
2295 __ Push(key->value());
2296 __ Push(Smi::FromInt(language_mode()));
2297 __ CallRuntime(Runtime::kLoadFromSuper, 4);
2301 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2302 SetExpressionPosition(prop);
2303 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), language_mode()).code();
2304 __ Move(LoadDescriptor::SlotRegister(),
2305 SmiFromSlot(prop->PropertyFeedbackSlot()));
2310 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2311 // Stack: receiver, home_object, key.
2312 SetExpressionPosition(prop);
2313 __ Push(Smi::FromInt(language_mode()));
2314 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2318 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2321 Expression* right) {
2322 // Do combined smi check of the operands. Left operand is on the
2323 // stack (popped into rdx). Right operand is in rax but moved into
2324 // rcx to make the shifts easier.
2325 Label done, stub_call, smi_case;
2329 JumpPatchSite patch_site(masm_);
2330 patch_site.EmitJumpIfSmi(rax, &smi_case, Label::kNear);
2332 __ bind(&stub_call);
2335 CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2336 CallIC(code, expr->BinaryOperationFeedbackId());
2337 patch_site.EmitPatchInfo();
2338 __ jmp(&done, Label::kNear);
2343 __ SmiShiftArithmeticRight(rax, rdx, rcx);
2346 __ SmiShiftLeft(rax, rdx, rcx, &stub_call);
2349 __ SmiShiftLogicalRight(rax, rdx, rcx, &stub_call);
2352 __ SmiAdd(rax, rdx, rcx, &stub_call);
2355 __ SmiSub(rax, rdx, rcx, &stub_call);
2358 __ SmiMul(rax, rdx, rcx, &stub_call);
2361 __ SmiOr(rax, rdx, rcx);
2363 case Token::BIT_AND:
2364 __ SmiAnd(rax, rdx, rcx);
2366 case Token::BIT_XOR:
2367 __ SmiXor(rax, rdx, rcx);
2375 context()->Plug(rax);
2379 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2380 // Constructor is in rax.
2381 DCHECK(lit != NULL);
2384 // No access check is needed here since the constructor is created by the
2386 Register scratch = rbx;
2387 __ movp(scratch, FieldOperand(rax, JSFunction::kPrototypeOrInitialMapOffset));
2390 for (int i = 0; i < lit->properties()->length(); i++) {
2391 ObjectLiteral::Property* property = lit->properties()->at(i);
2392 Expression* value = property->value();
2394 if (property->is_static()) {
2395 __ Push(Operand(rsp, kPointerSize)); // constructor
2397 __ Push(Operand(rsp, 0)); // prototype
2399 EmitPropertyKey(property, lit->GetIdForProperty(i));
2401 // The static prototype property is read only. We handle the non computed
2402 // property name case in the parser. Since this is the only case where we
2403 // need to check for an own read only property we special case this so we do
2404 // not need to do this for every property.
2405 if (property->is_static() && property->is_computed_name()) {
2406 __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
2410 VisitForStackValue(value);
2411 if (NeedsHomeObject(value)) {
2412 EmitSetHomeObject(value, 2, property->GetSlot());
2415 switch (property->kind()) {
2416 case ObjectLiteral::Property::CONSTANT:
2417 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2418 case ObjectLiteral::Property::PROTOTYPE:
2420 case ObjectLiteral::Property::COMPUTED:
2421 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2424 case ObjectLiteral::Property::GETTER:
2425 __ Push(Smi::FromInt(DONT_ENUM));
2426 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2429 case ObjectLiteral::Property::SETTER:
2430 __ Push(Smi::FromInt(DONT_ENUM));
2431 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2439 // Set both the prototype and constructor to have fast properties, and also
2440 // freeze them in strong mode.
2441 __ CallRuntime(Runtime::kFinalizeClassDefinition, 2);
2445 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2448 CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2449 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2450 CallIC(code, expr->BinaryOperationFeedbackId());
2451 patch_site.EmitPatchInfo();
2452 context()->Plug(rax);
2456 void FullCodeGenerator::EmitAssignment(Expression* expr,
2457 FeedbackVectorICSlot slot) {
2458 DCHECK(expr->IsValidReferenceExpressionOrThis());
2460 Property* prop = expr->AsProperty();
2461 LhsKind assign_type = Property::GetAssignType(prop);
2463 switch (assign_type) {
2465 Variable* var = expr->AsVariableProxy()->var();
2466 EffectContext context(this);
2467 EmitVariableAssignment(var, Token::ASSIGN, slot);
2470 case NAMED_PROPERTY: {
2471 __ Push(rax); // Preserve value.
2472 VisitForAccumulatorValue(prop->obj());
2473 __ Move(StoreDescriptor::ReceiverRegister(), rax);
2474 __ Pop(StoreDescriptor::ValueRegister()); // Restore value.
2475 __ Move(StoreDescriptor::NameRegister(),
2476 prop->key()->AsLiteral()->value());
2477 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2481 case NAMED_SUPER_PROPERTY: {
2483 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2484 VisitForAccumulatorValue(
2485 prop->obj()->AsSuperPropertyReference()->home_object());
2486 // stack: value, this; rax: home_object
2487 Register scratch = rcx;
2488 Register scratch2 = rdx;
2489 __ Move(scratch, result_register()); // home_object
2490 __ movp(rax, MemOperand(rsp, kPointerSize)); // value
2491 __ movp(scratch2, MemOperand(rsp, 0)); // this
2492 __ movp(MemOperand(rsp, kPointerSize), scratch2); // this
2493 __ movp(MemOperand(rsp, 0), scratch); // home_object
2494 // stack: this, home_object; rax: value
2495 EmitNamedSuperPropertyStore(prop);
2498 case KEYED_SUPER_PROPERTY: {
2500 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2502 prop->obj()->AsSuperPropertyReference()->home_object());
2503 VisitForAccumulatorValue(prop->key());
2504 Register scratch = rcx;
2505 Register scratch2 = rdx;
2506 __ movp(scratch2, MemOperand(rsp, 2 * kPointerSize)); // value
2507 // stack: value, this, home_object; rax: key, rdx: value
2508 __ movp(scratch, MemOperand(rsp, kPointerSize)); // this
2509 __ movp(MemOperand(rsp, 2 * kPointerSize), scratch);
2510 __ movp(scratch, MemOperand(rsp, 0)); // home_object
2511 __ movp(MemOperand(rsp, kPointerSize), scratch);
2512 __ movp(MemOperand(rsp, 0), rax);
2513 __ Move(rax, scratch2);
2514 // stack: this, home_object, key; rax: value.
2515 EmitKeyedSuperPropertyStore(prop);
2518 case KEYED_PROPERTY: {
2519 __ Push(rax); // Preserve value.
2520 VisitForStackValue(prop->obj());
2521 VisitForAccumulatorValue(prop->key());
2522 __ Move(StoreDescriptor::NameRegister(), rax);
2523 __ Pop(StoreDescriptor::ReceiverRegister());
2524 __ Pop(StoreDescriptor::ValueRegister()); // Restore value.
2525 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2527 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2532 context()->Plug(rax);
2536 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2537 Variable* var, MemOperand location) {
2538 __ movp(location, rax);
2539 if (var->IsContextSlot()) {
2541 __ RecordWriteContextSlot(
2542 rcx, Context::SlotOffset(var->index()), rdx, rbx, kDontSaveFPRegs);
2547 void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
2548 FeedbackVectorICSlot slot) {
2549 if (var->IsUnallocated()) {
2550 // Global var, const, or let.
2551 __ Move(StoreDescriptor::NameRegister(), var->name());
2552 __ movp(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2553 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2556 } else if (var->IsGlobalSlot()) {
2557 // Global var, const, or let.
2558 DCHECK(var->index() > 0);
2559 DCHECK(var->IsStaticGlobalObjectProperty());
2560 int const slot = var->index();
2561 int const depth = scope()->ContextChainLength(var->scope());
2562 if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
2563 __ Set(StoreGlobalViaContextDescriptor::SlotRegister(), slot);
2564 DCHECK(StoreGlobalViaContextDescriptor::ValueRegister().is(rax));
2565 StoreGlobalViaContextStub stub(isolate(), depth, language_mode());
2568 __ Push(Smi::FromInt(slot));
2570 __ CallRuntime(is_strict(language_mode())
2571 ? Runtime::kStoreGlobalViaContext_Strict
2572 : Runtime::kStoreGlobalViaContext_Sloppy,
2576 } else if (var->mode() == LET && op != Token::INIT_LET) {
2577 // Non-initializing assignment to let variable needs a write barrier.
2578 DCHECK(!var->IsLookupSlot());
2579 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2581 MemOperand location = VarOperand(var, rcx);
2582 __ movp(rdx, location);
2583 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2584 __ j(not_equal, &assign, Label::kNear);
2585 __ Push(var->name());
2586 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2588 EmitStoreToStackLocalOrContextSlot(var, location);
2590 } else if (var->mode() == CONST && op != Token::INIT_CONST) {
2591 // Assignment to const variable needs a write barrier.
2592 DCHECK(!var->IsLookupSlot());
2593 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2595 MemOperand location = VarOperand(var, rcx);
2596 __ movp(rdx, location);
2597 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2598 __ j(not_equal, &const_error, Label::kNear);
2599 __ Push(var->name());
2600 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2601 __ bind(&const_error);
2602 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2604 } else if (var->is_this() && op == Token::INIT_CONST) {
2605 // Initializing assignment to const {this} needs a write barrier.
2606 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2607 Label uninitialized_this;
2608 MemOperand location = VarOperand(var, rcx);
2609 __ movp(rdx, location);
2610 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2611 __ j(equal, &uninitialized_this);
2612 __ Push(var->name());
2613 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2614 __ bind(&uninitialized_this);
2615 EmitStoreToStackLocalOrContextSlot(var, location);
2617 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2618 if (var->IsLookupSlot()) {
2619 // Assignment to var.
2620 __ Push(rax); // Value.
2621 __ Push(rsi); // Context.
2622 __ Push(var->name());
2623 __ Push(Smi::FromInt(language_mode()));
2624 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2626 // Assignment to var or initializing assignment to let/const in harmony
2628 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2629 MemOperand location = VarOperand(var, rcx);
2630 if (generate_debug_code_ && op == Token::INIT_LET) {
2631 // Check for an uninitialized let binding.
2632 __ movp(rdx, location);
2633 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2634 __ Check(equal, kLetBindingReInitialization);
2636 EmitStoreToStackLocalOrContextSlot(var, location);
2639 } else if (op == Token::INIT_CONST_LEGACY) {
2640 // Const initializers need a write barrier.
2641 DCHECK(var->mode() == CONST_LEGACY);
2642 DCHECK(!var->IsParameter()); // No const parameters.
2643 if (var->IsLookupSlot()) {
2646 __ Push(var->name());
2647 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2649 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2651 MemOperand location = VarOperand(var, rcx);
2652 __ movp(rdx, location);
2653 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2654 __ j(not_equal, &skip);
2655 EmitStoreToStackLocalOrContextSlot(var, location);
2660 DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
2661 if (is_strict(language_mode())) {
2662 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2664 // Silently ignore store in sloppy mode.
2669 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2670 // Assignment to a property, using a named store IC.
2671 Property* prop = expr->target()->AsProperty();
2672 DCHECK(prop != NULL);
2673 DCHECK(prop->key()->IsLiteral());
2675 __ Move(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2676 __ Pop(StoreDescriptor::ReceiverRegister());
2677 if (FLAG_vector_stores) {
2678 EmitLoadStoreICSlot(expr->AssignmentSlot());
2681 CallStoreIC(expr->AssignmentFeedbackId());
2684 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2685 context()->Plug(rax);
2689 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2690 // Assignment to named property of super.
2692 // stack : receiver ('this'), home_object
2693 DCHECK(prop != NULL);
2694 Literal* key = prop->key()->AsLiteral();
2695 DCHECK(key != NULL);
2697 __ Push(key->value());
2699 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2700 : Runtime::kStoreToSuper_Sloppy),
2705 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2706 // Assignment to named property of super.
2708 // stack : receiver ('this'), home_object, key
2709 DCHECK(prop != NULL);
2713 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2714 : Runtime::kStoreKeyedToSuper_Sloppy),
2719 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2720 // Assignment to a property, using a keyed store IC.
2721 __ Pop(StoreDescriptor::NameRegister()); // Key.
2722 __ Pop(StoreDescriptor::ReceiverRegister());
2723 DCHECK(StoreDescriptor::ValueRegister().is(rax));
2725 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2726 if (FLAG_vector_stores) {
2727 EmitLoadStoreICSlot(expr->AssignmentSlot());
2730 CallIC(ic, expr->AssignmentFeedbackId());
2733 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2734 context()->Plug(rax);
2738 void FullCodeGenerator::VisitProperty(Property* expr) {
2739 Comment cmnt(masm_, "[ Property");
2740 SetExpressionPosition(expr);
2742 Expression* key = expr->key();
2744 if (key->IsPropertyName()) {
2745 if (!expr->IsSuperAccess()) {
2746 VisitForAccumulatorValue(expr->obj());
2747 DCHECK(!rax.is(LoadDescriptor::ReceiverRegister()));
2748 __ movp(LoadDescriptor::ReceiverRegister(), rax);
2749 EmitNamedPropertyLoad(expr);
2751 VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
2753 expr->obj()->AsSuperPropertyReference()->home_object());
2754 EmitNamedSuperPropertyLoad(expr);
2757 if (!expr->IsSuperAccess()) {
2758 VisitForStackValue(expr->obj());
2759 VisitForAccumulatorValue(expr->key());
2760 __ Move(LoadDescriptor::NameRegister(), rax);
2761 __ Pop(LoadDescriptor::ReceiverRegister());
2762 EmitKeyedPropertyLoad(expr);
2764 VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
2766 expr->obj()->AsSuperPropertyReference()->home_object());
2767 VisitForStackValue(expr->key());
2768 EmitKeyedSuperPropertyLoad(expr);
2771 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2772 context()->Plug(rax);
2776 void FullCodeGenerator::CallIC(Handle<Code> code,
2777 TypeFeedbackId ast_id) {
2779 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2783 // Code common for calls using the IC.
2784 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2785 Expression* callee = expr->expression();
2787 CallICState::CallType call_type =
2788 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2789 // Get the target function.
2790 if (call_type == CallICState::FUNCTION) {
2791 { StackValueContext context(this);
2792 EmitVariableLoad(callee->AsVariableProxy());
2793 PrepareForBailout(callee, NO_REGISTERS);
2795 // Push undefined as receiver. This is patched in the method prologue if it
2796 // is a sloppy mode method.
2797 __ Push(isolate()->factory()->undefined_value());
2799 // Load the function from the receiver.
2800 DCHECK(callee->IsProperty());
2801 DCHECK(!callee->AsProperty()->IsSuperAccess());
2802 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
2803 EmitNamedPropertyLoad(callee->AsProperty());
2804 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2805 // Push the target function under the receiver.
2806 __ Push(Operand(rsp, 0));
2807 __ movp(Operand(rsp, kPointerSize), rax);
2810 EmitCall(expr, call_type);
2814 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2815 Expression* callee = expr->expression();
2816 DCHECK(callee->IsProperty());
2817 Property* prop = callee->AsProperty();
2818 DCHECK(prop->IsSuperAccess());
2819 SetExpressionPosition(prop);
2821 Literal* key = prop->key()->AsLiteral();
2822 DCHECK(!key->value()->IsSmi());
2823 // Load the function from the receiver.
2824 SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2825 VisitForStackValue(super_ref->home_object());
2826 VisitForAccumulatorValue(super_ref->this_var());
2829 __ Push(Operand(rsp, kPointerSize * 2));
2830 __ Push(key->value());
2831 __ Push(Smi::FromInt(language_mode()));
2835 // - this (receiver)
2836 // - this (receiver) <-- LoadFromSuper will pop here and below.
2840 __ CallRuntime(Runtime::kLoadFromSuper, 4);
2842 // Replace home_object with target function.
2843 __ movp(Operand(rsp, kPointerSize), rax);
2846 // - target function
2847 // - this (receiver)
2848 EmitCall(expr, CallICState::METHOD);
2852 // Common code for calls using the IC.
2853 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2856 VisitForAccumulatorValue(key);
2858 Expression* callee = expr->expression();
2860 // Load the function from the receiver.
2861 DCHECK(callee->IsProperty());
2862 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
2863 __ Move(LoadDescriptor::NameRegister(), rax);
2864 EmitKeyedPropertyLoad(callee->AsProperty());
2865 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2867 // Push the target function under the receiver.
2868 __ Push(Operand(rsp, 0));
2869 __ movp(Operand(rsp, kPointerSize), rax);
2871 EmitCall(expr, CallICState::METHOD);
2875 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2876 Expression* callee = expr->expression();
2877 DCHECK(callee->IsProperty());
2878 Property* prop = callee->AsProperty();
2879 DCHECK(prop->IsSuperAccess());
2881 SetExpressionPosition(prop);
2882 // Load the function from the receiver.
2883 SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2884 VisitForStackValue(super_ref->home_object());
2885 VisitForAccumulatorValue(super_ref->this_var());
2888 __ Push(Operand(rsp, kPointerSize * 2));
2889 VisitForStackValue(prop->key());
2890 __ Push(Smi::FromInt(language_mode()));
2894 // - this (receiver)
2895 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2899 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2901 // Replace home_object with target function.
2902 __ movp(Operand(rsp, kPointerSize), rax);
2905 // - target function
2906 // - this (receiver)
2907 EmitCall(expr, CallICState::METHOD);
2911 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2912 // Load the arguments.
2913 ZoneList<Expression*>* args = expr->arguments();
2914 int arg_count = args->length();
2915 for (int i = 0; i < arg_count; i++) {
2916 VisitForStackValue(args->at(i));
2919 SetCallPosition(expr, arg_count);
2920 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2921 __ Move(rdx, SmiFromSlot(expr->CallFeedbackICSlot()));
2922 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
2923 // Don't assign a type feedback id to the IC, since type feedback is provided
2924 // by the vector above.
2927 RecordJSReturnSite(expr);
2929 // Restore context register.
2930 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2931 // Discard the function left on TOS.
2932 context()->DropAndPlug(1, rax);
2936 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2937 // Push copy of the first argument or undefined if it doesn't exist.
2938 if (arg_count > 0) {
2939 __ Push(Operand(rsp, arg_count * kPointerSize));
2941 __ PushRoot(Heap::kUndefinedValueRootIndex);
2944 // Push the enclosing function.
2945 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
2947 // Push the language mode.
2948 __ Push(Smi::FromInt(language_mode()));
2950 // Push the start position of the scope the calls resides in.
2951 __ Push(Smi::FromInt(scope()->start_position()));
2953 // Do the runtime call.
2954 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 5);
2958 // See http://www.ecma-international.org/ecma-262/6.0/#sec-function-calls.
2959 void FullCodeGenerator::PushCalleeAndWithBaseObject(Call* expr) {
2960 VariableProxy* callee = expr->expression()->AsVariableProxy();
2961 if (callee->var()->IsLookupSlot()) {
2963 SetExpressionPosition(callee);
2964 // Generate code for loading from variables potentially shadowed by
2965 // eval-introduced variables.
2966 EmitDynamicLookupFastCase(callee, NOT_INSIDE_TYPEOF, &slow, &done);
2968 // Call the runtime to find the function to call (returned in rax) and
2969 // the object holding it (returned in rdx).
2970 __ Push(context_register());
2971 __ Push(callee->name());
2972 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
2973 __ Push(rax); // Function.
2974 __ Push(rdx); // Receiver.
2975 PrepareForBailoutForId(expr->LookupId(), NO_REGISTERS);
2977 // If fast case code has been generated, emit code to push the function
2978 // and receiver and have the slow path jump around this code.
2979 if (done.is_linked()) {
2981 __ jmp(&call, Label::kNear);
2985 // Pass undefined as the receiver, which is the WithBaseObject of a
2986 // non-object environment record. If the callee is sloppy, it will patch
2987 // it up to be the global receiver.
2988 __ PushRoot(Heap::kUndefinedValueRootIndex);
2992 VisitForStackValue(callee);
2993 // refEnv.WithBaseObject()
2994 __ PushRoot(Heap::kUndefinedValueRootIndex);
2999 void FullCodeGenerator::VisitCall(Call* expr) {
3001 // We want to verify that RecordJSReturnSite gets called on all paths
3002 // through this function. Avoid early returns.
3003 expr->return_is_recorded_ = false;
3006 Comment cmnt(masm_, "[ Call");
3007 Expression* callee = expr->expression();
3008 Call::CallType call_type = expr->GetCallType(isolate());
3010 if (call_type == Call::POSSIBLY_EVAL_CALL) {
3011 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
3012 // to resolve the function we need to call. Then we call the resolved
3013 // function using the given arguments.
3014 ZoneList<Expression*>* args = expr->arguments();
3015 int arg_count = args->length();
3016 PushCalleeAndWithBaseObject(expr);
3018 // Push the arguments.
3019 for (int i = 0; i < arg_count; i++) {
3020 VisitForStackValue(args->at(i));
3023 // Push a copy of the function (found below the arguments) and resolve
3025 __ Push(Operand(rsp, (arg_count + 1) * kPointerSize));
3026 EmitResolvePossiblyDirectEval(arg_count);
3028 // Touch up the callee.
3029 __ movp(Operand(rsp, (arg_count + 1) * kPointerSize), rax);
3031 PrepareForBailoutForId(expr->EvalId(), NO_REGISTERS);
3033 SetCallPosition(expr, arg_count);
3034 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3035 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
3037 RecordJSReturnSite(expr);
3038 // Restore context register.
3039 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3040 context()->DropAndPlug(1, rax);
3041 } else if (call_type == Call::GLOBAL_CALL) {
3042 EmitCallWithLoadIC(expr);
3044 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3045 // Call to a lookup slot (dynamically introduced variable).
3046 PushCalleeAndWithBaseObject(expr);
3048 } else if (call_type == Call::PROPERTY_CALL) {
3049 Property* property = callee->AsProperty();
3050 bool is_named_call = property->key()->IsPropertyName();
3051 if (property->IsSuperAccess()) {
3052 if (is_named_call) {
3053 EmitSuperCallWithLoadIC(expr);
3055 EmitKeyedSuperCallWithLoadIC(expr);
3058 VisitForStackValue(property->obj());
3059 if (is_named_call) {
3060 EmitCallWithLoadIC(expr);
3062 EmitKeyedCallWithLoadIC(expr, property->key());
3065 } else if (call_type == Call::SUPER_CALL) {
3066 EmitSuperConstructorCall(expr);
3068 DCHECK(call_type == Call::OTHER_CALL);
3069 // Call to an arbitrary expression not handled specially above.
3070 VisitForStackValue(callee);
3071 __ PushRoot(Heap::kUndefinedValueRootIndex);
3072 // Emit function call.
3077 // RecordJSReturnSite should have been called.
3078 DCHECK(expr->return_is_recorded_);
3083 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3084 Comment cmnt(masm_, "[ CallNew");
3085 // According to ECMA-262, section 11.2.2, page 44, the function
3086 // expression in new calls must be evaluated before the
3089 // Push constructor on the stack. If it's not a function it's used as
3090 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3092 DCHECK(!expr->expression()->IsSuperPropertyReference());
3093 VisitForStackValue(expr->expression());
3095 // Push the arguments ("left-to-right") on the stack.
3096 ZoneList<Expression*>* args = expr->arguments();
3097 int arg_count = args->length();
3098 for (int i = 0; i < arg_count; i++) {
3099 VisitForStackValue(args->at(i));
3102 // Call the construct call builtin that handles allocation and
3103 // constructor invocation.
3104 SetConstructCallPosition(expr);
3106 // Load function and argument count into rdi and rax.
3107 __ Set(rax, arg_count);
3108 __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
3110 // Record call targets in unoptimized code, but not in the snapshot.
3111 if (FLAG_pretenuring_call_new) {
3112 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3113 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3114 expr->CallNewFeedbackSlot().ToInt() + 1);
3117 __ Move(rbx, FeedbackVector());
3118 __ Move(rdx, SmiFromSlot(expr->CallNewFeedbackSlot()));
3120 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3121 __ Call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3122 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3123 // Restore context register.
3124 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3125 context()->Plug(rax);
3129 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3130 SuperCallReference* super_call_ref =
3131 expr->expression()->AsSuperCallReference();
3132 DCHECK_NOT_NULL(super_call_ref);
3134 EmitLoadSuperConstructor(super_call_ref);
3135 __ Push(result_register());
3137 // Push the arguments ("left-to-right") on the stack.
3138 ZoneList<Expression*>* args = expr->arguments();
3139 int arg_count = args->length();
3140 for (int i = 0; i < arg_count; i++) {
3141 VisitForStackValue(args->at(i));
3144 // Call the construct call builtin that handles allocation and
3145 // constructor invocation.
3146 SetConstructCallPosition(expr);
3148 // Load original constructor into rcx.
3149 VisitForAccumulatorValue(super_call_ref->new_target_var());
3150 __ movp(rcx, result_register());
3152 // Load function and argument count into rdi and rax.
3153 __ Set(rax, arg_count);
3154 __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
3156 // Record call targets in unoptimized code.
3157 if (FLAG_pretenuring_call_new) {
3159 /* TODO(dslomov): support pretenuring.
3160 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3161 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3162 expr->CallNewFeedbackSlot().ToInt() + 1);
3166 __ Move(rbx, FeedbackVector());
3167 __ Move(rdx, SmiFromSlot(expr->CallFeedbackSlot()));
3169 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3170 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3172 RecordJSReturnSite(expr);
3174 // Restore context register.
3175 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3177 context()->Plug(rax);
3181 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3182 ZoneList<Expression*>* args = expr->arguments();
3183 DCHECK(args->length() == 1);
3185 VisitForAccumulatorValue(args->at(0));
3187 Label materialize_true, materialize_false;
3188 Label* if_true = NULL;
3189 Label* if_false = NULL;
3190 Label* fall_through = NULL;
3191 context()->PrepareTest(&materialize_true, &materialize_false,
3192 &if_true, &if_false, &fall_through);
3194 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3195 __ JumpIfSmi(rax, if_true);
3198 context()->Plug(if_true, if_false);
3202 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3203 ZoneList<Expression*>* args = expr->arguments();
3204 DCHECK(args->length() == 1);
3206 VisitForAccumulatorValue(args->at(0));
3208 Label materialize_true, materialize_false;
3209 Label* if_true = NULL;
3210 Label* if_false = NULL;
3211 Label* fall_through = NULL;
3212 context()->PrepareTest(&materialize_true, &materialize_false,
3213 &if_true, &if_false, &fall_through);
3215 __ JumpIfSmi(rax, if_false);
3216 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rbx);
3217 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3218 Split(above_equal, if_true, if_false, fall_through);
3220 context()->Plug(if_true, if_false);
3224 void FullCodeGenerator::EmitIsSimdValue(CallRuntime* expr) {
3225 ZoneList<Expression*>* args = expr->arguments();
3226 DCHECK(args->length() == 1);
3228 VisitForAccumulatorValue(args->at(0));
3230 Label materialize_true, materialize_false;
3231 Label* if_true = NULL;
3232 Label* if_false = NULL;
3233 Label* fall_through = NULL;
3234 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3235 &if_false, &fall_through);
3237 __ JumpIfSmi(rax, if_false);
3238 __ CmpObjectType(rax, SIMD128_VALUE_TYPE, rbx);
3239 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3240 Split(equal, if_true, if_false, fall_through);
3242 context()->Plug(if_true, if_false);
3246 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3247 CallRuntime* expr) {
3248 ZoneList<Expression*>* args = expr->arguments();
3249 DCHECK(args->length() == 1);
3251 VisitForAccumulatorValue(args->at(0));
3253 Label materialize_true, materialize_false, skip_lookup;
3254 Label* if_true = NULL;
3255 Label* if_false = NULL;
3256 Label* fall_through = NULL;
3257 context()->PrepareTest(&materialize_true, &materialize_false,
3258 &if_true, &if_false, &fall_through);
3260 __ AssertNotSmi(rax);
3262 // Check whether this map has already been checked to be safe for default
3264 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3265 __ testb(FieldOperand(rbx, Map::kBitField2Offset),
3266 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3267 __ j(not_zero, &skip_lookup);
3269 // Check for fast case object. Generate false result for slow case object.
3270 __ movp(rcx, FieldOperand(rax, JSObject::kPropertiesOffset));
3271 __ movp(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3272 __ CompareRoot(rcx, Heap::kHashTableMapRootIndex);
3273 __ j(equal, if_false);
3275 // Look for valueOf string in the descriptor array, and indicate false if
3276 // found. Since we omit an enumeration index check, if it is added via a
3277 // transition that shares its descriptor array, this is a false positive.
3278 Label entry, loop, done;
3280 // Skip loop if no descriptors are valid.
3281 __ NumberOfOwnDescriptors(rcx, rbx);
3282 __ cmpp(rcx, Immediate(0));
3285 __ LoadInstanceDescriptors(rbx, r8);
3286 // rbx: descriptor array.
3287 // rcx: valid entries in the descriptor array.
3288 // Calculate the end of the descriptor array.
3289 __ imulp(rcx, rcx, Immediate(DescriptorArray::kDescriptorSize));
3291 Operand(r8, rcx, times_pointer_size, DescriptorArray::kFirstOffset));
3292 // Calculate location of the first key name.
3293 __ addp(r8, Immediate(DescriptorArray::kFirstOffset));
3294 // Loop through all the keys in the descriptor array. If one of these is the
3295 // internalized string "valueOf" the result is false.
3298 __ movp(rdx, FieldOperand(r8, 0));
3299 __ CompareRoot(rdx, Heap::kvalueOf_stringRootIndex);
3300 __ j(equal, if_false);
3301 __ addp(r8, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3304 __ j(not_equal, &loop);
3308 // Set the bit in the map to indicate that there is no local valueOf field.
3309 __ orp(FieldOperand(rbx, Map::kBitField2Offset),
3310 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3312 __ bind(&skip_lookup);
3314 // If a valueOf property is not found on the object check that its
3315 // prototype is the un-modified String prototype. If not result is false.
3316 __ movp(rcx, FieldOperand(rbx, Map::kPrototypeOffset));
3317 __ testp(rcx, Immediate(kSmiTagMask));
3318 __ j(zero, if_false);
3319 __ movp(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3320 __ movp(rdx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3321 __ movp(rdx, FieldOperand(rdx, GlobalObject::kNativeContextOffset));
3323 ContextOperand(rdx, Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3324 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3325 Split(equal, if_true, if_false, fall_through);
3327 context()->Plug(if_true, if_false);
3331 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3332 ZoneList<Expression*>* args = expr->arguments();
3333 DCHECK(args->length() == 1);
3335 VisitForAccumulatorValue(args->at(0));
3337 Label materialize_true, materialize_false;
3338 Label* if_true = NULL;
3339 Label* if_false = NULL;
3340 Label* fall_through = NULL;
3341 context()->PrepareTest(&materialize_true, &materialize_false,
3342 &if_true, &if_false, &fall_through);
3344 __ JumpIfSmi(rax, if_false);
3345 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
3346 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3347 Split(equal, if_true, if_false, fall_through);
3349 context()->Plug(if_true, if_false);
3353 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3354 ZoneList<Expression*>* args = expr->arguments();
3355 DCHECK(args->length() == 1);
3357 VisitForAccumulatorValue(args->at(0));
3359 Label materialize_true, materialize_false;
3360 Label* if_true = NULL;
3361 Label* if_false = NULL;
3362 Label* fall_through = NULL;
3363 context()->PrepareTest(&materialize_true, &materialize_false,
3364 &if_true, &if_false, &fall_through);
3366 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3367 __ CheckMap(rax, map, if_false, DO_SMI_CHECK);
3368 __ cmpl(FieldOperand(rax, HeapNumber::kExponentOffset),
3370 __ j(no_overflow, if_false);
3371 __ cmpl(FieldOperand(rax, HeapNumber::kMantissaOffset),
3372 Immediate(0x00000000));
3373 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3374 Split(equal, if_true, if_false, fall_through);
3376 context()->Plug(if_true, if_false);
3380 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3381 ZoneList<Expression*>* args = expr->arguments();
3382 DCHECK(args->length() == 1);
3384 VisitForAccumulatorValue(args->at(0));
3386 Label materialize_true, materialize_false;
3387 Label* if_true = NULL;
3388 Label* if_false = NULL;
3389 Label* fall_through = NULL;
3390 context()->PrepareTest(&materialize_true, &materialize_false,
3391 &if_true, &if_false, &fall_through);
3393 __ JumpIfSmi(rax, if_false);
3394 __ CmpObjectType(rax, JS_ARRAY_TYPE, rbx);
3395 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3396 Split(equal, if_true, if_false, fall_through);
3398 context()->Plug(if_true, if_false);
3402 void FullCodeGenerator::EmitIsTypedArray(CallRuntime* expr) {
3403 ZoneList<Expression*>* args = expr->arguments();
3404 DCHECK(args->length() == 1);
3406 VisitForAccumulatorValue(args->at(0));
3408 Label materialize_true, materialize_false;
3409 Label* if_true = NULL;
3410 Label* if_false = NULL;
3411 Label* fall_through = NULL;
3412 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3413 &if_false, &fall_through);
3415 __ JumpIfSmi(rax, if_false);
3416 __ CmpObjectType(rax, JS_TYPED_ARRAY_TYPE, rbx);
3417 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3418 Split(equal, if_true, if_false, fall_through);
3420 context()->Plug(if_true, if_false);
3424 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3425 ZoneList<Expression*>* args = expr->arguments();
3426 DCHECK(args->length() == 1);
3428 VisitForAccumulatorValue(args->at(0));
3430 Label materialize_true, materialize_false;
3431 Label* if_true = NULL;
3432 Label* if_false = NULL;
3433 Label* fall_through = NULL;
3434 context()->PrepareTest(&materialize_true, &materialize_false,
3435 &if_true, &if_false, &fall_through);
3437 __ JumpIfSmi(rax, if_false);
3438 __ CmpObjectType(rax, JS_REGEXP_TYPE, rbx);
3439 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3440 Split(equal, if_true, if_false, fall_through);
3442 context()->Plug(if_true, if_false);
3446 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3447 ZoneList<Expression*>* args = expr->arguments();
3448 DCHECK(args->length() == 1);
3450 VisitForAccumulatorValue(args->at(0));
3452 Label materialize_true, materialize_false;
3453 Label* if_true = NULL;
3454 Label* if_false = NULL;
3455 Label* fall_through = NULL;
3456 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3457 &if_false, &fall_through);
3459 __ JumpIfSmi(rax, if_false);
3461 __ movp(map, FieldOperand(rax, HeapObject::kMapOffset));
3462 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3463 __ j(less, if_false);
3464 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3465 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3466 Split(less_equal, if_true, if_false, fall_through);
3468 context()->Plug(if_true, if_false);
3472 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3473 DCHECK(expr->arguments()->length() == 0);
3475 Label materialize_true, materialize_false;
3476 Label* if_true = NULL;
3477 Label* if_false = NULL;
3478 Label* fall_through = NULL;
3479 context()->PrepareTest(&materialize_true, &materialize_false,
3480 &if_true, &if_false, &fall_through);
3482 // Get the frame pointer for the calling frame.
3483 __ movp(rax, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3485 // Skip the arguments adaptor frame if it exists.
3486 Label check_frame_marker;
3487 __ Cmp(Operand(rax, StandardFrameConstants::kContextOffset),
3488 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3489 __ j(not_equal, &check_frame_marker);
3490 __ movp(rax, Operand(rax, StandardFrameConstants::kCallerFPOffset));
3492 // Check the marker in the calling frame.
3493 __ bind(&check_frame_marker);
3494 __ Cmp(Operand(rax, StandardFrameConstants::kMarkerOffset),
3495 Smi::FromInt(StackFrame::CONSTRUCT));
3496 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3497 Split(equal, if_true, if_false, fall_through);
3499 context()->Plug(if_true, if_false);
3503 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3504 ZoneList<Expression*>* args = expr->arguments();
3505 DCHECK(args->length() == 2);
3507 // Load the two objects into registers and perform the comparison.
3508 VisitForStackValue(args->at(0));
3509 VisitForAccumulatorValue(args->at(1));
3511 Label materialize_true, materialize_false;
3512 Label* if_true = NULL;
3513 Label* if_false = NULL;
3514 Label* fall_through = NULL;
3515 context()->PrepareTest(&materialize_true, &materialize_false,
3516 &if_true, &if_false, &fall_through);
3520 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3521 Split(equal, if_true, if_false, fall_through);
3523 context()->Plug(if_true, if_false);
3527 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3528 ZoneList<Expression*>* args = expr->arguments();
3529 DCHECK(args->length() == 1);
3531 // ArgumentsAccessStub expects the key in rdx and the formal
3532 // parameter count in rax.
3533 VisitForAccumulatorValue(args->at(0));
3535 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters()));
3536 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3538 context()->Plug(rax);
3542 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3543 DCHECK(expr->arguments()->length() == 0);
3546 // Get the number of formal parameters.
3547 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters()));
3549 // Check if the calling frame is an arguments adaptor frame.
3550 __ movp(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3551 __ Cmp(Operand(rbx, StandardFrameConstants::kContextOffset),
3552 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3553 __ j(not_equal, &exit, Label::kNear);
3555 // Arguments adaptor case: Read the arguments length from the
3557 __ movp(rax, Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3561 context()->Plug(rax);
3565 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3566 ZoneList<Expression*>* args = expr->arguments();
3567 DCHECK(args->length() == 1);
3568 Label done, null, function, non_function_constructor;
3570 VisitForAccumulatorValue(args->at(0));
3572 // If the object is a smi, we return null.
3573 __ JumpIfSmi(rax, &null);
3575 // Check that the object is a JS object but take special care of JS
3576 // functions to make sure they have 'Function' as their class.
3577 // Assume that there are only two callable types, and one of them is at
3578 // either end of the type range for JS object types. Saves extra comparisons.
3579 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3580 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rax);
3581 // Map is now in rax.
3583 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3584 FIRST_SPEC_OBJECT_TYPE + 1);
3585 __ j(equal, &function);
3587 __ CmpInstanceType(rax, LAST_SPEC_OBJECT_TYPE);
3588 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3589 LAST_SPEC_OBJECT_TYPE - 1);
3590 __ j(equal, &function);
3591 // Assume that there is no larger type.
3592 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3594 // Check if the constructor in the map is a JS function.
3595 __ GetMapConstructor(rax, rax, rbx);
3596 __ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
3597 __ j(not_equal, &non_function_constructor);
3599 // rax now contains the constructor function. Grab the
3600 // instance class name from there.
3601 __ movp(rax, FieldOperand(rax, JSFunction::kSharedFunctionInfoOffset));
3602 __ movp(rax, FieldOperand(rax, SharedFunctionInfo::kInstanceClassNameOffset));
3605 // Functions have class 'Function'.
3607 __ Move(rax, isolate()->factory()->Function_string());
3610 // Objects with a non-function constructor have class 'Object'.
3611 __ bind(&non_function_constructor);
3612 __ Move(rax, isolate()->factory()->Object_string());
3615 // Non-JS objects have class null.
3617 __ LoadRoot(rax, Heap::kNullValueRootIndex);
3622 context()->Plug(rax);
3626 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3627 ZoneList<Expression*>* args = expr->arguments();
3628 DCHECK(args->length() == 1);
3630 VisitForAccumulatorValue(args->at(0)); // Load the object.
3633 // If the object is a smi return the object.
3634 __ JumpIfSmi(rax, &done);
3635 // If the object is not a value type, return the object.
3636 __ CmpObjectType(rax, JS_VALUE_TYPE, rbx);
3637 __ j(not_equal, &done);
3638 __ movp(rax, FieldOperand(rax, JSValue::kValueOffset));
3641 context()->Plug(rax);
3645 void FullCodeGenerator::EmitIsDate(CallRuntime* expr) {
3646 ZoneList<Expression*>* args = expr->arguments();
3647 DCHECK_EQ(1, args->length());
3649 VisitForAccumulatorValue(args->at(0));
3651 Label materialize_true, materialize_false;
3652 Label* if_true = nullptr;
3653 Label* if_false = nullptr;
3654 Label* fall_through = nullptr;
3655 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3656 &if_false, &fall_through);
3658 __ JumpIfSmi(rax, if_false);
3659 __ CmpObjectType(rax, JS_DATE_TYPE, rbx);
3660 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3661 Split(equal, if_true, if_false, fall_through);
3663 context()->Plug(if_true, if_false);
3667 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3668 ZoneList<Expression*>* args = expr->arguments();
3669 DCHECK(args->length() == 2);
3670 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3671 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3673 VisitForAccumulatorValue(args->at(0)); // Load the object.
3675 Register object = rax;
3676 Register result = rax;
3677 Register scratch = rcx;
3679 if (FLAG_debug_code) {
3680 __ AssertNotSmi(object);
3681 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3682 __ Check(equal, kOperandIsNotADate);
3685 if (index->value() == 0) {
3686 __ movp(result, FieldOperand(object, JSDate::kValueOffset));
3688 Label runtime, done;
3689 if (index->value() < JSDate::kFirstUncachedField) {
3690 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3691 Operand stamp_operand = __ ExternalOperand(stamp);
3692 __ movp(scratch, stamp_operand);
3693 __ cmpp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3694 __ j(not_equal, &runtime, Label::kNear);
3695 __ movp(result, FieldOperand(object, JSDate::kValueOffset +
3696 kPointerSize * index->value()));
3697 __ jmp(&done, Label::kNear);
3700 __ PrepareCallCFunction(2);
3701 __ movp(arg_reg_1, object);
3702 __ Move(arg_reg_2, index, Assembler::RelocInfoNone());
3703 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3704 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3708 context()->Plug(rax);
3712 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3713 ZoneList<Expression*>* args = expr->arguments();
3714 DCHECK_EQ(3, args->length());
3716 Register string = rax;
3717 Register index = rbx;
3718 Register value = rcx;
3720 VisitForStackValue(args->at(0)); // index
3721 VisitForStackValue(args->at(1)); // value
3722 VisitForAccumulatorValue(args->at(2)); // string
3726 if (FLAG_debug_code) {
3727 __ Check(__ CheckSmi(value), kNonSmiValue);
3728 __ Check(__ CheckSmi(index), kNonSmiValue);
3731 __ SmiToInteger32(value, value);
3732 __ SmiToInteger32(index, index);
3734 if (FLAG_debug_code) {
3735 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3736 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3739 __ movb(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3741 context()->Plug(string);
3745 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3746 ZoneList<Expression*>* args = expr->arguments();
3747 DCHECK_EQ(3, args->length());
3749 Register string = rax;
3750 Register index = rbx;
3751 Register value = rcx;
3753 VisitForStackValue(args->at(0)); // index
3754 VisitForStackValue(args->at(1)); // value
3755 VisitForAccumulatorValue(args->at(2)); // string
3759 if (FLAG_debug_code) {
3760 __ Check(__ CheckSmi(value), kNonSmiValue);
3761 __ Check(__ CheckSmi(index), kNonSmiValue);
3764 __ SmiToInteger32(value, value);
3765 __ SmiToInteger32(index, index);
3767 if (FLAG_debug_code) {
3768 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3769 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3772 __ movw(FieldOperand(string, index, times_2, SeqTwoByteString::kHeaderSize),
3774 context()->Plug(rax);
3778 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3779 ZoneList<Expression*>* args = expr->arguments();
3780 DCHECK(args->length() == 2);
3782 VisitForStackValue(args->at(0)); // Load the object.
3783 VisitForAccumulatorValue(args->at(1)); // Load the value.
3784 __ Pop(rbx); // rax = value. rbx = object.
3787 // If the object is a smi, return the value.
3788 __ JumpIfSmi(rbx, &done);
3790 // If the object is not a value type, return the value.
3791 __ CmpObjectType(rbx, JS_VALUE_TYPE, rcx);
3792 __ j(not_equal, &done);
3795 __ movp(FieldOperand(rbx, JSValue::kValueOffset), rax);
3796 // Update the write barrier. Save the value as it will be
3797 // overwritten by the write barrier code and is needed afterward.
3799 __ RecordWriteField(rbx, JSValue::kValueOffset, rdx, rcx, kDontSaveFPRegs);
3802 context()->Plug(rax);
3806 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3807 ZoneList<Expression*>* args = expr->arguments();
3808 DCHECK_EQ(args->length(), 1);
3810 // Load the argument into rax and call the stub.
3811 VisitForAccumulatorValue(args->at(0));
3813 NumberToStringStub stub(isolate());
3815 context()->Plug(rax);
3819 void FullCodeGenerator::EmitToString(CallRuntime* expr) {
3820 ZoneList<Expression*>* args = expr->arguments();
3821 DCHECK_EQ(1, args->length());
3823 // Load the argument into rax and convert it.
3824 VisitForAccumulatorValue(args->at(0));
3826 ToStringStub stub(isolate());
3828 context()->Plug(rax);
3832 void FullCodeGenerator::EmitToName(CallRuntime* expr) {
3833 ZoneList<Expression*>* args = expr->arguments();
3834 DCHECK_EQ(1, args->length());
3836 // Load the argument into rax and convert it.
3837 VisitForAccumulatorValue(args->at(0));
3839 // Convert the object to a name.
3840 Label convert, done_convert;
3841 __ JumpIfSmi(rax, &convert, Label::kNear);
3842 STATIC_ASSERT(FIRST_NAME_TYPE == FIRST_TYPE);
3843 __ CmpObjectType(rax, LAST_NAME_TYPE, rcx);
3844 __ j(below_equal, &done_convert, Label::kNear);
3846 ToStringStub stub(isolate());
3848 __ bind(&done_convert);
3849 context()->Plug(rax);
3853 void FullCodeGenerator::EmitToObject(CallRuntime* expr) {
3854 ZoneList<Expression*>* args = expr->arguments();
3855 DCHECK_EQ(1, args->length());
3857 // Load the argument into rax and convert it.
3858 VisitForAccumulatorValue(args->at(0));
3860 ToObjectStub stub(isolate());
3862 context()->Plug(rax);
3866 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3867 ZoneList<Expression*>* args = expr->arguments();
3868 DCHECK(args->length() == 1);
3870 VisitForAccumulatorValue(args->at(0));
3873 StringCharFromCodeGenerator generator(rax, rbx);
3874 generator.GenerateFast(masm_);
3877 NopRuntimeCallHelper call_helper;
3878 generator.GenerateSlow(masm_, call_helper);
3881 context()->Plug(rbx);
3885 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3886 ZoneList<Expression*>* args = expr->arguments();
3887 DCHECK(args->length() == 2);
3889 VisitForStackValue(args->at(0));
3890 VisitForAccumulatorValue(args->at(1));
3892 Register object = rbx;
3893 Register index = rax;
3894 Register result = rdx;
3898 Label need_conversion;
3899 Label index_out_of_range;
3901 StringCharCodeAtGenerator generator(object,
3906 &index_out_of_range,
3907 STRING_INDEX_IS_NUMBER);
3908 generator.GenerateFast(masm_);
3911 __ bind(&index_out_of_range);
3912 // When the index is out of range, the spec requires us to return
3914 __ LoadRoot(result, Heap::kNanValueRootIndex);
3917 __ bind(&need_conversion);
3918 // Move the undefined value into the result register, which will
3919 // trigger conversion.
3920 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
3923 NopRuntimeCallHelper call_helper;
3924 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
3927 context()->Plug(result);
3931 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3932 ZoneList<Expression*>* args = expr->arguments();
3933 DCHECK(args->length() == 2);
3935 VisitForStackValue(args->at(0));
3936 VisitForAccumulatorValue(args->at(1));
3938 Register object = rbx;
3939 Register index = rax;
3940 Register scratch = rdx;
3941 Register result = rax;
3945 Label need_conversion;
3946 Label index_out_of_range;
3948 StringCharAtGenerator generator(object,
3954 &index_out_of_range,
3955 STRING_INDEX_IS_NUMBER);
3956 generator.GenerateFast(masm_);
3959 __ bind(&index_out_of_range);
3960 // When the index is out of range, the spec requires us to return
3961 // the empty string.
3962 __ LoadRoot(result, Heap::kempty_stringRootIndex);
3965 __ bind(&need_conversion);
3966 // Move smi zero into the result register, which will trigger
3968 __ Move(result, Smi::FromInt(0));
3971 NopRuntimeCallHelper call_helper;
3972 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
3975 context()->Plug(result);
3979 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
3980 ZoneList<Expression*>* args = expr->arguments();
3981 DCHECK_EQ(2, args->length());
3982 VisitForStackValue(args->at(0));
3983 VisitForAccumulatorValue(args->at(1));
3986 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
3988 context()->Plug(rax);
3992 void FullCodeGenerator::EmitCall(CallRuntime* expr) {
3993 ZoneList<Expression*>* args = expr->arguments();
3994 DCHECK_LE(2, args->length());
3995 // Push target, receiver and arguments onto the stack.
3996 for (Expression* const arg : *args) {
3997 VisitForStackValue(arg);
3999 // Move target to rdi.
4000 int const argc = args->length() - 2;
4001 __ movp(rdi, Operand(rsp, (argc + 1) * kPointerSize));
4004 __ Call(isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
4005 // Restore context register.
4006 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4007 // Discard the function left on TOS.
4008 context()->DropAndPlug(1, rax);
4012 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4013 ZoneList<Expression*>* args = expr->arguments();
4014 DCHECK(args->length() >= 2);
4016 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4017 for (int i = 0; i < arg_count + 1; i++) {
4018 VisitForStackValue(args->at(i));
4020 VisitForAccumulatorValue(args->last()); // Function.
4022 Label runtime, done;
4023 // Check for non-function argument (including proxy).
4024 __ JumpIfSmi(rax, &runtime);
4025 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
4026 __ j(not_equal, &runtime);
4028 // InvokeFunction requires the function in rdi. Move it in there.
4029 __ movp(rdi, result_register());
4030 ParameterCount count(arg_count);
4031 __ InvokeFunction(rdi, count, CALL_FUNCTION, NullCallWrapper());
4032 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4037 __ CallRuntime(Runtime::kCallFunction, args->length());
4040 context()->Plug(rax);
4044 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4045 ZoneList<Expression*>* args = expr->arguments();
4046 DCHECK(args->length() == 2);
4048 // Evaluate new.target and super constructor.
4049 VisitForStackValue(args->at(0));
4050 VisitForStackValue(args->at(1));
4052 // Load original constructor into rcx.
4053 __ movp(rcx, Operand(rsp, 1 * kPointerSize));
4055 // Check if the calling frame is an arguments adaptor frame.
4056 Label adaptor_frame, args_set_up, runtime;
4057 __ movp(rdx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
4058 __ movp(rbx, Operand(rdx, StandardFrameConstants::kContextOffset));
4059 __ Cmp(rbx, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
4060 __ j(equal, &adaptor_frame);
4061 // default constructor has no arguments, so no adaptor frame means no args.
4062 __ movp(rax, Immediate(0));
4063 __ jmp(&args_set_up);
4065 // Copy arguments from adaptor frame.
4067 __ bind(&adaptor_frame);
4068 __ movp(rbx, Operand(rdx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4069 __ SmiToInteger64(rbx, rbx);
4072 __ leap(rdx, Operand(rdx, rbx, times_pointer_size,
4073 StandardFrameConstants::kCallerSPOffset));
4076 __ Push(Operand(rdx, -1 * kPointerSize));
4077 __ subp(rdx, Immediate(kPointerSize));
4079 __ j(not_zero, &loop);
4082 __ bind(&args_set_up);
4083 __ movp(rdi, Operand(rsp, rax, times_pointer_size, 0));
4084 __ LoadRoot(rbx, Heap::kUndefinedValueRootIndex);
4086 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4087 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4089 // Restore context register.
4090 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4092 context()->DropAndPlug(1, rax);
4096 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4097 RegExpConstructResultStub stub(isolate());
4098 ZoneList<Expression*>* args = expr->arguments();
4099 DCHECK(args->length() == 3);
4100 VisitForStackValue(args->at(0));
4101 VisitForStackValue(args->at(1));
4102 VisitForAccumulatorValue(args->at(2));
4106 context()->Plug(rax);
4110 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4111 ZoneList<Expression*>* args = expr->arguments();
4112 DCHECK(args->length() == 1);
4114 VisitForAccumulatorValue(args->at(0));
4116 Label materialize_true, materialize_false;
4117 Label* if_true = NULL;
4118 Label* if_false = NULL;
4119 Label* fall_through = NULL;
4120 context()->PrepareTest(&materialize_true, &materialize_false,
4121 &if_true, &if_false, &fall_through);
4123 __ testl(FieldOperand(rax, String::kHashFieldOffset),
4124 Immediate(String::kContainsCachedArrayIndexMask));
4125 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4126 __ j(zero, if_true);
4129 context()->Plug(if_true, if_false);
4133 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4134 ZoneList<Expression*>* args = expr->arguments();
4135 DCHECK(args->length() == 1);
4136 VisitForAccumulatorValue(args->at(0));
4138 __ AssertString(rax);
4140 __ movl(rax, FieldOperand(rax, String::kHashFieldOffset));
4141 DCHECK(String::kHashShift >= kSmiTagSize);
4142 __ IndexFromHash(rax, rax);
4144 context()->Plug(rax);
4148 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4149 Label bailout, return_result, done, one_char_separator, long_separator,
4150 non_trivial_array, not_size_one_array, loop,
4151 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4152 ZoneList<Expression*>* args = expr->arguments();
4153 DCHECK(args->length() == 2);
4154 // We will leave the separator on the stack until the end of the function.
4155 VisitForStackValue(args->at(1));
4156 // Load this to rax (= array)
4157 VisitForAccumulatorValue(args->at(0));
4158 // All aliases of the same register have disjoint lifetimes.
4159 Register array = rax;
4160 Register elements = no_reg; // Will be rax.
4162 Register index = rdx;
4164 Register string_length = rcx;
4166 Register string = rsi;
4168 Register scratch = rbx;
4170 Register array_length = rdi;
4171 Register result_pos = no_reg; // Will be rdi.
4173 Operand separator_operand = Operand(rsp, 2 * kPointerSize);
4174 Operand result_operand = Operand(rsp, 1 * kPointerSize);
4175 Operand array_length_operand = Operand(rsp, 0 * kPointerSize);
4176 // Separator operand is already pushed. Make room for the two
4177 // other stack fields, and clear the direction flag in anticipation
4178 // of calling CopyBytes.
4179 __ subp(rsp, Immediate(2 * kPointerSize));
4181 // Check that the array is a JSArray
4182 __ JumpIfSmi(array, &bailout);
4183 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4184 __ j(not_equal, &bailout);
4186 // Check that the array has fast elements.
4187 __ CheckFastElements(scratch, &bailout);
4189 // Array has fast elements, so its length must be a smi.
4190 // If the array has length zero, return the empty string.
4191 __ movp(array_length, FieldOperand(array, JSArray::kLengthOffset));
4192 __ SmiCompare(array_length, Smi::FromInt(0));
4193 __ j(not_zero, &non_trivial_array);
4194 __ LoadRoot(rax, Heap::kempty_stringRootIndex);
4195 __ jmp(&return_result);
4197 // Save the array length on the stack.
4198 __ bind(&non_trivial_array);
4199 __ SmiToInteger32(array_length, array_length);
4200 __ movl(array_length_operand, array_length);
4202 // Save the FixedArray containing array's elements.
4203 // End of array's live range.
4205 __ movp(elements, FieldOperand(array, JSArray::kElementsOffset));
4209 // Check that all array elements are sequential one-byte strings, and
4210 // accumulate the sum of their lengths, as a smi-encoded value.
4212 __ Set(string_length, 0);
4213 // Loop condition: while (index < array_length).
4214 // Live loop registers: index(int32), array_length(int32), string(String*),
4215 // scratch, string_length(int32), elements(FixedArray*).
4216 if (generate_debug_code_) {
4217 __ cmpp(index, array_length);
4218 __ Assert(below, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4221 __ movp(string, FieldOperand(elements,
4224 FixedArray::kHeaderSize));
4225 __ JumpIfSmi(string, &bailout);
4226 __ movp(scratch, FieldOperand(string, HeapObject::kMapOffset));
4227 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4228 __ andb(scratch, Immediate(
4229 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4230 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag));
4231 __ j(not_equal, &bailout);
4232 __ AddSmiField(string_length,
4233 FieldOperand(string, SeqOneByteString::kLengthOffset));
4234 __ j(overflow, &bailout);
4236 __ cmpl(index, array_length);
4240 // string_length: Sum of string lengths.
4241 // elements: FixedArray of strings.
4242 // index: Array length.
4243 // array_length: Array length.
4245 // If array_length is 1, return elements[0], a string.
4246 __ cmpl(array_length, Immediate(1));
4247 __ j(not_equal, ¬_size_one_array);
4248 __ movp(rax, FieldOperand(elements, FixedArray::kHeaderSize));
4249 __ jmp(&return_result);
4251 __ bind(¬_size_one_array);
4253 // End of array_length live range.
4254 result_pos = array_length;
4255 array_length = no_reg;
4258 // string_length: Sum of string lengths.
4259 // elements: FixedArray of strings.
4260 // index: Array length.
4262 // Check that the separator is a sequential one-byte string.
4263 __ movp(string, separator_operand);
4264 __ JumpIfSmi(string, &bailout);
4265 __ movp(scratch, FieldOperand(string, HeapObject::kMapOffset));
4266 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4267 __ andb(scratch, Immediate(
4268 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4269 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag));
4270 __ j(not_equal, &bailout);
4273 // string_length: Sum of string lengths.
4274 // elements: FixedArray of strings.
4275 // index: Array length.
4276 // string: Separator string.
4278 // Add (separator length times (array_length - 1)) to string_length.
4279 __ SmiToInteger32(scratch,
4280 FieldOperand(string, SeqOneByteString::kLengthOffset));
4282 __ imull(scratch, index);
4283 __ j(overflow, &bailout);
4284 __ addl(string_length, scratch);
4285 __ j(overflow, &bailout);
4287 // Live registers and stack values:
4288 // string_length: Total length of result string.
4289 // elements: FixedArray of strings.
4290 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4292 __ movp(result_operand, result_pos);
4293 __ leap(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4295 __ movp(string, separator_operand);
4296 __ SmiCompare(FieldOperand(string, SeqOneByteString::kLengthOffset),
4298 __ j(equal, &one_char_separator);
4299 __ j(greater, &long_separator);
4302 // Empty separator case:
4304 __ movl(scratch, array_length_operand);
4305 __ jmp(&loop_1_condition);
4306 // Loop condition: while (index < array_length).
4308 // Each iteration of the loop concatenates one string to the result.
4309 // Live values in registers:
4310 // index: which element of the elements array we are adding to the result.
4311 // result_pos: the position to which we are currently copying characters.
4312 // elements: the FixedArray of strings we are joining.
4313 // scratch: array length.
4315 // Get string = array[index].
4316 __ movp(string, FieldOperand(elements, index,
4318 FixedArray::kHeaderSize));
4319 __ SmiToInteger32(string_length,
4320 FieldOperand(string, String::kLengthOffset));
4322 FieldOperand(string, SeqOneByteString::kHeaderSize));
4323 __ CopyBytes(result_pos, string, string_length);
4325 __ bind(&loop_1_condition);
4326 __ cmpl(index, scratch);
4327 __ j(less, &loop_1); // Loop while (index < array_length).
4330 // Generic bailout code used from several places.
4332 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
4333 __ jmp(&return_result);
4336 // One-character separator case
4337 __ bind(&one_char_separator);
4338 // Get the separator one-byte character value.
4339 // Register "string" holds the separator.
4340 __ movzxbl(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4342 // Jump into the loop after the code that copies the separator, so the first
4343 // element is not preceded by a separator
4344 __ jmp(&loop_2_entry);
4345 // Loop condition: while (index < length).
4347 // Each iteration of the loop concatenates one string to the result.
4348 // Live values in registers:
4349 // elements: The FixedArray of strings we are joining.
4350 // index: which element of the elements array we are adding to the result.
4351 // result_pos: the position to which we are currently copying characters.
4352 // scratch: Separator character.
4354 // Copy the separator character to the result.
4355 __ movb(Operand(result_pos, 0), scratch);
4356 __ incp(result_pos);
4358 __ bind(&loop_2_entry);
4359 // Get string = array[index].
4360 __ movp(string, FieldOperand(elements, index,
4362 FixedArray::kHeaderSize));
4363 __ SmiToInteger32(string_length,
4364 FieldOperand(string, String::kLengthOffset));
4366 FieldOperand(string, SeqOneByteString::kHeaderSize));
4367 __ CopyBytes(result_pos, string, string_length);
4369 __ cmpl(index, array_length_operand);
4370 __ j(less, &loop_2); // End while (index < length).
4374 // Long separator case (separator is more than one character).
4375 __ bind(&long_separator);
4377 // Make elements point to end of elements array, and index
4378 // count from -array_length to zero, so we don't need to maintain
4380 __ movl(index, array_length_operand);
4381 __ leap(elements, FieldOperand(elements, index, times_pointer_size,
4382 FixedArray::kHeaderSize));
4385 // Replace separator string with pointer to its first character, and
4386 // make scratch be its length.
4387 __ movp(string, separator_operand);
4388 __ SmiToInteger32(scratch,
4389 FieldOperand(string, String::kLengthOffset));
4391 FieldOperand(string, SeqOneByteString::kHeaderSize));
4392 __ movp(separator_operand, string);
4394 // Jump into the loop after the code that copies the separator, so the first
4395 // element is not preceded by a separator
4396 __ jmp(&loop_3_entry);
4397 // Loop condition: while (index < length).
4399 // Each iteration of the loop concatenates one string to the result.
4400 // Live values in registers:
4401 // index: which element of the elements array we are adding to the result.
4402 // result_pos: the position to which we are currently copying characters.
4403 // scratch: Separator length.
4404 // separator_operand (rsp[0x10]): Address of first char of separator.
4406 // Copy the separator to the result.
4407 __ movp(string, separator_operand);
4408 __ movl(string_length, scratch);
4409 __ CopyBytes(result_pos, string, string_length, 2);
4411 __ bind(&loop_3_entry);
4412 // Get string = array[index].
4413 __ movp(string, Operand(elements, index, times_pointer_size, 0));
4414 __ SmiToInteger32(string_length,
4415 FieldOperand(string, String::kLengthOffset));
4417 FieldOperand(string, SeqOneByteString::kHeaderSize));
4418 __ CopyBytes(result_pos, string, string_length);
4420 __ j(not_equal, &loop_3); // Loop while (index < 0).
4423 __ movp(rax, result_operand);
4425 __ bind(&return_result);
4426 // Drop temp values from the stack, and restore context register.
4427 __ addp(rsp, Immediate(3 * kPointerSize));
4428 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4429 context()->Plug(rax);
4433 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4434 DCHECK(expr->arguments()->length() == 0);
4435 ExternalReference debug_is_active =
4436 ExternalReference::debug_is_active_address(isolate());
4437 __ Move(kScratchRegister, debug_is_active);
4438 __ movzxbp(rax, Operand(kScratchRegister, 0));
4439 __ Integer32ToSmi(rax, rax);
4440 context()->Plug(rax);
4444 void FullCodeGenerator::EmitCreateIterResultObject(CallRuntime* expr) {
4445 ZoneList<Expression*>* args = expr->arguments();
4446 DCHECK_EQ(2, args->length());
4447 VisitForStackValue(args->at(0));
4448 VisitForStackValue(args->at(1));
4450 Label runtime, done;
4452 __ Allocate(JSIteratorResult::kSize, rax, rcx, rdx, &runtime, TAG_OBJECT);
4453 __ movp(rbx, GlobalObjectOperand());
4454 __ movp(rbx, FieldOperand(rbx, GlobalObject::kNativeContextOffset));
4455 __ movp(rbx, ContextOperand(rbx, Context::ITERATOR_RESULT_MAP_INDEX));
4456 __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
4457 __ LoadRoot(rbx, Heap::kEmptyFixedArrayRootIndex);
4458 __ movp(FieldOperand(rax, JSObject::kPropertiesOffset), rbx);
4459 __ movp(FieldOperand(rax, JSObject::kElementsOffset), rbx);
4460 __ Pop(FieldOperand(rax, JSIteratorResult::kDoneOffset));
4461 __ Pop(FieldOperand(rax, JSIteratorResult::kValueOffset));
4462 STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
4463 __ jmp(&done, Label::kNear);
4466 __ CallRuntime(Runtime::kCreateIterResultObject, 2);
4469 context()->Plug(rax);
4473 void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
4474 // Push the builtins object as receiver.
4475 __ PushRoot(Heap::kUndefinedValueRootIndex);
4477 __ movp(rax, GlobalObjectOperand());
4478 __ movp(rax, FieldOperand(rax, GlobalObject::kNativeContextOffset));
4479 __ movp(rax, ContextOperand(rax, expr->context_index()));
4483 void FullCodeGenerator::EmitCallJSRuntimeFunction(CallRuntime* expr) {
4484 ZoneList<Expression*>* args = expr->arguments();
4485 int arg_count = args->length();
4487 SetCallPosition(expr, arg_count);
4488 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4489 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
4494 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4495 ZoneList<Expression*>* args = expr->arguments();
4496 int arg_count = args->length();
4498 if (expr->is_jsruntime()) {
4499 Comment cmnt(masm_, "[ CallRuntime");
4501 EmitLoadJSRuntimeFunction(expr);
4503 // Push the target function under the receiver.
4504 __ Push(Operand(rsp, 0));
4505 __ movp(Operand(rsp, kPointerSize), rax);
4507 // Push the arguments ("left-to-right").
4508 for (int i = 0; i < arg_count; i++) {
4509 VisitForStackValue(args->at(i));
4512 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4513 EmitCallJSRuntimeFunction(expr);
4515 // Restore context register.
4516 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4517 context()->DropAndPlug(1, rax);
4520 const Runtime::Function* function = expr->function();
4521 switch (function->function_id) {
4522 #define CALL_INTRINSIC_GENERATOR(Name) \
4523 case Runtime::kInline##Name: { \
4524 Comment cmnt(masm_, "[ Inline" #Name); \
4525 return Emit##Name(expr); \
4527 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
4528 #undef CALL_INTRINSIC_GENERATOR
4530 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
4531 // Push the arguments ("left-to-right").
4532 for (int i = 0; i < arg_count; i++) {
4533 VisitForStackValue(args->at(i));
4536 // Call the C runtime.
4537 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4538 __ CallRuntime(function, arg_count);
4539 context()->Plug(rax);
4546 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4547 switch (expr->op()) {
4548 case Token::DELETE: {
4549 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4550 Property* property = expr->expression()->AsProperty();
4551 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4553 if (property != NULL) {
4554 VisitForStackValue(property->obj());
4555 VisitForStackValue(property->key());
4556 __ CallRuntime(is_strict(language_mode())
4557 ? Runtime::kDeleteProperty_Strict
4558 : Runtime::kDeleteProperty_Sloppy,
4560 context()->Plug(rax);
4561 } else if (proxy != NULL) {
4562 Variable* var = proxy->var();
4563 // Delete of an unqualified identifier is disallowed in strict mode but
4564 // "delete this" is allowed.
4565 bool is_this = var->HasThisName(isolate());
4566 DCHECK(is_sloppy(language_mode()) || is_this);
4567 if (var->IsUnallocatedOrGlobalSlot()) {
4568 __ Push(GlobalObjectOperand());
4569 __ Push(var->name());
4570 __ CallRuntime(Runtime::kDeleteProperty_Sloppy, 2);
4571 context()->Plug(rax);
4572 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4573 // Result of deleting non-global variables is false. 'this' is
4574 // not really a variable, though we implement it as one. The
4575 // subexpression does not have side effects.
4576 context()->Plug(is_this);
4578 // Non-global variable. Call the runtime to try to delete from the
4579 // context where the variable was introduced.
4580 __ Push(context_register());
4581 __ Push(var->name());
4582 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4583 context()->Plug(rax);
4586 // Result of deleting non-property, non-variable reference is true.
4587 // The subexpression may have side effects.
4588 VisitForEffect(expr->expression());
4589 context()->Plug(true);
4595 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4596 VisitForEffect(expr->expression());
4597 context()->Plug(Heap::kUndefinedValueRootIndex);
4602 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4603 if (context()->IsEffect()) {
4604 // Unary NOT has no side effects so it's only necessary to visit the
4605 // subexpression. Match the optimizing compiler by not branching.
4606 VisitForEffect(expr->expression());
4607 } else if (context()->IsTest()) {
4608 const TestContext* test = TestContext::cast(context());
4609 // The labels are swapped for the recursive call.
4610 VisitForControl(expr->expression(),
4611 test->false_label(),
4613 test->fall_through());
4614 context()->Plug(test->true_label(), test->false_label());
4616 // We handle value contexts explicitly rather than simply visiting
4617 // for control and plugging the control flow into the context,
4618 // because we need to prepare a pair of extra administrative AST ids
4619 // for the optimizing compiler.
4620 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4621 Label materialize_true, materialize_false, done;
4622 VisitForControl(expr->expression(),
4626 __ bind(&materialize_true);
4627 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4628 if (context()->IsAccumulatorValue()) {
4629 __ LoadRoot(rax, Heap::kTrueValueRootIndex);
4631 __ PushRoot(Heap::kTrueValueRootIndex);
4633 __ jmp(&done, Label::kNear);
4634 __ bind(&materialize_false);
4635 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4636 if (context()->IsAccumulatorValue()) {
4637 __ LoadRoot(rax, Heap::kFalseValueRootIndex);
4639 __ PushRoot(Heap::kFalseValueRootIndex);
4646 case Token::TYPEOF: {
4647 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4649 AccumulatorValueContext context(this);
4650 VisitForTypeofValue(expr->expression());
4653 TypeofStub typeof_stub(isolate());
4654 __ CallStub(&typeof_stub);
4655 context()->Plug(rax);
4665 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4666 DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
4668 Comment cmnt(masm_, "[ CountOperation");
4670 Property* prop = expr->expression()->AsProperty();
4671 LhsKind assign_type = Property::GetAssignType(prop);
4673 // Evaluate expression and get value.
4674 if (assign_type == VARIABLE) {
4675 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4676 AccumulatorValueContext context(this);
4677 EmitVariableLoad(expr->expression()->AsVariableProxy());
4679 // Reserve space for result of postfix operation.
4680 if (expr->is_postfix() && !context()->IsEffect()) {
4681 __ Push(Smi::FromInt(0));
4683 switch (assign_type) {
4684 case NAMED_PROPERTY: {
4685 VisitForStackValue(prop->obj());
4686 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
4687 EmitNamedPropertyLoad(prop);
4691 case NAMED_SUPER_PROPERTY: {
4692 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4693 VisitForAccumulatorValue(
4694 prop->obj()->AsSuperPropertyReference()->home_object());
4695 __ Push(result_register());
4696 __ Push(MemOperand(rsp, kPointerSize));
4697 __ Push(result_register());
4698 EmitNamedSuperPropertyLoad(prop);
4702 case KEYED_SUPER_PROPERTY: {
4703 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4705 prop->obj()->AsSuperPropertyReference()->home_object());
4706 VisitForAccumulatorValue(prop->key());
4707 __ Push(result_register());
4708 __ Push(MemOperand(rsp, 2 * kPointerSize));
4709 __ Push(MemOperand(rsp, 2 * kPointerSize));
4710 __ Push(result_register());
4711 EmitKeyedSuperPropertyLoad(prop);
4715 case KEYED_PROPERTY: {
4716 VisitForStackValue(prop->obj());
4717 VisitForStackValue(prop->key());
4718 // Leave receiver on stack
4719 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
4720 // Copy of key, needed for later store.
4721 __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
4722 EmitKeyedPropertyLoad(prop);
4731 // We need a second deoptimization point after loading the value
4732 // in case evaluating the property load my have a side effect.
4733 if (assign_type == VARIABLE) {
4734 PrepareForBailout(expr->expression(), TOS_REG);
4736 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4739 // Inline smi case if we are in a loop.
4740 Label done, stub_call;
4741 JumpPatchSite patch_site(masm_);
4742 if (ShouldInlineSmiCase(expr->op())) {
4744 patch_site.EmitJumpIfNotSmi(rax, &slow, Label::kNear);
4746 // Save result for postfix expressions.
4747 if (expr->is_postfix()) {
4748 if (!context()->IsEffect()) {
4749 // Save the result on the stack. If we have a named or keyed property
4750 // we store the result under the receiver that is currently on top
4752 switch (assign_type) {
4756 case NAMED_PROPERTY:
4757 __ movp(Operand(rsp, kPointerSize), rax);
4759 case NAMED_SUPER_PROPERTY:
4760 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4762 case KEYED_PROPERTY:
4763 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4765 case KEYED_SUPER_PROPERTY:
4766 __ movp(Operand(rsp, 3 * kPointerSize), rax);
4772 SmiOperationConstraints constraints =
4773 SmiOperationConstraint::kPreserveSourceRegister |
4774 SmiOperationConstraint::kBailoutOnNoOverflow;
4775 if (expr->op() == Token::INC) {
4776 __ SmiAddConstant(rax, rax, Smi::FromInt(1), constraints, &done,
4779 __ SmiSubConstant(rax, rax, Smi::FromInt(1), constraints, &done,
4782 __ jmp(&stub_call, Label::kNear);
4785 if (!is_strong(language_mode())) {
4786 ToNumberStub convert_stub(isolate());
4787 __ CallStub(&convert_stub);
4788 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4791 // Save result for postfix expressions.
4792 if (expr->is_postfix()) {
4793 if (!context()->IsEffect()) {
4794 // Save the result on the stack. If we have a named or keyed property
4795 // we store the result under the receiver that is currently on top
4797 switch (assign_type) {
4801 case NAMED_PROPERTY:
4802 __ movp(Operand(rsp, kPointerSize), rax);
4804 case NAMED_SUPER_PROPERTY:
4805 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4807 case KEYED_PROPERTY:
4808 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4810 case KEYED_SUPER_PROPERTY:
4811 __ movp(Operand(rsp, 3 * kPointerSize), rax);
4817 SetExpressionPosition(expr);
4819 // Call stub for +1/-1.
4820 __ bind(&stub_call);
4822 __ Move(rax, Smi::FromInt(1));
4823 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
4824 strength(language_mode())).code();
4825 CallIC(code, expr->CountBinOpFeedbackId());
4826 patch_site.EmitPatchInfo();
4829 if (is_strong(language_mode())) {
4830 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4832 // Store the value returned in rax.
4833 switch (assign_type) {
4835 if (expr->is_postfix()) {
4836 // Perform the assignment as if via '='.
4837 { EffectContext context(this);
4838 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4839 Token::ASSIGN, expr->CountSlot());
4840 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4843 // For all contexts except kEffect: We have the result on
4844 // top of the stack.
4845 if (!context()->IsEffect()) {
4846 context()->PlugTOS();
4849 // Perform the assignment as if via '='.
4850 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4851 Token::ASSIGN, expr->CountSlot());
4852 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4853 context()->Plug(rax);
4856 case NAMED_PROPERTY: {
4857 __ Move(StoreDescriptor::NameRegister(),
4858 prop->key()->AsLiteral()->value());
4859 __ Pop(StoreDescriptor::ReceiverRegister());
4860 if (FLAG_vector_stores) {
4861 EmitLoadStoreICSlot(expr->CountSlot());
4864 CallStoreIC(expr->CountStoreFeedbackId());
4866 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4867 if (expr->is_postfix()) {
4868 if (!context()->IsEffect()) {
4869 context()->PlugTOS();
4872 context()->Plug(rax);
4876 case NAMED_SUPER_PROPERTY: {
4877 EmitNamedSuperPropertyStore(prop);
4878 if (expr->is_postfix()) {
4879 if (!context()->IsEffect()) {
4880 context()->PlugTOS();
4883 context()->Plug(rax);
4887 case KEYED_SUPER_PROPERTY: {
4888 EmitKeyedSuperPropertyStore(prop);
4889 if (expr->is_postfix()) {
4890 if (!context()->IsEffect()) {
4891 context()->PlugTOS();
4894 context()->Plug(rax);
4898 case KEYED_PROPERTY: {
4899 __ Pop(StoreDescriptor::NameRegister());
4900 __ Pop(StoreDescriptor::ReceiverRegister());
4902 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4903 if (FLAG_vector_stores) {
4904 EmitLoadStoreICSlot(expr->CountSlot());
4907 CallIC(ic, expr->CountStoreFeedbackId());
4909 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4910 if (expr->is_postfix()) {
4911 if (!context()->IsEffect()) {
4912 context()->PlugTOS();
4915 context()->Plug(rax);
4923 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4924 Expression* sub_expr,
4925 Handle<String> check) {
4926 Label materialize_true, materialize_false;
4927 Label* if_true = NULL;
4928 Label* if_false = NULL;
4929 Label* fall_through = NULL;
4930 context()->PrepareTest(&materialize_true, &materialize_false,
4931 &if_true, &if_false, &fall_through);
4933 { AccumulatorValueContext context(this);
4934 VisitForTypeofValue(sub_expr);
4936 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4938 Factory* factory = isolate()->factory();
4939 if (String::Equals(check, factory->number_string())) {
4940 __ JumpIfSmi(rax, if_true);
4941 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
4942 __ CompareRoot(rax, Heap::kHeapNumberMapRootIndex);
4943 Split(equal, if_true, if_false, fall_through);
4944 } else if (String::Equals(check, factory->string_string())) {
4945 __ JumpIfSmi(rax, if_false);
4946 __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, rdx);
4947 Split(below, if_true, if_false, fall_through);
4948 } else if (String::Equals(check, factory->symbol_string())) {
4949 __ JumpIfSmi(rax, if_false);
4950 __ CmpObjectType(rax, SYMBOL_TYPE, rdx);
4951 Split(equal, if_true, if_false, fall_through);
4952 } else if (String::Equals(check, factory->boolean_string())) {
4953 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
4954 __ j(equal, if_true);
4955 __ CompareRoot(rax, Heap::kFalseValueRootIndex);
4956 Split(equal, if_true, if_false, fall_through);
4957 } else if (String::Equals(check, factory->undefined_string())) {
4958 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
4959 __ j(equal, if_true);
4960 __ JumpIfSmi(rax, if_false);
4961 // Check for undetectable objects => true.
4962 __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
4963 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
4964 Immediate(1 << Map::kIsUndetectable));
4965 Split(not_zero, if_true, if_false, fall_through);
4966 } else if (String::Equals(check, factory->function_string())) {
4967 __ JumpIfSmi(rax, if_false);
4968 // Check for callable and not undetectable objects => true.
4969 __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
4970 __ movzxbl(rdx, FieldOperand(rdx, Map::kBitFieldOffset));
4972 Immediate((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
4973 __ cmpb(rdx, Immediate(1 << Map::kIsCallable));
4974 Split(equal, if_true, if_false, fall_through);
4975 } else if (String::Equals(check, factory->object_string())) {
4976 __ JumpIfSmi(rax, if_false);
4977 __ CompareRoot(rax, Heap::kNullValueRootIndex);
4978 __ j(equal, if_true);
4979 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
4980 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rdx);
4981 __ j(below, if_false);
4982 // Check for callable or undetectable objects => false.
4983 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
4984 Immediate((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
4985 Split(zero, if_true, if_false, fall_through);
4987 #define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
4988 } else if (String::Equals(check, factory->type##_string())) { \
4989 __ JumpIfSmi(rax, if_false); \
4990 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset)); \
4991 __ CompareRoot(rax, Heap::k##Type##MapRootIndex); \
4992 Split(equal, if_true, if_false, fall_through);
4993 SIMD128_TYPES(SIMD128_TYPE)
4997 if (if_false != fall_through) __ jmp(if_false);
4999 context()->Plug(if_true, if_false);
5003 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5004 Comment cmnt(masm_, "[ CompareOperation");
5005 SetExpressionPosition(expr);
5007 // First we try a fast inlined version of the compare when one of
5008 // the operands is a literal.
5009 if (TryLiteralCompare(expr)) return;
5011 // Always perform the comparison for its control flow. Pack the result
5012 // into the expression's context after the comparison is performed.
5013 Label materialize_true, materialize_false;
5014 Label* if_true = NULL;
5015 Label* if_false = NULL;
5016 Label* fall_through = NULL;
5017 context()->PrepareTest(&materialize_true, &materialize_false,
5018 &if_true, &if_false, &fall_through);
5020 Token::Value op = expr->op();
5021 VisitForStackValue(expr->left());
5024 VisitForStackValue(expr->right());
5025 __ CallRuntime(Runtime::kHasProperty, 2);
5026 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5027 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
5028 Split(equal, if_true, if_false, fall_through);
5031 case Token::INSTANCEOF: {
5032 VisitForAccumulatorValue(expr->right());
5034 InstanceOfStub stub(isolate());
5036 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5037 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
5038 Split(equal, if_true, if_false, fall_through);
5043 VisitForAccumulatorValue(expr->right());
5044 Condition cc = CompareIC::ComputeCondition(op);
5047 bool inline_smi_code = ShouldInlineSmiCase(op);
5048 JumpPatchSite patch_site(masm_);
5049 if (inline_smi_code) {
5053 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
5055 Split(cc, if_true, if_false, NULL);
5056 __ bind(&slow_case);
5059 Handle<Code> ic = CodeFactory::CompareIC(
5060 isolate(), op, strength(language_mode())).code();
5061 CallIC(ic, expr->CompareOperationFeedbackId());
5062 patch_site.EmitPatchInfo();
5064 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5066 Split(cc, if_true, if_false, fall_through);
5070 // Convert the result of the comparison into one expected for this
5071 // expression's context.
5072 context()->Plug(if_true, if_false);
5076 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5077 Expression* sub_expr,
5079 Label materialize_true, materialize_false;
5080 Label* if_true = NULL;
5081 Label* if_false = NULL;
5082 Label* fall_through = NULL;
5083 context()->PrepareTest(&materialize_true, &materialize_false,
5084 &if_true, &if_false, &fall_through);
5086 VisitForAccumulatorValue(sub_expr);
5087 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5088 if (expr->op() == Token::EQ_STRICT) {
5089 Heap::RootListIndex nil_value = nil == kNullValue ?
5090 Heap::kNullValueRootIndex :
5091 Heap::kUndefinedValueRootIndex;
5092 __ CompareRoot(rax, nil_value);
5093 Split(equal, if_true, if_false, fall_through);
5095 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5096 CallIC(ic, expr->CompareOperationFeedbackId());
5098 Split(not_zero, if_true, if_false, fall_through);
5100 context()->Plug(if_true, if_false);
5104 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5105 __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
5106 context()->Plug(rax);
5110 Register FullCodeGenerator::result_register() {
5115 Register FullCodeGenerator::context_register() {
5120 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5121 DCHECK(IsAligned(frame_offset, kPointerSize));
5122 __ movp(Operand(rbp, frame_offset), value);
5126 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5127 __ movp(dst, ContextOperand(rsi, context_index));
5131 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5132 Scope* closure_scope = scope()->ClosureScope();
5133 if (closure_scope->is_script_scope() ||
5134 closure_scope->is_module_scope()) {
5135 // Contexts nested in the native context have a canonical empty function
5136 // as their closure, not the anonymous closure containing the global
5137 // code. Pass a smi sentinel and let the runtime look up the empty
5139 __ Push(Smi::FromInt(0));
5140 } else if (closure_scope->is_eval_scope()) {
5141 // Contexts created by a call to eval have the same closure as the
5142 // context calling eval, not the anonymous closure containing the eval
5143 // code. Fetch it from the context.
5144 __ Push(ContextOperand(rsi, Context::CLOSURE_INDEX));
5146 DCHECK(closure_scope->is_function_scope());
5147 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
5152 // ----------------------------------------------------------------------------
5153 // Non-local control flow support.
5156 void FullCodeGenerator::EnterFinallyBlock() {
5157 DCHECK(!result_register().is(rdx));
5158 DCHECK(!result_register().is(rcx));
5159 // Cook return address on top of stack (smi encoded Code* delta)
5160 __ PopReturnAddressTo(rdx);
5161 __ Move(rcx, masm_->CodeObject());
5163 __ Integer32ToSmi(rdx, rdx);
5166 // Store result register while executing finally block.
5167 __ Push(result_register());
5169 // Store pending message while executing finally block.
5170 ExternalReference pending_message_obj =
5171 ExternalReference::address_of_pending_message_obj(isolate());
5172 __ Load(rdx, pending_message_obj);
5175 ClearPendingMessage();
5179 void FullCodeGenerator::ExitFinallyBlock() {
5180 DCHECK(!result_register().is(rdx));
5181 DCHECK(!result_register().is(rcx));
5182 // Restore pending message from stack.
5184 ExternalReference pending_message_obj =
5185 ExternalReference::address_of_pending_message_obj(isolate());
5186 __ Store(pending_message_obj, rdx);
5188 // Restore result register from stack.
5189 __ Pop(result_register());
5191 // Uncook return address.
5193 __ SmiToInteger32(rdx, rdx);
5194 __ Move(rcx, masm_->CodeObject());
5200 void FullCodeGenerator::ClearPendingMessage() {
5201 DCHECK(!result_register().is(rdx));
5202 ExternalReference pending_message_obj =
5203 ExternalReference::address_of_pending_message_obj(isolate());
5204 __ LoadRoot(rdx, Heap::kTheHoleValueRootIndex);
5205 __ Store(pending_message_obj, rdx);
5209 void FullCodeGenerator::EmitLoadStoreICSlot(FeedbackVectorICSlot slot) {
5210 DCHECK(FLAG_vector_stores && !slot.IsInvalid());
5211 __ Move(VectorStoreICTrampolineDescriptor::SlotRegister(), SmiFromSlot(slot));
5218 static const byte kJnsInstruction = 0x79;
5219 static const byte kNopByteOne = 0x66;
5220 static const byte kNopByteTwo = 0x90;
5222 static const byte kCallInstruction = 0xe8;
5226 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5228 BackEdgeState target_state,
5229 Code* replacement_code) {
5230 Address call_target_address = pc - kIntSize;
5231 Address jns_instr_address = call_target_address - 3;
5232 Address jns_offset_address = call_target_address - 2;
5234 switch (target_state) {
5236 // sub <profiling_counter>, <delta> ;; Not changed
5238 // call <interrupt stub>
5240 *jns_instr_address = kJnsInstruction;
5241 *jns_offset_address = kJnsOffset;
5243 case ON_STACK_REPLACEMENT:
5244 case OSR_AFTER_STACK_CHECK:
5245 // sub <profiling_counter>, <delta> ;; Not changed
5248 // call <on-stack replacment>
5250 *jns_instr_address = kNopByteOne;
5251 *jns_offset_address = kNopByteTwo;
5255 Assembler::set_target_address_at(call_target_address,
5257 replacement_code->entry());
5258 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5259 unoptimized_code, call_target_address, replacement_code);
5263 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5265 Code* unoptimized_code,
5267 Address call_target_address = pc - kIntSize;
5268 Address jns_instr_address = call_target_address - 3;
5269 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5271 if (*jns_instr_address == kJnsInstruction) {
5272 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5273 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5274 Assembler::target_address_at(call_target_address,
5279 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5280 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5282 if (Assembler::target_address_at(call_target_address,
5283 unoptimized_code) ==
5284 isolate->builtins()->OnStackReplacement()->entry()) {
5285 return ON_STACK_REPLACEMENT;
5288 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5289 Assembler::target_address_at(call_target_address,
5291 return OSR_AFTER_STACK_CHECK;
5295 } // namespace internal
5298 #endif // V8_TARGET_ARCH_X64