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.
9 #include "src/code-factory.h"
10 #include "src/code-stubs.h"
11 #include "src/codegen.h"
12 #include "src/compiler.h"
13 #include "src/debug.h"
14 #include "src/full-codegen/full-codegen.h"
15 #include "src/ic/ic.h"
16 #include "src/parser.h"
17 #include "src/scopes.h"
22 #define __ ACCESS_MASM(masm_)
25 class JumpPatchSite BASE_EMBEDDED {
27 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
29 info_emitted_ = false;
34 DCHECK(patch_site_.is_bound() == info_emitted_);
37 void EmitJumpIfNotSmi(Register reg,
39 Label::Distance near_jump = Label::kFar) {
40 __ testb(reg, Immediate(kSmiTagMask));
41 EmitJump(not_carry, target, near_jump); // Always taken before patched.
44 void EmitJumpIfSmi(Register reg,
46 Label::Distance near_jump = Label::kFar) {
47 __ testb(reg, Immediate(kSmiTagMask));
48 EmitJump(carry, target, near_jump); // Never taken before patched.
51 void EmitPatchInfo() {
52 if (patch_site_.is_bound()) {
53 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
54 DCHECK(is_uint8(delta_to_patch_site));
55 __ testl(rax, Immediate(delta_to_patch_site));
60 __ nop(); // Signals no inlined code.
65 // jc will be patched with jz, jnc will become jnz.
66 void EmitJump(Condition cc, Label* target, Label::Distance near_jump) {
67 DCHECK(!patch_site_.is_bound() && !info_emitted_);
68 DCHECK(cc == carry || cc == not_carry);
69 __ bind(&patch_site_);
70 __ j(cc, target, near_jump);
73 MacroAssembler* masm_;
81 // Generate code for a JS function. On entry to the function the receiver
82 // and arguments have been pushed on the stack left to right, with the
83 // return address on top of them. The actual argument count matches the
84 // formal parameter count expected by the function.
86 // The live registers are:
87 // o rdi: the JS function object being called (i.e. ourselves)
89 // o rbp: our caller's frame pointer
90 // o rsp: stack pointer (pointing to return address)
92 // The function builds a JS frame. Please see JavaScriptFrameConstants in
93 // frames-x64.h for its layout.
94 void FullCodeGenerator::Generate() {
95 CompilationInfo* info = info_;
96 profiling_counter_ = isolate()->factory()->NewCell(
97 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
98 SetFunctionPosition(function());
99 Comment cmnt(masm_, "[ function compiled by full code generator");
101 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
104 if (strlen(FLAG_stop_at) > 0 &&
105 info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
110 // Sloppy mode functions and builtins need to replace the receiver with the
111 // global proxy when called as functions (without an explicit receiver
113 if (is_sloppy(info->language_mode()) && !info->is_native() &&
114 info->MayUseThis() && info->scope()->has_this_declaration()) {
116 // +1 for return address.
117 StackArgumentsAccessor args(rsp, info->scope()->num_parameters());
118 __ movp(rcx, args.GetReceiverOperand());
120 __ CompareRoot(rcx, Heap::kUndefinedValueRootIndex);
121 __ j(not_equal, &ok, Label::kNear);
123 __ movp(rcx, GlobalObjectOperand());
124 __ movp(rcx, FieldOperand(rcx, GlobalObject::kGlobalProxyOffset));
126 __ movp(args.GetReceiverOperand(), rcx);
131 // Open a frame scope to indicate that there is a frame on the stack. The
132 // MANUAL indicates that the scope shouldn't actually generate code to set up
133 // the frame (that is done below).
134 FrameScope frame_scope(masm_, StackFrame::MANUAL);
136 info->set_prologue_offset(masm_->pc_offset());
137 __ Prologue(info->IsCodePreAgingActive());
138 info->AddNoFrameRange(0, masm_->pc_offset());
140 { Comment cmnt(masm_, "[ Allocate locals");
141 int locals_count = info->scope()->num_stack_slots();
142 // Generators allocate locals, if any, in context slots.
143 DCHECK(!IsGeneratorFunction(info->function()->kind()) || locals_count == 0);
144 if (locals_count == 1) {
145 __ PushRoot(Heap::kUndefinedValueRootIndex);
146 } else if (locals_count > 1) {
147 if (locals_count >= 128) {
150 __ subp(rcx, Immediate(locals_count * kPointerSize));
151 __ CompareRoot(rcx, Heap::kRealStackLimitRootIndex);
152 __ j(above_equal, &ok, Label::kNear);
153 __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
156 __ LoadRoot(rdx, Heap::kUndefinedValueRootIndex);
157 const int kMaxPushes = 32;
158 if (locals_count >= kMaxPushes) {
159 int loop_iterations = locals_count / kMaxPushes;
160 __ movp(rcx, Immediate(loop_iterations));
162 __ bind(&loop_header);
164 for (int i = 0; i < kMaxPushes; i++) {
167 // Continue loop if not done.
169 __ j(not_zero, &loop_header, Label::kNear);
171 int remaining = locals_count % kMaxPushes;
172 // Emit the remaining pushes.
173 for (int i = 0; i < remaining; i++) {
179 bool function_in_register = true;
181 // Possibly allocate a local context.
182 if (info->scope()->num_heap_slots() > 0) {
183 Comment cmnt(masm_, "[ Allocate context");
184 bool need_write_barrier = true;
185 int slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
186 // Argument to NewContext is the function, which is still in rdi.
187 if (info->scope()->is_script_scope()) {
189 __ Push(info->scope()->GetScopeInfo(info->isolate()));
190 __ CallRuntime(Runtime::kNewScriptContext, 2);
191 } else if (slots <= FastNewContextStub::kMaximumSlots) {
192 FastNewContextStub stub(isolate(), slots);
194 // Result of FastNewContextStub is always in new space.
195 need_write_barrier = false;
198 __ CallRuntime(Runtime::kNewFunctionContext, 1);
200 function_in_register = false;
201 // Context is returned in rax. It replaces the context passed to us.
202 // It's saved in the stack and kept live in rsi.
204 __ movp(Operand(rbp, StandardFrameConstants::kContextOffset), rax);
206 // Copy any necessary parameters into the context.
207 int num_parameters = info->scope()->num_parameters();
208 int first_parameter = info->scope()->has_this_declaration() ? -1 : 0;
209 for (int i = first_parameter; i < num_parameters; i++) {
210 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
211 if (var->IsContextSlot()) {
212 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
213 (num_parameters - 1 - i) * kPointerSize;
214 // Load parameter from stack.
215 __ movp(rax, Operand(rbp, parameter_offset));
216 // Store it in the context.
217 int context_offset = Context::SlotOffset(var->index());
218 __ movp(Operand(rsi, context_offset), rax);
219 // Update the write barrier. This clobbers rax and rbx.
220 if (need_write_barrier) {
221 __ RecordWriteContextSlot(
222 rsi, context_offset, rax, rbx, kDontSaveFPRegs);
223 } else if (FLAG_debug_code) {
225 __ JumpIfInNewSpace(rsi, rax, &done, Label::kNear);
226 __ Abort(kExpectedNewSpaceObject);
233 // Possibly set up a local binding to the this function which is used in
234 // derived constructors with super calls.
235 Variable* this_function_var = scope()->this_function_var();
236 if (this_function_var != nullptr) {
237 Comment cmnt(masm_, "[ This function");
238 if (!function_in_register) {
239 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
240 // The write barrier clobbers register again, keep is marked as such.
242 SetVar(this_function_var, rdi, rbx, rdx);
245 Variable* new_target_var = scope()->new_target_var();
246 if (new_target_var != nullptr) {
247 Comment cmnt(masm_, "[ new.target");
249 __ movp(rax, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
250 Label non_adaptor_frame;
251 __ Cmp(Operand(rax, StandardFrameConstants::kContextOffset),
252 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
253 __ j(not_equal, &non_adaptor_frame);
254 __ movp(rax, Operand(rax, StandardFrameConstants::kCallerFPOffset));
256 __ bind(&non_adaptor_frame);
257 __ Cmp(Operand(rax, StandardFrameConstants::kMarkerOffset),
258 Smi::FromInt(StackFrame::CONSTRUCT));
260 Label non_construct_frame, done;
261 __ j(not_equal, &non_construct_frame);
265 Operand(rax, ConstructFrameConstants::kOriginalConstructorOffset));
268 // Non-construct frame
269 __ bind(&non_construct_frame);
270 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
273 SetVar(new_target_var, rax, rbx, rdx);
276 // Possibly allocate RestParameters
278 Variable* rest_param = scope()->rest_parameter(&rest_index);
280 Comment cmnt(masm_, "[ Allocate rest parameter array");
282 int num_parameters = info->scope()->num_parameters();
283 int offset = num_parameters * kPointerSize;
286 Operand(rbp, StandardFrameConstants::kCallerSPOffset + offset));
288 __ Push(Smi::FromInt(num_parameters));
289 __ Push(Smi::FromInt(rest_index));
290 __ Push(Smi::FromInt(language_mode()));
292 RestParamAccessStub stub(isolate());
295 SetVar(rest_param, rax, rbx, rdx);
298 // Possibly allocate an arguments object.
299 Variable* arguments = scope()->arguments();
300 if (arguments != NULL) {
301 // Arguments object must be allocated after the context object, in
302 // case the "arguments" or ".arguments" variables are in the context.
303 Comment cmnt(masm_, "[ Allocate arguments object");
304 if (function_in_register) {
307 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
309 // The receiver is just before the parameters on the caller's stack.
310 int num_parameters = info->scope()->num_parameters();
311 int offset = num_parameters * kPointerSize;
313 Operand(rbp, StandardFrameConstants::kCallerSPOffset + offset));
315 __ Push(Smi::FromInt(num_parameters));
316 // Arguments to ArgumentsAccessStub:
317 // function, receiver address, parameter count.
318 // The stub will rewrite receiver and parameter count if the previous
319 // stack frame was an arguments adapter frame.
321 ArgumentsAccessStub::Type type;
322 if (is_strict(language_mode()) || !is_simple_parameter_list()) {
323 type = ArgumentsAccessStub::NEW_STRICT;
324 } else if (function()->has_duplicate_parameters()) {
325 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
327 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
329 ArgumentsAccessStub stub(isolate(), type);
332 SetVar(arguments, rax, rbx, rdx);
336 __ CallRuntime(Runtime::kTraceEnter, 0);
339 // Visit the declarations and body unless there is an illegal
341 if (scope()->HasIllegalRedeclaration()) {
342 Comment cmnt(masm_, "[ Declarations");
343 scope()->VisitIllegalRedeclaration(this);
346 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
347 { Comment cmnt(masm_, "[ Declarations");
348 VisitDeclarations(scope()->declarations());
351 { Comment cmnt(masm_, "[ Stack check");
352 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
354 __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
355 __ j(above_equal, &ok, Label::kNear);
356 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
360 { Comment cmnt(masm_, "[ Body");
361 DCHECK(loop_depth() == 0);
362 VisitStatements(function()->body());
363 DCHECK(loop_depth() == 0);
367 // Always emit a 'return undefined' in case control fell off the end of
369 { Comment cmnt(masm_, "[ return <undefined>;");
370 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
371 EmitReturnSequence();
376 void FullCodeGenerator::ClearAccumulator() {
381 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
382 __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
383 __ SmiAddConstant(FieldOperand(rbx, Cell::kValueOffset),
384 Smi::FromInt(-delta));
388 void FullCodeGenerator::EmitProfilingCounterReset() {
389 int reset_value = FLAG_interrupt_budget;
390 __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
391 __ Move(kScratchRegister, Smi::FromInt(reset_value));
392 __ movp(FieldOperand(rbx, Cell::kValueOffset), kScratchRegister);
396 static const byte kJnsOffset = kPointerSize == kInt64Size ? 0x1d : 0x14;
399 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
400 Label* back_edge_target) {
401 Comment cmnt(masm_, "[ Back edge bookkeeping");
404 DCHECK(back_edge_target->is_bound());
405 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
406 int weight = Min(kMaxBackEdgeWeight,
407 Max(1, distance / kCodeSizeMultiplier));
408 EmitProfilingCounterDecrement(weight);
410 __ j(positive, &ok, Label::kNear);
412 PredictableCodeSizeScope predictible_code_size_scope(masm_, kJnsOffset);
413 DontEmitDebugCodeScope dont_emit_debug_code_scope(masm_);
414 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
416 // Record a mapping of this PC offset to the OSR id. This is used to find
417 // the AST id from the unoptimized code in order to use it as a key into
418 // the deoptimization input data found in the optimized code.
419 RecordBackEdge(stmt->OsrEntryId());
421 EmitProfilingCounterReset();
425 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
426 // Record a mapping of the OSR id to this PC. This is used if the OSR
427 // entry becomes the target of a bailout. We don't expect it to be, but
428 // we want it to work if it is.
429 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
433 void FullCodeGenerator::EmitReturnSequence() {
434 Comment cmnt(masm_, "[ Return sequence");
435 if (return_label_.is_bound()) {
436 __ jmp(&return_label_);
438 __ bind(&return_label_);
441 __ CallRuntime(Runtime::kTraceExit, 1);
443 // Pretend that the exit is a backwards jump to the entry.
445 if (info_->ShouldSelfOptimize()) {
446 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
448 int distance = masm_->pc_offset();
449 weight = Min(kMaxBackEdgeWeight,
450 Max(1, distance / kCodeSizeMultiplier));
452 EmitProfilingCounterDecrement(weight);
454 __ j(positive, &ok, Label::kNear);
456 __ call(isolate()->builtins()->InterruptCheck(),
457 RelocInfo::CODE_TARGET);
459 EmitProfilingCounterReset();
462 SetReturnPosition(function());
463 int no_frame_start = masm_->pc_offset();
466 int arg_count = info_->scope()->num_parameters() + 1;
467 int arguments_bytes = arg_count * kPointerSize;
468 __ Ret(arguments_bytes, rcx);
470 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
475 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
476 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
477 MemOperand operand = codegen()->VarOperand(var, result_register());
482 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
486 void FullCodeGenerator::AccumulatorValueContext::Plug(
487 Heap::RootListIndex index) const {
488 __ LoadRoot(result_register(), index);
492 void FullCodeGenerator::StackValueContext::Plug(
493 Heap::RootListIndex index) const {
498 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
499 codegen()->PrepareForBailoutBeforeSplit(condition(),
503 if (index == Heap::kUndefinedValueRootIndex ||
504 index == Heap::kNullValueRootIndex ||
505 index == Heap::kFalseValueRootIndex) {
506 if (false_label_ != fall_through_) __ jmp(false_label_);
507 } else if (index == Heap::kTrueValueRootIndex) {
508 if (true_label_ != fall_through_) __ jmp(true_label_);
510 __ LoadRoot(result_register(), index);
511 codegen()->DoTest(this);
516 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
520 void FullCodeGenerator::AccumulatorValueContext::Plug(
521 Handle<Object> lit) const {
523 __ SafeMove(result_register(), Smi::cast(*lit));
525 __ Move(result_register(), lit);
530 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
532 __ SafePush(Smi::cast(*lit));
539 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
540 codegen()->PrepareForBailoutBeforeSplit(condition(),
544 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
545 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
546 if (false_label_ != fall_through_) __ jmp(false_label_);
547 } else if (lit->IsTrue() || lit->IsJSObject()) {
548 if (true_label_ != fall_through_) __ jmp(true_label_);
549 } else if (lit->IsString()) {
550 if (String::cast(*lit)->length() == 0) {
551 if (false_label_ != fall_through_) __ jmp(false_label_);
553 if (true_label_ != fall_through_) __ jmp(true_label_);
555 } else if (lit->IsSmi()) {
556 if (Smi::cast(*lit)->value() == 0) {
557 if (false_label_ != fall_through_) __ jmp(false_label_);
559 if (true_label_ != fall_through_) __ jmp(true_label_);
562 // For simplicity we always test the accumulator register.
563 __ Move(result_register(), lit);
564 codegen()->DoTest(this);
569 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
570 Register reg) const {
576 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
578 Register reg) const {
581 __ Move(result_register(), reg);
585 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
586 Register reg) const {
588 if (count > 1) __ Drop(count - 1);
589 __ movp(Operand(rsp, 0), reg);
593 void FullCodeGenerator::TestContext::DropAndPlug(int count,
594 Register reg) const {
596 // For simplicity we always test the accumulator register.
598 __ Move(result_register(), reg);
599 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
600 codegen()->DoTest(this);
604 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
605 Label* materialize_false) const {
606 DCHECK(materialize_true == materialize_false);
607 __ bind(materialize_true);
611 void FullCodeGenerator::AccumulatorValueContext::Plug(
612 Label* materialize_true,
613 Label* materialize_false) const {
615 __ bind(materialize_true);
616 __ Move(result_register(), isolate()->factory()->true_value());
617 __ jmp(&done, Label::kNear);
618 __ bind(materialize_false);
619 __ Move(result_register(), isolate()->factory()->false_value());
624 void FullCodeGenerator::StackValueContext::Plug(
625 Label* materialize_true,
626 Label* materialize_false) const {
628 __ bind(materialize_true);
629 __ Push(isolate()->factory()->true_value());
630 __ jmp(&done, Label::kNear);
631 __ bind(materialize_false);
632 __ Push(isolate()->factory()->false_value());
637 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
638 Label* materialize_false) const {
639 DCHECK(materialize_true == true_label_);
640 DCHECK(materialize_false == false_label_);
644 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
645 Heap::RootListIndex value_root_index =
646 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
647 __ LoadRoot(result_register(), value_root_index);
651 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
652 Heap::RootListIndex value_root_index =
653 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
654 __ PushRoot(value_root_index);
658 void FullCodeGenerator::TestContext::Plug(bool flag) const {
659 codegen()->PrepareForBailoutBeforeSplit(condition(),
664 if (true_label_ != fall_through_) __ jmp(true_label_);
666 if (false_label_ != fall_through_) __ jmp(false_label_);
671 void FullCodeGenerator::DoTest(Expression* condition,
674 Label* fall_through) {
675 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
676 CallIC(ic, condition->test_id());
677 __ testp(result_register(), result_register());
678 // The stub returns nonzero for true.
679 Split(not_zero, if_true, if_false, fall_through);
683 void FullCodeGenerator::Split(Condition cc,
686 Label* fall_through) {
687 if (if_false == fall_through) {
689 } else if (if_true == fall_through) {
690 __ j(NegateCondition(cc), if_false);
698 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
699 DCHECK(var->IsStackAllocated());
700 // Offset is negative because higher indexes are at lower addresses.
701 int offset = -var->index() * kPointerSize;
702 // Adjust by a (parameter or local) base offset.
703 if (var->IsParameter()) {
704 offset += kFPOnStackSize + kPCOnStackSize +
705 (info_->scope()->num_parameters() - 1) * kPointerSize;
707 offset += JavaScriptFrameConstants::kLocal0Offset;
709 return Operand(rbp, offset);
713 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
714 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
715 if (var->IsContextSlot()) {
716 int context_chain_length = scope()->ContextChainLength(var->scope());
717 __ LoadContext(scratch, context_chain_length);
718 return ContextOperand(scratch, var->index());
720 return StackOperand(var);
725 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
726 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
727 MemOperand location = VarOperand(var, dest);
728 __ movp(dest, location);
732 void FullCodeGenerator::SetVar(Variable* var,
736 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
737 DCHECK(!scratch0.is(src));
738 DCHECK(!scratch0.is(scratch1));
739 DCHECK(!scratch1.is(src));
740 MemOperand location = VarOperand(var, scratch0);
741 __ movp(location, src);
743 // Emit the write barrier code if the location is in the heap.
744 if (var->IsContextSlot()) {
745 int offset = Context::SlotOffset(var->index());
746 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
751 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
752 bool should_normalize,
755 // Only prepare for bailouts before splits if we're in a test
756 // context. Otherwise, we let the Visit function deal with the
757 // preparation to avoid preparing with the same AST id twice.
758 if (!context()->IsTest() || !info_->IsOptimizable()) return;
761 if (should_normalize) __ jmp(&skip, Label::kNear);
762 PrepareForBailout(expr, TOS_REG);
763 if (should_normalize) {
764 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
765 Split(equal, if_true, if_false, NULL);
771 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
772 // The variable in the declaration always resides in the current context.
773 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
774 if (generate_debug_code_) {
775 // Check that we're not inside a with or catch context.
776 __ movp(rbx, FieldOperand(rsi, HeapObject::kMapOffset));
777 __ CompareRoot(rbx, Heap::kWithContextMapRootIndex);
778 __ Check(not_equal, kDeclarationInWithContext);
779 __ CompareRoot(rbx, Heap::kCatchContextMapRootIndex);
780 __ Check(not_equal, kDeclarationInCatchContext);
785 void FullCodeGenerator::VisitVariableDeclaration(
786 VariableDeclaration* declaration) {
787 // If it was not possible to allocate the variable at compile time, we
788 // need to "declare" it at runtime to make sure it actually exists in the
790 VariableProxy* proxy = declaration->proxy();
791 VariableMode mode = declaration->mode();
792 Variable* variable = proxy->var();
793 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
794 switch (variable->location()) {
795 case VariableLocation::GLOBAL:
796 case VariableLocation::UNALLOCATED:
797 globals_->Add(variable->name(), zone());
798 globals_->Add(variable->binding_needs_init()
799 ? isolate()->factory()->the_hole_value()
800 : isolate()->factory()->undefined_value(),
804 case VariableLocation::PARAMETER:
805 case VariableLocation::LOCAL:
807 Comment cmnt(masm_, "[ VariableDeclaration");
808 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
809 __ movp(StackOperand(variable), kScratchRegister);
813 case VariableLocation::CONTEXT:
815 Comment cmnt(masm_, "[ VariableDeclaration");
816 EmitDebugCheckDeclarationContext(variable);
817 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
818 __ movp(ContextOperand(rsi, variable->index()), kScratchRegister);
819 // No write barrier since the hole value is in old space.
820 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
824 case VariableLocation::LOOKUP: {
825 Comment cmnt(masm_, "[ VariableDeclaration");
827 __ Push(variable->name());
828 // Declaration nodes are always introduced in one of four modes.
829 DCHECK(IsDeclaredVariableMode(mode));
830 PropertyAttributes attr =
831 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
832 __ Push(Smi::FromInt(attr));
833 // Push initial value, if any.
834 // Note: For variables we must not push an initial value (such as
835 // 'undefined') because we may have a (legal) redeclaration and we
836 // must not destroy the current value.
838 __ PushRoot(Heap::kTheHoleValueRootIndex);
840 __ Push(Smi::FromInt(0)); // Indicates no initial value.
842 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
849 void FullCodeGenerator::VisitFunctionDeclaration(
850 FunctionDeclaration* declaration) {
851 VariableProxy* proxy = declaration->proxy();
852 Variable* variable = proxy->var();
853 switch (variable->location()) {
854 case VariableLocation::GLOBAL:
855 case VariableLocation::UNALLOCATED: {
856 globals_->Add(variable->name(), zone());
857 Handle<SharedFunctionInfo> function =
858 Compiler::GetSharedFunctionInfo(declaration->fun(), script(), info_);
859 // Check for stack-overflow exception.
860 if (function.is_null()) return SetStackOverflow();
861 globals_->Add(function, zone());
865 case VariableLocation::PARAMETER:
866 case VariableLocation::LOCAL: {
867 Comment cmnt(masm_, "[ FunctionDeclaration");
868 VisitForAccumulatorValue(declaration->fun());
869 __ movp(StackOperand(variable), result_register());
873 case VariableLocation::CONTEXT: {
874 Comment cmnt(masm_, "[ FunctionDeclaration");
875 EmitDebugCheckDeclarationContext(variable);
876 VisitForAccumulatorValue(declaration->fun());
877 __ movp(ContextOperand(rsi, variable->index()), result_register());
878 int offset = Context::SlotOffset(variable->index());
879 // We know that we have written a function, which is not a smi.
880 __ RecordWriteContextSlot(rsi,
887 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
891 case VariableLocation::LOOKUP: {
892 Comment cmnt(masm_, "[ FunctionDeclaration");
894 __ Push(variable->name());
895 __ Push(Smi::FromInt(NONE));
896 VisitForStackValue(declaration->fun());
897 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
904 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
905 // Call the runtime to declare the globals.
906 __ Push(rsi); // The context is the first argument.
908 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
909 __ CallRuntime(Runtime::kDeclareGlobals, 3);
910 // Return value is ignored.
914 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
915 // Call the runtime to declare the modules.
916 __ Push(descriptions);
917 __ CallRuntime(Runtime::kDeclareModules, 1);
918 // Return value is ignored.
922 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
923 Comment cmnt(masm_, "[ SwitchStatement");
924 Breakable nested_statement(this, stmt);
925 SetStatementPosition(stmt);
927 // Keep the switch value on the stack until a case matches.
928 VisitForStackValue(stmt->tag());
929 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
931 ZoneList<CaseClause*>* clauses = stmt->cases();
932 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
934 Label next_test; // Recycled for each test.
935 // Compile all the tests with branches to their bodies.
936 for (int i = 0; i < clauses->length(); i++) {
937 CaseClause* clause = clauses->at(i);
938 clause->body_target()->Unuse();
940 // The default is not a test, but remember it as final fall through.
941 if (clause->is_default()) {
942 default_clause = clause;
946 Comment cmnt(masm_, "[ Case comparison");
950 // Compile the label expression.
951 VisitForAccumulatorValue(clause->label());
953 // Perform the comparison as if via '==='.
954 __ movp(rdx, Operand(rsp, 0)); // Switch value.
955 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
956 JumpPatchSite patch_site(masm_);
957 if (inline_smi_code) {
961 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
964 __ j(not_equal, &next_test);
965 __ Drop(1); // Switch value is no longer needed.
966 __ jmp(clause->body_target());
970 // Record position before stub call for type feedback.
971 SetExpressionPosition(clause);
972 Handle<Code> ic = CodeFactory::CompareIC(isolate(), Token::EQ_STRICT,
973 strength(language_mode())).code();
974 CallIC(ic, clause->CompareId());
975 patch_site.EmitPatchInfo();
978 __ jmp(&skip, Label::kNear);
979 PrepareForBailout(clause, TOS_REG);
980 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
981 __ j(not_equal, &next_test);
983 __ jmp(clause->body_target());
987 __ j(not_equal, &next_test);
988 __ Drop(1); // Switch value is no longer needed.
989 __ jmp(clause->body_target());
992 // Discard the test value and jump to the default if present, otherwise to
993 // the end of the statement.
995 __ Drop(1); // Switch value is no longer needed.
996 if (default_clause == NULL) {
997 __ jmp(nested_statement.break_label());
999 __ jmp(default_clause->body_target());
1002 // Compile all the case bodies.
1003 for (int i = 0; i < clauses->length(); i++) {
1004 Comment cmnt(masm_, "[ Case body");
1005 CaseClause* clause = clauses->at(i);
1006 __ bind(clause->body_target());
1007 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1008 VisitStatements(clause->statements());
1011 __ bind(nested_statement.break_label());
1012 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1016 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1017 Comment cmnt(masm_, "[ ForInStatement");
1018 SetStatementPosition(stmt, SKIP_BREAK);
1020 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1023 ForIn loop_statement(this, stmt);
1024 increment_loop_depth();
1026 // Get the object to enumerate over. If the object is null or undefined, skip
1027 // over the loop. See ECMA-262 version 5, section 12.6.4.
1028 SetExpressionAsStatementPosition(stmt->enumerable());
1029 VisitForAccumulatorValue(stmt->enumerable());
1030 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1032 Register null_value = rdi;
1033 __ LoadRoot(null_value, Heap::kNullValueRootIndex);
1034 __ cmpp(rax, null_value);
1037 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1039 // Convert the object to a JS object.
1040 Label convert, done_convert;
1041 __ JumpIfSmi(rax, &convert);
1042 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rcx);
1043 __ j(above_equal, &done_convert);
1046 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1047 __ bind(&done_convert);
1048 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1051 // Check for proxies.
1053 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1054 __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx);
1055 __ j(below_equal, &call_runtime);
1057 // Check cache validity in generated code. This is a fast case for
1058 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1059 // guarantee cache validity, call the runtime system to check cache
1060 // validity or get the property names in a fixed array.
1061 __ CheckEnumCache(null_value, &call_runtime);
1063 // The enum cache is valid. Load the map of the object being
1064 // iterated over and use the cache for the iteration.
1066 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
1067 __ jmp(&use_cache, Label::kNear);
1069 // Get the set of properties to enumerate.
1070 __ bind(&call_runtime);
1071 __ Push(rax); // Duplicate the enumerable object on the stack.
1072 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1073 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1075 // If we got a map from the runtime call, we can do a fast
1076 // modification check. Otherwise, we got a fixed array, and we have
1077 // to do a slow check.
1079 __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
1080 Heap::kMetaMapRootIndex);
1081 __ j(not_equal, &fixed_array);
1083 // We got a map in register rax. Get the enumeration cache from it.
1084 __ bind(&use_cache);
1086 Label no_descriptors;
1088 __ EnumLength(rdx, rax);
1089 __ Cmp(rdx, Smi::FromInt(0));
1090 __ j(equal, &no_descriptors);
1092 __ LoadInstanceDescriptors(rax, rcx);
1093 __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheOffset));
1094 __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1096 // Set up the four remaining stack slots.
1097 __ Push(rax); // Map.
1098 __ Push(rcx); // Enumeration cache.
1099 __ Push(rdx); // Number of valid entries for the map in the enum cache.
1100 __ Push(Smi::FromInt(0)); // Initial index.
1103 __ bind(&no_descriptors);
1104 __ addp(rsp, Immediate(kPointerSize));
1107 // We got a fixed array in register rax. Iterate through that.
1109 __ bind(&fixed_array);
1111 // No need for a write barrier, we are storing a Smi in the feedback vector.
1112 __ Move(rbx, FeedbackVector());
1113 int vector_index = FeedbackVector()->GetIndex(slot);
1114 __ Move(FieldOperand(rbx, FixedArray::OffsetOfElementAt(vector_index)),
1115 TypeFeedbackVector::MegamorphicSentinel(isolate()));
1116 __ Move(rbx, Smi::FromInt(1)); // Smi indicates slow check
1117 __ movp(rcx, Operand(rsp, 0 * kPointerSize)); // Get enumerated object
1118 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1119 __ CmpObjectType(rcx, LAST_JS_PROXY_TYPE, rcx);
1120 __ j(above, &non_proxy);
1121 __ Move(rbx, Smi::FromInt(0)); // Zero indicates proxy
1122 __ bind(&non_proxy);
1123 __ Push(rbx); // Smi
1124 __ Push(rax); // Array
1125 __ movp(rax, FieldOperand(rax, FixedArray::kLengthOffset));
1126 __ Push(rax); // Fixed array length (as smi).
1127 __ Push(Smi::FromInt(0)); // Initial index.
1129 // Generate code for doing the condition check.
1130 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1132 SetExpressionAsStatementPosition(stmt->each());
1134 __ movp(rax, Operand(rsp, 0 * kPointerSize)); // Get the current index.
1135 __ cmpp(rax, Operand(rsp, 1 * kPointerSize)); // Compare to the array length.
1136 __ j(above_equal, loop_statement.break_label());
1138 // Get the current entry of the array into register rbx.
1139 __ movp(rbx, Operand(rsp, 2 * kPointerSize));
1140 SmiIndex index = masm()->SmiToIndex(rax, rax, kPointerSizeLog2);
1141 __ movp(rbx, FieldOperand(rbx,
1144 FixedArray::kHeaderSize));
1146 // Get the expected map from the stack or a smi in the
1147 // permanent slow case into register rdx.
1148 __ movp(rdx, Operand(rsp, 3 * kPointerSize));
1150 // Check if the expected map still matches that of the enumerable.
1151 // If not, we may have to filter the key.
1153 __ movp(rcx, Operand(rsp, 4 * kPointerSize));
1154 __ cmpp(rdx, FieldOperand(rcx, HeapObject::kMapOffset));
1155 __ j(equal, &update_each, Label::kNear);
1157 // For proxies, no filtering is done.
1158 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1159 __ Cmp(rdx, Smi::FromInt(0));
1160 __ j(equal, &update_each, Label::kNear);
1162 // Convert the entry to a string or null if it isn't a property
1163 // anymore. If the property has been removed while iterating, we
1165 __ Push(rcx); // Enumerable.
1166 __ Push(rbx); // Current entry.
1167 __ CallRuntime(Runtime::kForInFilter, 2);
1168 PrepareForBailoutForId(stmt->FilterId(), TOS_REG);
1169 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1170 __ j(equal, loop_statement.continue_label());
1173 // Update the 'each' property or variable from the possibly filtered
1174 // entry in register rbx.
1175 __ bind(&update_each);
1176 __ movp(result_register(), rbx);
1177 // Perform the assignment as if via '='.
1178 { EffectContext context(this);
1179 EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1180 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1183 // Generate code for the body of the loop.
1184 Visit(stmt->body());
1186 // Generate code for going to the next element by incrementing the
1187 // index (smi) stored on top of the stack.
1188 __ bind(loop_statement.continue_label());
1189 __ SmiAddConstant(Operand(rsp, 0 * kPointerSize), Smi::FromInt(1));
1191 EmitBackEdgeBookkeeping(stmt, &loop);
1194 // Remove the pointers stored on the stack.
1195 __ bind(loop_statement.break_label());
1196 __ addp(rsp, Immediate(5 * kPointerSize));
1198 // Exit and decrement the loop depth.
1199 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1201 decrement_loop_depth();
1205 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1207 // Use the fast case closure allocation code that allocates in new
1208 // space for nested functions that don't need literals cloning. If
1209 // we're running with the --always-opt or the --prepare-always-opt
1210 // flag, we need to use the runtime function so that the new function
1211 // we are creating here gets a chance to have its code optimized and
1212 // doesn't just get a copy of the existing unoptimized code.
1213 if (!FLAG_always_opt &&
1214 !FLAG_prepare_always_opt &&
1216 scope()->is_function_scope() &&
1217 info->num_literals() == 0) {
1218 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1225 ? isolate()->factory()->true_value()
1226 : isolate()->factory()->false_value());
1227 __ CallRuntime(Runtime::kNewClosure, 3);
1229 context()->Plug(rax);
1233 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1235 FeedbackVectorICSlot slot) {
1236 if (NeedsHomeObject(initializer)) {
1237 __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1238 __ Move(StoreDescriptor::NameRegister(),
1239 isolate()->factory()->home_object_symbol());
1240 __ movp(StoreDescriptor::ValueRegister(),
1241 Operand(rsp, offset * kPointerSize));
1242 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
1248 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1249 TypeofMode typeof_mode,
1251 Register context = rsi;
1252 Register temp = rdx;
1256 if (s->num_heap_slots() > 0) {
1257 if (s->calls_sloppy_eval()) {
1258 // Check that extension is NULL.
1259 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX),
1261 __ j(not_equal, slow);
1263 // Load next context in chain.
1264 __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1265 // Walk the rest of the chain without clobbering rsi.
1268 // If no outer scope calls eval, we do not need to check more
1269 // context extensions. If we have reached an eval scope, we check
1270 // all extensions from this point.
1271 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1272 s = s->outer_scope();
1275 if (s != NULL && s->is_eval_scope()) {
1276 // Loop up the context chain. There is no frame effect so it is
1277 // safe to use raw labels here.
1279 if (!context.is(temp)) {
1280 __ movp(temp, context);
1282 // Load map for comparison into register, outside loop.
1283 __ LoadRoot(kScratchRegister, Heap::kNativeContextMapRootIndex);
1285 // Terminate at native context.
1286 __ cmpp(kScratchRegister, FieldOperand(temp, HeapObject::kMapOffset));
1287 __ j(equal, &fast, Label::kNear);
1288 // Check that extension is NULL.
1289 __ cmpp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1290 __ j(not_equal, slow);
1291 // Load next context in chain.
1292 __ movp(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1297 // All extension objects were empty and it is safe to use a normal global
1299 EmitGlobalVariableLoad(proxy, typeof_mode);
1303 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1305 DCHECK(var->IsContextSlot());
1306 Register context = rsi;
1307 Register temp = rbx;
1309 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1310 if (s->num_heap_slots() > 0) {
1311 if (s->calls_sloppy_eval()) {
1312 // Check that extension is NULL.
1313 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX),
1315 __ j(not_equal, slow);
1317 __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1318 // Walk the rest of the chain without clobbering rsi.
1322 // Check that last extension is NULL.
1323 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1324 __ j(not_equal, slow);
1326 // This function is used only for loads, not stores, so it's safe to
1327 // return an rsi-based operand (the write barrier cannot be allowed to
1328 // destroy the rsi register).
1329 return ContextOperand(context, var->index());
1333 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1334 TypeofMode typeof_mode,
1335 Label* slow, Label* done) {
1336 // Generate fast-case code for variables that might be shadowed by
1337 // eval-introduced variables. Eval is used a lot without
1338 // introducing variables. In those cases, we do not want to
1339 // perform a runtime call for all variables in the scope
1340 // containing the eval.
1341 Variable* var = proxy->var();
1342 if (var->mode() == DYNAMIC_GLOBAL) {
1343 EmitLoadGlobalCheckExtensions(proxy, typeof_mode, slow);
1345 } else if (var->mode() == DYNAMIC_LOCAL) {
1346 Variable* local = var->local_if_not_shadowed();
1347 __ movp(rax, ContextSlotOperandCheckExtensions(local, slow));
1348 if (local->mode() == LET || local->mode() == CONST ||
1349 local->mode() == CONST_LEGACY) {
1350 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
1351 __ j(not_equal, done);
1352 if (local->mode() == CONST_LEGACY) {
1353 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
1354 } else { // LET || CONST
1355 __ Push(var->name());
1356 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1364 void FullCodeGenerator::EmitGlobalVariableLoad(VariableProxy* proxy,
1365 TypeofMode typeof_mode) {
1366 Variable* var = proxy->var();
1367 DCHECK(var->IsUnallocatedOrGlobalSlot() ||
1368 (var->IsLookupSlot() && var->mode() == DYNAMIC_GLOBAL));
1369 if (var->IsGlobalSlot()) {
1370 DCHECK(var->index() > 0);
1371 DCHECK(var->IsStaticGlobalObjectProperty());
1372 int const slot = var->index();
1373 int const depth = scope()->ContextChainLength(var->scope());
1374 if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
1375 __ Set(LoadGlobalViaContextDescriptor::SlotRegister(), slot);
1376 LoadGlobalViaContextStub stub(isolate(), depth);
1379 __ Push(Smi::FromInt(slot));
1380 __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
1384 __ Move(LoadDescriptor::NameRegister(), var->name());
1385 __ movp(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1386 __ Move(LoadDescriptor::SlotRegister(),
1387 SmiFromSlot(proxy->VariableFeedbackSlot()));
1388 CallLoadIC(typeof_mode);
1393 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy,
1394 TypeofMode typeof_mode) {
1395 // Record position before possible IC call.
1396 SetExpressionPosition(proxy);
1397 PrepareForBailoutForId(proxy->BeforeId(), NO_REGISTERS);
1398 Variable* var = proxy->var();
1400 // Three cases: global variables, lookup variables, and all other types of
1402 switch (var->location()) {
1403 case VariableLocation::GLOBAL:
1404 case VariableLocation::UNALLOCATED: {
1405 Comment cmnt(masm_, "[ Global variable");
1406 EmitGlobalVariableLoad(proxy, typeof_mode);
1407 context()->Plug(rax);
1411 case VariableLocation::PARAMETER:
1412 case VariableLocation::LOCAL:
1413 case VariableLocation::CONTEXT: {
1414 DCHECK_EQ(NOT_INSIDE_TYPEOF, typeof_mode);
1415 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context slot"
1417 if (var->binding_needs_init()) {
1418 // var->scope() may be NULL when the proxy is located in eval code and
1419 // refers to a potential outside binding. Currently those bindings are
1420 // always looked up dynamically, i.e. in that case
1421 // var->location() == LOOKUP.
1423 DCHECK(var->scope() != NULL);
1425 // Check if the binding really needs an initialization check. The check
1426 // can be skipped in the following situation: we have a LET or CONST
1427 // binding in harmony mode, both the Variable and the VariableProxy have
1428 // the same declaration scope (i.e. they are both in global code, in the
1429 // same function or in the same eval code) and the VariableProxy is in
1430 // the source physically located after the initializer of the variable.
1432 // We cannot skip any initialization checks for CONST in non-harmony
1433 // mode because const variables may be declared but never initialized:
1434 // if (false) { const x; }; var y = x;
1436 // The condition on the declaration scopes is a conservative check for
1437 // nested functions that access a binding and are called before the
1438 // binding is initialized:
1439 // function() { f(); let x = 1; function f() { x = 2; } }
1441 bool skip_init_check;
1442 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1443 skip_init_check = false;
1444 } else if (var->is_this()) {
1445 CHECK(info_->function() != nullptr &&
1446 (info_->function()->kind() & kSubclassConstructor) != 0);
1447 // TODO(dslomov): implement 'this' hole check elimination.
1448 skip_init_check = false;
1450 // Check that we always have valid source position.
1451 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1452 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1453 skip_init_check = var->mode() != CONST_LEGACY &&
1454 var->initializer_position() < proxy->position();
1457 if (!skip_init_check) {
1458 // Let and const need a read barrier.
1461 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
1462 __ j(not_equal, &done, Label::kNear);
1463 if (var->mode() == LET || var->mode() == CONST) {
1464 // Throw a reference error when using an uninitialized let/const
1465 // binding in harmony mode.
1466 __ Push(var->name());
1467 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1469 // Uninitalized const bindings outside of harmony mode are unholed.
1470 DCHECK(var->mode() == CONST_LEGACY);
1471 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
1474 context()->Plug(rax);
1478 context()->Plug(var);
1482 case VariableLocation::LOOKUP: {
1483 Comment cmnt(masm_, "[ Lookup slot");
1485 // Generate code for loading from variables potentially shadowed
1486 // by eval-introduced variables.
1487 EmitDynamicLookupFastCase(proxy, typeof_mode, &slow, &done);
1489 __ Push(rsi); // Context.
1490 __ Push(var->name());
1491 Runtime::FunctionId function_id =
1492 typeof_mode == NOT_INSIDE_TYPEOF
1493 ? Runtime::kLoadLookupSlot
1494 : Runtime::kLoadLookupSlotNoReferenceError;
1495 __ CallRuntime(function_id, 2);
1497 context()->Plug(rax);
1504 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1505 Comment cmnt(masm_, "[ RegExpLiteral");
1507 // Registers will be used as follows:
1508 // rdi = JS function.
1509 // rcx = literals array.
1510 // rbx = regexp literal.
1511 // rax = regexp literal clone.
1512 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1513 __ movp(rcx, FieldOperand(rdi, JSFunction::kLiteralsOffset));
1514 int literal_offset =
1515 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1516 __ movp(rbx, FieldOperand(rcx, literal_offset));
1517 __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex);
1518 __ j(not_equal, &materialized, Label::kNear);
1520 // Create regexp literal using runtime function
1521 // Result will be in rax.
1523 __ Push(Smi::FromInt(expr->literal_index()));
1524 __ Push(expr->pattern());
1525 __ Push(expr->flags());
1526 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1529 __ bind(&materialized);
1530 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1531 Label allocated, runtime_allocate;
1532 __ Allocate(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
1535 __ bind(&runtime_allocate);
1537 __ Push(Smi::FromInt(size));
1538 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1541 __ bind(&allocated);
1542 // Copy the content into the newly allocated memory.
1543 // (Unroll copy loop once for better throughput).
1544 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1545 __ movp(rdx, FieldOperand(rbx, i));
1546 __ movp(rcx, FieldOperand(rbx, i + kPointerSize));
1547 __ movp(FieldOperand(rax, i), rdx);
1548 __ movp(FieldOperand(rax, i + kPointerSize), rcx);
1550 if ((size % (2 * kPointerSize)) != 0) {
1551 __ movp(rdx, FieldOperand(rbx, size - kPointerSize));
1552 __ movp(FieldOperand(rax, size - kPointerSize), rdx);
1554 context()->Plug(rax);
1558 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1559 if (expression == NULL) {
1560 __ PushRoot(Heap::kNullValueRootIndex);
1562 VisitForStackValue(expression);
1567 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1568 Comment cmnt(masm_, "[ ObjectLiteral");
1570 Handle<FixedArray> constant_properties = expr->constant_properties();
1571 int flags = expr->ComputeFlags();
1572 if (MustCreateObjectLiteralWithRuntime(expr)) {
1573 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1574 __ Push(FieldOperand(rdi, JSFunction::kLiteralsOffset));
1575 __ Push(Smi::FromInt(expr->literal_index()));
1576 __ Push(constant_properties);
1577 __ Push(Smi::FromInt(flags));
1578 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1580 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1581 __ movp(rax, FieldOperand(rdi, JSFunction::kLiteralsOffset));
1582 __ Move(rbx, Smi::FromInt(expr->literal_index()));
1583 __ Move(rcx, constant_properties);
1584 __ Move(rdx, Smi::FromInt(flags));
1585 FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
1588 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1590 // If result_saved is true the result is on top of the stack. If
1591 // result_saved is false the result is in rax.
1592 bool result_saved = false;
1594 AccessorTable accessor_table(zone());
1595 int property_index = 0;
1596 // store_slot_index points to the vector IC slot for the next store IC used.
1597 // ObjectLiteral::ComputeFeedbackRequirements controls the allocation of slots
1598 // and must be updated if the number of store ICs emitted here changes.
1599 int store_slot_index = 0;
1600 for (; property_index < expr->properties()->length(); property_index++) {
1601 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1602 if (property->is_computed_name()) break;
1603 if (property->IsCompileTimeValue()) continue;
1605 Literal* key = property->key()->AsLiteral();
1606 Expression* value = property->value();
1607 if (!result_saved) {
1608 __ Push(rax); // Save result on the stack
1609 result_saved = true;
1611 switch (property->kind()) {
1612 case ObjectLiteral::Property::CONSTANT:
1614 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1615 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1617 case ObjectLiteral::Property::COMPUTED:
1618 // It is safe to use [[Put]] here because the boilerplate already
1619 // contains computed properties with an uninitialized value.
1620 if (key->value()->IsInternalizedString()) {
1621 if (property->emit_store()) {
1622 VisitForAccumulatorValue(value);
1623 DCHECK(StoreDescriptor::ValueRegister().is(rax));
1624 __ Move(StoreDescriptor::NameRegister(), key->value());
1625 __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1626 if (FLAG_vector_stores) {
1627 EmitLoadStoreICSlot(expr->GetNthSlot(store_slot_index++));
1630 CallStoreIC(key->LiteralFeedbackId());
1632 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1634 if (NeedsHomeObject(value)) {
1635 __ movp(StoreDescriptor::ReceiverRegister(), rax);
1636 __ Move(StoreDescriptor::NameRegister(),
1637 isolate()->factory()->home_object_symbol());
1638 __ movp(StoreDescriptor::ValueRegister(), Operand(rsp, 0));
1639 if (FLAG_vector_stores) {
1640 EmitLoadStoreICSlot(expr->GetNthSlot(store_slot_index++));
1645 VisitForEffect(value);
1649 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1650 VisitForStackValue(key);
1651 VisitForStackValue(value);
1652 if (property->emit_store()) {
1653 EmitSetHomeObjectIfNeeded(
1654 value, 2, expr->SlotForHomeObject(value, &store_slot_index));
1655 __ Push(Smi::FromInt(SLOPPY)); // Language mode
1656 __ CallRuntime(Runtime::kSetProperty, 4);
1661 case ObjectLiteral::Property::PROTOTYPE:
1662 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1663 VisitForStackValue(value);
1664 DCHECK(property->emit_store());
1665 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1667 case ObjectLiteral::Property::GETTER:
1668 if (property->emit_store()) {
1669 accessor_table.lookup(key)->second->getter = value;
1672 case ObjectLiteral::Property::SETTER:
1673 if (property->emit_store()) {
1674 accessor_table.lookup(key)->second->setter = value;
1680 // Emit code to define accessors, using only a single call to the runtime for
1681 // each pair of corresponding getters and setters.
1682 for (AccessorTable::Iterator it = accessor_table.begin();
1683 it != accessor_table.end();
1685 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1686 VisitForStackValue(it->first);
1687 EmitAccessor(it->second->getter);
1688 EmitSetHomeObjectIfNeeded(
1689 it->second->getter, 2,
1690 expr->SlotForHomeObject(it->second->getter, &store_slot_index));
1691 EmitAccessor(it->second->setter);
1692 EmitSetHomeObjectIfNeeded(
1693 it->second->setter, 3,
1694 expr->SlotForHomeObject(it->second->setter, &store_slot_index));
1695 __ Push(Smi::FromInt(NONE));
1696 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1699 // Object literals have two parts. The "static" part on the left contains no
1700 // computed property names, and so we can compute its map ahead of time; see
1701 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1702 // starts with the first computed property name, and continues with all
1703 // properties to its right. All the code from above initializes the static
1704 // component of the object literal, and arranges for the map of the result to
1705 // reflect the static order in which the keys appear. For the dynamic
1706 // properties, we compile them into a series of "SetOwnProperty" runtime
1707 // calls. This will preserve insertion order.
1708 for (; property_index < expr->properties()->length(); property_index++) {
1709 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1711 Expression* value = property->value();
1712 if (!result_saved) {
1713 __ Push(rax); // Save result on the stack
1714 result_saved = true;
1717 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1719 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1720 DCHECK(!property->is_computed_name());
1721 VisitForStackValue(value);
1722 DCHECK(property->emit_store());
1723 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1725 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1726 VisitForStackValue(value);
1727 EmitSetHomeObjectIfNeeded(
1728 value, 2, expr->SlotForHomeObject(value, &store_slot_index));
1730 switch (property->kind()) {
1731 case ObjectLiteral::Property::CONSTANT:
1732 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1733 case ObjectLiteral::Property::COMPUTED:
1734 if (property->emit_store()) {
1735 __ Push(Smi::FromInt(NONE));
1736 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1742 case ObjectLiteral::Property::PROTOTYPE:
1746 case ObjectLiteral::Property::GETTER:
1747 __ Push(Smi::FromInt(NONE));
1748 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1751 case ObjectLiteral::Property::SETTER:
1752 __ Push(Smi::FromInt(NONE));
1753 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1759 if (expr->has_function()) {
1760 DCHECK(result_saved);
1761 __ Push(Operand(rsp, 0));
1762 __ CallRuntime(Runtime::kToFastProperties, 1);
1766 context()->PlugTOS();
1768 context()->Plug(rax);
1771 // Verify that compilation exactly consumed the number of store ic slots that
1772 // the ObjectLiteral node had to offer.
1773 DCHECK(!FLAG_vector_stores || store_slot_index == expr->slot_count());
1777 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1778 Comment cmnt(masm_, "[ ArrayLiteral");
1780 expr->BuildConstantElements(isolate());
1781 Handle<FixedArray> constant_elements = expr->constant_elements();
1782 bool has_constant_fast_elements =
1783 IsFastObjectElementsKind(expr->constant_elements_kind());
1785 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1786 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1787 // If the only customer of allocation sites is transitioning, then
1788 // we can turn it off if we don't have anywhere else to transition to.
1789 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1792 if (MustCreateArrayLiteralWithRuntime(expr)) {
1793 __ movp(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1794 __ Push(FieldOperand(rbx, JSFunction::kLiteralsOffset));
1795 __ Push(Smi::FromInt(expr->literal_index()));
1796 __ Push(constant_elements);
1797 __ Push(Smi::FromInt(expr->ComputeFlags()));
1798 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1800 __ movp(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1801 __ movp(rax, FieldOperand(rbx, JSFunction::kLiteralsOffset));
1802 __ Move(rbx, Smi::FromInt(expr->literal_index()));
1803 __ Move(rcx, constant_elements);
1804 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1807 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1809 bool result_saved = false; // Is the result saved to the stack?
1810 ZoneList<Expression*>* subexprs = expr->values();
1811 int length = subexprs->length();
1813 // Emit code to evaluate all the non-constant subexpressions and to store
1814 // them into the newly cloned array.
1815 int array_index = 0;
1816 for (; array_index < length; array_index++) {
1817 Expression* subexpr = subexprs->at(array_index);
1818 if (subexpr->IsSpread()) break;
1820 // If the subexpression is a literal or a simple materialized literal it
1821 // is already set in the cloned array.
1822 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1824 if (!result_saved) {
1825 __ Push(rax); // array literal
1826 __ Push(Smi::FromInt(expr->literal_index()));
1827 result_saved = true;
1829 VisitForAccumulatorValue(subexpr);
1831 if (has_constant_fast_elements) {
1832 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1833 // cannot transition and don't need to call the runtime stub.
1834 int offset = FixedArray::kHeaderSize + (array_index * kPointerSize);
1835 __ movp(rbx, Operand(rsp, kPointerSize)); // Copy of array literal.
1836 __ movp(rbx, FieldOperand(rbx, JSObject::kElementsOffset));
1837 // Store the subexpression value in the array's elements.
1838 __ movp(FieldOperand(rbx, offset), result_register());
1839 // Update the write barrier for the array store.
1840 __ RecordWriteField(rbx, offset, result_register(), rcx,
1842 EMIT_REMEMBERED_SET,
1845 // Store the subexpression value in the array's elements.
1846 __ Move(rcx, Smi::FromInt(array_index));
1847 StoreArrayLiteralElementStub stub(isolate());
1851 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1854 // In case the array literal contains spread expressions it has two parts. The
1855 // first part is the "static" array which has a literal index is handled
1856 // above. The second part is the part after the first spread expression
1857 // (inclusive) and these elements gets appended to the array. Note that the
1858 // number elements an iterable produces is unknown ahead of time.
1859 if (array_index < length && result_saved) {
1860 __ Drop(1); // literal index
1862 result_saved = false;
1864 for (; array_index < length; array_index++) {
1865 Expression* subexpr = subexprs->at(array_index);
1868 if (subexpr->IsSpread()) {
1869 VisitForStackValue(subexpr->AsSpread()->expression());
1870 __ InvokeBuiltin(Builtins::CONCAT_ITERABLE_TO_ARRAY, CALL_FUNCTION);
1872 VisitForStackValue(subexpr);
1873 __ CallRuntime(Runtime::kAppendElement, 2);
1876 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1880 __ Drop(1); // literal index
1881 context()->PlugTOS();
1883 context()->Plug(rax);
1888 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1889 DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
1891 Comment cmnt(masm_, "[ Assignment");
1892 SetExpressionPosition(expr, INSERT_BREAK);
1894 Property* property = expr->target()->AsProperty();
1895 LhsKind assign_type = Property::GetAssignType(property);
1897 // Evaluate LHS expression.
1898 switch (assign_type) {
1900 // Nothing to do here.
1902 case NAMED_PROPERTY:
1903 if (expr->is_compound()) {
1904 // We need the receiver both on the stack and in the register.
1905 VisitForStackValue(property->obj());
1906 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
1908 VisitForStackValue(property->obj());
1911 case NAMED_SUPER_PROPERTY:
1913 property->obj()->AsSuperPropertyReference()->this_var());
1914 VisitForAccumulatorValue(
1915 property->obj()->AsSuperPropertyReference()->home_object());
1916 __ Push(result_register());
1917 if (expr->is_compound()) {
1918 __ Push(MemOperand(rsp, kPointerSize));
1919 __ Push(result_register());
1922 case KEYED_SUPER_PROPERTY:
1924 property->obj()->AsSuperPropertyReference()->this_var());
1926 property->obj()->AsSuperPropertyReference()->home_object());
1927 VisitForAccumulatorValue(property->key());
1928 __ Push(result_register());
1929 if (expr->is_compound()) {
1930 __ Push(MemOperand(rsp, 2 * kPointerSize));
1931 __ Push(MemOperand(rsp, 2 * kPointerSize));
1932 __ Push(result_register());
1935 case KEYED_PROPERTY: {
1936 if (expr->is_compound()) {
1937 VisitForStackValue(property->obj());
1938 VisitForStackValue(property->key());
1939 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
1940 __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
1942 VisitForStackValue(property->obj());
1943 VisitForStackValue(property->key());
1949 // For compound assignments we need another deoptimization point after the
1950 // variable/property load.
1951 if (expr->is_compound()) {
1952 { AccumulatorValueContext context(this);
1953 switch (assign_type) {
1955 EmitVariableLoad(expr->target()->AsVariableProxy());
1956 PrepareForBailout(expr->target(), TOS_REG);
1958 case NAMED_PROPERTY:
1959 EmitNamedPropertyLoad(property);
1960 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1962 case NAMED_SUPER_PROPERTY:
1963 EmitNamedSuperPropertyLoad(property);
1964 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1966 case KEYED_SUPER_PROPERTY:
1967 EmitKeyedSuperPropertyLoad(property);
1968 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1970 case KEYED_PROPERTY:
1971 EmitKeyedPropertyLoad(property);
1972 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1977 Token::Value op = expr->binary_op();
1978 __ Push(rax); // Left operand goes on the stack.
1979 VisitForAccumulatorValue(expr->value());
1981 AccumulatorValueContext context(this);
1982 if (ShouldInlineSmiCase(op)) {
1983 EmitInlineSmiBinaryOp(expr->binary_operation(),
1988 EmitBinaryOp(expr->binary_operation(), op);
1990 // Deoptimization point in case the binary operation may have side effects.
1991 PrepareForBailout(expr->binary_operation(), TOS_REG);
1993 VisitForAccumulatorValue(expr->value());
1996 SetExpressionPosition(expr);
1999 switch (assign_type) {
2001 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
2002 expr->op(), expr->AssignmentSlot());
2003 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2004 context()->Plug(rax);
2006 case NAMED_PROPERTY:
2007 EmitNamedPropertyAssignment(expr);
2009 case NAMED_SUPER_PROPERTY:
2010 EmitNamedSuperPropertyStore(property);
2011 context()->Plug(rax);
2013 case KEYED_SUPER_PROPERTY:
2014 EmitKeyedSuperPropertyStore(property);
2015 context()->Plug(rax);
2017 case KEYED_PROPERTY:
2018 EmitKeyedPropertyAssignment(expr);
2024 void FullCodeGenerator::VisitYield(Yield* expr) {
2025 Comment cmnt(masm_, "[ Yield");
2026 SetExpressionPosition(expr);
2028 // Evaluate yielded value first; the initial iterator definition depends on
2029 // this. It stays on the stack while we update the iterator.
2030 VisitForStackValue(expr->expression());
2032 switch (expr->yield_kind()) {
2033 case Yield::kSuspend:
2034 // Pop value from top-of-stack slot; box result into result register.
2035 EmitCreateIteratorResult(false);
2036 __ Push(result_register());
2038 case Yield::kInitial: {
2039 Label suspend, continuation, post_runtime, resume;
2042 __ bind(&continuation);
2043 __ RecordGeneratorContinuation();
2047 VisitForAccumulatorValue(expr->generator_object());
2048 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2049 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
2050 Smi::FromInt(continuation.pos()));
2051 __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
2053 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
2055 __ leap(rbx, Operand(rbp, StandardFrameConstants::kExpressionsOffset));
2057 __ j(equal, &post_runtime);
2058 __ Push(rax); // generator object
2059 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2060 __ movp(context_register(),
2061 Operand(rbp, StandardFrameConstants::kContextOffset));
2062 __ bind(&post_runtime);
2064 __ Pop(result_register());
2065 EmitReturnSequence();
2068 context()->Plug(result_register());
2072 case Yield::kFinal: {
2073 VisitForAccumulatorValue(expr->generator_object());
2074 __ Move(FieldOperand(result_register(),
2075 JSGeneratorObject::kContinuationOffset),
2076 Smi::FromInt(JSGeneratorObject::kGeneratorClosed));
2077 // Pop value from top-of-stack slot, box result into result register.
2078 EmitCreateIteratorResult(true);
2079 EmitUnwindBeforeReturn();
2080 EmitReturnSequence();
2084 case Yield::kDelegating: {
2085 VisitForStackValue(expr->generator_object());
2087 // Initial stack layout is as follows:
2088 // [sp + 1 * kPointerSize] iter
2089 // [sp + 0 * kPointerSize] g
2091 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2092 Label l_next, l_call, l_loop;
2093 Register load_receiver = LoadDescriptor::ReceiverRegister();
2094 Register load_name = LoadDescriptor::NameRegister();
2096 // Initial send value is undefined.
2097 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
2100 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2102 __ LoadRoot(load_name, Heap::kthrow_stringRootIndex); // "throw"
2104 __ Push(Operand(rsp, 2 * kPointerSize)); // iter
2105 __ Push(rax); // exception
2108 // try { received = %yield result }
2109 // Shuffle the received result above a try handler and yield it without
2112 __ Pop(rax); // result
2113 int handler_index = NewHandlerTableEntry();
2114 EnterTryBlock(handler_index, &l_catch);
2115 const int try_block_size = TryCatch::kElementCount * kPointerSize;
2116 __ Push(rax); // result
2119 __ bind(&l_continuation);
2120 __ RecordGeneratorContinuation();
2123 __ bind(&l_suspend);
2124 const int generator_object_depth = kPointerSize + try_block_size;
2125 __ movp(rax, Operand(rsp, generator_object_depth));
2127 __ Push(Smi::FromInt(handler_index)); // handler-index
2128 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2129 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
2130 Smi::FromInt(l_continuation.pos()));
2131 __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
2133 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
2135 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
2136 __ movp(context_register(),
2137 Operand(rbp, StandardFrameConstants::kContextOffset));
2138 __ Pop(rax); // result
2139 EmitReturnSequence();
2140 __ bind(&l_resume); // received in rax
2141 ExitTryBlock(handler_index);
2143 // receiver = iter; f = 'next'; arg = received;
2146 __ LoadRoot(load_name, Heap::knext_stringRootIndex);
2147 __ Push(load_name); // "next"
2148 __ Push(Operand(rsp, 2 * kPointerSize)); // iter
2149 __ Push(rax); // received
2151 // result = receiver[f](arg);
2153 __ movp(load_receiver, Operand(rsp, kPointerSize));
2154 __ Move(LoadDescriptor::SlotRegister(),
2155 SmiFromSlot(expr->KeyedLoadFeedbackSlot()));
2156 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), SLOPPY).code();
2157 CallIC(ic, TypeFeedbackId::None());
2159 __ movp(Operand(rsp, 2 * kPointerSize), rdi);
2161 SetCallPosition(expr, 1);
2162 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2165 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2166 __ Drop(1); // The function is still on the stack; drop it.
2168 // if (!result.done) goto l_try;
2170 __ Move(load_receiver, rax);
2171 __ Push(load_receiver); // save result
2172 __ LoadRoot(load_name, Heap::kdone_stringRootIndex); // "done"
2173 __ Move(LoadDescriptor::SlotRegister(),
2174 SmiFromSlot(expr->DoneFeedbackSlot()));
2175 CallLoadIC(NOT_INSIDE_TYPEOF); // rax=result.done
2176 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2178 __ testp(result_register(), result_register());
2182 __ Pop(load_receiver); // result
2183 __ LoadRoot(load_name, Heap::kvalue_stringRootIndex); // "value"
2184 __ Move(LoadDescriptor::SlotRegister(),
2185 SmiFromSlot(expr->ValueFeedbackSlot()));
2186 CallLoadIC(NOT_INSIDE_TYPEOF); // result.value in rax
2187 context()->DropAndPlug(2, rax); // drop iter and g
2194 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2196 JSGeneratorObject::ResumeMode resume_mode) {
2197 // The value stays in rax, and is ultimately read by the resumed generator, as
2198 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2199 // is read to throw the value when the resumed generator is already closed.
2200 // rbx will hold the generator object until the activation has been resumed.
2201 VisitForStackValue(generator);
2202 VisitForAccumulatorValue(value);
2205 // Load suspended function and context.
2206 __ movp(rsi, FieldOperand(rbx, JSGeneratorObject::kContextOffset));
2207 __ movp(rdi, FieldOperand(rbx, JSGeneratorObject::kFunctionOffset));
2210 __ Push(FieldOperand(rbx, JSGeneratorObject::kReceiverOffset));
2212 // Push holes for arguments to generator function.
2213 __ movp(rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
2214 __ LoadSharedFunctionInfoSpecialField(rdx, rdx,
2215 SharedFunctionInfo::kFormalParameterCountOffset);
2216 __ LoadRoot(rcx, Heap::kTheHoleValueRootIndex);
2217 Label push_argument_holes, push_frame;
2218 __ bind(&push_argument_holes);
2219 __ subp(rdx, Immediate(1));
2220 __ j(carry, &push_frame);
2222 __ jmp(&push_argument_holes);
2224 // Enter a new JavaScript frame, and initialize its slots as they were when
2225 // the generator was suspended.
2226 Label resume_frame, done;
2227 __ bind(&push_frame);
2228 __ call(&resume_frame);
2230 __ bind(&resume_frame);
2231 __ pushq(rbp); // Caller's frame pointer.
2233 __ Push(rsi); // Callee's context.
2234 __ Push(rdi); // Callee's JS Function.
2236 // Load the operand stack size.
2237 __ movp(rdx, FieldOperand(rbx, JSGeneratorObject::kOperandStackOffset));
2238 __ movp(rdx, FieldOperand(rdx, FixedArray::kLengthOffset));
2239 __ SmiToInteger32(rdx, rdx);
2241 // If we are sending a value and there is no operand stack, we can jump back
2243 if (resume_mode == JSGeneratorObject::NEXT) {
2245 __ cmpp(rdx, Immediate(0));
2246 __ j(not_zero, &slow_resume);
2247 __ movp(rdx, FieldOperand(rdi, JSFunction::kCodeEntryOffset));
2248 __ SmiToInteger64(rcx,
2249 FieldOperand(rbx, JSGeneratorObject::kContinuationOffset));
2251 __ Move(FieldOperand(rbx, JSGeneratorObject::kContinuationOffset),
2252 Smi::FromInt(JSGeneratorObject::kGeneratorExecuting));
2254 __ bind(&slow_resume);
2257 // Otherwise, we push holes for the operand stack and call the runtime to fix
2258 // up the stack and the handlers.
2259 Label push_operand_holes, call_resume;
2260 __ bind(&push_operand_holes);
2261 __ subp(rdx, Immediate(1));
2262 __ j(carry, &call_resume);
2264 __ jmp(&push_operand_holes);
2265 __ bind(&call_resume);
2267 __ Push(result_register());
2268 __ Push(Smi::FromInt(resume_mode));
2269 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2270 // Not reached: the runtime call returns elsewhere.
2271 __ Abort(kGeneratorFailedToResume);
2274 context()->Plug(result_register());
2278 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2282 const int instance_size = 5 * kPointerSize;
2283 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2286 __ Allocate(instance_size, rax, rcx, rdx, &gc_required, TAG_OBJECT);
2289 __ bind(&gc_required);
2290 __ Push(Smi::FromInt(instance_size));
2291 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2292 __ movp(context_register(),
2293 Operand(rbp, StandardFrameConstants::kContextOffset));
2295 __ bind(&allocated);
2296 __ movp(rbx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2297 __ movp(rbx, FieldOperand(rbx, GlobalObject::kNativeContextOffset));
2298 __ movp(rbx, ContextOperand(rbx, Context::ITERATOR_RESULT_MAP_INDEX));
2300 __ Move(rdx, isolate()->factory()->ToBoolean(done));
2301 __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
2302 __ Move(FieldOperand(rax, JSObject::kPropertiesOffset),
2303 isolate()->factory()->empty_fixed_array());
2304 __ Move(FieldOperand(rax, JSObject::kElementsOffset),
2305 isolate()->factory()->empty_fixed_array());
2306 __ movp(FieldOperand(rax, JSGeneratorObject::kResultValuePropertyOffset),
2308 __ movp(FieldOperand(rax, JSGeneratorObject::kResultDonePropertyOffset),
2311 // Only the value field needs a write barrier, as the other values are in the
2313 __ RecordWriteField(rax, JSGeneratorObject::kResultValuePropertyOffset,
2314 rcx, rdx, kDontSaveFPRegs);
2318 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2319 SetExpressionPosition(prop);
2320 Literal* key = prop->key()->AsLiteral();
2321 DCHECK(!prop->IsSuperAccess());
2323 __ Move(LoadDescriptor::NameRegister(), key->value());
2324 __ Move(LoadDescriptor::SlotRegister(),
2325 SmiFromSlot(prop->PropertyFeedbackSlot()));
2326 CallLoadIC(NOT_INSIDE_TYPEOF, language_mode());
2330 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2331 // Stack: receiver, home_object
2332 SetExpressionPosition(prop);
2333 Literal* key = prop->key()->AsLiteral();
2334 DCHECK(!key->value()->IsSmi());
2335 DCHECK(prop->IsSuperAccess());
2337 __ Push(key->value());
2338 __ Push(Smi::FromInt(language_mode()));
2339 __ CallRuntime(Runtime::kLoadFromSuper, 4);
2343 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2344 SetExpressionPosition(prop);
2345 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), language_mode()).code();
2346 __ Move(LoadDescriptor::SlotRegister(),
2347 SmiFromSlot(prop->PropertyFeedbackSlot()));
2352 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2353 // Stack: receiver, home_object, key.
2354 SetExpressionPosition(prop);
2355 __ Push(Smi::FromInt(language_mode()));
2356 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2360 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2363 Expression* right) {
2364 // Do combined smi check of the operands. Left operand is on the
2365 // stack (popped into rdx). Right operand is in rax but moved into
2366 // rcx to make the shifts easier.
2367 Label done, stub_call, smi_case;
2371 JumpPatchSite patch_site(masm_);
2372 patch_site.EmitJumpIfSmi(rax, &smi_case, Label::kNear);
2374 __ bind(&stub_call);
2377 CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2378 CallIC(code, expr->BinaryOperationFeedbackId());
2379 patch_site.EmitPatchInfo();
2380 __ jmp(&done, Label::kNear);
2385 __ SmiShiftArithmeticRight(rax, rdx, rcx);
2388 __ SmiShiftLeft(rax, rdx, rcx, &stub_call);
2391 __ SmiShiftLogicalRight(rax, rdx, rcx, &stub_call);
2394 __ SmiAdd(rax, rdx, rcx, &stub_call);
2397 __ SmiSub(rax, rdx, rcx, &stub_call);
2400 __ SmiMul(rax, rdx, rcx, &stub_call);
2403 __ SmiOr(rax, rdx, rcx);
2405 case Token::BIT_AND:
2406 __ SmiAnd(rax, rdx, rcx);
2408 case Token::BIT_XOR:
2409 __ SmiXor(rax, rdx, rcx);
2417 context()->Plug(rax);
2421 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit,
2422 int* used_store_slots) {
2423 // Constructor is in rax.
2424 DCHECK(lit != NULL);
2427 // No access check is needed here since the constructor is created by the
2429 Register scratch = rbx;
2430 __ movp(scratch, FieldOperand(rax, JSFunction::kPrototypeOrInitialMapOffset));
2433 for (int i = 0; i < lit->properties()->length(); i++) {
2434 ObjectLiteral::Property* property = lit->properties()->at(i);
2435 Expression* value = property->value();
2437 if (property->is_static()) {
2438 __ Push(Operand(rsp, kPointerSize)); // constructor
2440 __ Push(Operand(rsp, 0)); // prototype
2442 EmitPropertyKey(property, lit->GetIdForProperty(i));
2444 // The static prototype property is read only. We handle the non computed
2445 // property name case in the parser. Since this is the only case where we
2446 // need to check for an own read only property we special case this so we do
2447 // not need to do this for every property.
2448 if (property->is_static() && property->is_computed_name()) {
2449 __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
2453 VisitForStackValue(value);
2454 EmitSetHomeObjectIfNeeded(value, 2,
2455 lit->SlotForHomeObject(value, used_store_slots));
2457 switch (property->kind()) {
2458 case ObjectLiteral::Property::CONSTANT:
2459 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2460 case ObjectLiteral::Property::PROTOTYPE:
2462 case ObjectLiteral::Property::COMPUTED:
2463 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2466 case ObjectLiteral::Property::GETTER:
2467 __ Push(Smi::FromInt(DONT_ENUM));
2468 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2471 case ObjectLiteral::Property::SETTER:
2472 __ Push(Smi::FromInt(DONT_ENUM));
2473 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2482 __ CallRuntime(Runtime::kToFastProperties, 1);
2485 __ CallRuntime(Runtime::kToFastProperties, 1);
2487 if (is_strong(language_mode())) {
2489 FieldOperand(rax, JSFunction::kPrototypeOrInitialMapOffset));
2492 // TODO(conradw): It would be more efficient to define the properties with
2493 // the right attributes the first time round.
2494 // Freeze the prototype.
2495 __ CallRuntime(Runtime::kObjectFreeze, 1);
2496 // Freeze the constructor.
2497 __ CallRuntime(Runtime::kObjectFreeze, 1);
2502 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2505 CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2506 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2507 CallIC(code, expr->BinaryOperationFeedbackId());
2508 patch_site.EmitPatchInfo();
2509 context()->Plug(rax);
2513 void FullCodeGenerator::EmitAssignment(Expression* expr,
2514 FeedbackVectorICSlot slot) {
2515 DCHECK(expr->IsValidReferenceExpressionOrThis());
2517 Property* prop = expr->AsProperty();
2518 LhsKind assign_type = Property::GetAssignType(prop);
2520 switch (assign_type) {
2522 Variable* var = expr->AsVariableProxy()->var();
2523 EffectContext context(this);
2524 EmitVariableAssignment(var, Token::ASSIGN, slot);
2527 case NAMED_PROPERTY: {
2528 __ Push(rax); // Preserve value.
2529 VisitForAccumulatorValue(prop->obj());
2530 __ Move(StoreDescriptor::ReceiverRegister(), rax);
2531 __ Pop(StoreDescriptor::ValueRegister()); // Restore value.
2532 __ Move(StoreDescriptor::NameRegister(),
2533 prop->key()->AsLiteral()->value());
2534 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2538 case NAMED_SUPER_PROPERTY: {
2540 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2541 VisitForAccumulatorValue(
2542 prop->obj()->AsSuperPropertyReference()->home_object());
2543 // stack: value, this; rax: home_object
2544 Register scratch = rcx;
2545 Register scratch2 = rdx;
2546 __ Move(scratch, result_register()); // home_object
2547 __ movp(rax, MemOperand(rsp, kPointerSize)); // value
2548 __ movp(scratch2, MemOperand(rsp, 0)); // this
2549 __ movp(MemOperand(rsp, kPointerSize), scratch2); // this
2550 __ movp(MemOperand(rsp, 0), scratch); // home_object
2551 // stack: this, home_object; rax: value
2552 EmitNamedSuperPropertyStore(prop);
2555 case KEYED_SUPER_PROPERTY: {
2557 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2559 prop->obj()->AsSuperPropertyReference()->home_object());
2560 VisitForAccumulatorValue(prop->key());
2561 Register scratch = rcx;
2562 Register scratch2 = rdx;
2563 __ movp(scratch2, MemOperand(rsp, 2 * kPointerSize)); // value
2564 // stack: value, this, home_object; rax: key, rdx: value
2565 __ movp(scratch, MemOperand(rsp, kPointerSize)); // this
2566 __ movp(MemOperand(rsp, 2 * kPointerSize), scratch);
2567 __ movp(scratch, MemOperand(rsp, 0)); // home_object
2568 __ movp(MemOperand(rsp, kPointerSize), scratch);
2569 __ movp(MemOperand(rsp, 0), rax);
2570 __ Move(rax, scratch2);
2571 // stack: this, home_object, key; rax: value.
2572 EmitKeyedSuperPropertyStore(prop);
2575 case KEYED_PROPERTY: {
2576 __ Push(rax); // Preserve value.
2577 VisitForStackValue(prop->obj());
2578 VisitForAccumulatorValue(prop->key());
2579 __ Move(StoreDescriptor::NameRegister(), rax);
2580 __ Pop(StoreDescriptor::ReceiverRegister());
2581 __ Pop(StoreDescriptor::ValueRegister()); // Restore value.
2582 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2584 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2589 context()->Plug(rax);
2593 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2594 Variable* var, MemOperand location) {
2595 __ movp(location, rax);
2596 if (var->IsContextSlot()) {
2598 __ RecordWriteContextSlot(
2599 rcx, Context::SlotOffset(var->index()), rdx, rbx, kDontSaveFPRegs);
2604 void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
2605 FeedbackVectorICSlot slot) {
2606 if (var->IsUnallocated()) {
2607 // Global var, const, or let.
2608 __ Move(StoreDescriptor::NameRegister(), var->name());
2609 __ movp(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2610 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2613 } else if (var->IsGlobalSlot()) {
2614 // Global var, const, or let.
2615 DCHECK(var->index() > 0);
2616 DCHECK(var->IsStaticGlobalObjectProperty());
2617 int const slot = var->index();
2618 int const depth = scope()->ContextChainLength(var->scope());
2619 if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
2620 __ Set(StoreGlobalViaContextDescriptor::SlotRegister(), slot);
2621 DCHECK(StoreGlobalViaContextDescriptor::ValueRegister().is(rax));
2622 StoreGlobalViaContextStub stub(isolate(), depth, language_mode());
2625 __ Push(Smi::FromInt(slot));
2627 __ CallRuntime(is_strict(language_mode())
2628 ? Runtime::kStoreGlobalViaContext_Strict
2629 : Runtime::kStoreGlobalViaContext_Sloppy,
2633 } else if (var->mode() == LET && op != Token::INIT_LET) {
2634 // Non-initializing assignment to let variable needs a write barrier.
2635 DCHECK(!var->IsLookupSlot());
2636 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2638 MemOperand location = VarOperand(var, rcx);
2639 __ movp(rdx, location);
2640 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2641 __ j(not_equal, &assign, Label::kNear);
2642 __ Push(var->name());
2643 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2645 EmitStoreToStackLocalOrContextSlot(var, location);
2647 } else if (var->mode() == CONST && op != Token::INIT_CONST) {
2648 // Assignment to const variable needs a write barrier.
2649 DCHECK(!var->IsLookupSlot());
2650 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2652 MemOperand location = VarOperand(var, rcx);
2653 __ movp(rdx, location);
2654 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2655 __ j(not_equal, &const_error, Label::kNear);
2656 __ Push(var->name());
2657 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2658 __ bind(&const_error);
2659 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2661 } else if (var->is_this() && op == Token::INIT_CONST) {
2662 // Initializing assignment to const {this} needs a write barrier.
2663 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2664 Label uninitialized_this;
2665 MemOperand location = VarOperand(var, rcx);
2666 __ movp(rdx, location);
2667 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2668 __ j(equal, &uninitialized_this);
2669 __ Push(var->name());
2670 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2671 __ bind(&uninitialized_this);
2672 EmitStoreToStackLocalOrContextSlot(var, location);
2674 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2675 if (var->IsLookupSlot()) {
2676 // Assignment to var.
2677 __ Push(rax); // Value.
2678 __ Push(rsi); // Context.
2679 __ Push(var->name());
2680 __ Push(Smi::FromInt(language_mode()));
2681 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2683 // Assignment to var or initializing assignment to let/const in harmony
2685 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2686 MemOperand location = VarOperand(var, rcx);
2687 if (generate_debug_code_ && op == Token::INIT_LET) {
2688 // Check for an uninitialized let binding.
2689 __ movp(rdx, location);
2690 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2691 __ Check(equal, kLetBindingReInitialization);
2693 EmitStoreToStackLocalOrContextSlot(var, location);
2696 } else if (op == Token::INIT_CONST_LEGACY) {
2697 // Const initializers need a write barrier.
2698 DCHECK(var->mode() == CONST_LEGACY);
2699 DCHECK(!var->IsParameter()); // No const parameters.
2700 if (var->IsLookupSlot()) {
2703 __ Push(var->name());
2704 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2706 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2708 MemOperand location = VarOperand(var, rcx);
2709 __ movp(rdx, location);
2710 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2711 __ j(not_equal, &skip);
2712 EmitStoreToStackLocalOrContextSlot(var, location);
2717 DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
2718 if (is_strict(language_mode())) {
2719 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2721 // Silently ignore store in sloppy mode.
2726 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2727 // Assignment to a property, using a named store IC.
2728 Property* prop = expr->target()->AsProperty();
2729 DCHECK(prop != NULL);
2730 DCHECK(prop->key()->IsLiteral());
2732 __ Move(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2733 __ Pop(StoreDescriptor::ReceiverRegister());
2734 if (FLAG_vector_stores) {
2735 EmitLoadStoreICSlot(expr->AssignmentSlot());
2738 CallStoreIC(expr->AssignmentFeedbackId());
2741 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2742 context()->Plug(rax);
2746 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2747 // Assignment to named property of super.
2749 // stack : receiver ('this'), home_object
2750 DCHECK(prop != NULL);
2751 Literal* key = prop->key()->AsLiteral();
2752 DCHECK(key != NULL);
2754 __ Push(key->value());
2756 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2757 : Runtime::kStoreToSuper_Sloppy),
2762 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2763 // Assignment to named property of super.
2765 // stack : receiver ('this'), home_object, key
2766 DCHECK(prop != NULL);
2770 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2771 : Runtime::kStoreKeyedToSuper_Sloppy),
2776 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2777 // Assignment to a property, using a keyed store IC.
2778 __ Pop(StoreDescriptor::NameRegister()); // Key.
2779 __ Pop(StoreDescriptor::ReceiverRegister());
2780 DCHECK(StoreDescriptor::ValueRegister().is(rax));
2782 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2783 if (FLAG_vector_stores) {
2784 EmitLoadStoreICSlot(expr->AssignmentSlot());
2787 CallIC(ic, expr->AssignmentFeedbackId());
2790 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2791 context()->Plug(rax);
2795 void FullCodeGenerator::VisitProperty(Property* expr) {
2796 Comment cmnt(masm_, "[ Property");
2797 SetExpressionPosition(expr);
2799 Expression* key = expr->key();
2801 if (key->IsPropertyName()) {
2802 if (!expr->IsSuperAccess()) {
2803 VisitForAccumulatorValue(expr->obj());
2804 DCHECK(!rax.is(LoadDescriptor::ReceiverRegister()));
2805 __ movp(LoadDescriptor::ReceiverRegister(), rax);
2806 EmitNamedPropertyLoad(expr);
2808 VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
2810 expr->obj()->AsSuperPropertyReference()->home_object());
2811 EmitNamedSuperPropertyLoad(expr);
2814 if (!expr->IsSuperAccess()) {
2815 VisitForStackValue(expr->obj());
2816 VisitForAccumulatorValue(expr->key());
2817 __ Move(LoadDescriptor::NameRegister(), rax);
2818 __ Pop(LoadDescriptor::ReceiverRegister());
2819 EmitKeyedPropertyLoad(expr);
2821 VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
2823 expr->obj()->AsSuperPropertyReference()->home_object());
2824 VisitForStackValue(expr->key());
2825 EmitKeyedSuperPropertyLoad(expr);
2828 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2829 context()->Plug(rax);
2833 void FullCodeGenerator::CallIC(Handle<Code> code,
2834 TypeFeedbackId ast_id) {
2836 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2840 // Code common for calls using the IC.
2841 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2842 Expression* callee = expr->expression();
2844 CallICState::CallType call_type =
2845 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2846 // Get the target function.
2847 if (call_type == CallICState::FUNCTION) {
2848 { StackValueContext context(this);
2849 EmitVariableLoad(callee->AsVariableProxy());
2850 PrepareForBailout(callee, NO_REGISTERS);
2852 // Push undefined as receiver. This is patched in the method prologue if it
2853 // is a sloppy mode method.
2854 __ Push(isolate()->factory()->undefined_value());
2856 // Load the function from the receiver.
2857 DCHECK(callee->IsProperty());
2858 DCHECK(!callee->AsProperty()->IsSuperAccess());
2859 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
2860 EmitNamedPropertyLoad(callee->AsProperty());
2861 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2862 // Push the target function under the receiver.
2863 __ Push(Operand(rsp, 0));
2864 __ movp(Operand(rsp, kPointerSize), rax);
2867 EmitCall(expr, call_type);
2871 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2872 Expression* callee = expr->expression();
2873 DCHECK(callee->IsProperty());
2874 Property* prop = callee->AsProperty();
2875 DCHECK(prop->IsSuperAccess());
2876 SetExpressionPosition(prop);
2878 Literal* key = prop->key()->AsLiteral();
2879 DCHECK(!key->value()->IsSmi());
2880 // Load the function from the receiver.
2881 SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2882 VisitForStackValue(super_ref->home_object());
2883 VisitForAccumulatorValue(super_ref->this_var());
2886 __ Push(Operand(rsp, kPointerSize * 2));
2887 __ Push(key->value());
2888 __ Push(Smi::FromInt(language_mode()));
2892 // - this (receiver)
2893 // - this (receiver) <-- LoadFromSuper will pop here and below.
2897 __ CallRuntime(Runtime::kLoadFromSuper, 4);
2899 // Replace home_object with target function.
2900 __ movp(Operand(rsp, kPointerSize), rax);
2903 // - target function
2904 // - this (receiver)
2905 EmitCall(expr, CallICState::METHOD);
2909 // Common code for calls using the IC.
2910 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2913 VisitForAccumulatorValue(key);
2915 Expression* callee = expr->expression();
2917 // Load the function from the receiver.
2918 DCHECK(callee->IsProperty());
2919 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
2920 __ Move(LoadDescriptor::NameRegister(), rax);
2921 EmitKeyedPropertyLoad(callee->AsProperty());
2922 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2924 // Push the target function under the receiver.
2925 __ Push(Operand(rsp, 0));
2926 __ movp(Operand(rsp, kPointerSize), rax);
2928 EmitCall(expr, CallICState::METHOD);
2932 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2933 Expression* callee = expr->expression();
2934 DCHECK(callee->IsProperty());
2935 Property* prop = callee->AsProperty();
2936 DCHECK(prop->IsSuperAccess());
2938 SetExpressionPosition(prop);
2939 // Load the function from the receiver.
2940 SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2941 VisitForStackValue(super_ref->home_object());
2942 VisitForAccumulatorValue(super_ref->this_var());
2945 __ Push(Operand(rsp, kPointerSize * 2));
2946 VisitForStackValue(prop->key());
2947 __ Push(Smi::FromInt(language_mode()));
2951 // - this (receiver)
2952 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2956 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2958 // Replace home_object with target function.
2959 __ movp(Operand(rsp, kPointerSize), rax);
2962 // - target function
2963 // - this (receiver)
2964 EmitCall(expr, CallICState::METHOD);
2968 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2969 // Load the arguments.
2970 ZoneList<Expression*>* args = expr->arguments();
2971 int arg_count = args->length();
2972 for (int i = 0; i < arg_count; i++) {
2973 VisitForStackValue(args->at(i));
2976 SetCallPosition(expr, arg_count);
2977 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2978 __ Move(rdx, SmiFromSlot(expr->CallFeedbackICSlot()));
2979 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
2980 // Don't assign a type feedback id to the IC, since type feedback is provided
2981 // by the vector above.
2984 RecordJSReturnSite(expr);
2986 // Restore context register.
2987 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2988 // Discard the function left on TOS.
2989 context()->DropAndPlug(1, rax);
2993 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2994 // Push copy of the first argument or undefined if it doesn't exist.
2995 if (arg_count > 0) {
2996 __ Push(Operand(rsp, arg_count * kPointerSize));
2998 __ PushRoot(Heap::kUndefinedValueRootIndex);
3001 // Push the enclosing function.
3002 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
3004 // Push the language mode.
3005 __ Push(Smi::FromInt(language_mode()));
3007 // Push the start position of the scope the calls resides in.
3008 __ Push(Smi::FromInt(scope()->start_position()));
3010 // Do the runtime call.
3011 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 5);
3015 // See http://www.ecma-international.org/ecma-262/6.0/#sec-function-calls.
3016 void FullCodeGenerator::PushCalleeAndWithBaseObject(Call* expr) {
3017 VariableProxy* callee = expr->expression()->AsVariableProxy();
3018 if (callee->var()->IsLookupSlot()) {
3020 SetExpressionPosition(callee);
3021 // Generate code for loading from variables potentially shadowed by
3022 // eval-introduced variables.
3023 EmitDynamicLookupFastCase(callee, NOT_INSIDE_TYPEOF, &slow, &done);
3025 // Call the runtime to find the function to call (returned in rax) and
3026 // the object holding it (returned in rdx).
3027 __ Push(context_register());
3028 __ Push(callee->name());
3029 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3030 __ Push(rax); // Function.
3031 __ Push(rdx); // Receiver.
3032 PrepareForBailoutForId(expr->LookupId(), NO_REGISTERS);
3034 // If fast case code has been generated, emit code to push the function
3035 // and receiver and have the slow path jump around this code.
3036 if (done.is_linked()) {
3038 __ jmp(&call, Label::kNear);
3042 // Pass undefined as the receiver, which is the WithBaseObject of a
3043 // non-object environment record. If the callee is sloppy, it will patch
3044 // it up to be the global receiver.
3045 __ PushRoot(Heap::kUndefinedValueRootIndex);
3049 VisitForStackValue(callee);
3050 // refEnv.WithBaseObject()
3051 __ PushRoot(Heap::kUndefinedValueRootIndex);
3056 void FullCodeGenerator::VisitCall(Call* expr) {
3058 // We want to verify that RecordJSReturnSite gets called on all paths
3059 // through this function. Avoid early returns.
3060 expr->return_is_recorded_ = false;
3063 Comment cmnt(masm_, "[ Call");
3064 Expression* callee = expr->expression();
3065 Call::CallType call_type = expr->GetCallType(isolate());
3067 if (call_type == Call::POSSIBLY_EVAL_CALL) {
3068 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
3069 // to resolve the function we need to call. Then we call the resolved
3070 // function using the given arguments.
3071 ZoneList<Expression*>* args = expr->arguments();
3072 int arg_count = args->length();
3073 PushCalleeAndWithBaseObject(expr);
3075 // Push the arguments.
3076 for (int i = 0; i < arg_count; i++) {
3077 VisitForStackValue(args->at(i));
3080 // Push a copy of the function (found below the arguments) and resolve
3082 __ Push(Operand(rsp, (arg_count + 1) * kPointerSize));
3083 EmitResolvePossiblyDirectEval(arg_count);
3085 // Touch up the callee.
3086 __ movp(Operand(rsp, (arg_count + 1) * kPointerSize), rax);
3088 PrepareForBailoutForId(expr->EvalId(), NO_REGISTERS);
3090 SetCallPosition(expr, arg_count);
3091 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3092 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
3094 RecordJSReturnSite(expr);
3095 // Restore context register.
3096 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3097 context()->DropAndPlug(1, rax);
3098 } else if (call_type == Call::GLOBAL_CALL) {
3099 EmitCallWithLoadIC(expr);
3101 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3102 // Call to a lookup slot (dynamically introduced variable).
3103 PushCalleeAndWithBaseObject(expr);
3105 } else if (call_type == Call::PROPERTY_CALL) {
3106 Property* property = callee->AsProperty();
3107 bool is_named_call = property->key()->IsPropertyName();
3108 if (property->IsSuperAccess()) {
3109 if (is_named_call) {
3110 EmitSuperCallWithLoadIC(expr);
3112 EmitKeyedSuperCallWithLoadIC(expr);
3115 VisitForStackValue(property->obj());
3116 if (is_named_call) {
3117 EmitCallWithLoadIC(expr);
3119 EmitKeyedCallWithLoadIC(expr, property->key());
3122 } else if (call_type == Call::SUPER_CALL) {
3123 EmitSuperConstructorCall(expr);
3125 DCHECK(call_type == Call::OTHER_CALL);
3126 // Call to an arbitrary expression not handled specially above.
3127 VisitForStackValue(callee);
3128 __ PushRoot(Heap::kUndefinedValueRootIndex);
3129 // Emit function call.
3134 // RecordJSReturnSite should have been called.
3135 DCHECK(expr->return_is_recorded_);
3140 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3141 Comment cmnt(masm_, "[ CallNew");
3142 // According to ECMA-262, section 11.2.2, page 44, the function
3143 // expression in new calls must be evaluated before the
3146 // Push constructor on the stack. If it's not a function it's used as
3147 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3149 DCHECK(!expr->expression()->IsSuperPropertyReference());
3150 VisitForStackValue(expr->expression());
3152 // Push the arguments ("left-to-right") on the stack.
3153 ZoneList<Expression*>* args = expr->arguments();
3154 int arg_count = args->length();
3155 for (int i = 0; i < arg_count; i++) {
3156 VisitForStackValue(args->at(i));
3159 // Call the construct call builtin that handles allocation and
3160 // constructor invocation.
3161 SetConstructCallPosition(expr);
3163 // Load function and argument count into rdi and rax.
3164 __ Set(rax, arg_count);
3165 __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
3167 // Record call targets in unoptimized code, but not in the snapshot.
3168 if (FLAG_pretenuring_call_new) {
3169 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3170 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3171 expr->CallNewFeedbackSlot().ToInt() + 1);
3174 __ Move(rbx, FeedbackVector());
3175 __ Move(rdx, SmiFromSlot(expr->CallNewFeedbackSlot()));
3177 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3178 __ Call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3179 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3180 context()->Plug(rax);
3184 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3185 SuperCallReference* super_call_ref =
3186 expr->expression()->AsSuperCallReference();
3187 DCHECK_NOT_NULL(super_call_ref);
3189 EmitLoadSuperConstructor(super_call_ref);
3190 __ Push(result_register());
3192 // Push the arguments ("left-to-right") on the stack.
3193 ZoneList<Expression*>* args = expr->arguments();
3194 int arg_count = args->length();
3195 for (int i = 0; i < arg_count; i++) {
3196 VisitForStackValue(args->at(i));
3199 // Call the construct call builtin that handles allocation and
3200 // constructor invocation.
3201 SetConstructCallPosition(expr);
3203 // Load original constructor into rcx.
3204 VisitForAccumulatorValue(super_call_ref->new_target_var());
3205 __ movp(rcx, result_register());
3207 // Load function and argument count into rdi and rax.
3208 __ Set(rax, arg_count);
3209 __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
3211 // Record call targets in unoptimized code.
3212 if (FLAG_pretenuring_call_new) {
3214 /* TODO(dslomov): support pretenuring.
3215 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3216 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3217 expr->CallNewFeedbackSlot().ToInt() + 1);
3221 __ Move(rbx, FeedbackVector());
3222 __ Move(rdx, SmiFromSlot(expr->CallFeedbackSlot()));
3224 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3225 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3227 RecordJSReturnSite(expr);
3229 context()->Plug(rax);
3233 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3234 ZoneList<Expression*>* args = expr->arguments();
3235 DCHECK(args->length() == 1);
3237 VisitForAccumulatorValue(args->at(0));
3239 Label materialize_true, materialize_false;
3240 Label* if_true = NULL;
3241 Label* if_false = NULL;
3242 Label* fall_through = NULL;
3243 context()->PrepareTest(&materialize_true, &materialize_false,
3244 &if_true, &if_false, &fall_through);
3246 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3247 __ JumpIfSmi(rax, if_true);
3250 context()->Plug(if_true, if_false);
3254 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3255 ZoneList<Expression*>* args = expr->arguments();
3256 DCHECK(args->length() == 1);
3258 VisitForAccumulatorValue(args->at(0));
3260 Label materialize_true, materialize_false;
3261 Label* if_true = NULL;
3262 Label* if_false = NULL;
3263 Label* fall_through = NULL;
3264 context()->PrepareTest(&materialize_true, &materialize_false,
3265 &if_true, &if_false, &fall_through);
3267 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3268 Condition non_negative_smi = masm()->CheckNonNegativeSmi(rax);
3269 Split(non_negative_smi, if_true, if_false, fall_through);
3271 context()->Plug(if_true, if_false);
3275 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3276 ZoneList<Expression*>* args = expr->arguments();
3277 DCHECK(args->length() == 1);
3279 VisitForAccumulatorValue(args->at(0));
3281 Label materialize_true, materialize_false;
3282 Label* if_true = NULL;
3283 Label* if_false = NULL;
3284 Label* fall_through = NULL;
3285 context()->PrepareTest(&materialize_true, &materialize_false,
3286 &if_true, &if_false, &fall_through);
3288 __ JumpIfSmi(rax, if_false);
3289 __ CompareRoot(rax, Heap::kNullValueRootIndex);
3290 __ j(equal, if_true);
3291 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3292 // Undetectable objects behave like undefined when tested with typeof.
3293 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
3294 Immediate(1 << Map::kIsUndetectable));
3295 __ j(not_zero, if_false);
3296 __ movzxbp(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset));
3297 __ cmpp(rbx, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
3298 __ j(below, if_false);
3299 __ cmpp(rbx, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
3300 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3301 Split(below_equal, if_true, if_false, fall_through);
3303 context()->Plug(if_true, if_false);
3307 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3308 ZoneList<Expression*>* args = expr->arguments();
3309 DCHECK(args->length() == 1);
3311 VisitForAccumulatorValue(args->at(0));
3313 Label materialize_true, materialize_false;
3314 Label* if_true = NULL;
3315 Label* if_false = NULL;
3316 Label* fall_through = NULL;
3317 context()->PrepareTest(&materialize_true, &materialize_false,
3318 &if_true, &if_false, &fall_through);
3320 __ JumpIfSmi(rax, if_false);
3321 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rbx);
3322 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3323 Split(above_equal, if_true, if_false, fall_through);
3325 context()->Plug(if_true, if_false);
3329 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3330 ZoneList<Expression*>* args = expr->arguments();
3331 DCHECK(args->length() == 1);
3333 VisitForAccumulatorValue(args->at(0));
3335 Label materialize_true, materialize_false;
3336 Label* if_true = NULL;
3337 Label* if_false = NULL;
3338 Label* fall_through = NULL;
3339 context()->PrepareTest(&materialize_true, &materialize_false,
3340 &if_true, &if_false, &fall_through);
3342 __ JumpIfSmi(rax, if_false);
3343 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3344 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
3345 Immediate(1 << Map::kIsUndetectable));
3346 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3347 Split(not_zero, if_true, if_false, fall_through);
3349 context()->Plug(if_true, if_false);
3353 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3354 CallRuntime* expr) {
3355 ZoneList<Expression*>* args = expr->arguments();
3356 DCHECK(args->length() == 1);
3358 VisitForAccumulatorValue(args->at(0));
3360 Label materialize_true, materialize_false, skip_lookup;
3361 Label* if_true = NULL;
3362 Label* if_false = NULL;
3363 Label* fall_through = NULL;
3364 context()->PrepareTest(&materialize_true, &materialize_false,
3365 &if_true, &if_false, &fall_through);
3367 __ AssertNotSmi(rax);
3369 // Check whether this map has already been checked to be safe for default
3371 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3372 __ testb(FieldOperand(rbx, Map::kBitField2Offset),
3373 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3374 __ j(not_zero, &skip_lookup);
3376 // Check for fast case object. Generate false result for slow case object.
3377 __ movp(rcx, FieldOperand(rax, JSObject::kPropertiesOffset));
3378 __ movp(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3379 __ CompareRoot(rcx, Heap::kHashTableMapRootIndex);
3380 __ j(equal, if_false);
3382 // Look for valueOf string in the descriptor array, and indicate false if
3383 // found. Since we omit an enumeration index check, if it is added via a
3384 // transition that shares its descriptor array, this is a false positive.
3385 Label entry, loop, done;
3387 // Skip loop if no descriptors are valid.
3388 __ NumberOfOwnDescriptors(rcx, rbx);
3389 __ cmpp(rcx, Immediate(0));
3392 __ LoadInstanceDescriptors(rbx, r8);
3393 // rbx: descriptor array.
3394 // rcx: valid entries in the descriptor array.
3395 // Calculate the end of the descriptor array.
3396 __ imulp(rcx, rcx, Immediate(DescriptorArray::kDescriptorSize));
3398 Operand(r8, rcx, times_pointer_size, DescriptorArray::kFirstOffset));
3399 // Calculate location of the first key name.
3400 __ addp(r8, Immediate(DescriptorArray::kFirstOffset));
3401 // Loop through all the keys in the descriptor array. If one of these is the
3402 // internalized string "valueOf" the result is false.
3405 __ movp(rdx, FieldOperand(r8, 0));
3406 __ Cmp(rdx, isolate()->factory()->value_of_string());
3407 __ j(equal, if_false);
3408 __ addp(r8, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3411 __ j(not_equal, &loop);
3415 // Set the bit in the map to indicate that there is no local valueOf field.
3416 __ orp(FieldOperand(rbx, Map::kBitField2Offset),
3417 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3419 __ bind(&skip_lookup);
3421 // If a valueOf property is not found on the object check that its
3422 // prototype is the un-modified String prototype. If not result is false.
3423 __ movp(rcx, FieldOperand(rbx, Map::kPrototypeOffset));
3424 __ testp(rcx, Immediate(kSmiTagMask));
3425 __ j(zero, if_false);
3426 __ movp(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3427 __ movp(rdx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3428 __ movp(rdx, FieldOperand(rdx, GlobalObject::kNativeContextOffset));
3430 ContextOperand(rdx, Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3431 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3432 Split(equal, if_true, if_false, fall_through);
3434 context()->Plug(if_true, if_false);
3438 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3439 ZoneList<Expression*>* args = expr->arguments();
3440 DCHECK(args->length() == 1);
3442 VisitForAccumulatorValue(args->at(0));
3444 Label materialize_true, materialize_false;
3445 Label* if_true = NULL;
3446 Label* if_false = NULL;
3447 Label* fall_through = NULL;
3448 context()->PrepareTest(&materialize_true, &materialize_false,
3449 &if_true, &if_false, &fall_through);
3451 __ JumpIfSmi(rax, if_false);
3452 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
3453 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3454 Split(equal, if_true, if_false, fall_through);
3456 context()->Plug(if_true, if_false);
3460 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3461 ZoneList<Expression*>* args = expr->arguments();
3462 DCHECK(args->length() == 1);
3464 VisitForAccumulatorValue(args->at(0));
3466 Label materialize_true, materialize_false;
3467 Label* if_true = NULL;
3468 Label* if_false = NULL;
3469 Label* fall_through = NULL;
3470 context()->PrepareTest(&materialize_true, &materialize_false,
3471 &if_true, &if_false, &fall_through);
3473 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3474 __ CheckMap(rax, map, if_false, DO_SMI_CHECK);
3475 __ cmpl(FieldOperand(rax, HeapNumber::kExponentOffset),
3477 __ j(no_overflow, if_false);
3478 __ cmpl(FieldOperand(rax, HeapNumber::kMantissaOffset),
3479 Immediate(0x00000000));
3480 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3481 Split(equal, if_true, if_false, fall_through);
3483 context()->Plug(if_true, if_false);
3487 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3488 ZoneList<Expression*>* args = expr->arguments();
3489 DCHECK(args->length() == 1);
3491 VisitForAccumulatorValue(args->at(0));
3493 Label materialize_true, materialize_false;
3494 Label* if_true = NULL;
3495 Label* if_false = NULL;
3496 Label* fall_through = NULL;
3497 context()->PrepareTest(&materialize_true, &materialize_false,
3498 &if_true, &if_false, &fall_through);
3500 __ JumpIfSmi(rax, if_false);
3501 __ CmpObjectType(rax, JS_ARRAY_TYPE, rbx);
3502 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3503 Split(equal, if_true, if_false, fall_through);
3505 context()->Plug(if_true, if_false);
3509 void FullCodeGenerator::EmitIsTypedArray(CallRuntime* expr) {
3510 ZoneList<Expression*>* args = expr->arguments();
3511 DCHECK(args->length() == 1);
3513 VisitForAccumulatorValue(args->at(0));
3515 Label materialize_true, materialize_false;
3516 Label* if_true = NULL;
3517 Label* if_false = NULL;
3518 Label* fall_through = NULL;
3519 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3520 &if_false, &fall_through);
3522 __ JumpIfSmi(rax, if_false);
3523 __ CmpObjectType(rax, JS_TYPED_ARRAY_TYPE, rbx);
3524 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3525 Split(equal, if_true, if_false, fall_through);
3527 context()->Plug(if_true, if_false);
3531 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3532 ZoneList<Expression*>* args = expr->arguments();
3533 DCHECK(args->length() == 1);
3535 VisitForAccumulatorValue(args->at(0));
3537 Label materialize_true, materialize_false;
3538 Label* if_true = NULL;
3539 Label* if_false = NULL;
3540 Label* fall_through = NULL;
3541 context()->PrepareTest(&materialize_true, &materialize_false,
3542 &if_true, &if_false, &fall_through);
3544 __ JumpIfSmi(rax, if_false);
3545 __ CmpObjectType(rax, JS_REGEXP_TYPE, rbx);
3546 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3547 Split(equal, if_true, if_false, fall_through);
3549 context()->Plug(if_true, if_false);
3553 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3554 ZoneList<Expression*>* args = expr->arguments();
3555 DCHECK(args->length() == 1);
3557 VisitForAccumulatorValue(args->at(0));
3559 Label materialize_true, materialize_false;
3560 Label* if_true = NULL;
3561 Label* if_false = NULL;
3562 Label* fall_through = NULL;
3563 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3564 &if_false, &fall_through);
3566 __ JumpIfSmi(rax, if_false);
3568 __ movp(map, FieldOperand(rax, HeapObject::kMapOffset));
3569 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3570 __ j(less, if_false);
3571 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3572 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3573 Split(less_equal, if_true, if_false, fall_through);
3575 context()->Plug(if_true, if_false);
3579 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3580 DCHECK(expr->arguments()->length() == 0);
3582 Label materialize_true, materialize_false;
3583 Label* if_true = NULL;
3584 Label* if_false = NULL;
3585 Label* fall_through = NULL;
3586 context()->PrepareTest(&materialize_true, &materialize_false,
3587 &if_true, &if_false, &fall_through);
3589 // Get the frame pointer for the calling frame.
3590 __ movp(rax, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3592 // Skip the arguments adaptor frame if it exists.
3593 Label check_frame_marker;
3594 __ Cmp(Operand(rax, StandardFrameConstants::kContextOffset),
3595 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3596 __ j(not_equal, &check_frame_marker);
3597 __ movp(rax, Operand(rax, StandardFrameConstants::kCallerFPOffset));
3599 // Check the marker in the calling frame.
3600 __ bind(&check_frame_marker);
3601 __ Cmp(Operand(rax, StandardFrameConstants::kMarkerOffset),
3602 Smi::FromInt(StackFrame::CONSTRUCT));
3603 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3604 Split(equal, if_true, if_false, fall_through);
3606 context()->Plug(if_true, if_false);
3610 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3611 ZoneList<Expression*>* args = expr->arguments();
3612 DCHECK(args->length() == 2);
3614 // Load the two objects into registers and perform the comparison.
3615 VisitForStackValue(args->at(0));
3616 VisitForAccumulatorValue(args->at(1));
3618 Label materialize_true, materialize_false;
3619 Label* if_true = NULL;
3620 Label* if_false = NULL;
3621 Label* fall_through = NULL;
3622 context()->PrepareTest(&materialize_true, &materialize_false,
3623 &if_true, &if_false, &fall_through);
3627 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3628 Split(equal, if_true, if_false, fall_through);
3630 context()->Plug(if_true, if_false);
3634 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3635 ZoneList<Expression*>* args = expr->arguments();
3636 DCHECK(args->length() == 1);
3638 // ArgumentsAccessStub expects the key in rdx and the formal
3639 // parameter count in rax.
3640 VisitForAccumulatorValue(args->at(0));
3642 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters()));
3643 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3645 context()->Plug(rax);
3649 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3650 DCHECK(expr->arguments()->length() == 0);
3653 // Get the number of formal parameters.
3654 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters()));
3656 // Check if the calling frame is an arguments adaptor frame.
3657 __ movp(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3658 __ Cmp(Operand(rbx, StandardFrameConstants::kContextOffset),
3659 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3660 __ j(not_equal, &exit, Label::kNear);
3662 // Arguments adaptor case: Read the arguments length from the
3664 __ movp(rax, Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3668 context()->Plug(rax);
3672 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3673 ZoneList<Expression*>* args = expr->arguments();
3674 DCHECK(args->length() == 1);
3675 Label done, null, function, non_function_constructor;
3677 VisitForAccumulatorValue(args->at(0));
3679 // If the object is a smi, we return null.
3680 __ JumpIfSmi(rax, &null);
3682 // Check that the object is a JS object but take special care of JS
3683 // functions to make sure they have 'Function' as their class.
3684 // Assume that there are only two callable types, and one of them is at
3685 // either end of the type range for JS object types. Saves extra comparisons.
3686 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3687 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rax);
3688 // Map is now in rax.
3690 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3691 FIRST_SPEC_OBJECT_TYPE + 1);
3692 __ j(equal, &function);
3694 __ CmpInstanceType(rax, LAST_SPEC_OBJECT_TYPE);
3695 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3696 LAST_SPEC_OBJECT_TYPE - 1);
3697 __ j(equal, &function);
3698 // Assume that there is no larger type.
3699 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3701 // Check if the constructor in the map is a JS function.
3702 __ GetMapConstructor(rax, rax, rbx);
3703 __ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
3704 __ j(not_equal, &non_function_constructor);
3706 // rax now contains the constructor function. Grab the
3707 // instance class name from there.
3708 __ movp(rax, FieldOperand(rax, JSFunction::kSharedFunctionInfoOffset));
3709 __ movp(rax, FieldOperand(rax, SharedFunctionInfo::kInstanceClassNameOffset));
3712 // Functions have class 'Function'.
3714 __ Move(rax, isolate()->factory()->Function_string());
3717 // Objects with a non-function constructor have class 'Object'.
3718 __ bind(&non_function_constructor);
3719 __ Move(rax, isolate()->factory()->Object_string());
3722 // Non-JS objects have class null.
3724 __ LoadRoot(rax, Heap::kNullValueRootIndex);
3729 context()->Plug(rax);
3733 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3734 ZoneList<Expression*>* args = expr->arguments();
3735 DCHECK(args->length() == 1);
3737 VisitForAccumulatorValue(args->at(0)); // Load the object.
3740 // If the object is a smi return the object.
3741 __ JumpIfSmi(rax, &done);
3742 // If the object is not a value type, return the object.
3743 __ CmpObjectType(rax, JS_VALUE_TYPE, rbx);
3744 __ j(not_equal, &done);
3745 __ movp(rax, FieldOperand(rax, JSValue::kValueOffset));
3748 context()->Plug(rax);
3752 void FullCodeGenerator::EmitIsDate(CallRuntime* expr) {
3753 ZoneList<Expression*>* args = expr->arguments();
3754 DCHECK_EQ(1, args->length());
3756 VisitForAccumulatorValue(args->at(0));
3758 Label materialize_true, materialize_false;
3759 Label* if_true = nullptr;
3760 Label* if_false = nullptr;
3761 Label* fall_through = nullptr;
3762 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3763 &if_false, &fall_through);
3765 __ JumpIfSmi(rax, if_false);
3766 __ CmpObjectType(rax, JS_DATE_TYPE, rbx);
3767 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3768 Split(equal, if_true, if_false, fall_through);
3770 context()->Plug(if_true, if_false);
3774 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3775 ZoneList<Expression*>* args = expr->arguments();
3776 DCHECK(args->length() == 2);
3777 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3778 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3780 VisitForAccumulatorValue(args->at(0)); // Load the object.
3782 Register object = rax;
3783 Register result = rax;
3784 Register scratch = rcx;
3786 if (FLAG_debug_code) {
3787 __ AssertNotSmi(object);
3788 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3789 __ Check(equal, kOperandIsNotADate);
3792 if (index->value() == 0) {
3793 __ movp(result, FieldOperand(object, JSDate::kValueOffset));
3795 Label runtime, done;
3796 if (index->value() < JSDate::kFirstUncachedField) {
3797 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3798 Operand stamp_operand = __ ExternalOperand(stamp);
3799 __ movp(scratch, stamp_operand);
3800 __ cmpp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3801 __ j(not_equal, &runtime, Label::kNear);
3802 __ movp(result, FieldOperand(object, JSDate::kValueOffset +
3803 kPointerSize * index->value()));
3804 __ jmp(&done, Label::kNear);
3807 __ PrepareCallCFunction(2);
3808 __ movp(arg_reg_1, object);
3809 __ Move(arg_reg_2, index, Assembler::RelocInfoNone());
3810 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3811 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3815 context()->Plug(rax);
3819 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3820 ZoneList<Expression*>* args = expr->arguments();
3821 DCHECK_EQ(3, args->length());
3823 Register string = rax;
3824 Register index = rbx;
3825 Register value = rcx;
3827 VisitForStackValue(args->at(0)); // index
3828 VisitForStackValue(args->at(1)); // value
3829 VisitForAccumulatorValue(args->at(2)); // string
3833 if (FLAG_debug_code) {
3834 __ Check(__ CheckSmi(value), kNonSmiValue);
3835 __ Check(__ CheckSmi(index), kNonSmiValue);
3838 __ SmiToInteger32(value, value);
3839 __ SmiToInteger32(index, index);
3841 if (FLAG_debug_code) {
3842 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3843 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3846 __ movb(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3848 context()->Plug(string);
3852 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3853 ZoneList<Expression*>* args = expr->arguments();
3854 DCHECK_EQ(3, args->length());
3856 Register string = rax;
3857 Register index = rbx;
3858 Register value = rcx;
3860 VisitForStackValue(args->at(0)); // index
3861 VisitForStackValue(args->at(1)); // value
3862 VisitForAccumulatorValue(args->at(2)); // string
3866 if (FLAG_debug_code) {
3867 __ Check(__ CheckSmi(value), kNonSmiValue);
3868 __ Check(__ CheckSmi(index), kNonSmiValue);
3871 __ SmiToInteger32(value, value);
3872 __ SmiToInteger32(index, index);
3874 if (FLAG_debug_code) {
3875 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3876 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3879 __ movw(FieldOperand(string, index, times_2, SeqTwoByteString::kHeaderSize),
3881 context()->Plug(rax);
3885 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3886 ZoneList<Expression*>* args = expr->arguments();
3887 DCHECK(args->length() == 2);
3889 VisitForStackValue(args->at(0)); // Load the object.
3890 VisitForAccumulatorValue(args->at(1)); // Load the value.
3891 __ Pop(rbx); // rax = value. rbx = object.
3894 // If the object is a smi, return the value.
3895 __ JumpIfSmi(rbx, &done);
3897 // If the object is not a value type, return the value.
3898 __ CmpObjectType(rbx, JS_VALUE_TYPE, rcx);
3899 __ j(not_equal, &done);
3902 __ movp(FieldOperand(rbx, JSValue::kValueOffset), rax);
3903 // Update the write barrier. Save the value as it will be
3904 // overwritten by the write barrier code and is needed afterward.
3906 __ RecordWriteField(rbx, JSValue::kValueOffset, rdx, rcx, kDontSaveFPRegs);
3909 context()->Plug(rax);
3913 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3914 ZoneList<Expression*>* args = expr->arguments();
3915 DCHECK_EQ(args->length(), 1);
3917 // Load the argument into rax and call the stub.
3918 VisitForAccumulatorValue(args->at(0));
3920 NumberToStringStub stub(isolate());
3922 context()->Plug(rax);
3926 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3927 ZoneList<Expression*>* args = expr->arguments();
3928 DCHECK(args->length() == 1);
3930 VisitForAccumulatorValue(args->at(0));
3933 StringCharFromCodeGenerator generator(rax, rbx);
3934 generator.GenerateFast(masm_);
3937 NopRuntimeCallHelper call_helper;
3938 generator.GenerateSlow(masm_, call_helper);
3941 context()->Plug(rbx);
3945 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3946 ZoneList<Expression*>* args = expr->arguments();
3947 DCHECK(args->length() == 2);
3949 VisitForStackValue(args->at(0));
3950 VisitForAccumulatorValue(args->at(1));
3952 Register object = rbx;
3953 Register index = rax;
3954 Register result = rdx;
3958 Label need_conversion;
3959 Label index_out_of_range;
3961 StringCharCodeAtGenerator generator(object,
3966 &index_out_of_range,
3967 STRING_INDEX_IS_NUMBER);
3968 generator.GenerateFast(masm_);
3971 __ bind(&index_out_of_range);
3972 // When the index is out of range, the spec requires us to return
3974 __ LoadRoot(result, Heap::kNanValueRootIndex);
3977 __ bind(&need_conversion);
3978 // Move the undefined value into the result register, which will
3979 // trigger conversion.
3980 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
3983 NopRuntimeCallHelper call_helper;
3984 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
3987 context()->Plug(result);
3991 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3992 ZoneList<Expression*>* args = expr->arguments();
3993 DCHECK(args->length() == 2);
3995 VisitForStackValue(args->at(0));
3996 VisitForAccumulatorValue(args->at(1));
3998 Register object = rbx;
3999 Register index = rax;
4000 Register scratch = rdx;
4001 Register result = rax;
4005 Label need_conversion;
4006 Label index_out_of_range;
4008 StringCharAtGenerator generator(object,
4014 &index_out_of_range,
4015 STRING_INDEX_IS_NUMBER);
4016 generator.GenerateFast(masm_);
4019 __ bind(&index_out_of_range);
4020 // When the index is out of range, the spec requires us to return
4021 // the empty string.
4022 __ LoadRoot(result, Heap::kempty_stringRootIndex);
4025 __ bind(&need_conversion);
4026 // Move smi zero into the result register, which will trigger
4028 __ Move(result, Smi::FromInt(0));
4031 NopRuntimeCallHelper call_helper;
4032 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4035 context()->Plug(result);
4039 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4040 ZoneList<Expression*>* args = expr->arguments();
4041 DCHECK_EQ(2, args->length());
4042 VisitForStackValue(args->at(0));
4043 VisitForAccumulatorValue(args->at(1));
4046 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4048 context()->Plug(rax);
4052 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4053 ZoneList<Expression*>* args = expr->arguments();
4054 DCHECK(args->length() >= 2);
4056 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4057 for (int i = 0; i < arg_count + 1; i++) {
4058 VisitForStackValue(args->at(i));
4060 VisitForAccumulatorValue(args->last()); // Function.
4062 Label runtime, done;
4063 // Check for non-function argument (including proxy).
4064 __ JumpIfSmi(rax, &runtime);
4065 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
4066 __ j(not_equal, &runtime);
4068 // InvokeFunction requires the function in rdi. Move it in there.
4069 __ movp(rdi, result_register());
4070 ParameterCount count(arg_count);
4071 __ InvokeFunction(rdi, count, CALL_FUNCTION, NullCallWrapper());
4072 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4077 __ CallRuntime(Runtime::kCall, args->length());
4080 context()->Plug(rax);
4084 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4085 ZoneList<Expression*>* args = expr->arguments();
4086 DCHECK(args->length() == 2);
4089 VisitForStackValue(args->at(0));
4092 VisitForStackValue(args->at(1));
4093 __ CallRuntime(Runtime::kGetPrototype, 1);
4094 __ Push(result_register());
4096 // Load original constructor into rcx.
4097 __ movp(rcx, Operand(rsp, 1 * kPointerSize));
4099 // Check if the calling frame is an arguments adaptor frame.
4100 Label adaptor_frame, args_set_up, runtime;
4101 __ movp(rdx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
4102 __ movp(rbx, Operand(rdx, StandardFrameConstants::kContextOffset));
4103 __ Cmp(rbx, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
4104 __ j(equal, &adaptor_frame);
4105 // default constructor has no arguments, so no adaptor frame means no args.
4106 __ movp(rax, Immediate(0));
4107 __ jmp(&args_set_up);
4109 // Copy arguments from adaptor frame.
4111 __ bind(&adaptor_frame);
4112 __ movp(rbx, Operand(rdx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4113 __ SmiToInteger64(rbx, rbx);
4116 __ leap(rdx, Operand(rdx, rbx, times_pointer_size,
4117 StandardFrameConstants::kCallerSPOffset));
4120 __ Push(Operand(rdx, -1 * kPointerSize));
4121 __ subp(rdx, Immediate(kPointerSize));
4123 __ j(not_zero, &loop);
4126 __ bind(&args_set_up);
4127 __ movp(rdi, Operand(rsp, rax, times_pointer_size, 0));
4128 __ LoadRoot(rbx, Heap::kUndefinedValueRootIndex);
4130 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4131 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4135 context()->Plug(result_register());
4139 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4140 RegExpConstructResultStub stub(isolate());
4141 ZoneList<Expression*>* args = expr->arguments();
4142 DCHECK(args->length() == 3);
4143 VisitForStackValue(args->at(0));
4144 VisitForStackValue(args->at(1));
4145 VisitForAccumulatorValue(args->at(2));
4149 context()->Plug(rax);
4153 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4154 ZoneList<Expression*>* args = expr->arguments();
4155 DCHECK_EQ(2, args->length());
4157 DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4158 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4160 Handle<FixedArray> jsfunction_result_caches(
4161 isolate()->native_context()->jsfunction_result_caches());
4162 if (jsfunction_result_caches->length() <= cache_id) {
4163 __ Abort(kAttemptToUseUndefinedCache);
4164 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
4165 context()->Plug(rax);
4169 VisitForAccumulatorValue(args->at(1));
4172 Register cache = rbx;
4174 __ movp(cache, ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX));
4176 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4178 ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4180 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4182 Label done, not_found;
4183 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4184 __ movp(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4185 // tmp now holds finger offset as a smi.
4187 __ SmiToIndex(kScratchRegister, tmp, kPointerSizeLog2);
4188 __ cmpp(key, FieldOperand(cache,
4191 FixedArray::kHeaderSize));
4192 __ j(not_equal, ¬_found, Label::kNear);
4193 __ movp(rax, FieldOperand(cache,
4196 FixedArray::kHeaderSize + kPointerSize));
4197 __ jmp(&done, Label::kNear);
4199 __ bind(¬_found);
4200 // Call runtime to perform the lookup.
4203 __ CallRuntime(Runtime::kGetFromCacheRT, 2);
4206 context()->Plug(rax);
4210 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4211 ZoneList<Expression*>* args = expr->arguments();
4212 DCHECK(args->length() == 1);
4214 VisitForAccumulatorValue(args->at(0));
4216 Label materialize_true, materialize_false;
4217 Label* if_true = NULL;
4218 Label* if_false = NULL;
4219 Label* fall_through = NULL;
4220 context()->PrepareTest(&materialize_true, &materialize_false,
4221 &if_true, &if_false, &fall_through);
4223 __ testl(FieldOperand(rax, String::kHashFieldOffset),
4224 Immediate(String::kContainsCachedArrayIndexMask));
4225 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4226 __ j(zero, if_true);
4229 context()->Plug(if_true, if_false);
4233 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4234 ZoneList<Expression*>* args = expr->arguments();
4235 DCHECK(args->length() == 1);
4236 VisitForAccumulatorValue(args->at(0));
4238 __ AssertString(rax);
4240 __ movl(rax, FieldOperand(rax, String::kHashFieldOffset));
4241 DCHECK(String::kHashShift >= kSmiTagSize);
4242 __ IndexFromHash(rax, rax);
4244 context()->Plug(rax);
4248 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4249 Label bailout, return_result, done, one_char_separator, long_separator,
4250 non_trivial_array, not_size_one_array, loop,
4251 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4252 ZoneList<Expression*>* args = expr->arguments();
4253 DCHECK(args->length() == 2);
4254 // We will leave the separator on the stack until the end of the function.
4255 VisitForStackValue(args->at(1));
4256 // Load this to rax (= array)
4257 VisitForAccumulatorValue(args->at(0));
4258 // All aliases of the same register have disjoint lifetimes.
4259 Register array = rax;
4260 Register elements = no_reg; // Will be rax.
4262 Register index = rdx;
4264 Register string_length = rcx;
4266 Register string = rsi;
4268 Register scratch = rbx;
4270 Register array_length = rdi;
4271 Register result_pos = no_reg; // Will be rdi.
4273 Operand separator_operand = Operand(rsp, 2 * kPointerSize);
4274 Operand result_operand = Operand(rsp, 1 * kPointerSize);
4275 Operand array_length_operand = Operand(rsp, 0 * kPointerSize);
4276 // Separator operand is already pushed. Make room for the two
4277 // other stack fields, and clear the direction flag in anticipation
4278 // of calling CopyBytes.
4279 __ subp(rsp, Immediate(2 * kPointerSize));
4281 // Check that the array is a JSArray
4282 __ JumpIfSmi(array, &bailout);
4283 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4284 __ j(not_equal, &bailout);
4286 // Check that the array has fast elements.
4287 __ CheckFastElements(scratch, &bailout);
4289 // Array has fast elements, so its length must be a smi.
4290 // If the array has length zero, return the empty string.
4291 __ movp(array_length, FieldOperand(array, JSArray::kLengthOffset));
4292 __ SmiCompare(array_length, Smi::FromInt(0));
4293 __ j(not_zero, &non_trivial_array);
4294 __ LoadRoot(rax, Heap::kempty_stringRootIndex);
4295 __ jmp(&return_result);
4297 // Save the array length on the stack.
4298 __ bind(&non_trivial_array);
4299 __ SmiToInteger32(array_length, array_length);
4300 __ movl(array_length_operand, array_length);
4302 // Save the FixedArray containing array's elements.
4303 // End of array's live range.
4305 __ movp(elements, FieldOperand(array, JSArray::kElementsOffset));
4309 // Check that all array elements are sequential one-byte strings, and
4310 // accumulate the sum of their lengths, as a smi-encoded value.
4312 __ Set(string_length, 0);
4313 // Loop condition: while (index < array_length).
4314 // Live loop registers: index(int32), array_length(int32), string(String*),
4315 // scratch, string_length(int32), elements(FixedArray*).
4316 if (generate_debug_code_) {
4317 __ cmpp(index, array_length);
4318 __ Assert(below, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4321 __ movp(string, FieldOperand(elements,
4324 FixedArray::kHeaderSize));
4325 __ JumpIfSmi(string, &bailout);
4326 __ movp(scratch, FieldOperand(string, HeapObject::kMapOffset));
4327 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4328 __ andb(scratch, Immediate(
4329 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4330 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag));
4331 __ j(not_equal, &bailout);
4332 __ AddSmiField(string_length,
4333 FieldOperand(string, SeqOneByteString::kLengthOffset));
4334 __ j(overflow, &bailout);
4336 __ cmpl(index, array_length);
4340 // string_length: Sum of string lengths.
4341 // elements: FixedArray of strings.
4342 // index: Array length.
4343 // array_length: Array length.
4345 // If array_length is 1, return elements[0], a string.
4346 __ cmpl(array_length, Immediate(1));
4347 __ j(not_equal, ¬_size_one_array);
4348 __ movp(rax, FieldOperand(elements, FixedArray::kHeaderSize));
4349 __ jmp(&return_result);
4351 __ bind(¬_size_one_array);
4353 // End of array_length live range.
4354 result_pos = array_length;
4355 array_length = no_reg;
4358 // string_length: Sum of string lengths.
4359 // elements: FixedArray of strings.
4360 // index: Array length.
4362 // Check that the separator is a sequential one-byte string.
4363 __ movp(string, separator_operand);
4364 __ JumpIfSmi(string, &bailout);
4365 __ movp(scratch, FieldOperand(string, HeapObject::kMapOffset));
4366 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4367 __ andb(scratch, Immediate(
4368 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4369 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag));
4370 __ j(not_equal, &bailout);
4373 // string_length: Sum of string lengths.
4374 // elements: FixedArray of strings.
4375 // index: Array length.
4376 // string: Separator string.
4378 // Add (separator length times (array_length - 1)) to string_length.
4379 __ SmiToInteger32(scratch,
4380 FieldOperand(string, SeqOneByteString::kLengthOffset));
4382 __ imull(scratch, index);
4383 __ j(overflow, &bailout);
4384 __ addl(string_length, scratch);
4385 __ j(overflow, &bailout);
4387 // Live registers and stack values:
4388 // string_length: Total length of result string.
4389 // elements: FixedArray of strings.
4390 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4392 __ movp(result_operand, result_pos);
4393 __ leap(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4395 __ movp(string, separator_operand);
4396 __ SmiCompare(FieldOperand(string, SeqOneByteString::kLengthOffset),
4398 __ j(equal, &one_char_separator);
4399 __ j(greater, &long_separator);
4402 // Empty separator case:
4404 __ movl(scratch, array_length_operand);
4405 __ jmp(&loop_1_condition);
4406 // Loop condition: while (index < array_length).
4408 // Each iteration of the loop concatenates one string to the result.
4409 // Live values in registers:
4410 // index: which element of the elements array we are adding to the result.
4411 // result_pos: the position to which we are currently copying characters.
4412 // elements: the FixedArray of strings we are joining.
4413 // scratch: array length.
4415 // Get string = array[index].
4416 __ movp(string, FieldOperand(elements, index,
4418 FixedArray::kHeaderSize));
4419 __ SmiToInteger32(string_length,
4420 FieldOperand(string, String::kLengthOffset));
4422 FieldOperand(string, SeqOneByteString::kHeaderSize));
4423 __ CopyBytes(result_pos, string, string_length);
4425 __ bind(&loop_1_condition);
4426 __ cmpl(index, scratch);
4427 __ j(less, &loop_1); // Loop while (index < array_length).
4430 // Generic bailout code used from several places.
4432 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
4433 __ jmp(&return_result);
4436 // One-character separator case
4437 __ bind(&one_char_separator);
4438 // Get the separator one-byte character value.
4439 // Register "string" holds the separator.
4440 __ movzxbl(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4442 // Jump into the loop after the code that copies the separator, so the first
4443 // element is not preceded by a separator
4444 __ jmp(&loop_2_entry);
4445 // Loop condition: while (index < length).
4447 // Each iteration of the loop concatenates one string to the result.
4448 // Live values in registers:
4449 // elements: The FixedArray of strings we are joining.
4450 // index: which element of the elements array we are adding to the result.
4451 // result_pos: the position to which we are currently copying characters.
4452 // scratch: Separator character.
4454 // Copy the separator character to the result.
4455 __ movb(Operand(result_pos, 0), scratch);
4456 __ incp(result_pos);
4458 __ bind(&loop_2_entry);
4459 // Get string = array[index].
4460 __ movp(string, FieldOperand(elements, index,
4462 FixedArray::kHeaderSize));
4463 __ SmiToInteger32(string_length,
4464 FieldOperand(string, String::kLengthOffset));
4466 FieldOperand(string, SeqOneByteString::kHeaderSize));
4467 __ CopyBytes(result_pos, string, string_length);
4469 __ cmpl(index, array_length_operand);
4470 __ j(less, &loop_2); // End while (index < length).
4474 // Long separator case (separator is more than one character).
4475 __ bind(&long_separator);
4477 // Make elements point to end of elements array, and index
4478 // count from -array_length to zero, so we don't need to maintain
4480 __ movl(index, array_length_operand);
4481 __ leap(elements, FieldOperand(elements, index, times_pointer_size,
4482 FixedArray::kHeaderSize));
4485 // Replace separator string with pointer to its first character, and
4486 // make scratch be its length.
4487 __ movp(string, separator_operand);
4488 __ SmiToInteger32(scratch,
4489 FieldOperand(string, String::kLengthOffset));
4491 FieldOperand(string, SeqOneByteString::kHeaderSize));
4492 __ movp(separator_operand, string);
4494 // Jump into the loop after the code that copies the separator, so the first
4495 // element is not preceded by a separator
4496 __ jmp(&loop_3_entry);
4497 // Loop condition: while (index < length).
4499 // Each iteration of the loop concatenates one string to the result.
4500 // Live values in registers:
4501 // index: which element of the elements array we are adding to the result.
4502 // result_pos: the position to which we are currently copying characters.
4503 // scratch: Separator length.
4504 // separator_operand (rsp[0x10]): Address of first char of separator.
4506 // Copy the separator to the result.
4507 __ movp(string, separator_operand);
4508 __ movl(string_length, scratch);
4509 __ CopyBytes(result_pos, string, string_length, 2);
4511 __ bind(&loop_3_entry);
4512 // Get string = array[index].
4513 __ movp(string, Operand(elements, index, times_pointer_size, 0));
4514 __ SmiToInteger32(string_length,
4515 FieldOperand(string, String::kLengthOffset));
4517 FieldOperand(string, SeqOneByteString::kHeaderSize));
4518 __ CopyBytes(result_pos, string, string_length);
4520 __ j(not_equal, &loop_3); // Loop while (index < 0).
4523 __ movp(rax, result_operand);
4525 __ bind(&return_result);
4526 // Drop temp values from the stack, and restore context register.
4527 __ addp(rsp, Immediate(3 * kPointerSize));
4528 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4529 context()->Plug(rax);
4533 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4534 DCHECK(expr->arguments()->length() == 0);
4535 ExternalReference debug_is_active =
4536 ExternalReference::debug_is_active_address(isolate());
4537 __ Move(kScratchRegister, debug_is_active);
4538 __ movzxbp(rax, Operand(kScratchRegister, 0));
4539 __ Integer32ToSmi(rax, rax);
4540 context()->Plug(rax);
4544 void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
4545 // Push the builtins object as receiver.
4546 __ movp(rax, GlobalObjectOperand());
4547 __ Push(FieldOperand(rax, GlobalObject::kBuiltinsOffset));
4549 // Load the function from the receiver.
4550 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
4551 __ Move(LoadDescriptor::NameRegister(), expr->name());
4552 __ Move(LoadDescriptor::SlotRegister(),
4553 SmiFromSlot(expr->CallRuntimeFeedbackSlot()));
4554 CallLoadIC(NOT_INSIDE_TYPEOF);
4558 void FullCodeGenerator::EmitCallJSRuntimeFunction(CallRuntime* expr) {
4559 ZoneList<Expression*>* args = expr->arguments();
4560 int arg_count = args->length();
4562 SetCallPosition(expr, arg_count);
4563 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4564 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
4569 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4570 ZoneList<Expression*>* args = expr->arguments();
4571 int arg_count = args->length();
4573 if (expr->is_jsruntime()) {
4574 Comment cmnt(masm_, "[ CallRuntime");
4576 EmitLoadJSRuntimeFunction(expr);
4578 // Push the target function under the receiver.
4579 __ Push(Operand(rsp, 0));
4580 __ movp(Operand(rsp, kPointerSize), rax);
4582 // Push the arguments ("left-to-right").
4583 for (int i = 0; i < arg_count; i++) {
4584 VisitForStackValue(args->at(i));
4587 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4588 EmitCallJSRuntimeFunction(expr);
4590 // Restore context register.
4591 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4592 context()->DropAndPlug(1, rax);
4595 const Runtime::Function* function = expr->function();
4596 switch (function->function_id) {
4597 #define CALL_INTRINSIC_GENERATOR(Name) \
4598 case Runtime::kInline##Name: { \
4599 Comment cmnt(masm_, "[ Inline" #Name); \
4600 return Emit##Name(expr); \
4602 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
4603 #undef CALL_INTRINSIC_GENERATOR
4605 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
4606 // Push the arguments ("left-to-right").
4607 for (int i = 0; i < arg_count; i++) {
4608 VisitForStackValue(args->at(i));
4611 // Call the C runtime.
4612 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4613 __ CallRuntime(function, arg_count);
4614 context()->Plug(rax);
4621 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4622 switch (expr->op()) {
4623 case Token::DELETE: {
4624 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4625 Property* property = expr->expression()->AsProperty();
4626 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4628 if (property != NULL) {
4629 VisitForStackValue(property->obj());
4630 VisitForStackValue(property->key());
4631 __ Push(Smi::FromInt(language_mode()));
4632 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4633 context()->Plug(rax);
4634 } else if (proxy != NULL) {
4635 Variable* var = proxy->var();
4636 // Delete of an unqualified identifier is disallowed in strict mode but
4637 // "delete this" is allowed.
4638 bool is_this = var->HasThisName(isolate());
4639 DCHECK(is_sloppy(language_mode()) || is_this);
4640 if (var->IsUnallocatedOrGlobalSlot()) {
4641 __ Push(GlobalObjectOperand());
4642 __ Push(var->name());
4643 __ Push(Smi::FromInt(SLOPPY));
4644 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4645 context()->Plug(rax);
4646 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4647 // Result of deleting non-global variables is false. 'this' is
4648 // not really a variable, though we implement it as one. The
4649 // subexpression does not have side effects.
4650 context()->Plug(is_this);
4652 // Non-global variable. Call the runtime to try to delete from the
4653 // context where the variable was introduced.
4654 __ Push(context_register());
4655 __ Push(var->name());
4656 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4657 context()->Plug(rax);
4660 // Result of deleting non-property, non-variable reference is true.
4661 // The subexpression may have side effects.
4662 VisitForEffect(expr->expression());
4663 context()->Plug(true);
4669 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4670 VisitForEffect(expr->expression());
4671 context()->Plug(Heap::kUndefinedValueRootIndex);
4676 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4677 if (context()->IsEffect()) {
4678 // Unary NOT has no side effects so it's only necessary to visit the
4679 // subexpression. Match the optimizing compiler by not branching.
4680 VisitForEffect(expr->expression());
4681 } else if (context()->IsTest()) {
4682 const TestContext* test = TestContext::cast(context());
4683 // The labels are swapped for the recursive call.
4684 VisitForControl(expr->expression(),
4685 test->false_label(),
4687 test->fall_through());
4688 context()->Plug(test->true_label(), test->false_label());
4690 // We handle value contexts explicitly rather than simply visiting
4691 // for control and plugging the control flow into the context,
4692 // because we need to prepare a pair of extra administrative AST ids
4693 // for the optimizing compiler.
4694 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4695 Label materialize_true, materialize_false, done;
4696 VisitForControl(expr->expression(),
4700 __ bind(&materialize_true);
4701 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4702 if (context()->IsAccumulatorValue()) {
4703 __ LoadRoot(rax, Heap::kTrueValueRootIndex);
4705 __ PushRoot(Heap::kTrueValueRootIndex);
4707 __ jmp(&done, Label::kNear);
4708 __ bind(&materialize_false);
4709 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4710 if (context()->IsAccumulatorValue()) {
4711 __ LoadRoot(rax, Heap::kFalseValueRootIndex);
4713 __ PushRoot(Heap::kFalseValueRootIndex);
4720 case Token::TYPEOF: {
4721 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4723 AccumulatorValueContext context(this);
4724 VisitForTypeofValue(expr->expression());
4727 TypeofStub typeof_stub(isolate());
4728 __ CallStub(&typeof_stub);
4729 context()->Plug(rax);
4739 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4740 DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
4742 Comment cmnt(masm_, "[ CountOperation");
4744 Property* prop = expr->expression()->AsProperty();
4745 LhsKind assign_type = Property::GetAssignType(prop);
4747 // Evaluate expression and get value.
4748 if (assign_type == VARIABLE) {
4749 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4750 AccumulatorValueContext context(this);
4751 EmitVariableLoad(expr->expression()->AsVariableProxy());
4753 // Reserve space for result of postfix operation.
4754 if (expr->is_postfix() && !context()->IsEffect()) {
4755 __ Push(Smi::FromInt(0));
4757 switch (assign_type) {
4758 case NAMED_PROPERTY: {
4759 VisitForStackValue(prop->obj());
4760 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
4761 EmitNamedPropertyLoad(prop);
4765 case NAMED_SUPER_PROPERTY: {
4766 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4767 VisitForAccumulatorValue(
4768 prop->obj()->AsSuperPropertyReference()->home_object());
4769 __ Push(result_register());
4770 __ Push(MemOperand(rsp, kPointerSize));
4771 __ Push(result_register());
4772 EmitNamedSuperPropertyLoad(prop);
4776 case KEYED_SUPER_PROPERTY: {
4777 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4779 prop->obj()->AsSuperPropertyReference()->home_object());
4780 VisitForAccumulatorValue(prop->key());
4781 __ Push(result_register());
4782 __ Push(MemOperand(rsp, 2 * kPointerSize));
4783 __ Push(MemOperand(rsp, 2 * kPointerSize));
4784 __ Push(result_register());
4785 EmitKeyedSuperPropertyLoad(prop);
4789 case KEYED_PROPERTY: {
4790 VisitForStackValue(prop->obj());
4791 VisitForStackValue(prop->key());
4792 // Leave receiver on stack
4793 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
4794 // Copy of key, needed for later store.
4795 __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
4796 EmitKeyedPropertyLoad(prop);
4805 // We need a second deoptimization point after loading the value
4806 // in case evaluating the property load my have a side effect.
4807 if (assign_type == VARIABLE) {
4808 PrepareForBailout(expr->expression(), TOS_REG);
4810 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4813 // Inline smi case if we are in a loop.
4814 Label done, stub_call;
4815 JumpPatchSite patch_site(masm_);
4816 if (ShouldInlineSmiCase(expr->op())) {
4818 patch_site.EmitJumpIfNotSmi(rax, &slow, Label::kNear);
4820 // Save result for postfix expressions.
4821 if (expr->is_postfix()) {
4822 if (!context()->IsEffect()) {
4823 // Save the result on the stack. If we have a named or keyed property
4824 // we store the result under the receiver that is currently on top
4826 switch (assign_type) {
4830 case NAMED_PROPERTY:
4831 __ movp(Operand(rsp, kPointerSize), rax);
4833 case NAMED_SUPER_PROPERTY:
4834 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4836 case KEYED_PROPERTY:
4837 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4839 case KEYED_SUPER_PROPERTY:
4840 __ movp(Operand(rsp, 3 * kPointerSize), rax);
4846 SmiOperationConstraints constraints =
4847 SmiOperationConstraint::kPreserveSourceRegister |
4848 SmiOperationConstraint::kBailoutOnNoOverflow;
4849 if (expr->op() == Token::INC) {
4850 __ SmiAddConstant(rax, rax, Smi::FromInt(1), constraints, &done,
4853 __ SmiSubConstant(rax, rax, Smi::FromInt(1), constraints, &done,
4856 __ jmp(&stub_call, Label::kNear);
4859 if (!is_strong(language_mode())) {
4860 ToNumberStub convert_stub(isolate());
4861 __ CallStub(&convert_stub);
4862 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4865 // Save result for postfix expressions.
4866 if (expr->is_postfix()) {
4867 if (!context()->IsEffect()) {
4868 // Save the result on the stack. If we have a named or keyed property
4869 // we store the result under the receiver that is currently on top
4871 switch (assign_type) {
4875 case NAMED_PROPERTY:
4876 __ movp(Operand(rsp, kPointerSize), rax);
4878 case NAMED_SUPER_PROPERTY:
4879 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4881 case KEYED_PROPERTY:
4882 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4884 case KEYED_SUPER_PROPERTY:
4885 __ movp(Operand(rsp, 3 * kPointerSize), rax);
4891 SetExpressionPosition(expr);
4893 // Call stub for +1/-1.
4894 __ bind(&stub_call);
4896 __ Move(rax, Smi::FromInt(1));
4897 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
4898 strength(language_mode())).code();
4899 CallIC(code, expr->CountBinOpFeedbackId());
4900 patch_site.EmitPatchInfo();
4903 if (is_strong(language_mode())) {
4904 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4906 // Store the value returned in rax.
4907 switch (assign_type) {
4909 if (expr->is_postfix()) {
4910 // Perform the assignment as if via '='.
4911 { EffectContext context(this);
4912 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4913 Token::ASSIGN, expr->CountSlot());
4914 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4917 // For all contexts except kEffect: We have the result on
4918 // top of the stack.
4919 if (!context()->IsEffect()) {
4920 context()->PlugTOS();
4923 // Perform the assignment as if via '='.
4924 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4925 Token::ASSIGN, expr->CountSlot());
4926 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4927 context()->Plug(rax);
4930 case NAMED_PROPERTY: {
4931 __ Move(StoreDescriptor::NameRegister(),
4932 prop->key()->AsLiteral()->value());
4933 __ Pop(StoreDescriptor::ReceiverRegister());
4934 if (FLAG_vector_stores) {
4935 EmitLoadStoreICSlot(expr->CountSlot());
4938 CallStoreIC(expr->CountStoreFeedbackId());
4940 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4941 if (expr->is_postfix()) {
4942 if (!context()->IsEffect()) {
4943 context()->PlugTOS();
4946 context()->Plug(rax);
4950 case NAMED_SUPER_PROPERTY: {
4951 EmitNamedSuperPropertyStore(prop);
4952 if (expr->is_postfix()) {
4953 if (!context()->IsEffect()) {
4954 context()->PlugTOS();
4957 context()->Plug(rax);
4961 case KEYED_SUPER_PROPERTY: {
4962 EmitKeyedSuperPropertyStore(prop);
4963 if (expr->is_postfix()) {
4964 if (!context()->IsEffect()) {
4965 context()->PlugTOS();
4968 context()->Plug(rax);
4972 case KEYED_PROPERTY: {
4973 __ Pop(StoreDescriptor::NameRegister());
4974 __ Pop(StoreDescriptor::ReceiverRegister());
4976 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4977 if (FLAG_vector_stores) {
4978 EmitLoadStoreICSlot(expr->CountSlot());
4981 CallIC(ic, expr->CountStoreFeedbackId());
4983 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4984 if (expr->is_postfix()) {
4985 if (!context()->IsEffect()) {
4986 context()->PlugTOS();
4989 context()->Plug(rax);
4997 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4998 Expression* sub_expr,
4999 Handle<String> check) {
5000 Label materialize_true, materialize_false;
5001 Label* if_true = NULL;
5002 Label* if_false = NULL;
5003 Label* fall_through = NULL;
5004 context()->PrepareTest(&materialize_true, &materialize_false,
5005 &if_true, &if_false, &fall_through);
5007 { AccumulatorValueContext context(this);
5008 VisitForTypeofValue(sub_expr);
5010 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5012 Factory* factory = isolate()->factory();
5013 if (String::Equals(check, factory->number_string())) {
5014 __ JumpIfSmi(rax, if_true);
5015 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
5016 __ CompareRoot(rax, Heap::kHeapNumberMapRootIndex);
5017 Split(equal, if_true, if_false, fall_through);
5018 } else if (String::Equals(check, factory->string_string())) {
5019 __ JumpIfSmi(rax, if_false);
5020 // Check for undetectable objects => false.
5021 __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, rdx);
5022 __ j(above_equal, if_false);
5023 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
5024 Immediate(1 << Map::kIsUndetectable));
5025 Split(zero, if_true, if_false, fall_through);
5026 } else if (String::Equals(check, factory->symbol_string())) {
5027 __ JumpIfSmi(rax, if_false);
5028 __ CmpObjectType(rax, SYMBOL_TYPE, rdx);
5029 Split(equal, if_true, if_false, fall_through);
5030 } else if (String::Equals(check, factory->float32x4_string())) {
5031 __ JumpIfSmi(rax, if_false);
5032 __ CmpObjectType(rax, FLOAT32X4_TYPE, rdx);
5033 Split(equal, if_true, if_false, fall_through);
5034 } else if (String::Equals(check, factory->boolean_string())) {
5035 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
5036 __ j(equal, if_true);
5037 __ CompareRoot(rax, Heap::kFalseValueRootIndex);
5038 Split(equal, if_true, if_false, fall_through);
5039 } else if (String::Equals(check, factory->undefined_string())) {
5040 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
5041 __ j(equal, if_true);
5042 __ JumpIfSmi(rax, if_false);
5043 // Check for undetectable objects => true.
5044 __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
5045 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
5046 Immediate(1 << Map::kIsUndetectable));
5047 Split(not_zero, if_true, if_false, fall_through);
5048 } else if (String::Equals(check, factory->function_string())) {
5049 __ JumpIfSmi(rax, if_false);
5050 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5051 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rdx);
5052 __ j(equal, if_true);
5053 __ CmpInstanceType(rdx, JS_FUNCTION_PROXY_TYPE);
5054 Split(equal, if_true, if_false, fall_through);
5055 } else if (String::Equals(check, factory->object_string())) {
5056 __ JumpIfSmi(rax, if_false);
5057 __ CompareRoot(rax, Heap::kNullValueRootIndex);
5058 __ j(equal, if_true);
5059 __ CmpObjectType(rax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, rdx);
5060 __ j(below, if_false);
5061 __ CmpInstanceType(rdx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5062 __ j(above, if_false);
5063 // Check for undetectable objects => false.
5064 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
5065 Immediate(1 << Map::kIsUndetectable));
5066 Split(zero, if_true, if_false, fall_through);
5068 if (if_false != fall_through) __ jmp(if_false);
5070 context()->Plug(if_true, if_false);
5074 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5075 Comment cmnt(masm_, "[ CompareOperation");
5076 SetExpressionPosition(expr);
5078 // First we try a fast inlined version of the compare when one of
5079 // the operands is a literal.
5080 if (TryLiteralCompare(expr)) return;
5082 // Always perform the comparison for its control flow. Pack the result
5083 // into the expression's context after the comparison is performed.
5084 Label materialize_true, materialize_false;
5085 Label* if_true = NULL;
5086 Label* if_false = NULL;
5087 Label* fall_through = NULL;
5088 context()->PrepareTest(&materialize_true, &materialize_false,
5089 &if_true, &if_false, &fall_through);
5091 Token::Value op = expr->op();
5092 VisitForStackValue(expr->left());
5095 VisitForStackValue(expr->right());
5096 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5097 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5098 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
5099 Split(equal, if_true, if_false, fall_through);
5102 case Token::INSTANCEOF: {
5103 VisitForStackValue(expr->right());
5104 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5106 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5108 // The stub returns 0 for true.
5109 Split(zero, if_true, if_false, fall_through);
5114 VisitForAccumulatorValue(expr->right());
5115 Condition cc = CompareIC::ComputeCondition(op);
5118 bool inline_smi_code = ShouldInlineSmiCase(op);
5119 JumpPatchSite patch_site(masm_);
5120 if (inline_smi_code) {
5124 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
5126 Split(cc, if_true, if_false, NULL);
5127 __ bind(&slow_case);
5130 Handle<Code> ic = CodeFactory::CompareIC(
5131 isolate(), op, strength(language_mode())).code();
5132 CallIC(ic, expr->CompareOperationFeedbackId());
5133 patch_site.EmitPatchInfo();
5135 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5137 Split(cc, if_true, if_false, fall_through);
5141 // Convert the result of the comparison into one expected for this
5142 // expression's context.
5143 context()->Plug(if_true, if_false);
5147 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5148 Expression* sub_expr,
5150 Label materialize_true, materialize_false;
5151 Label* if_true = NULL;
5152 Label* if_false = NULL;
5153 Label* fall_through = NULL;
5154 context()->PrepareTest(&materialize_true, &materialize_false,
5155 &if_true, &if_false, &fall_through);
5157 VisitForAccumulatorValue(sub_expr);
5158 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5159 if (expr->op() == Token::EQ_STRICT) {
5160 Heap::RootListIndex nil_value = nil == kNullValue ?
5161 Heap::kNullValueRootIndex :
5162 Heap::kUndefinedValueRootIndex;
5163 __ CompareRoot(rax, nil_value);
5164 Split(equal, if_true, if_false, fall_through);
5166 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5167 CallIC(ic, expr->CompareOperationFeedbackId());
5169 Split(not_zero, if_true, if_false, fall_through);
5171 context()->Plug(if_true, if_false);
5175 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5176 __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
5177 context()->Plug(rax);
5181 Register FullCodeGenerator::result_register() {
5186 Register FullCodeGenerator::context_register() {
5191 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5192 DCHECK(IsAligned(frame_offset, kPointerSize));
5193 __ movp(Operand(rbp, frame_offset), value);
5197 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5198 __ movp(dst, ContextOperand(rsi, context_index));
5202 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5203 Scope* closure_scope = scope()->ClosureScope();
5204 if (closure_scope->is_script_scope() ||
5205 closure_scope->is_module_scope()) {
5206 // Contexts nested in the native context have a canonical empty function
5207 // as their closure, not the anonymous closure containing the global
5208 // code. Pass a smi sentinel and let the runtime look up the empty
5210 __ Push(Smi::FromInt(0));
5211 } else if (closure_scope->is_eval_scope()) {
5212 // Contexts created by a call to eval have the same closure as the
5213 // context calling eval, not the anonymous closure containing the eval
5214 // code. Fetch it from the context.
5215 __ Push(ContextOperand(rsi, Context::CLOSURE_INDEX));
5217 DCHECK(closure_scope->is_function_scope());
5218 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
5223 // ----------------------------------------------------------------------------
5224 // Non-local control flow support.
5227 void FullCodeGenerator::EnterFinallyBlock() {
5228 DCHECK(!result_register().is(rdx));
5229 DCHECK(!result_register().is(rcx));
5230 // Cook return address on top of stack (smi encoded Code* delta)
5231 __ PopReturnAddressTo(rdx);
5232 __ Move(rcx, masm_->CodeObject());
5234 __ Integer32ToSmi(rdx, rdx);
5237 // Store result register while executing finally block.
5238 __ Push(result_register());
5240 // Store pending message while executing finally block.
5241 ExternalReference pending_message_obj =
5242 ExternalReference::address_of_pending_message_obj(isolate());
5243 __ Load(rdx, pending_message_obj);
5246 ClearPendingMessage();
5250 void FullCodeGenerator::ExitFinallyBlock() {
5251 DCHECK(!result_register().is(rdx));
5252 DCHECK(!result_register().is(rcx));
5253 // Restore pending message from stack.
5255 ExternalReference pending_message_obj =
5256 ExternalReference::address_of_pending_message_obj(isolate());
5257 __ Store(pending_message_obj, rdx);
5259 // Restore result register from stack.
5260 __ Pop(result_register());
5262 // Uncook return address.
5264 __ SmiToInteger32(rdx, rdx);
5265 __ Move(rcx, masm_->CodeObject());
5271 void FullCodeGenerator::ClearPendingMessage() {
5272 DCHECK(!result_register().is(rdx));
5273 ExternalReference pending_message_obj =
5274 ExternalReference::address_of_pending_message_obj(isolate());
5275 __ LoadRoot(rdx, Heap::kTheHoleValueRootIndex);
5276 __ Store(pending_message_obj, rdx);
5280 void FullCodeGenerator::EmitLoadStoreICSlot(FeedbackVectorICSlot slot) {
5281 DCHECK(FLAG_vector_stores && !slot.IsInvalid());
5282 __ Move(VectorStoreICTrampolineDescriptor::SlotRegister(), SmiFromSlot(slot));
5289 static const byte kJnsInstruction = 0x79;
5290 static const byte kNopByteOne = 0x66;
5291 static const byte kNopByteTwo = 0x90;
5293 static const byte kCallInstruction = 0xe8;
5297 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5299 BackEdgeState target_state,
5300 Code* replacement_code) {
5301 Address call_target_address = pc - kIntSize;
5302 Address jns_instr_address = call_target_address - 3;
5303 Address jns_offset_address = call_target_address - 2;
5305 switch (target_state) {
5307 // sub <profiling_counter>, <delta> ;; Not changed
5309 // call <interrupt stub>
5311 *jns_instr_address = kJnsInstruction;
5312 *jns_offset_address = kJnsOffset;
5314 case ON_STACK_REPLACEMENT:
5315 case OSR_AFTER_STACK_CHECK:
5316 // sub <profiling_counter>, <delta> ;; Not changed
5319 // call <on-stack replacment>
5321 *jns_instr_address = kNopByteOne;
5322 *jns_offset_address = kNopByteTwo;
5326 Assembler::set_target_address_at(call_target_address,
5328 replacement_code->entry());
5329 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5330 unoptimized_code, call_target_address, replacement_code);
5334 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5336 Code* unoptimized_code,
5338 Address call_target_address = pc - kIntSize;
5339 Address jns_instr_address = call_target_address - 3;
5340 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5342 if (*jns_instr_address == kJnsInstruction) {
5343 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5344 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5345 Assembler::target_address_at(call_target_address,
5350 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5351 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5353 if (Assembler::target_address_at(call_target_address,
5354 unoptimized_code) ==
5355 isolate->builtins()->OnStackReplacement()->entry()) {
5356 return ON_STACK_REPLACEMENT;
5359 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5360 Assembler::target_address_at(call_target_address,
5362 return OSR_AFTER_STACK_CHECK;
5366 } // namespace internal
5369 #endif // V8_TARGET_ARCH_X64