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.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 // For named function expressions, declare the function name as a
350 if (scope()->is_function_scope() && scope()->function() != NULL) {
351 VariableDeclaration* function = scope()->function();
352 DCHECK(function->proxy()->var()->mode() == CONST ||
353 function->proxy()->var()->mode() == CONST_LEGACY);
354 DCHECK(!function->proxy()->var()->IsUnallocatedOrGlobalSlot());
355 VisitVariableDeclaration(function);
357 VisitDeclarations(scope()->declarations());
360 { Comment cmnt(masm_, "[ Stack check");
361 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
363 __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
364 __ j(above_equal, &ok, Label::kNear);
365 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
369 { Comment cmnt(masm_, "[ Body");
370 DCHECK(loop_depth() == 0);
371 VisitStatements(function()->body());
372 DCHECK(loop_depth() == 0);
376 // Always emit a 'return undefined' in case control fell off the end of
378 { Comment cmnt(masm_, "[ return <undefined>;");
379 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
380 EmitReturnSequence();
385 void FullCodeGenerator::ClearAccumulator() {
390 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
391 __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
392 __ SmiAddConstant(FieldOperand(rbx, Cell::kValueOffset),
393 Smi::FromInt(-delta));
397 void FullCodeGenerator::EmitProfilingCounterReset() {
398 int reset_value = FLAG_interrupt_budget;
399 __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
400 __ Move(kScratchRegister, Smi::FromInt(reset_value));
401 __ movp(FieldOperand(rbx, Cell::kValueOffset), kScratchRegister);
405 static const byte kJnsOffset = kPointerSize == kInt64Size ? 0x1d : 0x14;
408 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
409 Label* back_edge_target) {
410 Comment cmnt(masm_, "[ Back edge bookkeeping");
413 DCHECK(back_edge_target->is_bound());
414 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
415 int weight = Min(kMaxBackEdgeWeight,
416 Max(1, distance / kCodeSizeMultiplier));
417 EmitProfilingCounterDecrement(weight);
419 __ j(positive, &ok, Label::kNear);
421 PredictableCodeSizeScope predictible_code_size_scope(masm_, kJnsOffset);
422 DontEmitDebugCodeScope dont_emit_debug_code_scope(masm_);
423 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
425 // Record a mapping of this PC offset to the OSR id. This is used to find
426 // the AST id from the unoptimized code in order to use it as a key into
427 // the deoptimization input data found in the optimized code.
428 RecordBackEdge(stmt->OsrEntryId());
430 EmitProfilingCounterReset();
434 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
435 // Record a mapping of the OSR id to this PC. This is used if the OSR
436 // entry becomes the target of a bailout. We don't expect it to be, but
437 // we want it to work if it is.
438 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
442 void FullCodeGenerator::EmitReturnSequence() {
443 Comment cmnt(masm_, "[ Return sequence");
444 if (return_label_.is_bound()) {
445 __ jmp(&return_label_);
447 __ bind(&return_label_);
450 __ CallRuntime(Runtime::kTraceExit, 1);
452 // Pretend that the exit is a backwards jump to the entry.
454 if (info_->ShouldSelfOptimize()) {
455 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
457 int distance = masm_->pc_offset();
458 weight = Min(kMaxBackEdgeWeight,
459 Max(1, distance / kCodeSizeMultiplier));
461 EmitProfilingCounterDecrement(weight);
463 __ j(positive, &ok, Label::kNear);
465 __ call(isolate()->builtins()->InterruptCheck(),
466 RelocInfo::CODE_TARGET);
468 EmitProfilingCounterReset();
471 SetReturnPosition(function());
472 int no_frame_start = masm_->pc_offset();
475 int arg_count = info_->scope()->num_parameters() + 1;
476 int arguments_bytes = arg_count * kPointerSize;
477 __ Ret(arguments_bytes, rcx);
479 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
484 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
485 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
489 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
490 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
491 codegen()->GetVar(result_register(), var);
495 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
496 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
497 MemOperand operand = codegen()->VarOperand(var, result_register());
502 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
503 codegen()->GetVar(result_register(), var);
504 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
505 codegen()->DoTest(this);
509 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
513 void FullCodeGenerator::AccumulatorValueContext::Plug(
514 Heap::RootListIndex index) const {
515 __ LoadRoot(result_register(), index);
519 void FullCodeGenerator::StackValueContext::Plug(
520 Heap::RootListIndex index) const {
525 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
526 codegen()->PrepareForBailoutBeforeSplit(condition(),
530 if (index == Heap::kUndefinedValueRootIndex ||
531 index == Heap::kNullValueRootIndex ||
532 index == Heap::kFalseValueRootIndex) {
533 if (false_label_ != fall_through_) __ jmp(false_label_);
534 } else if (index == Heap::kTrueValueRootIndex) {
535 if (true_label_ != fall_through_) __ jmp(true_label_);
537 __ LoadRoot(result_register(), index);
538 codegen()->DoTest(this);
543 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
547 void FullCodeGenerator::AccumulatorValueContext::Plug(
548 Handle<Object> lit) const {
550 __ SafeMove(result_register(), Smi::cast(*lit));
552 __ Move(result_register(), lit);
557 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
559 __ SafePush(Smi::cast(*lit));
566 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
567 codegen()->PrepareForBailoutBeforeSplit(condition(),
571 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
572 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
573 if (false_label_ != fall_through_) __ jmp(false_label_);
574 } else if (lit->IsTrue() || lit->IsJSObject()) {
575 if (true_label_ != fall_through_) __ jmp(true_label_);
576 } else if (lit->IsString()) {
577 if (String::cast(*lit)->length() == 0) {
578 if (false_label_ != fall_through_) __ jmp(false_label_);
580 if (true_label_ != fall_through_) __ jmp(true_label_);
582 } else if (lit->IsSmi()) {
583 if (Smi::cast(*lit)->value() == 0) {
584 if (false_label_ != fall_through_) __ jmp(false_label_);
586 if (true_label_ != fall_through_) __ jmp(true_label_);
589 // For simplicity we always test the accumulator register.
590 __ Move(result_register(), lit);
591 codegen()->DoTest(this);
596 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
597 Register reg) const {
603 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
605 Register reg) const {
608 __ Move(result_register(), reg);
612 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
613 Register reg) const {
615 if (count > 1) __ Drop(count - 1);
616 __ movp(Operand(rsp, 0), reg);
620 void FullCodeGenerator::TestContext::DropAndPlug(int count,
621 Register reg) const {
623 // For simplicity we always test the accumulator register.
625 __ Move(result_register(), reg);
626 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
627 codegen()->DoTest(this);
631 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
632 Label* materialize_false) const {
633 DCHECK(materialize_true == materialize_false);
634 __ bind(materialize_true);
638 void FullCodeGenerator::AccumulatorValueContext::Plug(
639 Label* materialize_true,
640 Label* materialize_false) const {
642 __ bind(materialize_true);
643 __ Move(result_register(), isolate()->factory()->true_value());
644 __ jmp(&done, Label::kNear);
645 __ bind(materialize_false);
646 __ Move(result_register(), isolate()->factory()->false_value());
651 void FullCodeGenerator::StackValueContext::Plug(
652 Label* materialize_true,
653 Label* materialize_false) const {
655 __ bind(materialize_true);
656 __ Push(isolate()->factory()->true_value());
657 __ jmp(&done, Label::kNear);
658 __ bind(materialize_false);
659 __ Push(isolate()->factory()->false_value());
664 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
665 Label* materialize_false) const {
666 DCHECK(materialize_true == true_label_);
667 DCHECK(materialize_false == false_label_);
671 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
675 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
676 Heap::RootListIndex value_root_index =
677 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
678 __ LoadRoot(result_register(), value_root_index);
682 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
683 Heap::RootListIndex value_root_index =
684 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
685 __ PushRoot(value_root_index);
689 void FullCodeGenerator::TestContext::Plug(bool flag) const {
690 codegen()->PrepareForBailoutBeforeSplit(condition(),
695 if (true_label_ != fall_through_) __ jmp(true_label_);
697 if (false_label_ != fall_through_) __ jmp(false_label_);
702 void FullCodeGenerator::DoTest(Expression* condition,
705 Label* fall_through) {
706 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
707 CallIC(ic, condition->test_id());
708 __ testp(result_register(), result_register());
709 // The stub returns nonzero for true.
710 Split(not_zero, if_true, if_false, fall_through);
714 void FullCodeGenerator::Split(Condition cc,
717 Label* fall_through) {
718 if (if_false == fall_through) {
720 } else if (if_true == fall_through) {
721 __ j(NegateCondition(cc), if_false);
729 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
730 DCHECK(var->IsStackAllocated());
731 // Offset is negative because higher indexes are at lower addresses.
732 int offset = -var->index() * kPointerSize;
733 // Adjust by a (parameter or local) base offset.
734 if (var->IsParameter()) {
735 offset += kFPOnStackSize + kPCOnStackSize +
736 (info_->scope()->num_parameters() - 1) * kPointerSize;
738 offset += JavaScriptFrameConstants::kLocal0Offset;
740 return Operand(rbp, offset);
744 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
745 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
746 if (var->IsContextSlot()) {
747 int context_chain_length = scope()->ContextChainLength(var->scope());
748 __ LoadContext(scratch, context_chain_length);
749 return ContextOperand(scratch, var->index());
751 return StackOperand(var);
756 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
757 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
758 MemOperand location = VarOperand(var, dest);
759 __ movp(dest, location);
763 void FullCodeGenerator::SetVar(Variable* var,
767 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
768 DCHECK(!scratch0.is(src));
769 DCHECK(!scratch0.is(scratch1));
770 DCHECK(!scratch1.is(src));
771 MemOperand location = VarOperand(var, scratch0);
772 __ movp(location, src);
774 // Emit the write barrier code if the location is in the heap.
775 if (var->IsContextSlot()) {
776 int offset = Context::SlotOffset(var->index());
777 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
782 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
783 bool should_normalize,
786 // Only prepare for bailouts before splits if we're in a test
787 // context. Otherwise, we let the Visit function deal with the
788 // preparation to avoid preparing with the same AST id twice.
789 if (!context()->IsTest() || !info_->IsOptimizable()) return;
792 if (should_normalize) __ jmp(&skip, Label::kNear);
793 PrepareForBailout(expr, TOS_REG);
794 if (should_normalize) {
795 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
796 Split(equal, if_true, if_false, NULL);
802 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
803 // The variable in the declaration always resides in the current context.
804 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
805 if (generate_debug_code_) {
806 // Check that we're not inside a with or catch context.
807 __ movp(rbx, FieldOperand(rsi, HeapObject::kMapOffset));
808 __ CompareRoot(rbx, Heap::kWithContextMapRootIndex);
809 __ Check(not_equal, kDeclarationInWithContext);
810 __ CompareRoot(rbx, Heap::kCatchContextMapRootIndex);
811 __ Check(not_equal, kDeclarationInCatchContext);
816 void FullCodeGenerator::VisitVariableDeclaration(
817 VariableDeclaration* declaration) {
818 // If it was not possible to allocate the variable at compile time, we
819 // need to "declare" it at runtime to make sure it actually exists in the
821 VariableProxy* proxy = declaration->proxy();
822 VariableMode mode = declaration->mode();
823 Variable* variable = proxy->var();
824 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
825 switch (variable->location()) {
826 case VariableLocation::GLOBAL:
827 case VariableLocation::UNALLOCATED:
828 globals_->Add(variable->name(), zone());
829 globals_->Add(variable->binding_needs_init()
830 ? isolate()->factory()->the_hole_value()
831 : isolate()->factory()->undefined_value(),
835 case VariableLocation::PARAMETER:
836 case VariableLocation::LOCAL:
838 Comment cmnt(masm_, "[ VariableDeclaration");
839 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
840 __ movp(StackOperand(variable), kScratchRegister);
844 case VariableLocation::CONTEXT:
846 Comment cmnt(masm_, "[ VariableDeclaration");
847 EmitDebugCheckDeclarationContext(variable);
848 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
849 __ movp(ContextOperand(rsi, variable->index()), kScratchRegister);
850 // No write barrier since the hole value is in old space.
851 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
855 case VariableLocation::LOOKUP: {
856 Comment cmnt(masm_, "[ VariableDeclaration");
858 __ Push(variable->name());
859 // Declaration nodes are always introduced in one of four modes.
860 DCHECK(IsDeclaredVariableMode(mode));
861 PropertyAttributes attr =
862 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
863 __ Push(Smi::FromInt(attr));
864 // Push initial value, if any.
865 // Note: For variables we must not push an initial value (such as
866 // 'undefined') because we may have a (legal) redeclaration and we
867 // must not destroy the current value.
869 __ PushRoot(Heap::kTheHoleValueRootIndex);
871 __ Push(Smi::FromInt(0)); // Indicates no initial value.
873 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
880 void FullCodeGenerator::VisitFunctionDeclaration(
881 FunctionDeclaration* declaration) {
882 VariableProxy* proxy = declaration->proxy();
883 Variable* variable = proxy->var();
884 switch (variable->location()) {
885 case VariableLocation::GLOBAL:
886 case VariableLocation::UNALLOCATED: {
887 globals_->Add(variable->name(), zone());
888 Handle<SharedFunctionInfo> function =
889 Compiler::GetSharedFunctionInfo(declaration->fun(), script(), info_);
890 // Check for stack-overflow exception.
891 if (function.is_null()) return SetStackOverflow();
892 globals_->Add(function, zone());
896 case VariableLocation::PARAMETER:
897 case VariableLocation::LOCAL: {
898 Comment cmnt(masm_, "[ FunctionDeclaration");
899 VisitForAccumulatorValue(declaration->fun());
900 __ movp(StackOperand(variable), result_register());
904 case VariableLocation::CONTEXT: {
905 Comment cmnt(masm_, "[ FunctionDeclaration");
906 EmitDebugCheckDeclarationContext(variable);
907 VisitForAccumulatorValue(declaration->fun());
908 __ movp(ContextOperand(rsi, variable->index()), result_register());
909 int offset = Context::SlotOffset(variable->index());
910 // We know that we have written a function, which is not a smi.
911 __ RecordWriteContextSlot(rsi,
918 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
922 case VariableLocation::LOOKUP: {
923 Comment cmnt(masm_, "[ FunctionDeclaration");
925 __ Push(variable->name());
926 __ Push(Smi::FromInt(NONE));
927 VisitForStackValue(declaration->fun());
928 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
935 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
936 VariableProxy* proxy = declaration->proxy();
937 Variable* variable = proxy->var();
938 switch (variable->location()) {
939 case VariableLocation::UNALLOCATED:
940 case VariableLocation::GLOBAL:
944 case VariableLocation::CONTEXT: {
945 Comment cmnt(masm_, "[ ImportDeclaration");
946 EmitDebugCheckDeclarationContext(variable);
951 case VariableLocation::PARAMETER:
952 case VariableLocation::LOCAL:
953 case VariableLocation::LOOKUP:
959 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
964 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
965 // Call the runtime to declare the globals.
966 __ Push(rsi); // The context is the first argument.
968 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
969 __ CallRuntime(Runtime::kDeclareGlobals, 3);
970 // Return value is ignored.
974 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
975 // Call the runtime to declare the modules.
976 __ Push(descriptions);
977 __ CallRuntime(Runtime::kDeclareModules, 1);
978 // Return value is ignored.
982 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
983 Comment cmnt(masm_, "[ SwitchStatement");
984 Breakable nested_statement(this, stmt);
985 SetStatementPosition(stmt);
987 // Keep the switch value on the stack until a case matches.
988 VisitForStackValue(stmt->tag());
989 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
991 ZoneList<CaseClause*>* clauses = stmt->cases();
992 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
994 Label next_test; // Recycled for each test.
995 // Compile all the tests with branches to their bodies.
996 for (int i = 0; i < clauses->length(); i++) {
997 CaseClause* clause = clauses->at(i);
998 clause->body_target()->Unuse();
1000 // The default is not a test, but remember it as final fall through.
1001 if (clause->is_default()) {
1002 default_clause = clause;
1006 Comment cmnt(masm_, "[ Case comparison");
1007 __ bind(&next_test);
1010 // Compile the label expression.
1011 VisitForAccumulatorValue(clause->label());
1013 // Perform the comparison as if via '==='.
1014 __ movp(rdx, Operand(rsp, 0)); // Switch value.
1015 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
1016 JumpPatchSite patch_site(masm_);
1017 if (inline_smi_code) {
1021 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
1024 __ j(not_equal, &next_test);
1025 __ Drop(1); // Switch value is no longer needed.
1026 __ jmp(clause->body_target());
1027 __ bind(&slow_case);
1030 // Record position before stub call for type feedback.
1031 SetExpressionPosition(clause);
1032 Handle<Code> ic = CodeFactory::CompareIC(isolate(), Token::EQ_STRICT,
1033 strength(language_mode())).code();
1034 CallIC(ic, clause->CompareId());
1035 patch_site.EmitPatchInfo();
1038 __ jmp(&skip, Label::kNear);
1039 PrepareForBailout(clause, TOS_REG);
1040 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
1041 __ j(not_equal, &next_test);
1043 __ jmp(clause->body_target());
1047 __ j(not_equal, &next_test);
1048 __ Drop(1); // Switch value is no longer needed.
1049 __ jmp(clause->body_target());
1052 // Discard the test value and jump to the default if present, otherwise to
1053 // the end of the statement.
1054 __ bind(&next_test);
1055 __ Drop(1); // Switch value is no longer needed.
1056 if (default_clause == NULL) {
1057 __ jmp(nested_statement.break_label());
1059 __ jmp(default_clause->body_target());
1062 // Compile all the case bodies.
1063 for (int i = 0; i < clauses->length(); i++) {
1064 Comment cmnt(masm_, "[ Case body");
1065 CaseClause* clause = clauses->at(i);
1066 __ bind(clause->body_target());
1067 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1068 VisitStatements(clause->statements());
1071 __ bind(nested_statement.break_label());
1072 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1076 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1077 Comment cmnt(masm_, "[ ForInStatement");
1078 SetStatementPosition(stmt, SKIP_BREAK);
1080 FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1083 ForIn loop_statement(this, stmt);
1084 increment_loop_depth();
1086 // Get the object to enumerate over. If the object is null or undefined, skip
1087 // over the loop. See ECMA-262 version 5, section 12.6.4.
1088 SetExpressionAsStatementPosition(stmt->enumerable());
1089 VisitForAccumulatorValue(stmt->enumerable());
1090 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1092 Register null_value = rdi;
1093 __ LoadRoot(null_value, Heap::kNullValueRootIndex);
1094 __ cmpp(rax, null_value);
1097 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1099 // Convert the object to a JS object.
1100 Label convert, done_convert;
1101 __ JumpIfSmi(rax, &convert);
1102 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rcx);
1103 __ j(above_equal, &done_convert);
1106 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1107 __ bind(&done_convert);
1108 PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1111 // Check for proxies.
1113 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1114 __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx);
1115 __ j(below_equal, &call_runtime);
1117 // Check cache validity in generated code. This is a fast case for
1118 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1119 // guarantee cache validity, call the runtime system to check cache
1120 // validity or get the property names in a fixed array.
1121 __ CheckEnumCache(null_value, &call_runtime);
1123 // The enum cache is valid. Load the map of the object being
1124 // iterated over and use the cache for the iteration.
1126 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
1127 __ jmp(&use_cache, Label::kNear);
1129 // Get the set of properties to enumerate.
1130 __ bind(&call_runtime);
1131 __ Push(rax); // Duplicate the enumerable object on the stack.
1132 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1133 PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1135 // If we got a map from the runtime call, we can do a fast
1136 // modification check. Otherwise, we got a fixed array, and we have
1137 // to do a slow check.
1139 __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
1140 Heap::kMetaMapRootIndex);
1141 __ j(not_equal, &fixed_array);
1143 // We got a map in register rax. Get the enumeration cache from it.
1144 __ bind(&use_cache);
1146 Label no_descriptors;
1148 __ EnumLength(rdx, rax);
1149 __ Cmp(rdx, Smi::FromInt(0));
1150 __ j(equal, &no_descriptors);
1152 __ LoadInstanceDescriptors(rax, rcx);
1153 __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheOffset));
1154 __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1156 // Set up the four remaining stack slots.
1157 __ Push(rax); // Map.
1158 __ Push(rcx); // Enumeration cache.
1159 __ Push(rdx); // Number of valid entries for the map in the enum cache.
1160 __ Push(Smi::FromInt(0)); // Initial index.
1163 __ bind(&no_descriptors);
1164 __ addp(rsp, Immediate(kPointerSize));
1167 // We got a fixed array in register rax. Iterate through that.
1169 __ bind(&fixed_array);
1171 // No need for a write barrier, we are storing a Smi in the feedback vector.
1172 __ Move(rbx, FeedbackVector());
1173 int vector_index = FeedbackVector()->GetIndex(slot);
1174 __ Move(FieldOperand(rbx, FixedArray::OffsetOfElementAt(vector_index)),
1175 TypeFeedbackVector::MegamorphicSentinel(isolate()));
1176 __ Move(rbx, Smi::FromInt(1)); // Smi indicates slow check
1177 __ movp(rcx, Operand(rsp, 0 * kPointerSize)); // Get enumerated object
1178 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1179 __ CmpObjectType(rcx, LAST_JS_PROXY_TYPE, rcx);
1180 __ j(above, &non_proxy);
1181 __ Move(rbx, Smi::FromInt(0)); // Zero indicates proxy
1182 __ bind(&non_proxy);
1183 __ Push(rbx); // Smi
1184 __ Push(rax); // Array
1185 __ movp(rax, FieldOperand(rax, FixedArray::kLengthOffset));
1186 __ Push(rax); // Fixed array length (as smi).
1187 __ Push(Smi::FromInt(0)); // Initial index.
1189 // Generate code for doing the condition check.
1190 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1192 SetExpressionAsStatementPosition(stmt->each());
1194 __ movp(rax, Operand(rsp, 0 * kPointerSize)); // Get the current index.
1195 __ cmpp(rax, Operand(rsp, 1 * kPointerSize)); // Compare to the array length.
1196 __ j(above_equal, loop_statement.break_label());
1198 // Get the current entry of the array into register rbx.
1199 __ movp(rbx, Operand(rsp, 2 * kPointerSize));
1200 SmiIndex index = masm()->SmiToIndex(rax, rax, kPointerSizeLog2);
1201 __ movp(rbx, FieldOperand(rbx,
1204 FixedArray::kHeaderSize));
1206 // Get the expected map from the stack or a smi in the
1207 // permanent slow case into register rdx.
1208 __ movp(rdx, Operand(rsp, 3 * kPointerSize));
1210 // Check if the expected map still matches that of the enumerable.
1211 // If not, we may have to filter the key.
1213 __ movp(rcx, Operand(rsp, 4 * kPointerSize));
1214 __ cmpp(rdx, FieldOperand(rcx, HeapObject::kMapOffset));
1215 __ j(equal, &update_each, Label::kNear);
1217 // For proxies, no filtering is done.
1218 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1219 __ Cmp(rdx, Smi::FromInt(0));
1220 __ j(equal, &update_each, Label::kNear);
1222 // Convert the entry to a string or null if it isn't a property
1223 // anymore. If the property has been removed while iterating, we
1225 __ Push(rcx); // Enumerable.
1226 __ Push(rbx); // Current entry.
1227 __ CallRuntime(Runtime::kForInFilter, 2);
1228 PrepareForBailoutForId(stmt->FilterId(), TOS_REG);
1229 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1230 __ j(equal, loop_statement.continue_label());
1233 // Update the 'each' property or variable from the possibly filtered
1234 // entry in register rbx.
1235 __ bind(&update_each);
1236 __ movp(result_register(), rbx);
1237 // Perform the assignment as if via '='.
1238 { EffectContext context(this);
1239 EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1240 PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1243 // Generate code for the body of the loop.
1244 Visit(stmt->body());
1246 // Generate code for going to the next element by incrementing the
1247 // index (smi) stored on top of the stack.
1248 __ bind(loop_statement.continue_label());
1249 __ SmiAddConstant(Operand(rsp, 0 * kPointerSize), Smi::FromInt(1));
1251 EmitBackEdgeBookkeeping(stmt, &loop);
1254 // Remove the pointers stored on the stack.
1255 __ bind(loop_statement.break_label());
1256 __ addp(rsp, Immediate(5 * kPointerSize));
1258 // Exit and decrement the loop depth.
1259 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1261 decrement_loop_depth();
1265 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1267 // Use the fast case closure allocation code that allocates in new
1268 // space for nested functions that don't need literals cloning. If
1269 // we're running with the --always-opt or the --prepare-always-opt
1270 // flag, we need to use the runtime function so that the new function
1271 // we are creating here gets a chance to have its code optimized and
1272 // doesn't just get a copy of the existing unoptimized code.
1273 if (!FLAG_always_opt &&
1274 !FLAG_prepare_always_opt &&
1276 scope()->is_function_scope() &&
1277 info->num_literals() == 0) {
1278 FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1285 ? isolate()->factory()->true_value()
1286 : isolate()->factory()->false_value());
1287 __ CallRuntime(Runtime::kNewClosure, 3);
1289 context()->Plug(rax);
1293 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1294 Comment cmnt(masm_, "[ VariableProxy");
1295 EmitVariableLoad(expr);
1299 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1301 FeedbackVectorICSlot slot) {
1302 if (NeedsHomeObject(initializer)) {
1303 __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1304 __ Move(StoreDescriptor::NameRegister(),
1305 isolate()->factory()->home_object_symbol());
1306 __ movp(StoreDescriptor::ValueRegister(),
1307 Operand(rsp, offset * kPointerSize));
1308 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
1314 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1315 TypeofMode typeof_mode,
1317 Register context = rsi;
1318 Register temp = rdx;
1322 if (s->num_heap_slots() > 0) {
1323 if (s->calls_sloppy_eval()) {
1324 // Check that extension is NULL.
1325 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX),
1327 __ j(not_equal, slow);
1329 // Load next context in chain.
1330 __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1331 // Walk the rest of the chain without clobbering rsi.
1334 // If no outer scope calls eval, we do not need to check more
1335 // context extensions. If we have reached an eval scope, we check
1336 // all extensions from this point.
1337 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1338 s = s->outer_scope();
1341 if (s != NULL && s->is_eval_scope()) {
1342 // Loop up the context chain. There is no frame effect so it is
1343 // safe to use raw labels here.
1345 if (!context.is(temp)) {
1346 __ movp(temp, context);
1348 // Load map for comparison into register, outside loop.
1349 __ LoadRoot(kScratchRegister, Heap::kNativeContextMapRootIndex);
1351 // Terminate at native context.
1352 __ cmpp(kScratchRegister, FieldOperand(temp, HeapObject::kMapOffset));
1353 __ j(equal, &fast, Label::kNear);
1354 // Check that extension is NULL.
1355 __ cmpp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1356 __ j(not_equal, slow);
1357 // Load next context in chain.
1358 __ movp(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1363 // All extension objects were empty and it is safe to use a normal global
1365 EmitGlobalVariableLoad(proxy, typeof_mode);
1369 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1371 DCHECK(var->IsContextSlot());
1372 Register context = rsi;
1373 Register temp = rbx;
1375 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1376 if (s->num_heap_slots() > 0) {
1377 if (s->calls_sloppy_eval()) {
1378 // Check that extension is NULL.
1379 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX),
1381 __ j(not_equal, slow);
1383 __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1384 // Walk the rest of the chain without clobbering rsi.
1388 // Check that last extension is NULL.
1389 __ cmpp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1390 __ j(not_equal, slow);
1392 // This function is used only for loads, not stores, so it's safe to
1393 // return an rsi-based operand (the write barrier cannot be allowed to
1394 // destroy the rsi register).
1395 return ContextOperand(context, var->index());
1399 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1400 TypeofMode typeof_mode,
1401 Label* slow, Label* done) {
1402 // Generate fast-case code for variables that might be shadowed by
1403 // eval-introduced variables. Eval is used a lot without
1404 // introducing variables. In those cases, we do not want to
1405 // perform a runtime call for all variables in the scope
1406 // containing the eval.
1407 Variable* var = proxy->var();
1408 if (var->mode() == DYNAMIC_GLOBAL) {
1409 EmitLoadGlobalCheckExtensions(proxy, typeof_mode, slow);
1411 } else if (var->mode() == DYNAMIC_LOCAL) {
1412 Variable* local = var->local_if_not_shadowed();
1413 __ movp(rax, ContextSlotOperandCheckExtensions(local, slow));
1414 if (local->mode() == LET || local->mode() == CONST ||
1415 local->mode() == CONST_LEGACY) {
1416 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
1417 __ j(not_equal, done);
1418 if (local->mode() == CONST_LEGACY) {
1419 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
1420 } else { // LET || CONST
1421 __ Push(var->name());
1422 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1430 void FullCodeGenerator::EmitGlobalVariableLoad(VariableProxy* proxy,
1431 TypeofMode typeof_mode) {
1432 Variable* var = proxy->var();
1433 DCHECK(var->IsUnallocatedOrGlobalSlot() ||
1434 (var->IsLookupSlot() && var->mode() == DYNAMIC_GLOBAL));
1435 if (var->IsGlobalSlot()) {
1436 DCHECK(var->index() > 0);
1437 DCHECK(var->IsStaticGlobalObjectProperty());
1438 // Each var occupies two slots in the context: for reads and writes.
1439 int slot_index = var->index();
1440 int depth = scope()->ContextChainLength(var->scope());
1441 __ Move(LoadGlobalViaContextDescriptor::DepthRegister(),
1442 Smi::FromInt(depth));
1443 __ Move(LoadGlobalViaContextDescriptor::SlotRegister(),
1444 Smi::FromInt(slot_index));
1445 __ Move(LoadGlobalViaContextDescriptor::NameRegister(), var->name());
1446 LoadGlobalViaContextStub stub(isolate(), depth);
1450 __ Move(LoadDescriptor::NameRegister(), var->name());
1451 __ movp(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1452 __ Move(LoadDescriptor::SlotRegister(),
1453 SmiFromSlot(proxy->VariableFeedbackSlot()));
1454 CallLoadIC(typeof_mode);
1459 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy,
1460 TypeofMode typeof_mode) {
1461 // Record position before possible IC call.
1462 SetExpressionPosition(proxy);
1463 PrepareForBailoutForId(proxy->BeforeId(), NO_REGISTERS);
1464 Variable* var = proxy->var();
1466 // Three cases: global variables, lookup variables, and all other types of
1468 switch (var->location()) {
1469 case VariableLocation::GLOBAL:
1470 case VariableLocation::UNALLOCATED: {
1471 Comment cmnt(masm_, "[ Global variable");
1472 EmitGlobalVariableLoad(proxy, typeof_mode);
1473 context()->Plug(rax);
1477 case VariableLocation::PARAMETER:
1478 case VariableLocation::LOCAL:
1479 case VariableLocation::CONTEXT: {
1480 DCHECK_EQ(NOT_INSIDE_TYPEOF, typeof_mode);
1481 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context slot"
1483 if (var->binding_needs_init()) {
1484 // var->scope() may be NULL when the proxy is located in eval code and
1485 // refers to a potential outside binding. Currently those bindings are
1486 // always looked up dynamically, i.e. in that case
1487 // var->location() == LOOKUP.
1489 DCHECK(var->scope() != NULL);
1491 // Check if the binding really needs an initialization check. The check
1492 // can be skipped in the following situation: we have a LET or CONST
1493 // binding in harmony mode, both the Variable and the VariableProxy have
1494 // the same declaration scope (i.e. they are both in global code, in the
1495 // same function or in the same eval code) and the VariableProxy is in
1496 // the source physically located after the initializer of the variable.
1498 // We cannot skip any initialization checks for CONST in non-harmony
1499 // mode because const variables may be declared but never initialized:
1500 // if (false) { const x; }; var y = x;
1502 // The condition on the declaration scopes is a conservative check for
1503 // nested functions that access a binding and are called before the
1504 // binding is initialized:
1505 // function() { f(); let x = 1; function f() { x = 2; } }
1507 bool skip_init_check;
1508 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1509 skip_init_check = false;
1510 } else if (var->is_this()) {
1511 CHECK(info_->function() != nullptr &&
1512 (info_->function()->kind() & kSubclassConstructor) != 0);
1513 // TODO(dslomov): implement 'this' hole check elimination.
1514 skip_init_check = false;
1516 // Check that we always have valid source position.
1517 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1518 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1519 skip_init_check = var->mode() != CONST_LEGACY &&
1520 var->initializer_position() < proxy->position();
1523 if (!skip_init_check) {
1524 // Let and const need a read barrier.
1527 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
1528 __ j(not_equal, &done, Label::kNear);
1529 if (var->mode() == LET || var->mode() == CONST) {
1530 // Throw a reference error when using an uninitialized let/const
1531 // binding in harmony mode.
1532 __ Push(var->name());
1533 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1535 // Uninitalized const bindings outside of harmony mode are unholed.
1536 DCHECK(var->mode() == CONST_LEGACY);
1537 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
1540 context()->Plug(rax);
1544 context()->Plug(var);
1548 case VariableLocation::LOOKUP: {
1549 Comment cmnt(masm_, "[ Lookup slot");
1551 // Generate code for loading from variables potentially shadowed
1552 // by eval-introduced variables.
1553 EmitDynamicLookupFastCase(proxy, typeof_mode, &slow, &done);
1555 __ Push(rsi); // Context.
1556 __ Push(var->name());
1557 Runtime::FunctionId function_id =
1558 typeof_mode == NOT_INSIDE_TYPEOF
1559 ? Runtime::kLoadLookupSlot
1560 : Runtime::kLoadLookupSlotNoReferenceError;
1561 __ CallRuntime(function_id, 2);
1563 context()->Plug(rax);
1570 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1571 Comment cmnt(masm_, "[ RegExpLiteral");
1573 // Registers will be used as follows:
1574 // rdi = JS function.
1575 // rcx = literals array.
1576 // rbx = regexp literal.
1577 // rax = regexp literal clone.
1578 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1579 __ movp(rcx, FieldOperand(rdi, JSFunction::kLiteralsOffset));
1580 int literal_offset =
1581 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1582 __ movp(rbx, FieldOperand(rcx, literal_offset));
1583 __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex);
1584 __ j(not_equal, &materialized, Label::kNear);
1586 // Create regexp literal using runtime function
1587 // Result will be in rax.
1589 __ Push(Smi::FromInt(expr->literal_index()));
1590 __ Push(expr->pattern());
1591 __ Push(expr->flags());
1592 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1595 __ bind(&materialized);
1596 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1597 Label allocated, runtime_allocate;
1598 __ Allocate(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
1601 __ bind(&runtime_allocate);
1603 __ Push(Smi::FromInt(size));
1604 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1607 __ bind(&allocated);
1608 // Copy the content into the newly allocated memory.
1609 // (Unroll copy loop once for better throughput).
1610 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1611 __ movp(rdx, FieldOperand(rbx, i));
1612 __ movp(rcx, FieldOperand(rbx, i + kPointerSize));
1613 __ movp(FieldOperand(rax, i), rdx);
1614 __ movp(FieldOperand(rax, i + kPointerSize), rcx);
1616 if ((size % (2 * kPointerSize)) != 0) {
1617 __ movp(rdx, FieldOperand(rbx, size - kPointerSize));
1618 __ movp(FieldOperand(rax, size - kPointerSize), rdx);
1620 context()->Plug(rax);
1624 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1625 if (expression == NULL) {
1626 __ PushRoot(Heap::kNullValueRootIndex);
1628 VisitForStackValue(expression);
1633 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1634 Comment cmnt(masm_, "[ ObjectLiteral");
1636 Handle<FixedArray> constant_properties = expr->constant_properties();
1637 int flags = expr->ComputeFlags();
1638 if (MustCreateObjectLiteralWithRuntime(expr)) {
1639 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1640 __ Push(FieldOperand(rdi, JSFunction::kLiteralsOffset));
1641 __ Push(Smi::FromInt(expr->literal_index()));
1642 __ Push(constant_properties);
1643 __ Push(Smi::FromInt(flags));
1644 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1646 __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1647 __ movp(rax, FieldOperand(rdi, JSFunction::kLiteralsOffset));
1648 __ Move(rbx, Smi::FromInt(expr->literal_index()));
1649 __ Move(rcx, constant_properties);
1650 __ Move(rdx, Smi::FromInt(flags));
1651 FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
1654 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1656 // If result_saved is true the result is on top of the stack. If
1657 // result_saved is false the result is in rax.
1658 bool result_saved = false;
1660 AccessorTable accessor_table(zone());
1661 int property_index = 0;
1662 // store_slot_index points to the vector IC slot for the next store IC used.
1663 // ObjectLiteral::ComputeFeedbackRequirements controls the allocation of slots
1664 // and must be updated if the number of store ICs emitted here changes.
1665 int store_slot_index = 0;
1666 for (; property_index < expr->properties()->length(); property_index++) {
1667 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1668 if (property->is_computed_name()) break;
1669 if (property->IsCompileTimeValue()) continue;
1671 Literal* key = property->key()->AsLiteral();
1672 Expression* value = property->value();
1673 if (!result_saved) {
1674 __ Push(rax); // Save result on the stack
1675 result_saved = true;
1677 switch (property->kind()) {
1678 case ObjectLiteral::Property::CONSTANT:
1680 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1681 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1683 case ObjectLiteral::Property::COMPUTED:
1684 // It is safe to use [[Put]] here because the boilerplate already
1685 // contains computed properties with an uninitialized value.
1686 if (key->value()->IsInternalizedString()) {
1687 if (property->emit_store()) {
1688 VisitForAccumulatorValue(value);
1689 DCHECK(StoreDescriptor::ValueRegister().is(rax));
1690 __ Move(StoreDescriptor::NameRegister(), key->value());
1691 __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1692 if (FLAG_vector_stores) {
1693 EmitLoadStoreICSlot(expr->GetNthSlot(store_slot_index++));
1696 CallStoreIC(key->LiteralFeedbackId());
1698 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1700 if (NeedsHomeObject(value)) {
1701 __ movp(StoreDescriptor::ReceiverRegister(), rax);
1702 __ Move(StoreDescriptor::NameRegister(),
1703 isolate()->factory()->home_object_symbol());
1704 __ movp(StoreDescriptor::ValueRegister(), Operand(rsp, 0));
1705 if (FLAG_vector_stores) {
1706 EmitLoadStoreICSlot(expr->GetNthSlot(store_slot_index++));
1711 VisitForEffect(value);
1715 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1716 VisitForStackValue(key);
1717 VisitForStackValue(value);
1718 if (property->emit_store()) {
1719 EmitSetHomeObjectIfNeeded(
1720 value, 2, expr->SlotForHomeObject(value, &store_slot_index));
1721 __ Push(Smi::FromInt(SLOPPY)); // Language mode
1722 __ CallRuntime(Runtime::kSetProperty, 4);
1727 case ObjectLiteral::Property::PROTOTYPE:
1728 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1729 VisitForStackValue(value);
1730 DCHECK(property->emit_store());
1731 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1733 case ObjectLiteral::Property::GETTER:
1734 if (property->emit_store()) {
1735 accessor_table.lookup(key)->second->getter = value;
1738 case ObjectLiteral::Property::SETTER:
1739 if (property->emit_store()) {
1740 accessor_table.lookup(key)->second->setter = value;
1746 // Emit code to define accessors, using only a single call to the runtime for
1747 // each pair of corresponding getters and setters.
1748 for (AccessorTable::Iterator it = accessor_table.begin();
1749 it != accessor_table.end();
1751 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1752 VisitForStackValue(it->first);
1753 EmitAccessor(it->second->getter);
1754 EmitSetHomeObjectIfNeeded(
1755 it->second->getter, 2,
1756 expr->SlotForHomeObject(it->second->getter, &store_slot_index));
1757 EmitAccessor(it->second->setter);
1758 EmitSetHomeObjectIfNeeded(
1759 it->second->setter, 3,
1760 expr->SlotForHomeObject(it->second->setter, &store_slot_index));
1761 __ Push(Smi::FromInt(NONE));
1762 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1765 // Object literals have two parts. The "static" part on the left contains no
1766 // computed property names, and so we can compute its map ahead of time; see
1767 // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1768 // starts with the first computed property name, and continues with all
1769 // properties to its right. All the code from above initializes the static
1770 // component of the object literal, and arranges for the map of the result to
1771 // reflect the static order in which the keys appear. For the dynamic
1772 // properties, we compile them into a series of "SetOwnProperty" runtime
1773 // calls. This will preserve insertion order.
1774 for (; property_index < expr->properties()->length(); property_index++) {
1775 ObjectLiteral::Property* property = expr->properties()->at(property_index);
1777 Expression* value = property->value();
1778 if (!result_saved) {
1779 __ Push(rax); // Save result on the stack
1780 result_saved = true;
1783 __ Push(Operand(rsp, 0)); // Duplicate receiver.
1785 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1786 DCHECK(!property->is_computed_name());
1787 VisitForStackValue(value);
1788 DCHECK(property->emit_store());
1789 __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1791 EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1792 VisitForStackValue(value);
1793 EmitSetHomeObjectIfNeeded(
1794 value, 2, expr->SlotForHomeObject(value, &store_slot_index));
1796 switch (property->kind()) {
1797 case ObjectLiteral::Property::CONSTANT:
1798 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1799 case ObjectLiteral::Property::COMPUTED:
1800 if (property->emit_store()) {
1801 __ Push(Smi::FromInt(NONE));
1802 __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1808 case ObjectLiteral::Property::PROTOTYPE:
1812 case ObjectLiteral::Property::GETTER:
1813 __ Push(Smi::FromInt(NONE));
1814 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1817 case ObjectLiteral::Property::SETTER:
1818 __ Push(Smi::FromInt(NONE));
1819 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1825 if (expr->has_function()) {
1826 DCHECK(result_saved);
1827 __ Push(Operand(rsp, 0));
1828 __ CallRuntime(Runtime::kToFastProperties, 1);
1832 context()->PlugTOS();
1834 context()->Plug(rax);
1837 // Verify that compilation exactly consumed the number of store ic slots that
1838 // the ObjectLiteral node had to offer.
1839 DCHECK(!FLAG_vector_stores || store_slot_index == expr->slot_count());
1843 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1844 Comment cmnt(masm_, "[ ArrayLiteral");
1846 expr->BuildConstantElements(isolate());
1847 Handle<FixedArray> constant_elements = expr->constant_elements();
1848 bool has_constant_fast_elements =
1849 IsFastObjectElementsKind(expr->constant_elements_kind());
1851 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1852 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1853 // If the only customer of allocation sites is transitioning, then
1854 // we can turn it off if we don't have anywhere else to transition to.
1855 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1858 if (MustCreateArrayLiteralWithRuntime(expr)) {
1859 __ movp(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1860 __ Push(FieldOperand(rbx, JSFunction::kLiteralsOffset));
1861 __ Push(Smi::FromInt(expr->literal_index()));
1862 __ Push(constant_elements);
1863 __ Push(Smi::FromInt(expr->ComputeFlags()));
1864 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1866 __ movp(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1867 __ movp(rax, FieldOperand(rbx, JSFunction::kLiteralsOffset));
1868 __ Move(rbx, Smi::FromInt(expr->literal_index()));
1869 __ Move(rcx, constant_elements);
1870 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1873 PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1875 bool result_saved = false; // Is the result saved to the stack?
1876 ZoneList<Expression*>* subexprs = expr->values();
1877 int length = subexprs->length();
1879 // Emit code to evaluate all the non-constant subexpressions and to store
1880 // them into the newly cloned array.
1881 int array_index = 0;
1882 for (; array_index < length; array_index++) {
1883 Expression* subexpr = subexprs->at(array_index);
1884 if (subexpr->IsSpread()) break;
1886 // If the subexpression is a literal or a simple materialized literal it
1887 // is already set in the cloned array.
1888 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1890 if (!result_saved) {
1891 __ Push(rax); // array literal
1892 __ Push(Smi::FromInt(expr->literal_index()));
1893 result_saved = true;
1895 VisitForAccumulatorValue(subexpr);
1897 if (has_constant_fast_elements) {
1898 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1899 // cannot transition and don't need to call the runtime stub.
1900 int offset = FixedArray::kHeaderSize + (array_index * kPointerSize);
1901 __ movp(rbx, Operand(rsp, kPointerSize)); // Copy of array literal.
1902 __ movp(rbx, FieldOperand(rbx, JSObject::kElementsOffset));
1903 // Store the subexpression value in the array's elements.
1904 __ movp(FieldOperand(rbx, offset), result_register());
1905 // Update the write barrier for the array store.
1906 __ RecordWriteField(rbx, offset, result_register(), rcx,
1908 EMIT_REMEMBERED_SET,
1911 // Store the subexpression value in the array's elements.
1912 __ Move(rcx, Smi::FromInt(array_index));
1913 StoreArrayLiteralElementStub stub(isolate());
1917 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1920 // In case the array literal contains spread expressions it has two parts. The
1921 // first part is the "static" array which has a literal index is handled
1922 // above. The second part is the part after the first spread expression
1923 // (inclusive) and these elements gets appended to the array. Note that the
1924 // number elements an iterable produces is unknown ahead of time.
1925 if (array_index < length && result_saved) {
1926 __ Drop(1); // literal index
1928 result_saved = false;
1930 for (; array_index < length; array_index++) {
1931 Expression* subexpr = subexprs->at(array_index);
1934 if (subexpr->IsSpread()) {
1935 VisitForStackValue(subexpr->AsSpread()->expression());
1936 __ InvokeBuiltin(Builtins::CONCAT_ITERABLE_TO_ARRAY, CALL_FUNCTION);
1938 VisitForStackValue(subexpr);
1939 __ CallRuntime(Runtime::kAppendElement, 2);
1942 PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
1946 __ Drop(1); // literal index
1947 context()->PlugTOS();
1949 context()->Plug(rax);
1954 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1955 DCHECK(expr->target()->IsValidReferenceExpression());
1957 Comment cmnt(masm_, "[ Assignment");
1958 SetExpressionPosition(expr, INSERT_BREAK);
1960 Property* property = expr->target()->AsProperty();
1961 LhsKind assign_type = Property::GetAssignType(property);
1963 // Evaluate LHS expression.
1964 switch (assign_type) {
1966 // Nothing to do here.
1968 case NAMED_PROPERTY:
1969 if (expr->is_compound()) {
1970 // We need the receiver both on the stack and in the register.
1971 VisitForStackValue(property->obj());
1972 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
1974 VisitForStackValue(property->obj());
1977 case NAMED_SUPER_PROPERTY:
1979 property->obj()->AsSuperPropertyReference()->this_var());
1980 VisitForAccumulatorValue(
1981 property->obj()->AsSuperPropertyReference()->home_object());
1982 __ Push(result_register());
1983 if (expr->is_compound()) {
1984 __ Push(MemOperand(rsp, kPointerSize));
1985 __ Push(result_register());
1988 case KEYED_SUPER_PROPERTY:
1990 property->obj()->AsSuperPropertyReference()->this_var());
1992 property->obj()->AsSuperPropertyReference()->home_object());
1993 VisitForAccumulatorValue(property->key());
1994 __ Push(result_register());
1995 if (expr->is_compound()) {
1996 __ Push(MemOperand(rsp, 2 * kPointerSize));
1997 __ Push(MemOperand(rsp, 2 * kPointerSize));
1998 __ Push(result_register());
2001 case KEYED_PROPERTY: {
2002 if (expr->is_compound()) {
2003 VisitForStackValue(property->obj());
2004 VisitForStackValue(property->key());
2005 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
2006 __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
2008 VisitForStackValue(property->obj());
2009 VisitForStackValue(property->key());
2015 // For compound assignments we need another deoptimization point after the
2016 // variable/property load.
2017 if (expr->is_compound()) {
2018 { AccumulatorValueContext context(this);
2019 switch (assign_type) {
2021 EmitVariableLoad(expr->target()->AsVariableProxy());
2022 PrepareForBailout(expr->target(), TOS_REG);
2024 case NAMED_PROPERTY:
2025 EmitNamedPropertyLoad(property);
2026 PrepareForBailoutForId(property->LoadId(), TOS_REG);
2028 case NAMED_SUPER_PROPERTY:
2029 EmitNamedSuperPropertyLoad(property);
2030 PrepareForBailoutForId(property->LoadId(), TOS_REG);
2032 case KEYED_SUPER_PROPERTY:
2033 EmitKeyedSuperPropertyLoad(property);
2034 PrepareForBailoutForId(property->LoadId(), TOS_REG);
2036 case KEYED_PROPERTY:
2037 EmitKeyedPropertyLoad(property);
2038 PrepareForBailoutForId(property->LoadId(), TOS_REG);
2043 Token::Value op = expr->binary_op();
2044 __ Push(rax); // Left operand goes on the stack.
2045 VisitForAccumulatorValue(expr->value());
2047 AccumulatorValueContext context(this);
2048 if (ShouldInlineSmiCase(op)) {
2049 EmitInlineSmiBinaryOp(expr->binary_operation(),
2054 EmitBinaryOp(expr->binary_operation(), op);
2056 // Deoptimization point in case the binary operation may have side effects.
2057 PrepareForBailout(expr->binary_operation(), TOS_REG);
2059 VisitForAccumulatorValue(expr->value());
2062 SetExpressionPosition(expr);
2065 switch (assign_type) {
2067 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
2068 expr->op(), expr->AssignmentSlot());
2069 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2070 context()->Plug(rax);
2072 case NAMED_PROPERTY:
2073 EmitNamedPropertyAssignment(expr);
2075 case NAMED_SUPER_PROPERTY:
2076 EmitNamedSuperPropertyStore(property);
2077 context()->Plug(rax);
2079 case KEYED_SUPER_PROPERTY:
2080 EmitKeyedSuperPropertyStore(property);
2081 context()->Plug(rax);
2083 case KEYED_PROPERTY:
2084 EmitKeyedPropertyAssignment(expr);
2090 void FullCodeGenerator::VisitYield(Yield* expr) {
2091 Comment cmnt(masm_, "[ Yield");
2092 SetExpressionPosition(expr);
2094 // Evaluate yielded value first; the initial iterator definition depends on
2095 // this. It stays on the stack while we update the iterator.
2096 VisitForStackValue(expr->expression());
2098 switch (expr->yield_kind()) {
2099 case Yield::kSuspend:
2100 // Pop value from top-of-stack slot; box result into result register.
2101 EmitCreateIteratorResult(false);
2102 __ Push(result_register());
2104 case Yield::kInitial: {
2105 Label suspend, continuation, post_runtime, resume;
2108 __ bind(&continuation);
2109 __ RecordGeneratorContinuation();
2113 VisitForAccumulatorValue(expr->generator_object());
2114 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2115 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
2116 Smi::FromInt(continuation.pos()));
2117 __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
2119 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
2121 __ leap(rbx, Operand(rbp, StandardFrameConstants::kExpressionsOffset));
2123 __ j(equal, &post_runtime);
2124 __ Push(rax); // generator object
2125 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2126 __ movp(context_register(),
2127 Operand(rbp, StandardFrameConstants::kContextOffset));
2128 __ bind(&post_runtime);
2130 __ Pop(result_register());
2131 EmitReturnSequence();
2134 context()->Plug(result_register());
2138 case Yield::kFinal: {
2139 VisitForAccumulatorValue(expr->generator_object());
2140 __ Move(FieldOperand(result_register(),
2141 JSGeneratorObject::kContinuationOffset),
2142 Smi::FromInt(JSGeneratorObject::kGeneratorClosed));
2143 // Pop value from top-of-stack slot, box result into result register.
2144 EmitCreateIteratorResult(true);
2145 EmitUnwindBeforeReturn();
2146 EmitReturnSequence();
2150 case Yield::kDelegating: {
2151 VisitForStackValue(expr->generator_object());
2153 // Initial stack layout is as follows:
2154 // [sp + 1 * kPointerSize] iter
2155 // [sp + 0 * kPointerSize] g
2157 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2158 Label l_next, l_call, l_loop;
2159 Register load_receiver = LoadDescriptor::ReceiverRegister();
2160 Register load_name = LoadDescriptor::NameRegister();
2162 // Initial send value is undefined.
2163 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
2166 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2168 __ LoadRoot(load_name, Heap::kthrow_stringRootIndex); // "throw"
2170 __ Push(Operand(rsp, 2 * kPointerSize)); // iter
2171 __ Push(rax); // exception
2174 // try { received = %yield result }
2175 // Shuffle the received result above a try handler and yield it without
2178 __ Pop(rax); // result
2179 int handler_index = NewHandlerTableEntry();
2180 EnterTryBlock(handler_index, &l_catch);
2181 const int try_block_size = TryCatch::kElementCount * kPointerSize;
2182 __ Push(rax); // result
2185 __ bind(&l_continuation);
2186 __ RecordGeneratorContinuation();
2189 __ bind(&l_suspend);
2190 const int generator_object_depth = kPointerSize + try_block_size;
2191 __ movp(rax, Operand(rsp, generator_object_depth));
2193 __ Push(Smi::FromInt(handler_index)); // handler-index
2194 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2195 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
2196 Smi::FromInt(l_continuation.pos()));
2197 __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
2199 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
2201 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
2202 __ movp(context_register(),
2203 Operand(rbp, StandardFrameConstants::kContextOffset));
2204 __ Pop(rax); // result
2205 EmitReturnSequence();
2206 __ bind(&l_resume); // received in rax
2207 ExitTryBlock(handler_index);
2209 // receiver = iter; f = 'next'; arg = received;
2212 __ LoadRoot(load_name, Heap::knext_stringRootIndex);
2213 __ Push(load_name); // "next"
2214 __ Push(Operand(rsp, 2 * kPointerSize)); // iter
2215 __ Push(rax); // received
2217 // result = receiver[f](arg);
2219 __ movp(load_receiver, Operand(rsp, kPointerSize));
2220 __ Move(LoadDescriptor::SlotRegister(),
2221 SmiFromSlot(expr->KeyedLoadFeedbackSlot()));
2222 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), SLOPPY).code();
2223 CallIC(ic, TypeFeedbackId::None());
2225 __ movp(Operand(rsp, 2 * kPointerSize), rdi);
2227 SetCallPosition(expr, 1);
2228 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2231 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2232 __ Drop(1); // The function is still on the stack; drop it.
2234 // if (!result.done) goto l_try;
2236 __ Move(load_receiver, rax);
2237 __ Push(load_receiver); // save result
2238 __ LoadRoot(load_name, Heap::kdone_stringRootIndex); // "done"
2239 __ Move(LoadDescriptor::SlotRegister(),
2240 SmiFromSlot(expr->DoneFeedbackSlot()));
2241 CallLoadIC(NOT_INSIDE_TYPEOF); // rax=result.done
2242 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2244 __ testp(result_register(), result_register());
2248 __ Pop(load_receiver); // result
2249 __ LoadRoot(load_name, Heap::kvalue_stringRootIndex); // "value"
2250 __ Move(LoadDescriptor::SlotRegister(),
2251 SmiFromSlot(expr->ValueFeedbackSlot()));
2252 CallLoadIC(NOT_INSIDE_TYPEOF); // result.value in rax
2253 context()->DropAndPlug(2, rax); // drop iter and g
2260 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2262 JSGeneratorObject::ResumeMode resume_mode) {
2263 // The value stays in rax, and is ultimately read by the resumed generator, as
2264 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2265 // is read to throw the value when the resumed generator is already closed.
2266 // rbx will hold the generator object until the activation has been resumed.
2267 VisitForStackValue(generator);
2268 VisitForAccumulatorValue(value);
2271 // Load suspended function and context.
2272 __ movp(rsi, FieldOperand(rbx, JSGeneratorObject::kContextOffset));
2273 __ movp(rdi, FieldOperand(rbx, JSGeneratorObject::kFunctionOffset));
2276 __ Push(FieldOperand(rbx, JSGeneratorObject::kReceiverOffset));
2278 // Push holes for arguments to generator function.
2279 __ movp(rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
2280 __ LoadSharedFunctionInfoSpecialField(rdx, rdx,
2281 SharedFunctionInfo::kFormalParameterCountOffset);
2282 __ LoadRoot(rcx, Heap::kTheHoleValueRootIndex);
2283 Label push_argument_holes, push_frame;
2284 __ bind(&push_argument_holes);
2285 __ subp(rdx, Immediate(1));
2286 __ j(carry, &push_frame);
2288 __ jmp(&push_argument_holes);
2290 // Enter a new JavaScript frame, and initialize its slots as they were when
2291 // the generator was suspended.
2292 Label resume_frame, done;
2293 __ bind(&push_frame);
2294 __ call(&resume_frame);
2296 __ bind(&resume_frame);
2297 __ pushq(rbp); // Caller's frame pointer.
2299 __ Push(rsi); // Callee's context.
2300 __ Push(rdi); // Callee's JS Function.
2302 // Load the operand stack size.
2303 __ movp(rdx, FieldOperand(rbx, JSGeneratorObject::kOperandStackOffset));
2304 __ movp(rdx, FieldOperand(rdx, FixedArray::kLengthOffset));
2305 __ SmiToInteger32(rdx, rdx);
2307 // If we are sending a value and there is no operand stack, we can jump back
2309 if (resume_mode == JSGeneratorObject::NEXT) {
2311 __ cmpp(rdx, Immediate(0));
2312 __ j(not_zero, &slow_resume);
2313 __ movp(rdx, FieldOperand(rdi, JSFunction::kCodeEntryOffset));
2314 __ SmiToInteger64(rcx,
2315 FieldOperand(rbx, JSGeneratorObject::kContinuationOffset));
2317 __ Move(FieldOperand(rbx, JSGeneratorObject::kContinuationOffset),
2318 Smi::FromInt(JSGeneratorObject::kGeneratorExecuting));
2320 __ bind(&slow_resume);
2323 // Otherwise, we push holes for the operand stack and call the runtime to fix
2324 // up the stack and the handlers.
2325 Label push_operand_holes, call_resume;
2326 __ bind(&push_operand_holes);
2327 __ subp(rdx, Immediate(1));
2328 __ j(carry, &call_resume);
2330 __ jmp(&push_operand_holes);
2331 __ bind(&call_resume);
2333 __ Push(result_register());
2334 __ Push(Smi::FromInt(resume_mode));
2335 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2336 // Not reached: the runtime call returns elsewhere.
2337 __ Abort(kGeneratorFailedToResume);
2340 context()->Plug(result_register());
2344 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2348 const int instance_size = 5 * kPointerSize;
2349 DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2352 __ Allocate(instance_size, rax, rcx, rdx, &gc_required, TAG_OBJECT);
2355 __ bind(&gc_required);
2356 __ Push(Smi::FromInt(instance_size));
2357 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2358 __ movp(context_register(),
2359 Operand(rbp, StandardFrameConstants::kContextOffset));
2361 __ bind(&allocated);
2362 __ movp(rbx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2363 __ movp(rbx, FieldOperand(rbx, GlobalObject::kNativeContextOffset));
2364 __ movp(rbx, ContextOperand(rbx, Context::ITERATOR_RESULT_MAP_INDEX));
2366 __ Move(rdx, isolate()->factory()->ToBoolean(done));
2367 __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
2368 __ Move(FieldOperand(rax, JSObject::kPropertiesOffset),
2369 isolate()->factory()->empty_fixed_array());
2370 __ Move(FieldOperand(rax, JSObject::kElementsOffset),
2371 isolate()->factory()->empty_fixed_array());
2372 __ movp(FieldOperand(rax, JSGeneratorObject::kResultValuePropertyOffset),
2374 __ movp(FieldOperand(rax, JSGeneratorObject::kResultDonePropertyOffset),
2377 // Only the value field needs a write barrier, as the other values are in the
2379 __ RecordWriteField(rax, JSGeneratorObject::kResultValuePropertyOffset,
2380 rcx, rdx, kDontSaveFPRegs);
2384 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2385 SetExpressionPosition(prop);
2386 Literal* key = prop->key()->AsLiteral();
2387 DCHECK(!prop->IsSuperAccess());
2389 __ Move(LoadDescriptor::NameRegister(), key->value());
2390 __ Move(LoadDescriptor::SlotRegister(),
2391 SmiFromSlot(prop->PropertyFeedbackSlot()));
2392 CallLoadIC(NOT_INSIDE_TYPEOF, language_mode());
2396 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2397 // Stack: receiver, home_object
2398 SetExpressionPosition(prop);
2399 Literal* key = prop->key()->AsLiteral();
2400 DCHECK(!key->value()->IsSmi());
2401 DCHECK(prop->IsSuperAccess());
2403 __ Push(key->value());
2404 __ Push(Smi::FromInt(language_mode()));
2405 __ CallRuntime(Runtime::kLoadFromSuper, 4);
2409 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2410 SetExpressionPosition(prop);
2411 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), language_mode()).code();
2412 __ Move(LoadDescriptor::SlotRegister(),
2413 SmiFromSlot(prop->PropertyFeedbackSlot()));
2418 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2419 // Stack: receiver, home_object, key.
2420 SetExpressionPosition(prop);
2421 __ Push(Smi::FromInt(language_mode()));
2422 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2426 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2429 Expression* right) {
2430 // Do combined smi check of the operands. Left operand is on the
2431 // stack (popped into rdx). Right operand is in rax but moved into
2432 // rcx to make the shifts easier.
2433 Label done, stub_call, smi_case;
2437 JumpPatchSite patch_site(masm_);
2438 patch_site.EmitJumpIfSmi(rax, &smi_case, Label::kNear);
2440 __ bind(&stub_call);
2443 CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2444 CallIC(code, expr->BinaryOperationFeedbackId());
2445 patch_site.EmitPatchInfo();
2446 __ jmp(&done, Label::kNear);
2451 __ SmiShiftArithmeticRight(rax, rdx, rcx);
2454 __ SmiShiftLeft(rax, rdx, rcx, &stub_call);
2457 __ SmiShiftLogicalRight(rax, rdx, rcx, &stub_call);
2460 __ SmiAdd(rax, rdx, rcx, &stub_call);
2463 __ SmiSub(rax, rdx, rcx, &stub_call);
2466 __ SmiMul(rax, rdx, rcx, &stub_call);
2469 __ SmiOr(rax, rdx, rcx);
2471 case Token::BIT_AND:
2472 __ SmiAnd(rax, rdx, rcx);
2474 case Token::BIT_XOR:
2475 __ SmiXor(rax, rdx, rcx);
2483 context()->Plug(rax);
2487 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit,
2488 int* used_store_slots) {
2489 // Constructor is in rax.
2490 DCHECK(lit != NULL);
2493 // No access check is needed here since the constructor is created by the
2495 Register scratch = rbx;
2496 __ movp(scratch, FieldOperand(rax, JSFunction::kPrototypeOrInitialMapOffset));
2499 for (int i = 0; i < lit->properties()->length(); i++) {
2500 ObjectLiteral::Property* property = lit->properties()->at(i);
2501 Expression* value = property->value();
2503 if (property->is_static()) {
2504 __ Push(Operand(rsp, kPointerSize)); // constructor
2506 __ Push(Operand(rsp, 0)); // prototype
2508 EmitPropertyKey(property, lit->GetIdForProperty(i));
2510 // The static prototype property is read only. We handle the non computed
2511 // property name case in the parser. Since this is the only case where we
2512 // need to check for an own read only property we special case this so we do
2513 // not need to do this for every property.
2514 if (property->is_static() && property->is_computed_name()) {
2515 __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
2519 VisitForStackValue(value);
2520 EmitSetHomeObjectIfNeeded(value, 2,
2521 lit->SlotForHomeObject(value, used_store_slots));
2523 switch (property->kind()) {
2524 case ObjectLiteral::Property::CONSTANT:
2525 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2526 case ObjectLiteral::Property::PROTOTYPE:
2528 case ObjectLiteral::Property::COMPUTED:
2529 __ CallRuntime(Runtime::kDefineClassMethod, 3);
2532 case ObjectLiteral::Property::GETTER:
2533 __ Push(Smi::FromInt(DONT_ENUM));
2534 __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2537 case ObjectLiteral::Property::SETTER:
2538 __ Push(Smi::FromInt(DONT_ENUM));
2539 __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2548 __ CallRuntime(Runtime::kToFastProperties, 1);
2551 __ CallRuntime(Runtime::kToFastProperties, 1);
2553 if (is_strong(language_mode())) {
2555 FieldOperand(rax, JSFunction::kPrototypeOrInitialMapOffset));
2558 // TODO(conradw): It would be more efficient to define the properties with
2559 // the right attributes the first time round.
2560 // Freeze the prototype.
2561 __ CallRuntime(Runtime::kObjectFreeze, 1);
2562 // Freeze the constructor.
2563 __ CallRuntime(Runtime::kObjectFreeze, 1);
2568 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2571 CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2572 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2573 CallIC(code, expr->BinaryOperationFeedbackId());
2574 patch_site.EmitPatchInfo();
2575 context()->Plug(rax);
2579 void FullCodeGenerator::EmitAssignment(Expression* expr,
2580 FeedbackVectorICSlot slot) {
2581 DCHECK(expr->IsValidReferenceExpression());
2583 Property* prop = expr->AsProperty();
2584 LhsKind assign_type = Property::GetAssignType(prop);
2586 switch (assign_type) {
2588 Variable* var = expr->AsVariableProxy()->var();
2589 EffectContext context(this);
2590 EmitVariableAssignment(var, Token::ASSIGN, slot);
2593 case NAMED_PROPERTY: {
2594 __ Push(rax); // Preserve value.
2595 VisitForAccumulatorValue(prop->obj());
2596 __ Move(StoreDescriptor::ReceiverRegister(), rax);
2597 __ Pop(StoreDescriptor::ValueRegister()); // Restore value.
2598 __ Move(StoreDescriptor::NameRegister(),
2599 prop->key()->AsLiteral()->value());
2600 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2604 case NAMED_SUPER_PROPERTY: {
2606 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2607 VisitForAccumulatorValue(
2608 prop->obj()->AsSuperPropertyReference()->home_object());
2609 // stack: value, this; rax: home_object
2610 Register scratch = rcx;
2611 Register scratch2 = rdx;
2612 __ Move(scratch, result_register()); // home_object
2613 __ movp(rax, MemOperand(rsp, kPointerSize)); // value
2614 __ movp(scratch2, MemOperand(rsp, 0)); // this
2615 __ movp(MemOperand(rsp, kPointerSize), scratch2); // this
2616 __ movp(MemOperand(rsp, 0), scratch); // home_object
2617 // stack: this, home_object; rax: value
2618 EmitNamedSuperPropertyStore(prop);
2621 case KEYED_SUPER_PROPERTY: {
2623 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2625 prop->obj()->AsSuperPropertyReference()->home_object());
2626 VisitForAccumulatorValue(prop->key());
2627 Register scratch = rcx;
2628 Register scratch2 = rdx;
2629 __ movp(scratch2, MemOperand(rsp, 2 * kPointerSize)); // value
2630 // stack: value, this, home_object; rax: key, rdx: value
2631 __ movp(scratch, MemOperand(rsp, kPointerSize)); // this
2632 __ movp(MemOperand(rsp, 2 * kPointerSize), scratch);
2633 __ movp(scratch, MemOperand(rsp, 0)); // home_object
2634 __ movp(MemOperand(rsp, kPointerSize), scratch);
2635 __ movp(MemOperand(rsp, 0), rax);
2636 __ Move(rax, scratch2);
2637 // stack: this, home_object, key; rax: value.
2638 EmitKeyedSuperPropertyStore(prop);
2641 case KEYED_PROPERTY: {
2642 __ Push(rax); // Preserve value.
2643 VisitForStackValue(prop->obj());
2644 VisitForAccumulatorValue(prop->key());
2645 __ Move(StoreDescriptor::NameRegister(), rax);
2646 __ Pop(StoreDescriptor::ReceiverRegister());
2647 __ Pop(StoreDescriptor::ValueRegister()); // Restore value.
2648 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2650 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2655 context()->Plug(rax);
2659 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2660 Variable* var, MemOperand location) {
2661 __ movp(location, rax);
2662 if (var->IsContextSlot()) {
2664 __ RecordWriteContextSlot(
2665 rcx, Context::SlotOffset(var->index()), rdx, rbx, kDontSaveFPRegs);
2670 void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
2671 FeedbackVectorICSlot slot) {
2672 if (var->IsUnallocated()) {
2673 // Global var, const, or let.
2674 __ Move(StoreDescriptor::NameRegister(), var->name());
2675 __ movp(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2676 if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2679 } else if (var->IsGlobalSlot()) {
2680 // Global var, const, or let.
2681 DCHECK(var->index() > 0);
2682 DCHECK(var->IsStaticGlobalObjectProperty());
2683 // Each var occupies two slots in the context: for reads and writes.
2684 int slot_index = var->index() + 1;
2685 int depth = scope()->ContextChainLength(var->scope());
2686 __ Move(StoreGlobalViaContextDescriptor::DepthRegister(),
2687 Smi::FromInt(depth));
2688 __ Move(StoreGlobalViaContextDescriptor::SlotRegister(),
2689 Smi::FromInt(slot_index));
2690 __ Move(StoreGlobalViaContextDescriptor::NameRegister(), var->name());
2691 DCHECK(StoreGlobalViaContextDescriptor::ValueRegister().is(rax));
2692 StoreGlobalViaContextStub stub(isolate(), depth, language_mode());
2695 } else if (var->mode() == LET && op != Token::INIT_LET) {
2696 // Non-initializing assignment to let variable needs a write barrier.
2697 DCHECK(!var->IsLookupSlot());
2698 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2700 MemOperand location = VarOperand(var, rcx);
2701 __ movp(rdx, location);
2702 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2703 __ j(not_equal, &assign, Label::kNear);
2704 __ Push(var->name());
2705 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2707 EmitStoreToStackLocalOrContextSlot(var, location);
2709 } else if (var->mode() == CONST && op != Token::INIT_CONST) {
2710 // Assignment to const variable needs a write barrier.
2711 DCHECK(!var->IsLookupSlot());
2712 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2714 MemOperand location = VarOperand(var, rcx);
2715 __ movp(rdx, location);
2716 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2717 __ j(not_equal, &const_error, Label::kNear);
2718 __ Push(var->name());
2719 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2720 __ bind(&const_error);
2721 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2723 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2724 if (var->IsLookupSlot()) {
2725 // Assignment to var.
2726 __ Push(rax); // Value.
2727 __ Push(rsi); // Context.
2728 __ Push(var->name());
2729 __ Push(Smi::FromInt(language_mode()));
2730 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2732 // Assignment to var or initializing assignment to let/const in harmony
2734 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2735 MemOperand location = VarOperand(var, rcx);
2736 if (generate_debug_code_ && op == Token::INIT_LET) {
2737 // Check for an uninitialized let binding.
2738 __ movp(rdx, location);
2739 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2740 __ Check(equal, kLetBindingReInitialization);
2742 EmitStoreToStackLocalOrContextSlot(var, location);
2745 } else if (op == Token::INIT_CONST_LEGACY) {
2746 // Const initializers need a write barrier.
2747 DCHECK(var->mode() == CONST_LEGACY);
2748 DCHECK(!var->IsParameter()); // No const parameters.
2749 if (var->IsLookupSlot()) {
2752 __ Push(var->name());
2753 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2755 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2757 MemOperand location = VarOperand(var, rcx);
2758 __ movp(rdx, location);
2759 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2760 __ j(not_equal, &skip);
2761 EmitStoreToStackLocalOrContextSlot(var, location);
2766 DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
2767 if (is_strict(language_mode())) {
2768 __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2770 // Silently ignore store in sloppy mode.
2775 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2776 // Assignment to a property, using a named store IC.
2777 Property* prop = expr->target()->AsProperty();
2778 DCHECK(prop != NULL);
2779 DCHECK(prop->key()->IsLiteral());
2781 __ Move(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2782 __ Pop(StoreDescriptor::ReceiverRegister());
2783 if (FLAG_vector_stores) {
2784 EmitLoadStoreICSlot(expr->AssignmentSlot());
2787 CallStoreIC(expr->AssignmentFeedbackId());
2790 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2791 context()->Plug(rax);
2795 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2796 // Assignment to named property of super.
2798 // stack : receiver ('this'), home_object
2799 DCHECK(prop != NULL);
2800 Literal* key = prop->key()->AsLiteral();
2801 DCHECK(key != NULL);
2803 __ Push(key->value());
2805 __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2806 : Runtime::kStoreToSuper_Sloppy),
2811 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2812 // Assignment to named property of super.
2814 // stack : receiver ('this'), home_object, key
2815 DCHECK(prop != NULL);
2819 (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2820 : Runtime::kStoreKeyedToSuper_Sloppy),
2825 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2826 // Assignment to a property, using a keyed store IC.
2827 __ Pop(StoreDescriptor::NameRegister()); // Key.
2828 __ Pop(StoreDescriptor::ReceiverRegister());
2829 DCHECK(StoreDescriptor::ValueRegister().is(rax));
2831 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2832 if (FLAG_vector_stores) {
2833 EmitLoadStoreICSlot(expr->AssignmentSlot());
2836 CallIC(ic, expr->AssignmentFeedbackId());
2839 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2840 context()->Plug(rax);
2844 void FullCodeGenerator::VisitProperty(Property* expr) {
2845 Comment cmnt(masm_, "[ Property");
2846 SetExpressionPosition(expr);
2848 Expression* key = expr->key();
2850 if (key->IsPropertyName()) {
2851 if (!expr->IsSuperAccess()) {
2852 VisitForAccumulatorValue(expr->obj());
2853 DCHECK(!rax.is(LoadDescriptor::ReceiverRegister()));
2854 __ movp(LoadDescriptor::ReceiverRegister(), rax);
2855 EmitNamedPropertyLoad(expr);
2857 VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
2859 expr->obj()->AsSuperPropertyReference()->home_object());
2860 EmitNamedSuperPropertyLoad(expr);
2863 if (!expr->IsSuperAccess()) {
2864 VisitForStackValue(expr->obj());
2865 VisitForAccumulatorValue(expr->key());
2866 __ Move(LoadDescriptor::NameRegister(), rax);
2867 __ Pop(LoadDescriptor::ReceiverRegister());
2868 EmitKeyedPropertyLoad(expr);
2870 VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
2872 expr->obj()->AsSuperPropertyReference()->home_object());
2873 VisitForStackValue(expr->key());
2874 EmitKeyedSuperPropertyLoad(expr);
2877 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2878 context()->Plug(rax);
2882 void FullCodeGenerator::CallIC(Handle<Code> code,
2883 TypeFeedbackId ast_id) {
2885 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2889 // Code common for calls using the IC.
2890 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2891 Expression* callee = expr->expression();
2893 CallICState::CallType call_type =
2894 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2895 // Get the target function.
2896 if (call_type == CallICState::FUNCTION) {
2897 { StackValueContext context(this);
2898 EmitVariableLoad(callee->AsVariableProxy());
2899 PrepareForBailout(callee, NO_REGISTERS);
2901 // Push undefined as receiver. This is patched in the method prologue if it
2902 // is a sloppy mode method.
2903 __ Push(isolate()->factory()->undefined_value());
2905 // Load the function from the receiver.
2906 DCHECK(callee->IsProperty());
2907 DCHECK(!callee->AsProperty()->IsSuperAccess());
2908 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
2909 EmitNamedPropertyLoad(callee->AsProperty());
2910 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2911 // Push the target function under the receiver.
2912 __ Push(Operand(rsp, 0));
2913 __ movp(Operand(rsp, kPointerSize), rax);
2916 EmitCall(expr, call_type);
2920 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2921 Expression* callee = expr->expression();
2922 DCHECK(callee->IsProperty());
2923 Property* prop = callee->AsProperty();
2924 DCHECK(prop->IsSuperAccess());
2925 SetExpressionPosition(prop);
2927 Literal* key = prop->key()->AsLiteral();
2928 DCHECK(!key->value()->IsSmi());
2929 // Load the function from the receiver.
2930 SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2931 VisitForStackValue(super_ref->home_object());
2932 VisitForAccumulatorValue(super_ref->this_var());
2935 __ Push(Operand(rsp, kPointerSize * 2));
2936 __ Push(key->value());
2937 __ Push(Smi::FromInt(language_mode()));
2941 // - this (receiver)
2942 // - this (receiver) <-- LoadFromSuper will pop here and below.
2946 __ CallRuntime(Runtime::kLoadFromSuper, 4);
2948 // Replace home_object with target function.
2949 __ movp(Operand(rsp, kPointerSize), rax);
2952 // - target function
2953 // - this (receiver)
2954 EmitCall(expr, CallICState::METHOD);
2958 // Common code for calls using the IC.
2959 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2962 VisitForAccumulatorValue(key);
2964 Expression* callee = expr->expression();
2966 // Load the function from the receiver.
2967 DCHECK(callee->IsProperty());
2968 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
2969 __ Move(LoadDescriptor::NameRegister(), rax);
2970 EmitKeyedPropertyLoad(callee->AsProperty());
2971 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2973 // Push the target function under the receiver.
2974 __ Push(Operand(rsp, 0));
2975 __ movp(Operand(rsp, kPointerSize), rax);
2977 EmitCall(expr, CallICState::METHOD);
2981 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2982 Expression* callee = expr->expression();
2983 DCHECK(callee->IsProperty());
2984 Property* prop = callee->AsProperty();
2985 DCHECK(prop->IsSuperAccess());
2987 SetExpressionPosition(prop);
2988 // Load the function from the receiver.
2989 SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2990 VisitForStackValue(super_ref->home_object());
2991 VisitForAccumulatorValue(super_ref->this_var());
2994 __ Push(Operand(rsp, kPointerSize * 2));
2995 VisitForStackValue(prop->key());
2996 __ Push(Smi::FromInt(language_mode()));
3000 // - this (receiver)
3001 // - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
3005 __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
3007 // Replace home_object with target function.
3008 __ movp(Operand(rsp, kPointerSize), rax);
3011 // - target function
3012 // - this (receiver)
3013 EmitCall(expr, CallICState::METHOD);
3017 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
3018 // Load the arguments.
3019 ZoneList<Expression*>* args = expr->arguments();
3020 int arg_count = args->length();
3021 for (int i = 0; i < arg_count; i++) {
3022 VisitForStackValue(args->at(i));
3025 SetCallPosition(expr, arg_count);
3026 Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
3027 __ Move(rdx, SmiFromSlot(expr->CallFeedbackICSlot()));
3028 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
3029 // Don't assign a type feedback id to the IC, since type feedback is provided
3030 // by the vector above.
3033 RecordJSReturnSite(expr);
3035 // Restore context register.
3036 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3037 // Discard the function left on TOS.
3038 context()->DropAndPlug(1, rax);
3042 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
3043 // Push copy of the first argument or undefined if it doesn't exist.
3044 if (arg_count > 0) {
3045 __ Push(Operand(rsp, arg_count * kPointerSize));
3047 __ PushRoot(Heap::kUndefinedValueRootIndex);
3050 // Push the enclosing function.
3051 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
3053 // Push the language mode.
3054 __ Push(Smi::FromInt(language_mode()));
3056 // Push the start position of the scope the calls resides in.
3057 __ Push(Smi::FromInt(scope()->start_position()));
3059 // Do the runtime call.
3060 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 5);
3064 void FullCodeGenerator::EmitInitializeThisAfterSuper(
3065 SuperCallReference* super_ref, FeedbackVectorICSlot slot) {
3066 Variable* this_var = super_ref->this_var()->var();
3067 GetVar(rcx, this_var);
3068 __ CompareRoot(rcx, Heap::kTheHoleValueRootIndex);
3069 Label uninitialized_this;
3070 __ j(equal, &uninitialized_this);
3071 __ Push(this_var->name());
3072 __ CallRuntime(Runtime::kThrowReferenceError, 1);
3073 __ bind(&uninitialized_this);
3075 EmitVariableAssignment(this_var, Token::INIT_CONST, slot);
3079 // See http://www.ecma-international.org/ecma-262/6.0/#sec-function-calls.
3080 void FullCodeGenerator::PushCalleeAndWithBaseObject(Call* expr) {
3081 VariableProxy* callee = expr->expression()->AsVariableProxy();
3082 if (callee->var()->IsLookupSlot()) {
3084 SetExpressionPosition(callee);
3085 // Generate code for loading from variables potentially shadowed by
3086 // eval-introduced variables.
3087 EmitDynamicLookupFastCase(callee, NOT_INSIDE_TYPEOF, &slow, &done);
3089 // Call the runtime to find the function to call (returned in rax) and
3090 // the object holding it (returned in rdx).
3091 __ Push(context_register());
3092 __ Push(callee->name());
3093 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3094 __ Push(rax); // Function.
3095 __ Push(rdx); // Receiver.
3096 PrepareForBailoutForId(expr->LookupId(), NO_REGISTERS);
3098 // If fast case code has been generated, emit code to push the function
3099 // and receiver and have the slow path jump around this code.
3100 if (done.is_linked()) {
3102 __ jmp(&call, Label::kNear);
3106 // Pass undefined as the receiver, which is the WithBaseObject of a
3107 // non-object environment record. If the callee is sloppy, it will patch
3108 // it up to be the global receiver.
3109 __ PushRoot(Heap::kUndefinedValueRootIndex);
3113 VisitForStackValue(callee);
3114 // refEnv.WithBaseObject()
3115 __ PushRoot(Heap::kUndefinedValueRootIndex);
3120 void FullCodeGenerator::VisitCall(Call* expr) {
3122 // We want to verify that RecordJSReturnSite gets called on all paths
3123 // through this function. Avoid early returns.
3124 expr->return_is_recorded_ = false;
3127 Comment cmnt(masm_, "[ Call");
3128 Expression* callee = expr->expression();
3129 Call::CallType call_type = expr->GetCallType(isolate());
3131 if (call_type == Call::POSSIBLY_EVAL_CALL) {
3132 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
3133 // to resolve the function we need to call. Then we call the resolved
3134 // function using the given arguments.
3135 ZoneList<Expression*>* args = expr->arguments();
3136 int arg_count = args->length();
3137 PushCalleeAndWithBaseObject(expr);
3139 // Push the arguments.
3140 for (int i = 0; i < arg_count; i++) {
3141 VisitForStackValue(args->at(i));
3144 // Push a copy of the function (found below the arguments) and resolve
3146 __ Push(Operand(rsp, (arg_count + 1) * kPointerSize));
3147 EmitResolvePossiblyDirectEval(arg_count);
3149 // Touch up the callee.
3150 __ movp(Operand(rsp, (arg_count + 1) * kPointerSize), rax);
3152 PrepareForBailoutForId(expr->EvalId(), NO_REGISTERS);
3154 SetCallPosition(expr, arg_count);
3155 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3156 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
3158 RecordJSReturnSite(expr);
3159 // Restore context register.
3160 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3161 context()->DropAndPlug(1, rax);
3162 } else if (call_type == Call::GLOBAL_CALL) {
3163 EmitCallWithLoadIC(expr);
3165 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3166 // Call to a lookup slot (dynamically introduced variable).
3167 PushCalleeAndWithBaseObject(expr);
3169 } else if (call_type == Call::PROPERTY_CALL) {
3170 Property* property = callee->AsProperty();
3171 bool is_named_call = property->key()->IsPropertyName();
3172 if (property->IsSuperAccess()) {
3173 if (is_named_call) {
3174 EmitSuperCallWithLoadIC(expr);
3176 EmitKeyedSuperCallWithLoadIC(expr);
3179 VisitForStackValue(property->obj());
3180 if (is_named_call) {
3181 EmitCallWithLoadIC(expr);
3183 EmitKeyedCallWithLoadIC(expr, property->key());
3186 } else if (call_type == Call::SUPER_CALL) {
3187 EmitSuperConstructorCall(expr);
3189 DCHECK(call_type == Call::OTHER_CALL);
3190 // Call to an arbitrary expression not handled specially above.
3191 VisitForStackValue(callee);
3192 __ PushRoot(Heap::kUndefinedValueRootIndex);
3193 // Emit function call.
3198 // RecordJSReturnSite should have been called.
3199 DCHECK(expr->return_is_recorded_);
3204 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3205 Comment cmnt(masm_, "[ CallNew");
3206 // According to ECMA-262, section 11.2.2, page 44, the function
3207 // expression in new calls must be evaluated before the
3210 // Push constructor on the stack. If it's not a function it's used as
3211 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3213 DCHECK(!expr->expression()->IsSuperPropertyReference());
3214 VisitForStackValue(expr->expression());
3216 // Push the arguments ("left-to-right") on the stack.
3217 ZoneList<Expression*>* args = expr->arguments();
3218 int arg_count = args->length();
3219 for (int i = 0; i < arg_count; i++) {
3220 VisitForStackValue(args->at(i));
3223 // Call the construct call builtin that handles allocation and
3224 // constructor invocation.
3225 SetConstructCallPosition(expr);
3227 // Load function and argument count into rdi and rax.
3228 __ Set(rax, arg_count);
3229 __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
3231 // Record call targets in unoptimized code, but not in the snapshot.
3232 if (FLAG_pretenuring_call_new) {
3233 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3234 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3235 expr->CallNewFeedbackSlot().ToInt() + 1);
3238 __ Move(rbx, FeedbackVector());
3239 __ Move(rdx, SmiFromSlot(expr->CallNewFeedbackSlot()));
3241 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3242 __ Call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3243 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3244 context()->Plug(rax);
3248 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3249 SuperCallReference* super_call_ref =
3250 expr->expression()->AsSuperCallReference();
3251 DCHECK_NOT_NULL(super_call_ref);
3253 EmitLoadSuperConstructor(super_call_ref);
3254 __ Push(result_register());
3256 // Push the arguments ("left-to-right") on the stack.
3257 ZoneList<Expression*>* args = expr->arguments();
3258 int arg_count = args->length();
3259 for (int i = 0; i < arg_count; i++) {
3260 VisitForStackValue(args->at(i));
3263 // Call the construct call builtin that handles allocation and
3264 // constructor invocation.
3265 SetConstructCallPosition(expr);
3267 // Load original constructor into rcx.
3268 VisitForAccumulatorValue(super_call_ref->new_target_var());
3269 __ movp(rcx, result_register());
3271 // Load function and argument count into rdi and rax.
3272 __ Set(rax, arg_count);
3273 __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
3275 // Record call targets in unoptimized code.
3276 if (FLAG_pretenuring_call_new) {
3278 /* TODO(dslomov): support pretenuring.
3279 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3280 DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3281 expr->CallNewFeedbackSlot().ToInt() + 1);
3285 __ Move(rbx, FeedbackVector());
3286 __ Move(rdx, SmiFromSlot(expr->CallFeedbackSlot()));
3288 CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3289 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3291 RecordJSReturnSite(expr);
3293 EmitInitializeThisAfterSuper(super_call_ref, expr->CallFeedbackICSlot());
3294 context()->Plug(rax);
3298 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3299 ZoneList<Expression*>* args = expr->arguments();
3300 DCHECK(args->length() == 1);
3302 VisitForAccumulatorValue(args->at(0));
3304 Label materialize_true, materialize_false;
3305 Label* if_true = NULL;
3306 Label* if_false = NULL;
3307 Label* fall_through = NULL;
3308 context()->PrepareTest(&materialize_true, &materialize_false,
3309 &if_true, &if_false, &fall_through);
3311 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3312 __ JumpIfSmi(rax, if_true);
3315 context()->Plug(if_true, if_false);
3319 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3320 ZoneList<Expression*>* args = expr->arguments();
3321 DCHECK(args->length() == 1);
3323 VisitForAccumulatorValue(args->at(0));
3325 Label materialize_true, materialize_false;
3326 Label* if_true = NULL;
3327 Label* if_false = NULL;
3328 Label* fall_through = NULL;
3329 context()->PrepareTest(&materialize_true, &materialize_false,
3330 &if_true, &if_false, &fall_through);
3332 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3333 Condition non_negative_smi = masm()->CheckNonNegativeSmi(rax);
3334 Split(non_negative_smi, if_true, if_false, fall_through);
3336 context()->Plug(if_true, if_false);
3340 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3341 ZoneList<Expression*>* args = expr->arguments();
3342 DCHECK(args->length() == 1);
3344 VisitForAccumulatorValue(args->at(0));
3346 Label materialize_true, materialize_false;
3347 Label* if_true = NULL;
3348 Label* if_false = NULL;
3349 Label* fall_through = NULL;
3350 context()->PrepareTest(&materialize_true, &materialize_false,
3351 &if_true, &if_false, &fall_through);
3353 __ JumpIfSmi(rax, if_false);
3354 __ CompareRoot(rax, Heap::kNullValueRootIndex);
3355 __ j(equal, if_true);
3356 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3357 // Undetectable objects behave like undefined when tested with typeof.
3358 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
3359 Immediate(1 << Map::kIsUndetectable));
3360 __ j(not_zero, if_false);
3361 __ movzxbp(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset));
3362 __ cmpp(rbx, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
3363 __ j(below, if_false);
3364 __ cmpp(rbx, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
3365 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3366 Split(below_equal, if_true, if_false, fall_through);
3368 context()->Plug(if_true, if_false);
3372 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3373 ZoneList<Expression*>* args = expr->arguments();
3374 DCHECK(args->length() == 1);
3376 VisitForAccumulatorValue(args->at(0));
3378 Label materialize_true, materialize_false;
3379 Label* if_true = NULL;
3380 Label* if_false = NULL;
3381 Label* fall_through = NULL;
3382 context()->PrepareTest(&materialize_true, &materialize_false,
3383 &if_true, &if_false, &fall_through);
3385 __ JumpIfSmi(rax, if_false);
3386 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rbx);
3387 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3388 Split(above_equal, if_true, if_false, fall_through);
3390 context()->Plug(if_true, if_false);
3394 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3395 ZoneList<Expression*>* args = expr->arguments();
3396 DCHECK(args->length() == 1);
3398 VisitForAccumulatorValue(args->at(0));
3400 Label materialize_true, materialize_false;
3401 Label* if_true = NULL;
3402 Label* if_false = NULL;
3403 Label* fall_through = NULL;
3404 context()->PrepareTest(&materialize_true, &materialize_false,
3405 &if_true, &if_false, &fall_through);
3407 __ JumpIfSmi(rax, if_false);
3408 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3409 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
3410 Immediate(1 << Map::kIsUndetectable));
3411 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3412 Split(not_zero, if_true, if_false, fall_through);
3414 context()->Plug(if_true, if_false);
3418 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3419 CallRuntime* expr) {
3420 ZoneList<Expression*>* args = expr->arguments();
3421 DCHECK(args->length() == 1);
3423 VisitForAccumulatorValue(args->at(0));
3425 Label materialize_true, materialize_false, skip_lookup;
3426 Label* if_true = NULL;
3427 Label* if_false = NULL;
3428 Label* fall_through = NULL;
3429 context()->PrepareTest(&materialize_true, &materialize_false,
3430 &if_true, &if_false, &fall_through);
3432 __ AssertNotSmi(rax);
3434 // Check whether this map has already been checked to be safe for default
3436 __ movp(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3437 __ testb(FieldOperand(rbx, Map::kBitField2Offset),
3438 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3439 __ j(not_zero, &skip_lookup);
3441 // Check for fast case object. Generate false result for slow case object.
3442 __ movp(rcx, FieldOperand(rax, JSObject::kPropertiesOffset));
3443 __ movp(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3444 __ CompareRoot(rcx, Heap::kHashTableMapRootIndex);
3445 __ j(equal, if_false);
3447 // Look for valueOf string in the descriptor array, and indicate false if
3448 // found. Since we omit an enumeration index check, if it is added via a
3449 // transition that shares its descriptor array, this is a false positive.
3450 Label entry, loop, done;
3452 // Skip loop if no descriptors are valid.
3453 __ NumberOfOwnDescriptors(rcx, rbx);
3454 __ cmpp(rcx, Immediate(0));
3457 __ LoadInstanceDescriptors(rbx, r8);
3458 // rbx: descriptor array.
3459 // rcx: valid entries in the descriptor array.
3460 // Calculate the end of the descriptor array.
3461 __ imulp(rcx, rcx, Immediate(DescriptorArray::kDescriptorSize));
3463 Operand(r8, rcx, times_pointer_size, DescriptorArray::kFirstOffset));
3464 // Calculate location of the first key name.
3465 __ addp(r8, Immediate(DescriptorArray::kFirstOffset));
3466 // Loop through all the keys in the descriptor array. If one of these is the
3467 // internalized string "valueOf" the result is false.
3470 __ movp(rdx, FieldOperand(r8, 0));
3471 __ Cmp(rdx, isolate()->factory()->value_of_string());
3472 __ j(equal, if_false);
3473 __ addp(r8, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3476 __ j(not_equal, &loop);
3480 // Set the bit in the map to indicate that there is no local valueOf field.
3481 __ orp(FieldOperand(rbx, Map::kBitField2Offset),
3482 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3484 __ bind(&skip_lookup);
3486 // If a valueOf property is not found on the object check that its
3487 // prototype is the un-modified String prototype. If not result is false.
3488 __ movp(rcx, FieldOperand(rbx, Map::kPrototypeOffset));
3489 __ testp(rcx, Immediate(kSmiTagMask));
3490 __ j(zero, if_false);
3491 __ movp(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3492 __ movp(rdx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3493 __ movp(rdx, FieldOperand(rdx, GlobalObject::kNativeContextOffset));
3495 ContextOperand(rdx, Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3496 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3497 Split(equal, if_true, if_false, fall_through);
3499 context()->Plug(if_true, if_false);
3503 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3504 ZoneList<Expression*>* args = expr->arguments();
3505 DCHECK(args->length() == 1);
3507 VisitForAccumulatorValue(args->at(0));
3509 Label materialize_true, materialize_false;
3510 Label* if_true = NULL;
3511 Label* if_false = NULL;
3512 Label* fall_through = NULL;
3513 context()->PrepareTest(&materialize_true, &materialize_false,
3514 &if_true, &if_false, &fall_through);
3516 __ JumpIfSmi(rax, if_false);
3517 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
3518 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3519 Split(equal, if_true, if_false, fall_through);
3521 context()->Plug(if_true, if_false);
3525 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3526 ZoneList<Expression*>* args = expr->arguments();
3527 DCHECK(args->length() == 1);
3529 VisitForAccumulatorValue(args->at(0));
3531 Label materialize_true, materialize_false;
3532 Label* if_true = NULL;
3533 Label* if_false = NULL;
3534 Label* fall_through = NULL;
3535 context()->PrepareTest(&materialize_true, &materialize_false,
3536 &if_true, &if_false, &fall_through);
3538 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3539 __ CheckMap(rax, map, if_false, DO_SMI_CHECK);
3540 __ cmpl(FieldOperand(rax, HeapNumber::kExponentOffset),
3542 __ j(no_overflow, if_false);
3543 __ cmpl(FieldOperand(rax, HeapNumber::kMantissaOffset),
3544 Immediate(0x00000000));
3545 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3546 Split(equal, if_true, if_false, fall_through);
3548 context()->Plug(if_true, if_false);
3552 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3553 ZoneList<Expression*>* args = expr->arguments();
3554 DCHECK(args->length() == 1);
3556 VisitForAccumulatorValue(args->at(0));
3558 Label materialize_true, materialize_false;
3559 Label* if_true = NULL;
3560 Label* if_false = NULL;
3561 Label* fall_through = NULL;
3562 context()->PrepareTest(&materialize_true, &materialize_false,
3563 &if_true, &if_false, &fall_through);
3565 __ JumpIfSmi(rax, if_false);
3566 __ CmpObjectType(rax, JS_ARRAY_TYPE, rbx);
3567 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3568 Split(equal, if_true, if_false, fall_through);
3570 context()->Plug(if_true, if_false);
3574 void FullCodeGenerator::EmitIsTypedArray(CallRuntime* expr) {
3575 ZoneList<Expression*>* args = expr->arguments();
3576 DCHECK(args->length() == 1);
3578 VisitForAccumulatorValue(args->at(0));
3580 Label materialize_true, materialize_false;
3581 Label* if_true = NULL;
3582 Label* if_false = NULL;
3583 Label* fall_through = NULL;
3584 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3585 &if_false, &fall_through);
3587 __ JumpIfSmi(rax, if_false);
3588 __ CmpObjectType(rax, JS_TYPED_ARRAY_TYPE, rbx);
3589 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3590 Split(equal, if_true, if_false, fall_through);
3592 context()->Plug(if_true, if_false);
3596 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3597 ZoneList<Expression*>* args = expr->arguments();
3598 DCHECK(args->length() == 1);
3600 VisitForAccumulatorValue(args->at(0));
3602 Label materialize_true, materialize_false;
3603 Label* if_true = NULL;
3604 Label* if_false = NULL;
3605 Label* fall_through = NULL;
3606 context()->PrepareTest(&materialize_true, &materialize_false,
3607 &if_true, &if_false, &fall_through);
3609 __ JumpIfSmi(rax, if_false);
3610 __ CmpObjectType(rax, JS_REGEXP_TYPE, rbx);
3611 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3612 Split(equal, if_true, if_false, fall_through);
3614 context()->Plug(if_true, if_false);
3618 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3619 ZoneList<Expression*>* args = expr->arguments();
3620 DCHECK(args->length() == 1);
3622 VisitForAccumulatorValue(args->at(0));
3624 Label materialize_true, materialize_false;
3625 Label* if_true = NULL;
3626 Label* if_false = NULL;
3627 Label* fall_through = NULL;
3628 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3629 &if_false, &fall_through);
3631 __ JumpIfSmi(rax, if_false);
3633 __ movp(map, FieldOperand(rax, HeapObject::kMapOffset));
3634 __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3635 __ j(less, if_false);
3636 __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3637 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3638 Split(less_equal, if_true, if_false, fall_through);
3640 context()->Plug(if_true, if_false);
3644 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3645 DCHECK(expr->arguments()->length() == 0);
3647 Label materialize_true, materialize_false;
3648 Label* if_true = NULL;
3649 Label* if_false = NULL;
3650 Label* fall_through = NULL;
3651 context()->PrepareTest(&materialize_true, &materialize_false,
3652 &if_true, &if_false, &fall_through);
3654 // Get the frame pointer for the calling frame.
3655 __ movp(rax, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3657 // Skip the arguments adaptor frame if it exists.
3658 Label check_frame_marker;
3659 __ Cmp(Operand(rax, StandardFrameConstants::kContextOffset),
3660 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3661 __ j(not_equal, &check_frame_marker);
3662 __ movp(rax, Operand(rax, StandardFrameConstants::kCallerFPOffset));
3664 // Check the marker in the calling frame.
3665 __ bind(&check_frame_marker);
3666 __ Cmp(Operand(rax, StandardFrameConstants::kMarkerOffset),
3667 Smi::FromInt(StackFrame::CONSTRUCT));
3668 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3669 Split(equal, if_true, if_false, fall_through);
3671 context()->Plug(if_true, if_false);
3675 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3676 ZoneList<Expression*>* args = expr->arguments();
3677 DCHECK(args->length() == 2);
3679 // Load the two objects into registers and perform the comparison.
3680 VisitForStackValue(args->at(0));
3681 VisitForAccumulatorValue(args->at(1));
3683 Label materialize_true, materialize_false;
3684 Label* if_true = NULL;
3685 Label* if_false = NULL;
3686 Label* fall_through = NULL;
3687 context()->PrepareTest(&materialize_true, &materialize_false,
3688 &if_true, &if_false, &fall_through);
3692 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3693 Split(equal, if_true, if_false, fall_through);
3695 context()->Plug(if_true, if_false);
3699 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3700 ZoneList<Expression*>* args = expr->arguments();
3701 DCHECK(args->length() == 1);
3703 // ArgumentsAccessStub expects the key in rdx and the formal
3704 // parameter count in rax.
3705 VisitForAccumulatorValue(args->at(0));
3707 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters()));
3708 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3710 context()->Plug(rax);
3714 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3715 DCHECK(expr->arguments()->length() == 0);
3718 // Get the number of formal parameters.
3719 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters()));
3721 // Check if the calling frame is an arguments adaptor frame.
3722 __ movp(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3723 __ Cmp(Operand(rbx, StandardFrameConstants::kContextOffset),
3724 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3725 __ j(not_equal, &exit, Label::kNear);
3727 // Arguments adaptor case: Read the arguments length from the
3729 __ movp(rax, Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3733 context()->Plug(rax);
3737 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3738 ZoneList<Expression*>* args = expr->arguments();
3739 DCHECK(args->length() == 1);
3740 Label done, null, function, non_function_constructor;
3742 VisitForAccumulatorValue(args->at(0));
3744 // If the object is a smi, we return null.
3745 __ JumpIfSmi(rax, &null);
3747 // Check that the object is a JS object but take special care of JS
3748 // functions to make sure they have 'Function' as their class.
3749 // Assume that there are only two callable types, and one of them is at
3750 // either end of the type range for JS object types. Saves extra comparisons.
3751 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3752 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rax);
3753 // Map is now in rax.
3755 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3756 FIRST_SPEC_OBJECT_TYPE + 1);
3757 __ j(equal, &function);
3759 __ CmpInstanceType(rax, LAST_SPEC_OBJECT_TYPE);
3760 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3761 LAST_SPEC_OBJECT_TYPE - 1);
3762 __ j(equal, &function);
3763 // Assume that there is no larger type.
3764 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3766 // Check if the constructor in the map is a JS function.
3767 __ GetMapConstructor(rax, rax, rbx);
3768 __ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
3769 __ j(not_equal, &non_function_constructor);
3771 // rax now contains the constructor function. Grab the
3772 // instance class name from there.
3773 __ movp(rax, FieldOperand(rax, JSFunction::kSharedFunctionInfoOffset));
3774 __ movp(rax, FieldOperand(rax, SharedFunctionInfo::kInstanceClassNameOffset));
3777 // Functions have class 'Function'.
3779 __ Move(rax, isolate()->factory()->Function_string());
3782 // Objects with a non-function constructor have class 'Object'.
3783 __ bind(&non_function_constructor);
3784 __ Move(rax, isolate()->factory()->Object_string());
3787 // Non-JS objects have class null.
3789 __ LoadRoot(rax, Heap::kNullValueRootIndex);
3794 context()->Plug(rax);
3798 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3799 // Load the arguments on the stack and call the stub.
3800 SubStringStub stub(isolate());
3801 ZoneList<Expression*>* args = expr->arguments();
3802 DCHECK(args->length() == 3);
3803 VisitForStackValue(args->at(0));
3804 VisitForStackValue(args->at(1));
3805 VisitForStackValue(args->at(2));
3807 context()->Plug(rax);
3811 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3812 // Load the arguments on the stack and call the stub.
3813 RegExpExecStub stub(isolate());
3814 ZoneList<Expression*>* args = expr->arguments();
3815 DCHECK(args->length() == 4);
3816 VisitForStackValue(args->at(0));
3817 VisitForStackValue(args->at(1));
3818 VisitForStackValue(args->at(2));
3819 VisitForStackValue(args->at(3));
3821 context()->Plug(rax);
3825 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3826 ZoneList<Expression*>* args = expr->arguments();
3827 DCHECK(args->length() == 1);
3829 VisitForAccumulatorValue(args->at(0)); // Load the object.
3832 // If the object is a smi return the object.
3833 __ JumpIfSmi(rax, &done);
3834 // If the object is not a value type, return the object.
3835 __ CmpObjectType(rax, JS_VALUE_TYPE, rbx);
3836 __ j(not_equal, &done);
3837 __ movp(rax, FieldOperand(rax, JSValue::kValueOffset));
3840 context()->Plug(rax);
3844 void FullCodeGenerator::EmitIsDate(CallRuntime* expr) {
3845 ZoneList<Expression*>* args = expr->arguments();
3846 DCHECK_EQ(1, args->length());
3848 VisitForAccumulatorValue(args->at(0));
3850 Label materialize_true, materialize_false;
3851 Label* if_true = nullptr;
3852 Label* if_false = nullptr;
3853 Label* fall_through = nullptr;
3854 context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3855 &if_false, &fall_through);
3857 __ JumpIfSmi(rax, if_false);
3858 __ CmpObjectType(rax, JS_DATE_TYPE, rbx);
3859 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3860 Split(equal, if_true, if_false, fall_through);
3862 context()->Plug(if_true, if_false);
3866 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3867 ZoneList<Expression*>* args = expr->arguments();
3868 DCHECK(args->length() == 2);
3869 DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3870 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3872 VisitForAccumulatorValue(args->at(0)); // Load the object.
3874 Register object = rax;
3875 Register result = rax;
3876 Register scratch = rcx;
3878 if (FLAG_debug_code) {
3879 __ AssertNotSmi(object);
3880 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3881 __ Check(equal, kOperandIsNotADate);
3884 if (index->value() == 0) {
3885 __ movp(result, FieldOperand(object, JSDate::kValueOffset));
3887 Label runtime, done;
3888 if (index->value() < JSDate::kFirstUncachedField) {
3889 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3890 Operand stamp_operand = __ ExternalOperand(stamp);
3891 __ movp(scratch, stamp_operand);
3892 __ cmpp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3893 __ j(not_equal, &runtime, Label::kNear);
3894 __ movp(result, FieldOperand(object, JSDate::kValueOffset +
3895 kPointerSize * index->value()));
3896 __ jmp(&done, Label::kNear);
3899 __ PrepareCallCFunction(2);
3900 __ movp(arg_reg_1, object);
3901 __ Move(arg_reg_2, index, Assembler::RelocInfoNone());
3902 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3903 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3907 context()->Plug(rax);
3911 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3912 ZoneList<Expression*>* args = expr->arguments();
3913 DCHECK_EQ(3, args->length());
3915 Register string = rax;
3916 Register index = rbx;
3917 Register value = rcx;
3919 VisitForStackValue(args->at(0)); // index
3920 VisitForStackValue(args->at(1)); // value
3921 VisitForAccumulatorValue(args->at(2)); // string
3925 if (FLAG_debug_code) {
3926 __ Check(__ CheckSmi(value), kNonSmiValue);
3927 __ Check(__ CheckSmi(index), kNonSmiValue);
3930 __ SmiToInteger32(value, value);
3931 __ SmiToInteger32(index, index);
3933 if (FLAG_debug_code) {
3934 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3935 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3938 __ movb(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3940 context()->Plug(string);
3944 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3945 ZoneList<Expression*>* args = expr->arguments();
3946 DCHECK_EQ(3, args->length());
3948 Register string = rax;
3949 Register index = rbx;
3950 Register value = rcx;
3952 VisitForStackValue(args->at(0)); // index
3953 VisitForStackValue(args->at(1)); // value
3954 VisitForAccumulatorValue(args->at(2)); // string
3958 if (FLAG_debug_code) {
3959 __ Check(__ CheckSmi(value), kNonSmiValue);
3960 __ Check(__ CheckSmi(index), kNonSmiValue);
3963 __ SmiToInteger32(value, value);
3964 __ SmiToInteger32(index, index);
3966 if (FLAG_debug_code) {
3967 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3968 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3971 __ movw(FieldOperand(string, index, times_2, SeqTwoByteString::kHeaderSize),
3973 context()->Plug(rax);
3977 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3978 // Load the arguments on the stack and call the runtime function.
3979 ZoneList<Expression*>* args = expr->arguments();
3980 DCHECK(args->length() == 2);
3981 VisitForStackValue(args->at(0));
3982 VisitForStackValue(args->at(1));
3983 MathPowStub stub(isolate(), MathPowStub::ON_STACK);
3985 context()->Plug(rax);
3989 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3990 ZoneList<Expression*>* args = expr->arguments();
3991 DCHECK(args->length() == 2);
3993 VisitForStackValue(args->at(0)); // Load the object.
3994 VisitForAccumulatorValue(args->at(1)); // Load the value.
3995 __ Pop(rbx); // rax = value. rbx = object.
3998 // If the object is a smi, return the value.
3999 __ JumpIfSmi(rbx, &done);
4001 // If the object is not a value type, return the value.
4002 __ CmpObjectType(rbx, JS_VALUE_TYPE, rcx);
4003 __ j(not_equal, &done);
4006 __ movp(FieldOperand(rbx, JSValue::kValueOffset), rax);
4007 // Update the write barrier. Save the value as it will be
4008 // overwritten by the write barrier code and is needed afterward.
4010 __ RecordWriteField(rbx, JSValue::kValueOffset, rdx, rcx, kDontSaveFPRegs);
4013 context()->Plug(rax);
4017 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
4018 ZoneList<Expression*>* args = expr->arguments();
4019 DCHECK_EQ(args->length(), 1);
4021 // Load the argument into rax and call the stub.
4022 VisitForAccumulatorValue(args->at(0));
4024 NumberToStringStub stub(isolate());
4026 context()->Plug(rax);
4030 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
4031 ZoneList<Expression*>* args = expr->arguments();
4032 DCHECK(args->length() == 1);
4034 VisitForAccumulatorValue(args->at(0));
4037 StringCharFromCodeGenerator generator(rax, rbx);
4038 generator.GenerateFast(masm_);
4041 NopRuntimeCallHelper call_helper;
4042 generator.GenerateSlow(masm_, call_helper);
4045 context()->Plug(rbx);
4049 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
4050 ZoneList<Expression*>* args = expr->arguments();
4051 DCHECK(args->length() == 2);
4053 VisitForStackValue(args->at(0));
4054 VisitForAccumulatorValue(args->at(1));
4056 Register object = rbx;
4057 Register index = rax;
4058 Register result = rdx;
4062 Label need_conversion;
4063 Label index_out_of_range;
4065 StringCharCodeAtGenerator generator(object,
4070 &index_out_of_range,
4071 STRING_INDEX_IS_NUMBER);
4072 generator.GenerateFast(masm_);
4075 __ bind(&index_out_of_range);
4076 // When the index is out of range, the spec requires us to return
4078 __ LoadRoot(result, Heap::kNanValueRootIndex);
4081 __ bind(&need_conversion);
4082 // Move the undefined value into the result register, which will
4083 // trigger conversion.
4084 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
4087 NopRuntimeCallHelper call_helper;
4088 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4091 context()->Plug(result);
4095 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
4096 ZoneList<Expression*>* args = expr->arguments();
4097 DCHECK(args->length() == 2);
4099 VisitForStackValue(args->at(0));
4100 VisitForAccumulatorValue(args->at(1));
4102 Register object = rbx;
4103 Register index = rax;
4104 Register scratch = rdx;
4105 Register result = rax;
4109 Label need_conversion;
4110 Label index_out_of_range;
4112 StringCharAtGenerator generator(object,
4118 &index_out_of_range,
4119 STRING_INDEX_IS_NUMBER);
4120 generator.GenerateFast(masm_);
4123 __ bind(&index_out_of_range);
4124 // When the index is out of range, the spec requires us to return
4125 // the empty string.
4126 __ LoadRoot(result, Heap::kempty_stringRootIndex);
4129 __ bind(&need_conversion);
4130 // Move smi zero into the result register, which will trigger
4132 __ Move(result, Smi::FromInt(0));
4135 NopRuntimeCallHelper call_helper;
4136 generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
4139 context()->Plug(result);
4143 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4144 ZoneList<Expression*>* args = expr->arguments();
4145 DCHECK_EQ(2, args->length());
4146 VisitForStackValue(args->at(0));
4147 VisitForAccumulatorValue(args->at(1));
4150 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4152 context()->Plug(rax);
4156 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
4157 ZoneList<Expression*>* args = expr->arguments();
4158 DCHECK_EQ(2, args->length());
4160 VisitForStackValue(args->at(0));
4161 VisitForStackValue(args->at(1));
4163 StringCompareStub stub(isolate());
4165 context()->Plug(rax);
4169 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4170 ZoneList<Expression*>* args = expr->arguments();
4171 DCHECK(args->length() >= 2);
4173 int arg_count = args->length() - 2; // 2 ~ receiver and function.
4174 for (int i = 0; i < arg_count + 1; i++) {
4175 VisitForStackValue(args->at(i));
4177 VisitForAccumulatorValue(args->last()); // Function.
4179 Label runtime, done;
4180 // Check for non-function argument (including proxy).
4181 __ JumpIfSmi(rax, &runtime);
4182 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx);
4183 __ j(not_equal, &runtime);
4185 // InvokeFunction requires the function in rdi. Move it in there.
4186 __ movp(rdi, result_register());
4187 ParameterCount count(arg_count);
4188 __ InvokeFunction(rdi, count, CALL_FUNCTION, NullCallWrapper());
4189 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4194 __ CallRuntime(Runtime::kCall, args->length());
4197 context()->Plug(rax);
4201 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4202 ZoneList<Expression*>* args = expr->arguments();
4203 DCHECK(args->length() == 2);
4206 VisitForStackValue(args->at(0));
4209 VisitForStackValue(args->at(1));
4210 __ CallRuntime(Runtime::kGetPrototype, 1);
4211 __ Push(result_register());
4213 // Load original constructor into rcx.
4214 __ movp(rcx, Operand(rsp, 1 * kPointerSize));
4216 // Check if the calling frame is an arguments adaptor frame.
4217 Label adaptor_frame, args_set_up, runtime;
4218 __ movp(rdx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
4219 __ movp(rbx, Operand(rdx, StandardFrameConstants::kContextOffset));
4220 __ Cmp(rbx, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
4221 __ j(equal, &adaptor_frame);
4222 // default constructor has no arguments, so no adaptor frame means no args.
4223 __ movp(rax, Immediate(0));
4224 __ jmp(&args_set_up);
4226 // Copy arguments from adaptor frame.
4228 __ bind(&adaptor_frame);
4229 __ movp(rbx, Operand(rdx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4230 __ SmiToInteger64(rbx, rbx);
4233 __ leap(rdx, Operand(rdx, rbx, times_pointer_size,
4234 StandardFrameConstants::kCallerSPOffset));
4237 __ Push(Operand(rdx, -1 * kPointerSize));
4238 __ subp(rdx, Immediate(kPointerSize));
4240 __ j(not_zero, &loop);
4243 __ bind(&args_set_up);
4244 __ movp(rdi, Operand(rsp, rax, times_pointer_size, 0));
4245 __ LoadRoot(rbx, Heap::kUndefinedValueRootIndex);
4247 CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4248 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4252 context()->Plug(result_register());
4256 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4257 RegExpConstructResultStub stub(isolate());
4258 ZoneList<Expression*>* args = expr->arguments();
4259 DCHECK(args->length() == 3);
4260 VisitForStackValue(args->at(0));
4261 VisitForStackValue(args->at(1));
4262 VisitForAccumulatorValue(args->at(2));
4266 context()->Plug(rax);
4270 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4271 ZoneList<Expression*>* args = expr->arguments();
4272 DCHECK_EQ(2, args->length());
4274 DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4275 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4277 Handle<FixedArray> jsfunction_result_caches(
4278 isolate()->native_context()->jsfunction_result_caches());
4279 if (jsfunction_result_caches->length() <= cache_id) {
4280 __ Abort(kAttemptToUseUndefinedCache);
4281 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
4282 context()->Plug(rax);
4286 VisitForAccumulatorValue(args->at(1));
4289 Register cache = rbx;
4291 __ movp(cache, ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX));
4293 FieldOperand(cache, GlobalObject::kNativeContextOffset));
4295 ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4297 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4299 Label done, not_found;
4300 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4301 __ movp(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4302 // tmp now holds finger offset as a smi.
4304 __ SmiToIndex(kScratchRegister, tmp, kPointerSizeLog2);
4305 __ cmpp(key, FieldOperand(cache,
4308 FixedArray::kHeaderSize));
4309 __ j(not_equal, ¬_found, Label::kNear);
4310 __ movp(rax, FieldOperand(cache,
4313 FixedArray::kHeaderSize + kPointerSize));
4314 __ jmp(&done, Label::kNear);
4316 __ bind(¬_found);
4317 // Call runtime to perform the lookup.
4320 __ CallRuntime(Runtime::kGetFromCacheRT, 2);
4323 context()->Plug(rax);
4327 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4328 ZoneList<Expression*>* args = expr->arguments();
4329 DCHECK(args->length() == 1);
4331 VisitForAccumulatorValue(args->at(0));
4333 Label materialize_true, materialize_false;
4334 Label* if_true = NULL;
4335 Label* if_false = NULL;
4336 Label* fall_through = NULL;
4337 context()->PrepareTest(&materialize_true, &materialize_false,
4338 &if_true, &if_false, &fall_through);
4340 __ testl(FieldOperand(rax, String::kHashFieldOffset),
4341 Immediate(String::kContainsCachedArrayIndexMask));
4342 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4343 __ j(zero, if_true);
4346 context()->Plug(if_true, if_false);
4350 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4351 ZoneList<Expression*>* args = expr->arguments();
4352 DCHECK(args->length() == 1);
4353 VisitForAccumulatorValue(args->at(0));
4355 __ AssertString(rax);
4357 __ movl(rax, FieldOperand(rax, String::kHashFieldOffset));
4358 DCHECK(String::kHashShift >= kSmiTagSize);
4359 __ IndexFromHash(rax, rax);
4361 context()->Plug(rax);
4365 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4366 Label bailout, return_result, done, one_char_separator, long_separator,
4367 non_trivial_array, not_size_one_array, loop,
4368 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4369 ZoneList<Expression*>* args = expr->arguments();
4370 DCHECK(args->length() == 2);
4371 // We will leave the separator on the stack until the end of the function.
4372 VisitForStackValue(args->at(1));
4373 // Load this to rax (= array)
4374 VisitForAccumulatorValue(args->at(0));
4375 // All aliases of the same register have disjoint lifetimes.
4376 Register array = rax;
4377 Register elements = no_reg; // Will be rax.
4379 Register index = rdx;
4381 Register string_length = rcx;
4383 Register string = rsi;
4385 Register scratch = rbx;
4387 Register array_length = rdi;
4388 Register result_pos = no_reg; // Will be rdi.
4390 Operand separator_operand = Operand(rsp, 2 * kPointerSize);
4391 Operand result_operand = Operand(rsp, 1 * kPointerSize);
4392 Operand array_length_operand = Operand(rsp, 0 * kPointerSize);
4393 // Separator operand is already pushed. Make room for the two
4394 // other stack fields, and clear the direction flag in anticipation
4395 // of calling CopyBytes.
4396 __ subp(rsp, Immediate(2 * kPointerSize));
4398 // Check that the array is a JSArray
4399 __ JumpIfSmi(array, &bailout);
4400 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4401 __ j(not_equal, &bailout);
4403 // Check that the array has fast elements.
4404 __ CheckFastElements(scratch, &bailout);
4406 // Array has fast elements, so its length must be a smi.
4407 // If the array has length zero, return the empty string.
4408 __ movp(array_length, FieldOperand(array, JSArray::kLengthOffset));
4409 __ SmiCompare(array_length, Smi::FromInt(0));
4410 __ j(not_zero, &non_trivial_array);
4411 __ LoadRoot(rax, Heap::kempty_stringRootIndex);
4412 __ jmp(&return_result);
4414 // Save the array length on the stack.
4415 __ bind(&non_trivial_array);
4416 __ SmiToInteger32(array_length, array_length);
4417 __ movl(array_length_operand, array_length);
4419 // Save the FixedArray containing array's elements.
4420 // End of array's live range.
4422 __ movp(elements, FieldOperand(array, JSArray::kElementsOffset));
4426 // Check that all array elements are sequential one-byte strings, and
4427 // accumulate the sum of their lengths, as a smi-encoded value.
4429 __ Set(string_length, 0);
4430 // Loop condition: while (index < array_length).
4431 // Live loop registers: index(int32), array_length(int32), string(String*),
4432 // scratch, string_length(int32), elements(FixedArray*).
4433 if (generate_debug_code_) {
4434 __ cmpp(index, array_length);
4435 __ Assert(below, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4438 __ movp(string, FieldOperand(elements,
4441 FixedArray::kHeaderSize));
4442 __ JumpIfSmi(string, &bailout);
4443 __ movp(scratch, FieldOperand(string, HeapObject::kMapOffset));
4444 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4445 __ andb(scratch, Immediate(
4446 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4447 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag));
4448 __ j(not_equal, &bailout);
4449 __ AddSmiField(string_length,
4450 FieldOperand(string, SeqOneByteString::kLengthOffset));
4451 __ j(overflow, &bailout);
4453 __ cmpl(index, array_length);
4457 // string_length: Sum of string lengths.
4458 // elements: FixedArray of strings.
4459 // index: Array length.
4460 // array_length: Array length.
4462 // If array_length is 1, return elements[0], a string.
4463 __ cmpl(array_length, Immediate(1));
4464 __ j(not_equal, ¬_size_one_array);
4465 __ movp(rax, FieldOperand(elements, FixedArray::kHeaderSize));
4466 __ jmp(&return_result);
4468 __ bind(¬_size_one_array);
4470 // End of array_length live range.
4471 result_pos = array_length;
4472 array_length = no_reg;
4475 // string_length: Sum of string lengths.
4476 // elements: FixedArray of strings.
4477 // index: Array length.
4479 // Check that the separator is a sequential one-byte string.
4480 __ movp(string, separator_operand);
4481 __ JumpIfSmi(string, &bailout);
4482 __ movp(scratch, FieldOperand(string, HeapObject::kMapOffset));
4483 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4484 __ andb(scratch, Immediate(
4485 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4486 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag));
4487 __ j(not_equal, &bailout);
4490 // string_length: Sum of string lengths.
4491 // elements: FixedArray of strings.
4492 // index: Array length.
4493 // string: Separator string.
4495 // Add (separator length times (array_length - 1)) to string_length.
4496 __ SmiToInteger32(scratch,
4497 FieldOperand(string, SeqOneByteString::kLengthOffset));
4499 __ imull(scratch, index);
4500 __ j(overflow, &bailout);
4501 __ addl(string_length, scratch);
4502 __ j(overflow, &bailout);
4504 // Live registers and stack values:
4505 // string_length: Total length of result string.
4506 // elements: FixedArray of strings.
4507 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4509 __ movp(result_operand, result_pos);
4510 __ leap(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4512 __ movp(string, separator_operand);
4513 __ SmiCompare(FieldOperand(string, SeqOneByteString::kLengthOffset),
4515 __ j(equal, &one_char_separator);
4516 __ j(greater, &long_separator);
4519 // Empty separator case:
4521 __ movl(scratch, array_length_operand);
4522 __ jmp(&loop_1_condition);
4523 // Loop condition: while (index < array_length).
4525 // Each iteration of the loop concatenates one string to the result.
4526 // Live values in registers:
4527 // index: which element of the elements array we are adding to the result.
4528 // result_pos: the position to which we are currently copying characters.
4529 // elements: the FixedArray of strings we are joining.
4530 // scratch: array length.
4532 // Get string = array[index].
4533 __ movp(string, FieldOperand(elements, index,
4535 FixedArray::kHeaderSize));
4536 __ SmiToInteger32(string_length,
4537 FieldOperand(string, String::kLengthOffset));
4539 FieldOperand(string, SeqOneByteString::kHeaderSize));
4540 __ CopyBytes(result_pos, string, string_length);
4542 __ bind(&loop_1_condition);
4543 __ cmpl(index, scratch);
4544 __ j(less, &loop_1); // Loop while (index < array_length).
4547 // Generic bailout code used from several places.
4549 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
4550 __ jmp(&return_result);
4553 // One-character separator case
4554 __ bind(&one_char_separator);
4555 // Get the separator one-byte character value.
4556 // Register "string" holds the separator.
4557 __ movzxbl(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4559 // Jump into the loop after the code that copies the separator, so the first
4560 // element is not preceded by a separator
4561 __ jmp(&loop_2_entry);
4562 // Loop condition: while (index < length).
4564 // Each iteration of the loop concatenates one string to the result.
4565 // Live values in registers:
4566 // elements: The FixedArray of strings we are joining.
4567 // index: which element of the elements array we are adding to the result.
4568 // result_pos: the position to which we are currently copying characters.
4569 // scratch: Separator character.
4571 // Copy the separator character to the result.
4572 __ movb(Operand(result_pos, 0), scratch);
4573 __ incp(result_pos);
4575 __ bind(&loop_2_entry);
4576 // Get string = array[index].
4577 __ movp(string, FieldOperand(elements, index,
4579 FixedArray::kHeaderSize));
4580 __ SmiToInteger32(string_length,
4581 FieldOperand(string, String::kLengthOffset));
4583 FieldOperand(string, SeqOneByteString::kHeaderSize));
4584 __ CopyBytes(result_pos, string, string_length);
4586 __ cmpl(index, array_length_operand);
4587 __ j(less, &loop_2); // End while (index < length).
4591 // Long separator case (separator is more than one character).
4592 __ bind(&long_separator);
4594 // Make elements point to end of elements array, and index
4595 // count from -array_length to zero, so we don't need to maintain
4597 __ movl(index, array_length_operand);
4598 __ leap(elements, FieldOperand(elements, index, times_pointer_size,
4599 FixedArray::kHeaderSize));
4602 // Replace separator string with pointer to its first character, and
4603 // make scratch be its length.
4604 __ movp(string, separator_operand);
4605 __ SmiToInteger32(scratch,
4606 FieldOperand(string, String::kLengthOffset));
4608 FieldOperand(string, SeqOneByteString::kHeaderSize));
4609 __ movp(separator_operand, string);
4611 // Jump into the loop after the code that copies the separator, so the first
4612 // element is not preceded by a separator
4613 __ jmp(&loop_3_entry);
4614 // Loop condition: while (index < length).
4616 // Each iteration of the loop concatenates one string to the result.
4617 // Live values in registers:
4618 // index: which element of the elements array we are adding to the result.
4619 // result_pos: the position to which we are currently copying characters.
4620 // scratch: Separator length.
4621 // separator_operand (rsp[0x10]): Address of first char of separator.
4623 // Copy the separator to the result.
4624 __ movp(string, separator_operand);
4625 __ movl(string_length, scratch);
4626 __ CopyBytes(result_pos, string, string_length, 2);
4628 __ bind(&loop_3_entry);
4629 // Get string = array[index].
4630 __ movp(string, Operand(elements, index, times_pointer_size, 0));
4631 __ SmiToInteger32(string_length,
4632 FieldOperand(string, String::kLengthOffset));
4634 FieldOperand(string, SeqOneByteString::kHeaderSize));
4635 __ CopyBytes(result_pos, string, string_length);
4637 __ j(not_equal, &loop_3); // Loop while (index < 0).
4640 __ movp(rax, result_operand);
4642 __ bind(&return_result);
4643 // Drop temp values from the stack, and restore context register.
4644 __ addp(rsp, Immediate(3 * kPointerSize));
4645 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4646 context()->Plug(rax);
4650 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4651 DCHECK(expr->arguments()->length() == 0);
4652 ExternalReference debug_is_active =
4653 ExternalReference::debug_is_active_address(isolate());
4654 __ Move(kScratchRegister, debug_is_active);
4655 __ movzxbp(rax, Operand(kScratchRegister, 0));
4656 __ Integer32ToSmi(rax, rax);
4657 context()->Plug(rax);
4661 void FullCodeGenerator::EmitCallSuperWithSpread(CallRuntime* expr) {
4662 // Assert: expr === CallRuntime("ReflectConstruct")
4663 DCHECK_EQ(1, expr->arguments()->length());
4664 CallRuntime* call = expr->arguments()->at(0)->AsCallRuntime();
4666 ZoneList<Expression*>* args = call->arguments();
4667 DCHECK_EQ(3, args->length());
4669 SuperCallReference* super_call_ref = args->at(0)->AsSuperCallReference();
4670 DCHECK_NOT_NULL(super_call_ref);
4672 // Load ReflectConstruct function
4673 EmitLoadJSRuntimeFunction(call);
4675 // Push the target function under the receiver.
4676 __ Push(Operand(rsp, 0));
4677 __ movp(Operand(rsp, kPointerSize), rax);
4679 // Push super constructor
4680 EmitLoadSuperConstructor(super_call_ref);
4681 __ Push(result_register());
4683 // Push arguments array
4684 VisitForStackValue(args->at(1));
4687 DCHECK(args->at(2)->IsVariableProxy());
4688 VisitForStackValue(args->at(2));
4690 EmitCallJSRuntimeFunction(call);
4692 // Restore context register.
4693 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4694 context()->DropAndPlug(1, rax);
4696 // TODO(mvstanton): with FLAG_vector_stores this needs a slot id.
4697 EmitInitializeThisAfterSuper(super_call_ref);
4701 void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
4702 // Push the builtins object as receiver.
4703 __ movp(rax, GlobalObjectOperand());
4704 __ Push(FieldOperand(rax, GlobalObject::kBuiltinsOffset));
4706 // Load the function from the receiver.
4707 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
4708 __ Move(LoadDescriptor::NameRegister(), expr->name());
4709 __ Move(LoadDescriptor::SlotRegister(),
4710 SmiFromSlot(expr->CallRuntimeFeedbackSlot()));
4711 CallLoadIC(NOT_INSIDE_TYPEOF);
4715 void FullCodeGenerator::EmitCallJSRuntimeFunction(CallRuntime* expr) {
4716 ZoneList<Expression*>* args = expr->arguments();
4717 int arg_count = args->length();
4719 SetCallPosition(expr, arg_count);
4720 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4721 __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
4726 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4727 ZoneList<Expression*>* args = expr->arguments();
4728 int arg_count = args->length();
4730 if (expr->is_jsruntime()) {
4731 Comment cmnt(masm_, "[ CallRuntime");
4733 EmitLoadJSRuntimeFunction(expr);
4735 // Push the target function under the receiver.
4736 __ Push(Operand(rsp, 0));
4737 __ movp(Operand(rsp, kPointerSize), rax);
4739 // Push the arguments ("left-to-right").
4740 for (int i = 0; i < arg_count; i++) {
4741 VisitForStackValue(args->at(i));
4744 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4745 EmitCallJSRuntimeFunction(expr);
4747 // Restore context register.
4748 __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4749 context()->DropAndPlug(1, rax);
4752 const Runtime::Function* function = expr->function();
4753 switch (function->function_id) {
4754 #define CALL_INTRINSIC_GENERATOR(Name) \
4755 case Runtime::kInline##Name: { \
4756 Comment cmnt(masm_, "[ Inline" #Name); \
4757 return Emit##Name(expr); \
4759 FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
4760 #undef CALL_INTRINSIC_GENERATOR
4762 Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
4763 // Push the arguments ("left-to-right").
4764 for (int i = 0; i < arg_count; i++) {
4765 VisitForStackValue(args->at(i));
4768 // Call the C runtime.
4769 PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4770 __ CallRuntime(function, arg_count);
4771 context()->Plug(rax);
4778 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4779 switch (expr->op()) {
4780 case Token::DELETE: {
4781 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4782 Property* property = expr->expression()->AsProperty();
4783 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4785 if (property != NULL) {
4786 VisitForStackValue(property->obj());
4787 VisitForStackValue(property->key());
4788 __ Push(Smi::FromInt(language_mode()));
4789 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4790 context()->Plug(rax);
4791 } else if (proxy != NULL) {
4792 Variable* var = proxy->var();
4793 // Delete of an unqualified identifier is disallowed in strict mode but
4794 // "delete this" is allowed.
4795 bool is_this = var->HasThisName(isolate());
4796 DCHECK(is_sloppy(language_mode()) || is_this);
4797 if (var->IsUnallocatedOrGlobalSlot()) {
4798 __ Push(GlobalObjectOperand());
4799 __ Push(var->name());
4800 __ Push(Smi::FromInt(SLOPPY));
4801 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4802 context()->Plug(rax);
4803 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4804 // Result of deleting non-global variables is false. 'this' is
4805 // not really a variable, though we implement it as one. The
4806 // subexpression does not have side effects.
4807 context()->Plug(is_this);
4809 // Non-global variable. Call the runtime to try to delete from the
4810 // context where the variable was introduced.
4811 __ Push(context_register());
4812 __ Push(var->name());
4813 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4814 context()->Plug(rax);
4817 // Result of deleting non-property, non-variable reference is true.
4818 // The subexpression may have side effects.
4819 VisitForEffect(expr->expression());
4820 context()->Plug(true);
4826 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4827 VisitForEffect(expr->expression());
4828 context()->Plug(Heap::kUndefinedValueRootIndex);
4833 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4834 if (context()->IsEffect()) {
4835 // Unary NOT has no side effects so it's only necessary to visit the
4836 // subexpression. Match the optimizing compiler by not branching.
4837 VisitForEffect(expr->expression());
4838 } else if (context()->IsTest()) {
4839 const TestContext* test = TestContext::cast(context());
4840 // The labels are swapped for the recursive call.
4841 VisitForControl(expr->expression(),
4842 test->false_label(),
4844 test->fall_through());
4845 context()->Plug(test->true_label(), test->false_label());
4847 // We handle value contexts explicitly rather than simply visiting
4848 // for control and plugging the control flow into the context,
4849 // because we need to prepare a pair of extra administrative AST ids
4850 // for the optimizing compiler.
4851 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4852 Label materialize_true, materialize_false, done;
4853 VisitForControl(expr->expression(),
4857 __ bind(&materialize_true);
4858 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4859 if (context()->IsAccumulatorValue()) {
4860 __ LoadRoot(rax, Heap::kTrueValueRootIndex);
4862 __ PushRoot(Heap::kTrueValueRootIndex);
4864 __ jmp(&done, Label::kNear);
4865 __ bind(&materialize_false);
4866 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4867 if (context()->IsAccumulatorValue()) {
4868 __ LoadRoot(rax, Heap::kFalseValueRootIndex);
4870 __ PushRoot(Heap::kFalseValueRootIndex);
4877 case Token::TYPEOF: {
4878 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4880 AccumulatorValueContext context(this);
4881 VisitForTypeofValue(expr->expression());
4884 TypeofStub typeof_stub(isolate());
4885 __ CallStub(&typeof_stub);
4886 context()->Plug(rax);
4896 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4897 DCHECK(expr->expression()->IsValidReferenceExpression());
4899 Comment cmnt(masm_, "[ CountOperation");
4901 Property* prop = expr->expression()->AsProperty();
4902 LhsKind assign_type = Property::GetAssignType(prop);
4904 // Evaluate expression and get value.
4905 if (assign_type == VARIABLE) {
4906 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4907 AccumulatorValueContext context(this);
4908 EmitVariableLoad(expr->expression()->AsVariableProxy());
4910 // Reserve space for result of postfix operation.
4911 if (expr->is_postfix() && !context()->IsEffect()) {
4912 __ Push(Smi::FromInt(0));
4914 switch (assign_type) {
4915 case NAMED_PROPERTY: {
4916 VisitForStackValue(prop->obj());
4917 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
4918 EmitNamedPropertyLoad(prop);
4922 case NAMED_SUPER_PROPERTY: {
4923 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4924 VisitForAccumulatorValue(
4925 prop->obj()->AsSuperPropertyReference()->home_object());
4926 __ Push(result_register());
4927 __ Push(MemOperand(rsp, kPointerSize));
4928 __ Push(result_register());
4929 EmitNamedSuperPropertyLoad(prop);
4933 case KEYED_SUPER_PROPERTY: {
4934 VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4936 prop->obj()->AsSuperPropertyReference()->home_object());
4937 VisitForAccumulatorValue(prop->key());
4938 __ Push(result_register());
4939 __ Push(MemOperand(rsp, 2 * kPointerSize));
4940 __ Push(MemOperand(rsp, 2 * kPointerSize));
4941 __ Push(result_register());
4942 EmitKeyedSuperPropertyLoad(prop);
4946 case KEYED_PROPERTY: {
4947 VisitForStackValue(prop->obj());
4948 VisitForStackValue(prop->key());
4949 // Leave receiver on stack
4950 __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
4951 // Copy of key, needed for later store.
4952 __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
4953 EmitKeyedPropertyLoad(prop);
4962 // We need a second deoptimization point after loading the value
4963 // in case evaluating the property load my have a side effect.
4964 if (assign_type == VARIABLE) {
4965 PrepareForBailout(expr->expression(), TOS_REG);
4967 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4970 // Inline smi case if we are in a loop.
4971 Label done, stub_call;
4972 JumpPatchSite patch_site(masm_);
4973 if (ShouldInlineSmiCase(expr->op())) {
4975 patch_site.EmitJumpIfNotSmi(rax, &slow, Label::kNear);
4977 // Save result for postfix expressions.
4978 if (expr->is_postfix()) {
4979 if (!context()->IsEffect()) {
4980 // Save the result on the stack. If we have a named or keyed property
4981 // we store the result under the receiver that is currently on top
4983 switch (assign_type) {
4987 case NAMED_PROPERTY:
4988 __ movp(Operand(rsp, kPointerSize), rax);
4990 case NAMED_SUPER_PROPERTY:
4991 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4993 case KEYED_PROPERTY:
4994 __ movp(Operand(rsp, 2 * kPointerSize), rax);
4996 case KEYED_SUPER_PROPERTY:
4997 __ movp(Operand(rsp, 3 * kPointerSize), rax);
5003 SmiOperationConstraints constraints =
5004 SmiOperationConstraint::kPreserveSourceRegister |
5005 SmiOperationConstraint::kBailoutOnNoOverflow;
5006 if (expr->op() == Token::INC) {
5007 __ SmiAddConstant(rax, rax, Smi::FromInt(1), constraints, &done,
5010 __ SmiSubConstant(rax, rax, Smi::FromInt(1), constraints, &done,
5013 __ jmp(&stub_call, Label::kNear);
5016 if (!is_strong(language_mode())) {
5017 ToNumberStub convert_stub(isolate());
5018 __ CallStub(&convert_stub);
5019 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
5022 // Save result for postfix expressions.
5023 if (expr->is_postfix()) {
5024 if (!context()->IsEffect()) {
5025 // Save the result on the stack. If we have a named or keyed property
5026 // we store the result under the receiver that is currently on top
5028 switch (assign_type) {
5032 case NAMED_PROPERTY:
5033 __ movp(Operand(rsp, kPointerSize), rax);
5035 case NAMED_SUPER_PROPERTY:
5036 __ movp(Operand(rsp, 2 * kPointerSize), rax);
5038 case KEYED_PROPERTY:
5039 __ movp(Operand(rsp, 2 * kPointerSize), rax);
5041 case KEYED_SUPER_PROPERTY:
5042 __ movp(Operand(rsp, 3 * kPointerSize), rax);
5048 SetExpressionPosition(expr);
5050 // Call stub for +1/-1.
5051 __ bind(&stub_call);
5053 __ Move(rax, Smi::FromInt(1));
5054 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
5055 strength(language_mode())).code();
5056 CallIC(code, expr->CountBinOpFeedbackId());
5057 patch_site.EmitPatchInfo();
5060 if (is_strong(language_mode())) {
5061 PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
5063 // Store the value returned in rax.
5064 switch (assign_type) {
5066 if (expr->is_postfix()) {
5067 // Perform the assignment as if via '='.
5068 { EffectContext context(this);
5069 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
5070 Token::ASSIGN, expr->CountSlot());
5071 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
5074 // For all contexts except kEffect: We have the result on
5075 // top of the stack.
5076 if (!context()->IsEffect()) {
5077 context()->PlugTOS();
5080 // Perform the assignment as if via '='.
5081 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
5082 Token::ASSIGN, expr->CountSlot());
5083 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
5084 context()->Plug(rax);
5087 case NAMED_PROPERTY: {
5088 __ Move(StoreDescriptor::NameRegister(),
5089 prop->key()->AsLiteral()->value());
5090 __ Pop(StoreDescriptor::ReceiverRegister());
5091 if (FLAG_vector_stores) {
5092 EmitLoadStoreICSlot(expr->CountSlot());
5095 CallStoreIC(expr->CountStoreFeedbackId());
5097 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
5098 if (expr->is_postfix()) {
5099 if (!context()->IsEffect()) {
5100 context()->PlugTOS();
5103 context()->Plug(rax);
5107 case NAMED_SUPER_PROPERTY: {
5108 EmitNamedSuperPropertyStore(prop);
5109 if (expr->is_postfix()) {
5110 if (!context()->IsEffect()) {
5111 context()->PlugTOS();
5114 context()->Plug(rax);
5118 case KEYED_SUPER_PROPERTY: {
5119 EmitKeyedSuperPropertyStore(prop);
5120 if (expr->is_postfix()) {
5121 if (!context()->IsEffect()) {
5122 context()->PlugTOS();
5125 context()->Plug(rax);
5129 case KEYED_PROPERTY: {
5130 __ Pop(StoreDescriptor::NameRegister());
5131 __ Pop(StoreDescriptor::ReceiverRegister());
5133 CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
5134 if (FLAG_vector_stores) {
5135 EmitLoadStoreICSlot(expr->CountSlot());
5138 CallIC(ic, expr->CountStoreFeedbackId());
5140 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
5141 if (expr->is_postfix()) {
5142 if (!context()->IsEffect()) {
5143 context()->PlugTOS();
5146 context()->Plug(rax);
5154 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
5155 Expression* sub_expr,
5156 Handle<String> check) {
5157 Label materialize_true, materialize_false;
5158 Label* if_true = NULL;
5159 Label* if_false = NULL;
5160 Label* fall_through = NULL;
5161 context()->PrepareTest(&materialize_true, &materialize_false,
5162 &if_true, &if_false, &fall_through);
5164 { AccumulatorValueContext context(this);
5165 VisitForTypeofValue(sub_expr);
5167 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5169 Factory* factory = isolate()->factory();
5170 if (String::Equals(check, factory->number_string())) {
5171 __ JumpIfSmi(rax, if_true);
5172 __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
5173 __ CompareRoot(rax, Heap::kHeapNumberMapRootIndex);
5174 Split(equal, if_true, if_false, fall_through);
5175 } else if (String::Equals(check, factory->string_string())) {
5176 __ JumpIfSmi(rax, if_false);
5177 // Check for undetectable objects => false.
5178 __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, rdx);
5179 __ j(above_equal, if_false);
5180 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
5181 Immediate(1 << Map::kIsUndetectable));
5182 Split(zero, if_true, if_false, fall_through);
5183 } else if (String::Equals(check, factory->symbol_string())) {
5184 __ JumpIfSmi(rax, if_false);
5185 __ CmpObjectType(rax, SYMBOL_TYPE, rdx);
5186 Split(equal, if_true, if_false, fall_through);
5187 } else if (String::Equals(check, factory->float32x4_string())) {
5188 __ JumpIfSmi(rax, if_false);
5189 __ CmpObjectType(rax, FLOAT32X4_TYPE, rdx);
5190 Split(equal, if_true, if_false, fall_through);
5191 } else if (String::Equals(check, factory->boolean_string())) {
5192 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
5193 __ j(equal, if_true);
5194 __ CompareRoot(rax, Heap::kFalseValueRootIndex);
5195 Split(equal, if_true, if_false, fall_through);
5196 } else if (String::Equals(check, factory->undefined_string())) {
5197 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
5198 __ j(equal, if_true);
5199 __ JumpIfSmi(rax, if_false);
5200 // Check for undetectable objects => true.
5201 __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
5202 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
5203 Immediate(1 << Map::kIsUndetectable));
5204 Split(not_zero, if_true, if_false, fall_through);
5205 } else if (String::Equals(check, factory->function_string())) {
5206 __ JumpIfSmi(rax, if_false);
5207 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5208 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rdx);
5209 __ j(equal, if_true);
5210 __ CmpInstanceType(rdx, JS_FUNCTION_PROXY_TYPE);
5211 Split(equal, if_true, if_false, fall_through);
5212 } else if (String::Equals(check, factory->object_string())) {
5213 __ JumpIfSmi(rax, if_false);
5214 __ CompareRoot(rax, Heap::kNullValueRootIndex);
5215 __ j(equal, if_true);
5216 __ CmpObjectType(rax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, rdx);
5217 __ j(below, if_false);
5218 __ CmpInstanceType(rdx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5219 __ j(above, if_false);
5220 // Check for undetectable objects => false.
5221 __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
5222 Immediate(1 << Map::kIsUndetectable));
5223 Split(zero, if_true, if_false, fall_through);
5225 if (if_false != fall_through) __ jmp(if_false);
5227 context()->Plug(if_true, if_false);
5231 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5232 Comment cmnt(masm_, "[ CompareOperation");
5233 SetExpressionPosition(expr);
5235 // First we try a fast inlined version of the compare when one of
5236 // the operands is a literal.
5237 if (TryLiteralCompare(expr)) return;
5239 // Always perform the comparison for its control flow. Pack the result
5240 // into the expression's context after the comparison is performed.
5241 Label materialize_true, materialize_false;
5242 Label* if_true = NULL;
5243 Label* if_false = NULL;
5244 Label* fall_through = NULL;
5245 context()->PrepareTest(&materialize_true, &materialize_false,
5246 &if_true, &if_false, &fall_through);
5248 Token::Value op = expr->op();
5249 VisitForStackValue(expr->left());
5252 VisitForStackValue(expr->right());
5253 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5254 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5255 __ CompareRoot(rax, Heap::kTrueValueRootIndex);
5256 Split(equal, if_true, if_false, fall_through);
5259 case Token::INSTANCEOF: {
5260 VisitForStackValue(expr->right());
5261 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5263 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5265 // The stub returns 0 for true.
5266 Split(zero, if_true, if_false, fall_through);
5271 VisitForAccumulatorValue(expr->right());
5272 Condition cc = CompareIC::ComputeCondition(op);
5275 bool inline_smi_code = ShouldInlineSmiCase(op);
5276 JumpPatchSite patch_site(masm_);
5277 if (inline_smi_code) {
5281 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
5283 Split(cc, if_true, if_false, NULL);
5284 __ bind(&slow_case);
5287 Handle<Code> ic = CodeFactory::CompareIC(
5288 isolate(), op, strength(language_mode())).code();
5289 CallIC(ic, expr->CompareOperationFeedbackId());
5290 patch_site.EmitPatchInfo();
5292 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5294 Split(cc, if_true, if_false, fall_through);
5298 // Convert the result of the comparison into one expected for this
5299 // expression's context.
5300 context()->Plug(if_true, if_false);
5304 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5305 Expression* sub_expr,
5307 Label materialize_true, materialize_false;
5308 Label* if_true = NULL;
5309 Label* if_false = NULL;
5310 Label* fall_through = NULL;
5311 context()->PrepareTest(&materialize_true, &materialize_false,
5312 &if_true, &if_false, &fall_through);
5314 VisitForAccumulatorValue(sub_expr);
5315 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5316 if (expr->op() == Token::EQ_STRICT) {
5317 Heap::RootListIndex nil_value = nil == kNullValue ?
5318 Heap::kNullValueRootIndex :
5319 Heap::kUndefinedValueRootIndex;
5320 __ CompareRoot(rax, nil_value);
5321 Split(equal, if_true, if_false, fall_through);
5323 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5324 CallIC(ic, expr->CompareOperationFeedbackId());
5326 Split(not_zero, if_true, if_false, fall_through);
5328 context()->Plug(if_true, if_false);
5332 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5333 __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
5334 context()->Plug(rax);
5338 Register FullCodeGenerator::result_register() {
5343 Register FullCodeGenerator::context_register() {
5348 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5349 DCHECK(IsAligned(frame_offset, kPointerSize));
5350 __ movp(Operand(rbp, frame_offset), value);
5354 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5355 __ movp(dst, ContextOperand(rsi, context_index));
5359 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5360 Scope* declaration_scope = scope()->DeclarationScope();
5361 if (declaration_scope->is_script_scope() ||
5362 declaration_scope->is_module_scope()) {
5363 // Contexts nested in the native context have a canonical empty function
5364 // as their closure, not the anonymous closure containing the global
5365 // code. Pass a smi sentinel and let the runtime look up the empty
5367 __ Push(Smi::FromInt(0));
5368 } else if (declaration_scope->is_eval_scope()) {
5369 // Contexts created by a call to eval have the same closure as the
5370 // context calling eval, not the anonymous closure containing the eval
5371 // code. Fetch it from the context.
5372 __ Push(ContextOperand(rsi, Context::CLOSURE_INDEX));
5374 DCHECK(declaration_scope->is_function_scope());
5375 __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
5380 // ----------------------------------------------------------------------------
5381 // Non-local control flow support.
5384 void FullCodeGenerator::EnterFinallyBlock() {
5385 DCHECK(!result_register().is(rdx));
5386 DCHECK(!result_register().is(rcx));
5387 // Cook return address on top of stack (smi encoded Code* delta)
5388 __ PopReturnAddressTo(rdx);
5389 __ Move(rcx, masm_->CodeObject());
5391 __ Integer32ToSmi(rdx, rdx);
5394 // Store result register while executing finally block.
5395 __ Push(result_register());
5397 // Store pending message while executing finally block.
5398 ExternalReference pending_message_obj =
5399 ExternalReference::address_of_pending_message_obj(isolate());
5400 __ Load(rdx, pending_message_obj);
5403 ClearPendingMessage();
5407 void FullCodeGenerator::ExitFinallyBlock() {
5408 DCHECK(!result_register().is(rdx));
5409 DCHECK(!result_register().is(rcx));
5410 // Restore pending message from stack.
5412 ExternalReference pending_message_obj =
5413 ExternalReference::address_of_pending_message_obj(isolate());
5414 __ Store(pending_message_obj, rdx);
5416 // Restore result register from stack.
5417 __ Pop(result_register());
5419 // Uncook return address.
5421 __ SmiToInteger32(rdx, rdx);
5422 __ Move(rcx, masm_->CodeObject());
5428 void FullCodeGenerator::ClearPendingMessage() {
5429 DCHECK(!result_register().is(rdx));
5430 ExternalReference pending_message_obj =
5431 ExternalReference::address_of_pending_message_obj(isolate());
5432 __ LoadRoot(rdx, Heap::kTheHoleValueRootIndex);
5433 __ Store(pending_message_obj, rdx);
5437 void FullCodeGenerator::EmitLoadStoreICSlot(FeedbackVectorICSlot slot) {
5438 DCHECK(FLAG_vector_stores && !slot.IsInvalid());
5439 __ Move(VectorStoreICTrampolineDescriptor::SlotRegister(), SmiFromSlot(slot));
5446 static const byte kJnsInstruction = 0x79;
5447 static const byte kNopByteOne = 0x66;
5448 static const byte kNopByteTwo = 0x90;
5450 static const byte kCallInstruction = 0xe8;
5454 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5456 BackEdgeState target_state,
5457 Code* replacement_code) {
5458 Address call_target_address = pc - kIntSize;
5459 Address jns_instr_address = call_target_address - 3;
5460 Address jns_offset_address = call_target_address - 2;
5462 switch (target_state) {
5464 // sub <profiling_counter>, <delta> ;; Not changed
5466 // call <interrupt stub>
5468 *jns_instr_address = kJnsInstruction;
5469 *jns_offset_address = kJnsOffset;
5471 case ON_STACK_REPLACEMENT:
5472 case OSR_AFTER_STACK_CHECK:
5473 // sub <profiling_counter>, <delta> ;; Not changed
5476 // call <on-stack replacment>
5478 *jns_instr_address = kNopByteOne;
5479 *jns_offset_address = kNopByteTwo;
5483 Assembler::set_target_address_at(call_target_address,
5485 replacement_code->entry());
5486 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5487 unoptimized_code, call_target_address, replacement_code);
5491 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5493 Code* unoptimized_code,
5495 Address call_target_address = pc - kIntSize;
5496 Address jns_instr_address = call_target_address - 3;
5497 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5499 if (*jns_instr_address == kJnsInstruction) {
5500 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5501 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5502 Assembler::target_address_at(call_target_address,
5507 DCHECK_EQ(kNopByteOne, *jns_instr_address);
5508 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5510 if (Assembler::target_address_at(call_target_address,
5511 unoptimized_code) ==
5512 isolate->builtins()->OnStackReplacement()->entry()) {
5513 return ON_STACK_REPLACEMENT;
5516 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5517 Assembler::target_address_at(call_target_address,
5519 return OSR_AFTER_STACK_CHECK;
5523 } // namespace internal
5526 #endif // V8_TARGET_ARCH_X64