1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #if V8_TARGET_ARCH_IA32
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/isolate-inl.h"
17 #include "src/parser.h"
18 #include "src/scopes.h"
23 #define __ ACCESS_MASM(masm_)
26 class JumpPatchSite BASE_EMBEDDED {
28 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
30 info_emitted_ = false;
35 DCHECK(patch_site_.is_bound() == info_emitted_);
38 void EmitJumpIfNotSmi(Register reg,
40 Label::Distance distance = Label::kFar) {
41 __ test(reg, Immediate(kSmiTagMask));
42 EmitJump(not_carry, target, distance); // Always taken before patched.
45 void EmitJumpIfSmi(Register reg,
47 Label::Distance distance = Label::kFar) {
48 __ test(reg, Immediate(kSmiTagMask));
49 EmitJump(carry, target, distance); // Never taken before patched.
52 void EmitPatchInfo() {
53 if (patch_site_.is_bound()) {
54 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
55 DCHECK(is_uint8(delta_to_patch_site));
56 __ test(eax, Immediate(delta_to_patch_site));
61 __ nop(); // Signals no inlined code.
66 // jc will be patched with jz, jnc will become jnz.
67 void EmitJump(Condition cc, Label* target, Label::Distance distance) {
68 DCHECK(!patch_site_.is_bound() && !info_emitted_);
69 DCHECK(cc == carry || cc == not_carry);
70 __ bind(&patch_site_);
71 __ j(cc, target, distance);
74 MacroAssembler* masm_;
82 // Generate code for a JS function. On entry to the function the receiver
83 // and arguments have been pushed on the stack left to right, with the
84 // return address on top of them. The actual argument count matches the
85 // formal parameter count expected by the function.
87 // The live registers are:
88 // o edi: the JS function object being called (i.e. ourselves)
90 // o ebp: our caller's frame pointer
91 // o esp: stack pointer (pointing to return address)
93 // The function builds a JS frame. Please see JavaScriptFrameConstants in
94 // frames-ia32.h for its layout.
95 void FullCodeGenerator::Generate() {
96 CompilationInfo* info = info_;
98 isolate()->factory()->NewFixedArray(function()->handler_count(), TENURED);
100 profiling_counter_ = isolate()->factory()->NewCell(
101 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
102 SetFunctionPosition(function());
103 Comment cmnt(masm_, "[ function compiled by full code generator");
105 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
108 if (strlen(FLAG_stop_at) > 0 &&
109 info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
114 // Sloppy mode functions and builtins need to replace the receiver with the
115 // global proxy when called as functions (without an explicit receiver
117 if (info->strict_mode() == SLOPPY && !info->is_native()) {
119 // +1 for return address.
120 int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
121 __ mov(ecx, Operand(esp, receiver_offset));
123 __ cmp(ecx, isolate()->factory()->undefined_value());
124 __ j(not_equal, &ok, Label::kNear);
126 __ mov(ecx, GlobalObjectOperand());
127 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
129 __ mov(Operand(esp, receiver_offset), ecx);
134 // Open a frame scope to indicate that there is a frame on the stack. The
135 // MANUAL indicates that the scope shouldn't actually generate code to set up
136 // the frame (that is done below).
137 FrameScope frame_scope(masm_, StackFrame::MANUAL);
139 info->set_prologue_offset(masm_->pc_offset());
140 __ Prologue(info->IsCodePreAgingActive());
141 info->AddNoFrameRange(0, masm_->pc_offset());
143 { Comment cmnt(masm_, "[ Allocate locals");
144 int locals_count = info->scope()->num_stack_slots();
145 // Generators allocate locals, if any, in context slots.
146 DCHECK(!info->function()->is_generator() || locals_count == 0);
147 if (locals_count == 1) {
148 __ push(Immediate(isolate()->factory()->undefined_value()));
149 } else if (locals_count > 1) {
150 if (locals_count >= 128) {
153 __ sub(ecx, Immediate(locals_count * kPointerSize));
154 ExternalReference stack_limit =
155 ExternalReference::address_of_real_stack_limit(isolate());
156 __ cmp(ecx, Operand::StaticVariable(stack_limit));
157 __ j(above_equal, &ok, Label::kNear);
158 __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
161 __ mov(eax, Immediate(isolate()->factory()->undefined_value()));
162 const int kMaxPushes = 32;
163 if (locals_count >= kMaxPushes) {
164 int loop_iterations = locals_count / kMaxPushes;
165 __ mov(ecx, loop_iterations);
167 __ bind(&loop_header);
169 for (int i = 0; i < kMaxPushes; i++) {
173 __ j(not_zero, &loop_header, Label::kNear);
175 int remaining = locals_count % kMaxPushes;
176 // Emit the remaining pushes.
177 for (int i = 0; i < remaining; i++) {
183 bool function_in_register = true;
185 // Possibly allocate a local context.
186 int heap_slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
187 if (heap_slots > 0) {
188 Comment cmnt(masm_, "[ Allocate context");
189 bool need_write_barrier = true;
190 // Argument to NewContext is the function, which is still in edi.
191 if (FLAG_harmony_scoping && info->scope()->is_global_scope()) {
193 __ Push(info->scope()->GetScopeInfo());
194 __ CallRuntime(Runtime::kNewGlobalContext, 2);
195 } else if (heap_slots <= FastNewContextStub::kMaximumSlots) {
196 FastNewContextStub stub(isolate(), heap_slots);
198 // Result of FastNewContextStub is always in new space.
199 need_write_barrier = false;
202 __ CallRuntime(Runtime::kNewFunctionContext, 1);
204 function_in_register = false;
205 // Context is returned in eax. It replaces the context passed to us.
206 // It's saved in the stack and kept live in esi.
208 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
210 // Copy parameters into context if necessary.
211 int num_parameters = info->scope()->num_parameters();
212 for (int i = 0; i < num_parameters; i++) {
213 Variable* var = scope()->parameter(i);
214 if (var->IsContextSlot()) {
215 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
216 (num_parameters - 1 - i) * kPointerSize;
217 // Load parameter from stack.
218 __ mov(eax, Operand(ebp, parameter_offset));
219 // Store it in the context.
220 int context_offset = Context::SlotOffset(var->index());
221 __ mov(Operand(esi, context_offset), eax);
222 // Update the write barrier. This clobbers eax and ebx.
223 if (need_write_barrier) {
224 __ RecordWriteContextSlot(esi,
229 } else if (FLAG_debug_code) {
231 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
232 __ Abort(kExpectedNewSpaceObject);
239 Variable* arguments = scope()->arguments();
240 if (arguments != NULL) {
241 // Function uses arguments object.
242 Comment cmnt(masm_, "[ Allocate arguments object");
243 if (function_in_register) {
246 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
248 // Receiver is just before the parameters on the caller's stack.
249 int num_parameters = info->scope()->num_parameters();
250 int offset = num_parameters * kPointerSize;
252 Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
254 __ push(Immediate(Smi::FromInt(num_parameters)));
255 // Arguments to ArgumentsAccessStub:
256 // function, receiver address, parameter count.
257 // The stub will rewrite receiver and parameter count if the previous
258 // stack frame was an arguments adapter frame.
259 ArgumentsAccessStub::Type type;
260 if (strict_mode() == STRICT) {
261 type = ArgumentsAccessStub::NEW_STRICT;
262 } else if (function()->has_duplicate_parameters()) {
263 type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
265 type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
267 ArgumentsAccessStub stub(isolate(), type);
270 SetVar(arguments, eax, ebx, edx);
274 __ CallRuntime(Runtime::kTraceEnter, 0);
277 // Visit the declarations and body unless there is an illegal
279 if (scope()->HasIllegalRedeclaration()) {
280 Comment cmnt(masm_, "[ Declarations");
281 scope()->VisitIllegalRedeclaration(this);
284 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
285 { Comment cmnt(masm_, "[ Declarations");
286 // For named function expressions, declare the function name as a
288 if (scope()->is_function_scope() && scope()->function() != NULL) {
289 VariableDeclaration* function = scope()->function();
290 DCHECK(function->proxy()->var()->mode() == CONST ||
291 function->proxy()->var()->mode() == CONST_LEGACY);
292 DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
293 VisitVariableDeclaration(function);
295 VisitDeclarations(scope()->declarations());
298 { Comment cmnt(masm_, "[ Stack check");
299 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
301 ExternalReference stack_limit
302 = ExternalReference::address_of_stack_limit(isolate());
303 __ cmp(esp, Operand::StaticVariable(stack_limit));
304 __ j(above_equal, &ok, Label::kNear);
305 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
309 { Comment cmnt(masm_, "[ Body");
310 DCHECK(loop_depth() == 0);
311 VisitStatements(function()->body());
312 DCHECK(loop_depth() == 0);
316 // Always emit a 'return undefined' in case control fell off the end of
318 { Comment cmnt(masm_, "[ return <undefined>;");
319 __ mov(eax, isolate()->factory()->undefined_value());
320 EmitReturnSequence();
325 void FullCodeGenerator::ClearAccumulator() {
326 __ Move(eax, Immediate(Smi::FromInt(0)));
330 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
331 __ mov(ebx, Immediate(profiling_counter_));
332 __ sub(FieldOperand(ebx, Cell::kValueOffset),
333 Immediate(Smi::FromInt(delta)));
337 void FullCodeGenerator::EmitProfilingCounterReset() {
338 int reset_value = FLAG_interrupt_budget;
339 __ mov(ebx, Immediate(profiling_counter_));
340 __ mov(FieldOperand(ebx, Cell::kValueOffset),
341 Immediate(Smi::FromInt(reset_value)));
345 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
346 Label* back_edge_target) {
347 Comment cmnt(masm_, "[ Back edge bookkeeping");
350 DCHECK(back_edge_target->is_bound());
351 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
352 int weight = Min(kMaxBackEdgeWeight,
353 Max(1, distance / kCodeSizeMultiplier));
354 EmitProfilingCounterDecrement(weight);
355 __ j(positive, &ok, Label::kNear);
356 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
358 // Record a mapping of this PC offset to the OSR id. This is used to find
359 // the AST id from the unoptimized code in order to use it as a key into
360 // the deoptimization input data found in the optimized code.
361 RecordBackEdge(stmt->OsrEntryId());
363 EmitProfilingCounterReset();
366 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
367 // Record a mapping of the OSR id to this PC. This is used if the OSR
368 // entry becomes the target of a bailout. We don't expect it to be, but
369 // we want it to work if it is.
370 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
374 void FullCodeGenerator::EmitReturnSequence() {
375 Comment cmnt(masm_, "[ Return sequence");
376 if (return_label_.is_bound()) {
377 __ jmp(&return_label_);
379 // Common return label
380 __ bind(&return_label_);
383 __ CallRuntime(Runtime::kTraceExit, 1);
385 // Pretend that the exit is a backwards jump to the entry.
387 if (info_->ShouldSelfOptimize()) {
388 weight = FLAG_interrupt_budget / FLAG_self_opt_count;
390 int distance = masm_->pc_offset();
391 weight = Min(kMaxBackEdgeWeight,
392 Max(1, distance / kCodeSizeMultiplier));
394 EmitProfilingCounterDecrement(weight);
396 __ j(positive, &ok, Label::kNear);
398 __ call(isolate()->builtins()->InterruptCheck(),
399 RelocInfo::CODE_TARGET);
401 EmitProfilingCounterReset();
404 // Add a label for checking the size of the code used for returning.
405 Label check_exit_codesize;
406 masm_->bind(&check_exit_codesize);
408 SetSourcePosition(function()->end_position() - 1);
410 // Do not use the leave instruction here because it is too short to
411 // patch with the code required by the debugger.
413 int no_frame_start = masm_->pc_offset();
416 int arguments_bytes = (info_->scope()->num_parameters() + 1) * kPointerSize;
417 __ Ret(arguments_bytes, ecx);
418 // Check that the size of the code used for returning is large enough
419 // for the debugger's requirements.
420 DCHECK(Assembler::kJSReturnSequenceLength <=
421 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
422 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
427 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
428 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
432 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
433 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
434 codegen()->GetVar(result_register(), var);
438 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
439 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
440 MemOperand operand = codegen()->VarOperand(var, result_register());
441 // Memory operands can be pushed directly.
446 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
447 // For simplicity we always test the accumulator register.
448 codegen()->GetVar(result_register(), var);
449 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
450 codegen()->DoTest(this);
454 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
455 UNREACHABLE(); // Not used on IA32.
459 void FullCodeGenerator::AccumulatorValueContext::Plug(
460 Heap::RootListIndex index) const {
461 UNREACHABLE(); // Not used on IA32.
465 void FullCodeGenerator::StackValueContext::Plug(
466 Heap::RootListIndex index) const {
467 UNREACHABLE(); // Not used on IA32.
471 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
472 UNREACHABLE(); // Not used on IA32.
476 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
480 void FullCodeGenerator::AccumulatorValueContext::Plug(
481 Handle<Object> lit) const {
483 __ SafeMove(result_register(), Immediate(lit));
485 __ Move(result_register(), Immediate(lit));
490 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
492 __ SafePush(Immediate(lit));
494 __ push(Immediate(lit));
499 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
500 codegen()->PrepareForBailoutBeforeSplit(condition(),
504 DCHECK(!lit->IsUndetectableObject()); // There are no undetectable literals.
505 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
506 if (false_label_ != fall_through_) __ jmp(false_label_);
507 } else if (lit->IsTrue() || lit->IsJSObject()) {
508 if (true_label_ != fall_through_) __ jmp(true_label_);
509 } else if (lit->IsString()) {
510 if (String::cast(*lit)->length() == 0) {
511 if (false_label_ != fall_through_) __ jmp(false_label_);
513 if (true_label_ != fall_through_) __ jmp(true_label_);
515 } else if (lit->IsSmi()) {
516 if (Smi::cast(*lit)->value() == 0) {
517 if (false_label_ != fall_through_) __ jmp(false_label_);
519 if (true_label_ != fall_through_) __ jmp(true_label_);
522 // For simplicity we always test the accumulator register.
523 __ mov(result_register(), lit);
524 codegen()->DoTest(this);
529 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
530 Register reg) const {
536 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
538 Register reg) const {
541 __ Move(result_register(), reg);
545 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
546 Register reg) const {
548 if (count > 1) __ Drop(count - 1);
549 __ mov(Operand(esp, 0), reg);
553 void FullCodeGenerator::TestContext::DropAndPlug(int count,
554 Register reg) const {
556 // For simplicity we always test the accumulator register.
558 __ Move(result_register(), reg);
559 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
560 codegen()->DoTest(this);
564 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
565 Label* materialize_false) const {
566 DCHECK(materialize_true == materialize_false);
567 __ bind(materialize_true);
571 void FullCodeGenerator::AccumulatorValueContext::Plug(
572 Label* materialize_true,
573 Label* materialize_false) const {
575 __ bind(materialize_true);
576 __ mov(result_register(), isolate()->factory()->true_value());
577 __ jmp(&done, Label::kNear);
578 __ bind(materialize_false);
579 __ mov(result_register(), isolate()->factory()->false_value());
584 void FullCodeGenerator::StackValueContext::Plug(
585 Label* materialize_true,
586 Label* materialize_false) const {
588 __ bind(materialize_true);
589 __ push(Immediate(isolate()->factory()->true_value()));
590 __ jmp(&done, Label::kNear);
591 __ bind(materialize_false);
592 __ push(Immediate(isolate()->factory()->false_value()));
597 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
598 Label* materialize_false) const {
599 DCHECK(materialize_true == true_label_);
600 DCHECK(materialize_false == false_label_);
604 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
608 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
609 Handle<Object> value = flag
610 ? isolate()->factory()->true_value()
611 : isolate()->factory()->false_value();
612 __ mov(result_register(), value);
616 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
617 Handle<Object> value = flag
618 ? isolate()->factory()->true_value()
619 : isolate()->factory()->false_value();
620 __ push(Immediate(value));
624 void FullCodeGenerator::TestContext::Plug(bool flag) const {
625 codegen()->PrepareForBailoutBeforeSplit(condition(),
630 if (true_label_ != fall_through_) __ jmp(true_label_);
632 if (false_label_ != fall_through_) __ jmp(false_label_);
637 void FullCodeGenerator::DoTest(Expression* condition,
640 Label* fall_through) {
641 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
642 CallIC(ic, condition->test_id());
643 __ test(result_register(), result_register());
644 // The stub returns nonzero for true.
645 Split(not_zero, if_true, if_false, fall_through);
649 void FullCodeGenerator::Split(Condition cc,
652 Label* fall_through) {
653 if (if_false == fall_through) {
655 } else if (if_true == fall_through) {
656 __ j(NegateCondition(cc), if_false);
664 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
665 DCHECK(var->IsStackAllocated());
666 // Offset is negative because higher indexes are at lower addresses.
667 int offset = -var->index() * kPointerSize;
668 // Adjust by a (parameter or local) base offset.
669 if (var->IsParameter()) {
670 offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
672 offset += JavaScriptFrameConstants::kLocal0Offset;
674 return Operand(ebp, offset);
678 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
679 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
680 if (var->IsContextSlot()) {
681 int context_chain_length = scope()->ContextChainLength(var->scope());
682 __ LoadContext(scratch, context_chain_length);
683 return ContextOperand(scratch, var->index());
685 return StackOperand(var);
690 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
691 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
692 MemOperand location = VarOperand(var, dest);
693 __ mov(dest, location);
697 void FullCodeGenerator::SetVar(Variable* var,
701 DCHECK(var->IsContextSlot() || var->IsStackAllocated());
702 DCHECK(!scratch0.is(src));
703 DCHECK(!scratch0.is(scratch1));
704 DCHECK(!scratch1.is(src));
705 MemOperand location = VarOperand(var, scratch0);
706 __ mov(location, src);
708 // Emit the write barrier code if the location is in the heap.
709 if (var->IsContextSlot()) {
710 int offset = Context::SlotOffset(var->index());
711 DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
712 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
717 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
718 bool should_normalize,
721 // Only prepare for bailouts before splits if we're in a test
722 // context. Otherwise, we let the Visit function deal with the
723 // preparation to avoid preparing with the same AST id twice.
724 if (!context()->IsTest() || !info_->IsOptimizable()) return;
727 if (should_normalize) __ jmp(&skip, Label::kNear);
728 PrepareForBailout(expr, TOS_REG);
729 if (should_normalize) {
730 __ cmp(eax, isolate()->factory()->true_value());
731 Split(equal, if_true, if_false, NULL);
737 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
738 // The variable in the declaration always resides in the current context.
739 DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
740 if (generate_debug_code_) {
741 // Check that we're not inside a with or catch context.
742 __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
743 __ cmp(ebx, isolate()->factory()->with_context_map());
744 __ Check(not_equal, kDeclarationInWithContext);
745 __ cmp(ebx, isolate()->factory()->catch_context_map());
746 __ Check(not_equal, kDeclarationInCatchContext);
751 void FullCodeGenerator::VisitVariableDeclaration(
752 VariableDeclaration* declaration) {
753 // If it was not possible to allocate the variable at compile time, we
754 // need to "declare" it at runtime to make sure it actually exists in the
756 VariableProxy* proxy = declaration->proxy();
757 VariableMode mode = declaration->mode();
758 Variable* variable = proxy->var();
759 bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
760 switch (variable->location()) {
761 case Variable::UNALLOCATED:
762 globals_->Add(variable->name(), zone());
763 globals_->Add(variable->binding_needs_init()
764 ? isolate()->factory()->the_hole_value()
765 : isolate()->factory()->undefined_value(), zone());
768 case Variable::PARAMETER:
769 case Variable::LOCAL:
771 Comment cmnt(masm_, "[ VariableDeclaration");
772 __ mov(StackOperand(variable),
773 Immediate(isolate()->factory()->the_hole_value()));
777 case Variable::CONTEXT:
779 Comment cmnt(masm_, "[ VariableDeclaration");
780 EmitDebugCheckDeclarationContext(variable);
781 __ mov(ContextOperand(esi, variable->index()),
782 Immediate(isolate()->factory()->the_hole_value()));
783 // No write barrier since the hole value is in old space.
784 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
788 case Variable::LOOKUP: {
789 Comment cmnt(masm_, "[ VariableDeclaration");
791 __ push(Immediate(variable->name()));
792 // VariableDeclaration nodes are always introduced in one of four modes.
793 DCHECK(IsDeclaredVariableMode(mode));
794 PropertyAttributes attr =
795 IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
796 __ push(Immediate(Smi::FromInt(attr)));
797 // Push initial value, if any.
798 // Note: For variables we must not push an initial value (such as
799 // 'undefined') because we may have a (legal) redeclaration and we
800 // must not destroy the current value.
802 __ push(Immediate(isolate()->factory()->the_hole_value()));
804 __ push(Immediate(Smi::FromInt(0))); // Indicates no initial value.
806 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
813 void FullCodeGenerator::VisitFunctionDeclaration(
814 FunctionDeclaration* declaration) {
815 VariableProxy* proxy = declaration->proxy();
816 Variable* variable = proxy->var();
817 switch (variable->location()) {
818 case Variable::UNALLOCATED: {
819 globals_->Add(variable->name(), zone());
820 Handle<SharedFunctionInfo> function =
821 Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
822 // Check for stack-overflow exception.
823 if (function.is_null()) return SetStackOverflow();
824 globals_->Add(function, zone());
828 case Variable::PARAMETER:
829 case Variable::LOCAL: {
830 Comment cmnt(masm_, "[ FunctionDeclaration");
831 VisitForAccumulatorValue(declaration->fun());
832 __ mov(StackOperand(variable), result_register());
836 case Variable::CONTEXT: {
837 Comment cmnt(masm_, "[ FunctionDeclaration");
838 EmitDebugCheckDeclarationContext(variable);
839 VisitForAccumulatorValue(declaration->fun());
840 __ mov(ContextOperand(esi, variable->index()), result_register());
841 // We know that we have written a function, which is not a smi.
842 __ RecordWriteContextSlot(esi,
843 Context::SlotOffset(variable->index()),
849 PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
853 case Variable::LOOKUP: {
854 Comment cmnt(masm_, "[ FunctionDeclaration");
856 __ push(Immediate(variable->name()));
857 __ push(Immediate(Smi::FromInt(NONE)));
858 VisitForStackValue(declaration->fun());
859 __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
866 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
867 Variable* variable = declaration->proxy()->var();
868 DCHECK(variable->location() == Variable::CONTEXT);
869 DCHECK(variable->interface()->IsFrozen());
871 Comment cmnt(masm_, "[ ModuleDeclaration");
872 EmitDebugCheckDeclarationContext(variable);
874 // Load instance object.
875 __ LoadContext(eax, scope_->ContextChainLength(scope_->GlobalScope()));
876 __ mov(eax, ContextOperand(eax, variable->interface()->Index()));
877 __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
880 __ mov(ContextOperand(esi, variable->index()), eax);
881 // We know that we have written a module, which is not a smi.
882 __ RecordWriteContextSlot(esi,
883 Context::SlotOffset(variable->index()),
889 PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
891 // Traverse into body.
892 Visit(declaration->module());
896 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
897 VariableProxy* proxy = declaration->proxy();
898 Variable* variable = proxy->var();
899 switch (variable->location()) {
900 case Variable::UNALLOCATED:
904 case Variable::CONTEXT: {
905 Comment cmnt(masm_, "[ ImportDeclaration");
906 EmitDebugCheckDeclarationContext(variable);
911 case Variable::PARAMETER:
912 case Variable::LOCAL:
913 case Variable::LOOKUP:
919 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
924 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
925 // Call the runtime to declare the globals.
926 __ push(esi); // The context is the first argument.
928 __ Push(Smi::FromInt(DeclareGlobalsFlags()));
929 __ CallRuntime(Runtime::kDeclareGlobals, 3);
930 // Return value is ignored.
934 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
935 // Call the runtime to declare the modules.
936 __ Push(descriptions);
937 __ CallRuntime(Runtime::kDeclareModules, 1);
938 // Return value is ignored.
942 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
943 Comment cmnt(masm_, "[ SwitchStatement");
944 Breakable nested_statement(this, stmt);
945 SetStatementPosition(stmt);
947 // Keep the switch value on the stack until a case matches.
948 VisitForStackValue(stmt->tag());
949 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
951 ZoneList<CaseClause*>* clauses = stmt->cases();
952 CaseClause* default_clause = NULL; // Can occur anywhere in the list.
954 Label next_test; // Recycled for each test.
955 // Compile all the tests with branches to their bodies.
956 for (int i = 0; i < clauses->length(); i++) {
957 CaseClause* clause = clauses->at(i);
958 clause->body_target()->Unuse();
960 // The default is not a test, but remember it as final fall through.
961 if (clause->is_default()) {
962 default_clause = clause;
966 Comment cmnt(masm_, "[ Case comparison");
970 // Compile the label expression.
971 VisitForAccumulatorValue(clause->label());
973 // Perform the comparison as if via '==='.
974 __ mov(edx, Operand(esp, 0)); // Switch value.
975 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
976 JumpPatchSite patch_site(masm_);
977 if (inline_smi_code) {
981 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
984 __ j(not_equal, &next_test);
985 __ Drop(1); // Switch value is no longer needed.
986 __ jmp(clause->body_target());
990 // Record position before stub call for type feedback.
991 SetSourcePosition(clause->position());
993 CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
994 CallIC(ic, clause->CompareId());
995 patch_site.EmitPatchInfo();
998 __ jmp(&skip, Label::kNear);
999 PrepareForBailout(clause, TOS_REG);
1000 __ cmp(eax, isolate()->factory()->true_value());
1001 __ j(not_equal, &next_test);
1003 __ jmp(clause->body_target());
1007 __ j(not_equal, &next_test);
1008 __ Drop(1); // Switch value is no longer needed.
1009 __ jmp(clause->body_target());
1012 // Discard the test value and jump to the default if present, otherwise to
1013 // the end of the statement.
1014 __ bind(&next_test);
1015 __ Drop(1); // Switch value is no longer needed.
1016 if (default_clause == NULL) {
1017 __ jmp(nested_statement.break_label());
1019 __ jmp(default_clause->body_target());
1022 // Compile all the case bodies.
1023 for (int i = 0; i < clauses->length(); i++) {
1024 Comment cmnt(masm_, "[ Case body");
1025 CaseClause* clause = clauses->at(i);
1026 __ bind(clause->body_target());
1027 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1028 VisitStatements(clause->statements());
1031 __ bind(nested_statement.break_label());
1032 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1036 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1037 Comment cmnt(masm_, "[ ForInStatement");
1038 int slot = stmt->ForInFeedbackSlot();
1040 SetStatementPosition(stmt);
1043 ForIn loop_statement(this, stmt);
1044 increment_loop_depth();
1046 // Get the object to enumerate over. If the object is null or undefined, skip
1047 // over the loop. See ECMA-262 version 5, section 12.6.4.
1048 VisitForAccumulatorValue(stmt->enumerable());
1049 __ cmp(eax, isolate()->factory()->undefined_value());
1051 __ cmp(eax, isolate()->factory()->null_value());
1054 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1056 // Convert the object to a JS object.
1057 Label convert, done_convert;
1058 __ JumpIfSmi(eax, &convert, Label::kNear);
1059 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1060 __ j(above_equal, &done_convert, Label::kNear);
1063 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1064 __ bind(&done_convert);
1067 // Check for proxies.
1068 Label call_runtime, use_cache, fixed_array;
1069 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1070 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1071 __ j(below_equal, &call_runtime);
1073 // Check cache validity in generated code. This is a fast case for
1074 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1075 // guarantee cache validity, call the runtime system to check cache
1076 // validity or get the property names in a fixed array.
1077 __ CheckEnumCache(&call_runtime);
1079 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1080 __ jmp(&use_cache, Label::kNear);
1082 // Get the set of properties to enumerate.
1083 __ bind(&call_runtime);
1085 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1086 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1087 isolate()->factory()->meta_map());
1088 __ j(not_equal, &fixed_array);
1091 // We got a map in register eax. Get the enumeration cache from it.
1092 Label no_descriptors;
1093 __ bind(&use_cache);
1095 __ EnumLength(edx, eax);
1096 __ cmp(edx, Immediate(Smi::FromInt(0)));
1097 __ j(equal, &no_descriptors);
1099 __ LoadInstanceDescriptors(eax, ecx);
1100 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1101 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1103 // Set up the four remaining stack slots.
1104 __ push(eax); // Map.
1105 __ push(ecx); // Enumeration cache.
1106 __ push(edx); // Number of valid entries for the map in the enum cache.
1107 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1110 __ bind(&no_descriptors);
1111 __ add(esp, Immediate(kPointerSize));
1114 // We got a fixed array in register eax. Iterate through that.
1116 __ bind(&fixed_array);
1118 // No need for a write barrier, we are storing a Smi in the feedback vector.
1119 __ LoadHeapObject(ebx, FeedbackVector());
1120 __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(slot)),
1121 Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1123 __ mov(ebx, Immediate(Smi::FromInt(1))); // Smi indicates slow check
1124 __ mov(ecx, Operand(esp, 0 * kPointerSize)); // Get enumerated object
1125 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1126 __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1127 __ j(above, &non_proxy);
1128 __ Move(ebx, Immediate(Smi::FromInt(0))); // Zero indicates proxy
1129 __ bind(&non_proxy);
1130 __ push(ebx); // Smi
1131 __ push(eax); // Array
1132 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1133 __ push(eax); // Fixed array length (as smi).
1134 __ push(Immediate(Smi::FromInt(0))); // Initial index.
1136 // Generate code for doing the condition check.
1137 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1139 __ mov(eax, Operand(esp, 0 * kPointerSize)); // Get the current index.
1140 __ cmp(eax, Operand(esp, 1 * kPointerSize)); // Compare to the array length.
1141 __ j(above_equal, loop_statement.break_label());
1143 // Get the current entry of the array into register ebx.
1144 __ mov(ebx, Operand(esp, 2 * kPointerSize));
1145 __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1147 // Get the expected map from the stack or a smi in the
1148 // permanent slow case into register edx.
1149 __ mov(edx, Operand(esp, 3 * kPointerSize));
1151 // Check if the expected map still matches that of the enumerable.
1152 // If not, we may have to filter the key.
1154 __ mov(ecx, Operand(esp, 4 * kPointerSize));
1155 __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1156 __ j(equal, &update_each, Label::kNear);
1158 // For proxies, no filtering is done.
1159 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1160 DCHECK(Smi::FromInt(0) == 0);
1162 __ j(zero, &update_each);
1164 // Convert the entry to a string or null if it isn't a property
1165 // anymore. If the property has been removed while iterating, we
1167 __ push(ecx); // Enumerable.
1168 __ push(ebx); // Current entry.
1169 __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1171 __ j(equal, loop_statement.continue_label());
1174 // Update the 'each' property or variable from the possibly filtered
1175 // entry in register ebx.
1176 __ bind(&update_each);
1177 __ mov(result_register(), ebx);
1178 // Perform the assignment as if via '='.
1179 { EffectContext context(this);
1180 EmitAssignment(stmt->each());
1183 // Generate code for the body of the loop.
1184 Visit(stmt->body());
1186 // Generate code for going to the next element by incrementing the
1187 // index (smi) stored on top of the stack.
1188 __ bind(loop_statement.continue_label());
1189 __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1191 EmitBackEdgeBookkeeping(stmt, &loop);
1194 // Remove the pointers stored on the stack.
1195 __ bind(loop_statement.break_label());
1196 __ add(esp, Immediate(5 * kPointerSize));
1198 // Exit and decrement the loop depth.
1199 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1201 decrement_loop_depth();
1205 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1206 Comment cmnt(masm_, "[ ForOfStatement");
1207 SetStatementPosition(stmt);
1209 Iteration loop_statement(this, stmt);
1210 increment_loop_depth();
1212 // var iterator = iterable[Symbol.iterator]();
1213 VisitForEffect(stmt->assign_iterator());
1216 __ bind(loop_statement.continue_label());
1218 // result = iterator.next()
1219 VisitForEffect(stmt->next_result());
1221 // if (result.done) break;
1222 Label result_not_done;
1223 VisitForControl(stmt->result_done(),
1224 loop_statement.break_label(),
1227 __ bind(&result_not_done);
1229 // each = result.value
1230 VisitForEffect(stmt->assign_each());
1232 // Generate code for the body of the loop.
1233 Visit(stmt->body());
1235 // Check stack before looping.
1236 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1237 EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1238 __ jmp(loop_statement.continue_label());
1240 // Exit and decrement the loop depth.
1241 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1242 __ bind(loop_statement.break_label());
1243 decrement_loop_depth();
1247 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1249 // Use the fast case closure allocation code that allocates in new
1250 // space for nested functions that don't need literals cloning. If
1251 // we're running with the --always-opt or the --prepare-always-opt
1252 // flag, we need to use the runtime function so that the new function
1253 // we are creating here gets a chance to have its code optimized and
1254 // doesn't just get a copy of the existing unoptimized code.
1255 if (!FLAG_always_opt &&
1256 !FLAG_prepare_always_opt &&
1258 scope()->is_function_scope() &&
1259 info->num_literals() == 0) {
1260 FastNewClosureStub stub(isolate(), info->strict_mode(), info->kind());
1261 __ mov(ebx, Immediate(info));
1265 __ push(Immediate(info));
1266 __ push(Immediate(pretenure
1267 ? isolate()->factory()->true_value()
1268 : isolate()->factory()->false_value()));
1269 __ CallRuntime(Runtime::kNewClosure, 3);
1271 context()->Plug(eax);
1275 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1276 Comment cmnt(masm_, "[ VariableProxy");
1277 EmitVariableLoad(expr);
1281 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1282 Comment cnmt(masm_, "[ SuperReference ");
1284 __ mov(LoadDescriptor::ReceiverRegister(),
1285 Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1287 Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1288 __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1290 CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1292 __ cmp(eax, isolate()->factory()->undefined_value());
1294 __ j(not_equal, &done);
1295 __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1300 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1301 TypeofState typeof_state,
1303 Register context = esi;
1304 Register temp = edx;
1308 if (s->num_heap_slots() > 0) {
1309 if (s->calls_sloppy_eval()) {
1310 // Check that extension is NULL.
1311 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1313 __ j(not_equal, slow);
1315 // Load next context in chain.
1316 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1317 // Walk the rest of the chain without clobbering esi.
1320 // If no outer scope calls eval, we do not need to check more
1321 // context extensions. If we have reached an eval scope, we check
1322 // all extensions from this point.
1323 if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1324 s = s->outer_scope();
1327 if (s != NULL && s->is_eval_scope()) {
1328 // Loop up the context chain. There is no frame effect so it is
1329 // safe to use raw labels here.
1331 if (!context.is(temp)) {
1332 __ mov(temp, context);
1335 // Terminate at native context.
1336 __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1337 Immediate(isolate()->factory()->native_context_map()));
1338 __ j(equal, &fast, Label::kNear);
1339 // Check that extension is NULL.
1340 __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1341 __ j(not_equal, slow);
1342 // Load next context in chain.
1343 __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1348 // All extension objects were empty and it is safe to use a global
1350 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1351 __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1352 if (FLAG_vector_ics) {
1353 __ mov(VectorLoadICDescriptor::SlotRegister(),
1354 Immediate(Smi::FromInt(proxy->VariableFeedbackSlot())));
1357 ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1365 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1367 DCHECK(var->IsContextSlot());
1368 Register context = esi;
1369 Register temp = ebx;
1371 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1372 if (s->num_heap_slots() > 0) {
1373 if (s->calls_sloppy_eval()) {
1374 // Check that extension is NULL.
1375 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1377 __ j(not_equal, slow);
1379 __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1380 // Walk the rest of the chain without clobbering esi.
1384 // Check that last extension is NULL.
1385 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1386 __ j(not_equal, slow);
1388 // This function is used only for loads, not stores, so it's safe to
1389 // return an esi-based operand (the write barrier cannot be allowed to
1390 // destroy the esi register).
1391 return ContextOperand(context, var->index());
1395 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1396 TypeofState typeof_state,
1399 // Generate fast-case code for variables that might be shadowed by
1400 // eval-introduced variables. Eval is used a lot without
1401 // introducing variables. In those cases, we do not want to
1402 // perform a runtime call for all variables in the scope
1403 // containing the eval.
1404 Variable* var = proxy->var();
1405 if (var->mode() == DYNAMIC_GLOBAL) {
1406 EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1408 } else if (var->mode() == DYNAMIC_LOCAL) {
1409 Variable* local = var->local_if_not_shadowed();
1410 __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1411 if (local->mode() == LET || local->mode() == CONST ||
1412 local->mode() == CONST_LEGACY) {
1413 __ cmp(eax, isolate()->factory()->the_hole_value());
1414 __ j(not_equal, done);
1415 if (local->mode() == CONST_LEGACY) {
1416 __ mov(eax, isolate()->factory()->undefined_value());
1417 } else { // LET || CONST
1418 __ push(Immediate(var->name()));
1419 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1427 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1428 // Record position before possible IC call.
1429 SetSourcePosition(proxy->position());
1430 Variable* var = proxy->var();
1432 // Three cases: global variables, lookup variables, and all other types of
1434 switch (var->location()) {
1435 case Variable::UNALLOCATED: {
1436 Comment cmnt(masm_, "[ Global variable");
1437 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1438 __ mov(LoadDescriptor::NameRegister(), var->name());
1439 if (FLAG_vector_ics) {
1440 __ mov(VectorLoadICDescriptor::SlotRegister(),
1441 Immediate(Smi::FromInt(proxy->VariableFeedbackSlot())));
1443 CallLoadIC(CONTEXTUAL);
1444 context()->Plug(eax);
1448 case Variable::PARAMETER:
1449 case Variable::LOCAL:
1450 case Variable::CONTEXT: {
1451 Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1452 : "[ Stack variable");
1453 if (var->binding_needs_init()) {
1454 // var->scope() may be NULL when the proxy is located in eval code and
1455 // refers to a potential outside binding. Currently those bindings are
1456 // always looked up dynamically, i.e. in that case
1457 // var->location() == LOOKUP.
1459 DCHECK(var->scope() != NULL);
1461 // Check if the binding really needs an initialization check. The check
1462 // can be skipped in the following situation: we have a LET or CONST
1463 // binding in harmony mode, both the Variable and the VariableProxy have
1464 // the same declaration scope (i.e. they are both in global code, in the
1465 // same function or in the same eval code) and the VariableProxy is in
1466 // the source physically located after the initializer of the variable.
1468 // We cannot skip any initialization checks for CONST in non-harmony
1469 // mode because const variables may be declared but never initialized:
1470 // if (false) { const x; }; var y = x;
1472 // The condition on the declaration scopes is a conservative check for
1473 // nested functions that access a binding and are called before the
1474 // binding is initialized:
1475 // function() { f(); let x = 1; function f() { x = 2; } }
1477 bool skip_init_check;
1478 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1479 skip_init_check = false;
1481 // Check that we always have valid source position.
1482 DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1483 DCHECK(proxy->position() != RelocInfo::kNoPosition);
1484 skip_init_check = var->mode() != CONST_LEGACY &&
1485 var->initializer_position() < proxy->position();
1488 if (!skip_init_check) {
1489 // Let and const need a read barrier.
1492 __ cmp(eax, isolate()->factory()->the_hole_value());
1493 __ j(not_equal, &done, Label::kNear);
1494 if (var->mode() == LET || var->mode() == CONST) {
1495 // Throw a reference error when using an uninitialized let/const
1496 // binding in harmony mode.
1497 __ push(Immediate(var->name()));
1498 __ CallRuntime(Runtime::kThrowReferenceError, 1);
1500 // Uninitalized const bindings outside of harmony mode are unholed.
1501 DCHECK(var->mode() == CONST_LEGACY);
1502 __ mov(eax, isolate()->factory()->undefined_value());
1505 context()->Plug(eax);
1509 context()->Plug(var);
1513 case Variable::LOOKUP: {
1514 Comment cmnt(masm_, "[ Lookup variable");
1516 // Generate code for loading from variables potentially shadowed
1517 // by eval-introduced variables.
1518 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1520 __ push(esi); // Context.
1521 __ push(Immediate(var->name()));
1522 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1524 context()->Plug(eax);
1531 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1532 Comment cmnt(masm_, "[ RegExpLiteral");
1534 // Registers will be used as follows:
1535 // edi = JS function.
1536 // ecx = literals array.
1537 // ebx = regexp literal.
1538 // eax = regexp literal clone.
1539 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1540 __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1541 int literal_offset =
1542 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1543 __ mov(ebx, FieldOperand(ecx, literal_offset));
1544 __ cmp(ebx, isolate()->factory()->undefined_value());
1545 __ j(not_equal, &materialized, Label::kNear);
1547 // Create regexp literal using runtime function
1548 // Result will be in eax.
1550 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1551 __ push(Immediate(expr->pattern()));
1552 __ push(Immediate(expr->flags()));
1553 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1556 __ bind(&materialized);
1557 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1558 Label allocated, runtime_allocate;
1559 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1562 __ bind(&runtime_allocate);
1564 __ push(Immediate(Smi::FromInt(size)));
1565 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1568 __ bind(&allocated);
1569 // Copy the content into the newly allocated memory.
1570 // (Unroll copy loop once for better throughput).
1571 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1572 __ mov(edx, FieldOperand(ebx, i));
1573 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1574 __ mov(FieldOperand(eax, i), edx);
1575 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1577 if ((size % (2 * kPointerSize)) != 0) {
1578 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1579 __ mov(FieldOperand(eax, size - kPointerSize), edx);
1581 context()->Plug(eax);
1585 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1586 if (expression == NULL) {
1587 __ push(Immediate(isolate()->factory()->null_value()));
1589 VisitForStackValue(expression);
1594 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1595 Comment cmnt(masm_, "[ ObjectLiteral");
1597 expr->BuildConstantProperties(isolate());
1598 Handle<FixedArray> constant_properties = expr->constant_properties();
1599 int flags = expr->fast_elements()
1600 ? ObjectLiteral::kFastElements
1601 : ObjectLiteral::kNoFlags;
1602 flags |= expr->has_function()
1603 ? ObjectLiteral::kHasFunction
1604 : ObjectLiteral::kNoFlags;
1605 int properties_count = constant_properties->length() / 2;
1606 if (expr->may_store_doubles() || expr->depth() > 1 ||
1607 masm()->serializer_enabled() ||
1608 flags != ObjectLiteral::kFastElements ||
1609 properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
1610 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1611 __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1612 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1613 __ push(Immediate(constant_properties));
1614 __ push(Immediate(Smi::FromInt(flags)));
1615 __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1617 __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1618 __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1619 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1620 __ mov(ecx, Immediate(constant_properties));
1621 __ mov(edx, Immediate(Smi::FromInt(flags)));
1622 FastCloneShallowObjectStub stub(isolate(), properties_count);
1626 // If result_saved is true the result is on top of the stack. If
1627 // result_saved is false the result is in eax.
1628 bool result_saved = false;
1630 // Mark all computed expressions that are bound to a key that
1631 // is shadowed by a later occurrence of the same key. For the
1632 // marked expressions, no store code is emitted.
1633 expr->CalculateEmitStore(zone());
1635 AccessorTable accessor_table(zone());
1636 for (int i = 0; i < expr->properties()->length(); i++) {
1637 ObjectLiteral::Property* property = expr->properties()->at(i);
1638 if (property->IsCompileTimeValue()) continue;
1640 Literal* key = property->key();
1641 Expression* value = property->value();
1642 if (!result_saved) {
1643 __ push(eax); // Save result on the stack
1644 result_saved = true;
1646 switch (property->kind()) {
1647 case ObjectLiteral::Property::CONSTANT:
1649 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1650 DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1652 case ObjectLiteral::Property::COMPUTED:
1653 if (key->value()->IsInternalizedString()) {
1654 if (property->emit_store()) {
1655 VisitForAccumulatorValue(value);
1656 DCHECK(StoreDescriptor::ValueRegister().is(eax));
1657 __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1658 __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1659 CallStoreIC(key->LiteralFeedbackId());
1660 PrepareForBailoutForId(key->id(), NO_REGISTERS);
1662 VisitForEffect(value);
1666 __ push(Operand(esp, 0)); // Duplicate receiver.
1667 VisitForStackValue(key);
1668 VisitForStackValue(value);
1669 if (property->emit_store()) {
1670 __ push(Immediate(Smi::FromInt(SLOPPY))); // Strict mode
1671 __ CallRuntime(Runtime::kSetProperty, 4);
1676 case ObjectLiteral::Property::PROTOTYPE:
1677 __ push(Operand(esp, 0)); // Duplicate receiver.
1678 VisitForStackValue(value);
1679 if (property->emit_store()) {
1680 __ CallRuntime(Runtime::kSetPrototype, 2);
1685 case ObjectLiteral::Property::GETTER:
1686 accessor_table.lookup(key)->second->getter = value;
1688 case ObjectLiteral::Property::SETTER:
1689 accessor_table.lookup(key)->second->setter = value;
1694 // Emit code to define accessors, using only a single call to the runtime for
1695 // each pair of corresponding getters and setters.
1696 for (AccessorTable::Iterator it = accessor_table.begin();
1697 it != accessor_table.end();
1699 __ push(Operand(esp, 0)); // Duplicate receiver.
1700 VisitForStackValue(it->first);
1701 EmitAccessor(it->second->getter);
1702 EmitAccessor(it->second->setter);
1703 __ push(Immediate(Smi::FromInt(NONE)));
1704 __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1707 if (expr->has_function()) {
1708 DCHECK(result_saved);
1709 __ push(Operand(esp, 0));
1710 __ CallRuntime(Runtime::kToFastProperties, 1);
1714 context()->PlugTOS();
1716 context()->Plug(eax);
1721 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1722 Comment cmnt(masm_, "[ ArrayLiteral");
1724 expr->BuildConstantElements(isolate());
1725 int flags = expr->depth() == 1
1726 ? ArrayLiteral::kShallowElements
1727 : ArrayLiteral::kNoFlags;
1729 ZoneList<Expression*>* subexprs = expr->values();
1730 int length = subexprs->length();
1731 Handle<FixedArray> constant_elements = expr->constant_elements();
1732 DCHECK_EQ(2, constant_elements->length());
1733 ElementsKind constant_elements_kind =
1734 static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value());
1735 bool has_constant_fast_elements =
1736 IsFastObjectElementsKind(constant_elements_kind);
1737 Handle<FixedArrayBase> constant_elements_values(
1738 FixedArrayBase::cast(constant_elements->get(1)));
1740 AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1741 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1742 // If the only customer of allocation sites is transitioning, then
1743 // we can turn it off if we don't have anywhere else to transition to.
1744 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1747 if (expr->depth() > 1 || length > JSObject::kInitialMaxFastElementArray) {
1748 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1749 __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1750 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1751 __ push(Immediate(constant_elements));
1752 __ push(Immediate(Smi::FromInt(flags)));
1753 __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1755 __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1756 __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1757 __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1758 __ mov(ecx, Immediate(constant_elements));
1759 FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1763 bool result_saved = false; // Is the result saved to the stack?
1765 // Emit code to evaluate all the non-constant subexpressions and to store
1766 // them into the newly cloned array.
1767 for (int i = 0; i < length; i++) {
1768 Expression* subexpr = subexprs->at(i);
1769 // If the subexpression is a literal or a simple materialized literal it
1770 // is already set in the cloned array.
1771 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1773 if (!result_saved) {
1774 __ push(eax); // array literal.
1775 __ push(Immediate(Smi::FromInt(expr->literal_index())));
1776 result_saved = true;
1778 VisitForAccumulatorValue(subexpr);
1780 if (IsFastObjectElementsKind(constant_elements_kind)) {
1781 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1782 // cannot transition and don't need to call the runtime stub.
1783 int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1784 __ mov(ebx, Operand(esp, kPointerSize)); // Copy of array literal.
1785 __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1786 // Store the subexpression value in the array's elements.
1787 __ mov(FieldOperand(ebx, offset), result_register());
1788 // Update the write barrier for the array store.
1789 __ RecordWriteField(ebx, offset, result_register(), ecx,
1791 EMIT_REMEMBERED_SET,
1794 // Store the subexpression value in the array's elements.
1795 __ mov(ecx, Immediate(Smi::FromInt(i)));
1796 StoreArrayLiteralElementStub stub(isolate());
1800 PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1804 __ add(esp, Immediate(kPointerSize)); // literal index
1805 context()->PlugTOS();
1807 context()->Plug(eax);
1812 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1813 DCHECK(expr->target()->IsValidReferenceExpression());
1815 Comment cmnt(masm_, "[ Assignment");
1817 // Left-hand side can only be a property, a global or a (parameter or local)
1819 enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY };
1820 LhsKind assign_type = VARIABLE;
1821 Property* property = expr->target()->AsProperty();
1822 if (property != NULL) {
1823 assign_type = (property->key()->IsPropertyName())
1828 // Evaluate LHS expression.
1829 switch (assign_type) {
1831 // Nothing to do here.
1833 case NAMED_PROPERTY:
1834 if (expr->is_compound()) {
1835 // We need the receiver both on the stack and in the register.
1836 VisitForStackValue(property->obj());
1837 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1839 VisitForStackValue(property->obj());
1842 case KEYED_PROPERTY: {
1843 if (expr->is_compound()) {
1844 VisitForStackValue(property->obj());
1845 VisitForStackValue(property->key());
1846 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1847 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1849 VisitForStackValue(property->obj());
1850 VisitForStackValue(property->key());
1856 // For compound assignments we need another deoptimization point after the
1857 // variable/property load.
1858 if (expr->is_compound()) {
1859 AccumulatorValueContext result_context(this);
1860 { AccumulatorValueContext left_operand_context(this);
1861 switch (assign_type) {
1863 EmitVariableLoad(expr->target()->AsVariableProxy());
1864 PrepareForBailout(expr->target(), TOS_REG);
1866 case NAMED_PROPERTY:
1867 EmitNamedPropertyLoad(property);
1868 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1870 case KEYED_PROPERTY:
1871 EmitKeyedPropertyLoad(property);
1872 PrepareForBailoutForId(property->LoadId(), TOS_REG);
1877 Token::Value op = expr->binary_op();
1878 __ push(eax); // Left operand goes on the stack.
1879 VisitForAccumulatorValue(expr->value());
1881 OverwriteMode mode = expr->value()->ResultOverwriteAllowed()
1884 SetSourcePosition(expr->position() + 1);
1885 if (ShouldInlineSmiCase(op)) {
1886 EmitInlineSmiBinaryOp(expr->binary_operation(),
1892 EmitBinaryOp(expr->binary_operation(), op, mode);
1895 // Deoptimization point in case the binary operation may have side effects.
1896 PrepareForBailout(expr->binary_operation(), TOS_REG);
1898 VisitForAccumulatorValue(expr->value());
1901 // Record source position before possible IC call.
1902 SetSourcePosition(expr->position());
1905 switch (assign_type) {
1907 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1909 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
1910 context()->Plug(eax);
1912 case NAMED_PROPERTY:
1913 EmitNamedPropertyAssignment(expr);
1915 case KEYED_PROPERTY:
1916 EmitKeyedPropertyAssignment(expr);
1922 void FullCodeGenerator::VisitYield(Yield* expr) {
1923 Comment cmnt(masm_, "[ Yield");
1924 // Evaluate yielded value first; the initial iterator definition depends on
1925 // this. It stays on the stack while we update the iterator.
1926 VisitForStackValue(expr->expression());
1928 switch (expr->yield_kind()) {
1929 case Yield::kSuspend:
1930 // Pop value from top-of-stack slot; box result into result register.
1931 EmitCreateIteratorResult(false);
1932 __ push(result_register());
1934 case Yield::kInitial: {
1935 Label suspend, continuation, post_runtime, resume;
1939 __ bind(&continuation);
1943 VisitForAccumulatorValue(expr->generator_object());
1944 DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
1945 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
1946 Immediate(Smi::FromInt(continuation.pos())));
1947 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
1949 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
1951 __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
1953 __ j(equal, &post_runtime);
1954 __ push(eax); // generator object
1955 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
1956 __ mov(context_register(),
1957 Operand(ebp, StandardFrameConstants::kContextOffset));
1958 __ bind(&post_runtime);
1959 __ pop(result_register());
1960 EmitReturnSequence();
1963 context()->Plug(result_register());
1967 case Yield::kFinal: {
1968 VisitForAccumulatorValue(expr->generator_object());
1969 __ mov(FieldOperand(result_register(),
1970 JSGeneratorObject::kContinuationOffset),
1971 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
1972 // Pop value from top-of-stack slot, box result into result register.
1973 EmitCreateIteratorResult(true);
1974 EmitUnwindBeforeReturn();
1975 EmitReturnSequence();
1979 case Yield::kDelegating: {
1980 VisitForStackValue(expr->generator_object());
1982 // Initial stack layout is as follows:
1983 // [sp + 1 * kPointerSize] iter
1984 // [sp + 0 * kPointerSize] g
1986 Label l_catch, l_try, l_suspend, l_continuation, l_resume;
1987 Label l_next, l_call, l_loop;
1988 Register load_receiver = LoadDescriptor::ReceiverRegister();
1989 Register load_name = LoadDescriptor::NameRegister();
1991 // Initial send value is undefined.
1992 __ mov(eax, isolate()->factory()->undefined_value());
1995 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
1997 handler_table()->set(expr->index(), Smi::FromInt(l_catch.pos()));
1998 __ mov(load_name, isolate()->factory()->throw_string()); // "throw"
1999 __ push(load_name); // "throw"
2000 __ push(Operand(esp, 2 * kPointerSize)); // iter
2001 __ push(eax); // exception
2004 // try { received = %yield result }
2005 // Shuffle the received result above a try handler and yield it without
2008 __ pop(eax); // result
2009 __ PushTryHandler(StackHandler::CATCH, expr->index());
2010 const int handler_size = StackHandlerConstants::kSize;
2011 __ push(eax); // result
2013 __ bind(&l_continuation);
2015 __ bind(&l_suspend);
2016 const int generator_object_depth = kPointerSize + handler_size;
2017 __ mov(eax, Operand(esp, generator_object_depth));
2019 DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2020 __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2021 Immediate(Smi::FromInt(l_continuation.pos())));
2022 __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2024 __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2026 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2027 __ mov(context_register(),
2028 Operand(ebp, StandardFrameConstants::kContextOffset));
2029 __ pop(eax); // result
2030 EmitReturnSequence();
2031 __ bind(&l_resume); // received in eax
2034 // receiver = iter; f = iter.next; arg = received;
2037 __ mov(load_name, isolate()->factory()->next_string());
2038 __ push(load_name); // "next"
2039 __ push(Operand(esp, 2 * kPointerSize)); // iter
2040 __ push(eax); // received
2042 // result = receiver[f](arg);
2044 __ mov(load_receiver, Operand(esp, kPointerSize));
2045 if (FLAG_vector_ics) {
2046 __ mov(VectorLoadICDescriptor::SlotRegister(),
2047 Immediate(Smi::FromInt(expr->KeyedLoadFeedbackSlot())));
2049 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2050 CallIC(ic, TypeFeedbackId::None());
2052 __ mov(Operand(esp, 2 * kPointerSize), edi);
2053 CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2056 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2057 __ Drop(1); // The function is still on the stack; drop it.
2059 // if (!result.done) goto l_try;
2061 __ push(eax); // save result
2062 __ Move(load_receiver, eax); // result
2064 isolate()->factory()->done_string()); // "done"
2065 if (FLAG_vector_ics) {
2066 __ mov(VectorLoadICDescriptor::SlotRegister(),
2067 Immediate(Smi::FromInt(expr->DoneFeedbackSlot())));
2069 CallLoadIC(NOT_CONTEXTUAL); // result.done in eax
2070 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2076 __ pop(load_receiver); // result
2078 isolate()->factory()->value_string()); // "value"
2079 if (FLAG_vector_ics) {
2080 __ mov(VectorLoadICDescriptor::SlotRegister(),
2081 Immediate(Smi::FromInt(expr->ValueFeedbackSlot())));
2083 CallLoadIC(NOT_CONTEXTUAL); // result.value in eax
2084 context()->DropAndPlug(2, eax); // drop iter and g
2091 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2093 JSGeneratorObject::ResumeMode resume_mode) {
2094 // The value stays in eax, and is ultimately read by the resumed generator, as
2095 // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2096 // is read to throw the value when the resumed generator is already closed.
2097 // ebx will hold the generator object until the activation has been resumed.
2098 VisitForStackValue(generator);
2099 VisitForAccumulatorValue(value);
2102 // Check generator state.
2103 Label wrong_state, closed_state, done;
2104 STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting < 0);
2105 STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed == 0);
2106 __ cmp(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2107 Immediate(Smi::FromInt(0)));
2108 __ j(equal, &closed_state);
2109 __ j(less, &wrong_state);
2111 // Load suspended function and context.
2112 __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2113 __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2116 __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2118 // Push holes for arguments to generator function.
2119 __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2121 FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2122 __ mov(ecx, isolate()->factory()->the_hole_value());
2123 Label push_argument_holes, push_frame;
2124 __ bind(&push_argument_holes);
2125 __ sub(edx, Immediate(Smi::FromInt(1)));
2126 __ j(carry, &push_frame);
2128 __ jmp(&push_argument_holes);
2130 // Enter a new JavaScript frame, and initialize its slots as they were when
2131 // the generator was suspended.
2133 __ bind(&push_frame);
2134 __ call(&resume_frame);
2136 __ bind(&resume_frame);
2137 __ push(ebp); // Caller's frame pointer.
2139 __ push(esi); // Callee's context.
2140 __ push(edi); // Callee's JS Function.
2142 // Load the operand stack size.
2143 __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2144 __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2147 // If we are sending a value and there is no operand stack, we can jump back
2149 if (resume_mode == JSGeneratorObject::NEXT) {
2151 __ cmp(edx, Immediate(0));
2152 __ j(not_zero, &slow_resume);
2153 __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2154 __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2157 __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2158 Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2160 __ bind(&slow_resume);
2163 // Otherwise, we push holes for the operand stack and call the runtime to fix
2164 // up the stack and the handlers.
2165 Label push_operand_holes, call_resume;
2166 __ bind(&push_operand_holes);
2167 __ sub(edx, Immediate(1));
2168 __ j(carry, &call_resume);
2170 __ jmp(&push_operand_holes);
2171 __ bind(&call_resume);
2173 __ push(result_register());
2174 __ Push(Smi::FromInt(resume_mode));
2175 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2176 // Not reached: the runtime call returns elsewhere.
2177 __ Abort(kGeneratorFailedToResume);
2179 // Reach here when generator is closed.
2180 __ bind(&closed_state);
2181 if (resume_mode == JSGeneratorObject::NEXT) {
2182 // Return completed iterator result when generator is closed.
2183 __ push(Immediate(isolate()->factory()->undefined_value()));
2184 // Pop value from top-of-stack slot; box result into result register.
2185 EmitCreateIteratorResult(true);
2187 // Throw the provided value.
2189 __ CallRuntime(Runtime::kThrow, 1);
2193 // Throw error if we attempt to operate on a running generator.
2194 __ bind(&wrong_state);
2196 __ CallRuntime(Runtime::kThrowGeneratorStateError, 1);
2199 context()->Plug(result_register());
2203 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2207 Handle<Map> map(isolate()->native_context()->iterator_result_map());
2209 __ Allocate(map->instance_size(), eax, ecx, edx, &gc_required, TAG_OBJECT);
2212 __ bind(&gc_required);
2213 __ Push(Smi::FromInt(map->instance_size()));
2214 __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2215 __ mov(context_register(),
2216 Operand(ebp, StandardFrameConstants::kContextOffset));
2218 __ bind(&allocated);
2221 __ mov(edx, isolate()->factory()->ToBoolean(done));
2222 DCHECK_EQ(map->instance_size(), 5 * kPointerSize);
2223 __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2224 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2225 isolate()->factory()->empty_fixed_array());
2226 __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2227 isolate()->factory()->empty_fixed_array());
2228 __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2229 __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2231 // Only the value field needs a write barrier, as the other values are in the
2233 __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset,
2234 ecx, edx, kDontSaveFPRegs);
2238 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2239 SetSourcePosition(prop->position());
2240 Literal* key = prop->key()->AsLiteral();
2241 DCHECK(!key->value()->IsSmi());
2242 __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2243 if (FLAG_vector_ics) {
2244 __ mov(VectorLoadICDescriptor::SlotRegister(),
2245 Immediate(Smi::FromInt(prop->PropertyFeedbackSlot())));
2246 CallLoadIC(NOT_CONTEXTUAL);
2248 CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2253 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2254 SetSourcePosition(prop->position());
2255 Literal* key = prop->key()->AsLiteral();
2256 DCHECK(!key->value()->IsSmi());
2257 DCHECK(prop->IsSuperAccess());
2259 SuperReference* super_ref = prop->obj()->AsSuperReference();
2260 EmitLoadHomeObject(super_ref);
2262 VisitForStackValue(super_ref->this_var());
2263 __ push(Immediate(key->value()));
2264 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2268 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2269 SetSourcePosition(prop->position());
2270 Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2271 if (FLAG_vector_ics) {
2272 __ mov(VectorLoadICDescriptor::SlotRegister(),
2273 Immediate(Smi::FromInt(prop->PropertyFeedbackSlot())));
2276 CallIC(ic, prop->PropertyFeedbackId());
2281 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2285 Expression* right) {
2286 // Do combined smi check of the operands. Left operand is on the
2287 // stack. Right operand is in eax.
2288 Label smi_case, done, stub_call;
2292 JumpPatchSite patch_site(masm_);
2293 patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2295 __ bind(&stub_call);
2297 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op, mode).code();
2298 CallIC(code, expr->BinaryOperationFeedbackId());
2299 patch_site.EmitPatchInfo();
2300 __ jmp(&done, Label::kNear);
2304 __ mov(eax, edx); // Copy left operand in case of a stub call.
2309 __ sar_cl(eax); // No checks of result necessary
2310 __ and_(eax, Immediate(~kSmiTagMask));
2317 // Check that the *signed* result fits in a smi.
2318 __ cmp(eax, 0xc0000000);
2319 __ j(positive, &result_ok);
2322 __ bind(&result_ok);
2331 __ test(eax, Immediate(0xc0000000));
2332 __ j(zero, &result_ok);
2335 __ bind(&result_ok);
2341 __ j(overflow, &stub_call);
2345 __ j(overflow, &stub_call);
2350 __ j(overflow, &stub_call);
2352 __ j(not_zero, &done, Label::kNear);
2355 __ j(negative, &stub_call);
2361 case Token::BIT_AND:
2364 case Token::BIT_XOR:
2372 context()->Plug(eax);
2376 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr,
2378 OverwriteMode mode) {
2380 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op, mode).code();
2381 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code.
2382 CallIC(code, expr->BinaryOperationFeedbackId());
2383 patch_site.EmitPatchInfo();
2384 context()->Plug(eax);
2388 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2389 DCHECK(expr->IsValidReferenceExpression());
2391 // Left-hand side can only be a property, a global or a (parameter or local)
2393 enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY };
2394 LhsKind assign_type = VARIABLE;
2395 Property* prop = expr->AsProperty();
2397 assign_type = (prop->key()->IsPropertyName())
2402 switch (assign_type) {
2404 Variable* var = expr->AsVariableProxy()->var();
2405 EffectContext context(this);
2406 EmitVariableAssignment(var, Token::ASSIGN);
2409 case NAMED_PROPERTY: {
2410 __ push(eax); // Preserve value.
2411 VisitForAccumulatorValue(prop->obj());
2412 __ Move(StoreDescriptor::ReceiverRegister(), eax);
2413 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2414 __ mov(StoreDescriptor::NameRegister(),
2415 prop->key()->AsLiteral()->value());
2419 case KEYED_PROPERTY: {
2420 __ push(eax); // Preserve value.
2421 VisitForStackValue(prop->obj());
2422 VisitForAccumulatorValue(prop->key());
2423 __ Move(StoreDescriptor::NameRegister(), eax);
2424 __ pop(StoreDescriptor::ReceiverRegister()); // Receiver.
2425 __ pop(StoreDescriptor::ValueRegister()); // Restore value.
2427 CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
2432 context()->Plug(eax);
2436 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2437 Variable* var, MemOperand location) {
2438 __ mov(location, eax);
2439 if (var->IsContextSlot()) {
2441 int offset = Context::SlotOffset(var->index());
2442 __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2447 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2449 if (var->IsUnallocated()) {
2450 // Global var, const, or let.
2451 __ mov(StoreDescriptor::NameRegister(), var->name());
2452 __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2455 } else if (op == Token::INIT_CONST_LEGACY) {
2456 // Const initializers need a write barrier.
2457 DCHECK(!var->IsParameter()); // No const parameters.
2458 if (var->IsLookupSlot()) {
2461 __ push(Immediate(var->name()));
2462 __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2464 DCHECK(var->IsStackLocal() || var->IsContextSlot());
2466 MemOperand location = VarOperand(var, ecx);
2467 __ mov(edx, location);
2468 __ cmp(edx, isolate()->factory()->the_hole_value());
2469 __ j(not_equal, &skip, Label::kNear);
2470 EmitStoreToStackLocalOrContextSlot(var, location);
2474 } else if (var->mode() == LET && op != Token::INIT_LET) {
2475 // Non-initializing assignment to let variable needs a write barrier.
2476 DCHECK(!var->IsLookupSlot());
2477 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2479 MemOperand location = VarOperand(var, ecx);
2480 __ mov(edx, location);
2481 __ cmp(edx, isolate()->factory()->the_hole_value());
2482 __ j(not_equal, &assign, Label::kNear);
2483 __ push(Immediate(var->name()));
2484 __ CallRuntime(Runtime::kThrowReferenceError, 1);
2486 EmitStoreToStackLocalOrContextSlot(var, location);
2488 } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2489 if (var->IsLookupSlot()) {
2490 // Assignment to var.
2491 __ push(eax); // Value.
2492 __ push(esi); // Context.
2493 __ push(Immediate(var->name()));
2494 __ push(Immediate(Smi::FromInt(strict_mode())));
2495 __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2497 // Assignment to var or initializing assignment to let/const in harmony
2499 DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2500 MemOperand location = VarOperand(var, ecx);
2501 if (generate_debug_code_ && op == Token::INIT_LET) {
2502 // Check for an uninitialized let binding.
2503 __ mov(edx, location);
2504 __ cmp(edx, isolate()->factory()->the_hole_value());
2505 __ Check(equal, kLetBindingReInitialization);
2507 EmitStoreToStackLocalOrContextSlot(var, location);
2510 // Non-initializing assignments to consts are ignored.
2514 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2515 // Assignment to a property, using a named store IC.
2517 // esp[0] : receiver
2519 Property* prop = expr->target()->AsProperty();
2520 DCHECK(prop != NULL);
2521 DCHECK(prop->key()->IsLiteral());
2523 // Record source code position before IC call.
2524 SetSourcePosition(expr->position());
2525 __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2526 __ pop(StoreDescriptor::ReceiverRegister());
2527 CallStoreIC(expr->AssignmentFeedbackId());
2528 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2529 context()->Plug(eax);
2533 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2534 // Assignment to a property, using a keyed store IC.
2537 // esp[kPointerSize] : receiver
2539 __ pop(StoreDescriptor::NameRegister()); // Key.
2540 __ pop(StoreDescriptor::ReceiverRegister());
2541 DCHECK(StoreDescriptor::ValueRegister().is(eax));
2542 // Record source code position before IC call.
2543 SetSourcePosition(expr->position());
2544 Handle<Code> ic = CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
2545 CallIC(ic, expr->AssignmentFeedbackId());
2547 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2548 context()->Plug(eax);
2552 void FullCodeGenerator::VisitProperty(Property* expr) {
2553 Comment cmnt(masm_, "[ Property");
2554 Expression* key = expr->key();
2556 if (key->IsPropertyName()) {
2557 if (!expr->IsSuperAccess()) {
2558 VisitForAccumulatorValue(expr->obj());
2559 __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2560 EmitNamedPropertyLoad(expr);
2562 EmitNamedSuperPropertyLoad(expr);
2564 PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2565 context()->Plug(eax);
2567 VisitForStackValue(expr->obj());
2568 VisitForAccumulatorValue(expr->key());
2569 __ pop(LoadDescriptor::ReceiverRegister()); // Object.
2570 __ Move(LoadDescriptor::NameRegister(), result_register()); // Key.
2571 EmitKeyedPropertyLoad(expr);
2572 context()->Plug(eax);
2577 void FullCodeGenerator::CallIC(Handle<Code> code,
2578 TypeFeedbackId ast_id) {
2580 __ call(code, RelocInfo::CODE_TARGET, ast_id);
2584 // Code common for calls using the IC.
2585 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2586 Expression* callee = expr->expression();
2588 CallICState::CallType call_type =
2589 callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2590 // Get the target function.
2591 if (call_type == CallICState::FUNCTION) {
2592 { StackValueContext context(this);
2593 EmitVariableLoad(callee->AsVariableProxy());
2594 PrepareForBailout(callee, NO_REGISTERS);
2596 // Push undefined as receiver. This is patched in the method prologue if it
2597 // is a sloppy mode method.
2598 __ push(Immediate(isolate()->factory()->undefined_value()));
2600 // Load the function from the receiver.
2601 DCHECK(callee->IsProperty());
2602 DCHECK(!callee->AsProperty()->IsSuperAccess());
2603 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2604 EmitNamedPropertyLoad(callee->AsProperty());
2605 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2606 // Push the target function under the receiver.
2607 __ push(Operand(esp, 0));
2608 __ mov(Operand(esp, kPointerSize), eax);
2611 EmitCall(expr, call_type);
2615 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2616 Expression* callee = expr->expression();
2617 DCHECK(callee->IsProperty());
2618 Property* prop = callee->AsProperty();
2619 DCHECK(prop->IsSuperAccess());
2621 SetSourcePosition(prop->position());
2622 Literal* key = prop->key()->AsLiteral();
2623 DCHECK(!key->value()->IsSmi());
2624 // Load the function from the receiver.
2625 SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2626 EmitLoadHomeObject(super_ref);
2628 VisitForAccumulatorValue(super_ref->this_var());
2630 __ push(Operand(esp, kPointerSize));
2632 __ push(Immediate(key->value()));
2635 // - this (receiver)
2636 // - home_object <-- LoadFromSuper will pop here and below.
2637 // - this (receiver)
2639 __ CallRuntime(Runtime::kLoadFromSuper, 3);
2641 // Replace home_object with target function.
2642 __ mov(Operand(esp, kPointerSize), eax);
2645 // - target function
2646 // - this (receiver)
2647 EmitCall(expr, CallICState::METHOD);
2651 // Code common for calls using the IC.
2652 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2655 VisitForAccumulatorValue(key);
2657 Expression* callee = expr->expression();
2659 // Load the function from the receiver.
2660 DCHECK(callee->IsProperty());
2661 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2662 __ mov(LoadDescriptor::NameRegister(), eax);
2663 EmitKeyedPropertyLoad(callee->AsProperty());
2664 PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2666 // Push the target function under the receiver.
2667 __ push(Operand(esp, 0));
2668 __ mov(Operand(esp, kPointerSize), eax);
2670 EmitCall(expr, CallICState::METHOD);
2674 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2675 // Load the arguments.
2676 ZoneList<Expression*>* args = expr->arguments();
2677 int arg_count = args->length();
2678 { PreservePositionScope scope(masm()->positions_recorder());
2679 for (int i = 0; i < arg_count; i++) {
2680 VisitForStackValue(args->at(i));
2684 // Record source position of the IC call.
2685 SetSourcePosition(expr->position());
2686 Handle<Code> ic = CallIC::initialize_stub(
2687 isolate(), arg_count, call_type);
2688 __ Move(edx, Immediate(Smi::FromInt(expr->CallFeedbackSlot())));
2689 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2690 // Don't assign a type feedback id to the IC, since type feedback is provided
2691 // by the vector above.
2694 RecordJSReturnSite(expr);
2696 // Restore context register.
2697 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2699 context()->DropAndPlug(1, eax);
2703 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2704 // Push copy of the first argument or undefined if it doesn't exist.
2705 if (arg_count > 0) {
2706 __ push(Operand(esp, arg_count * kPointerSize));
2708 __ push(Immediate(isolate()->factory()->undefined_value()));
2711 // Push the receiver of the enclosing function.
2712 __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2713 // Push the language mode.
2714 __ push(Immediate(Smi::FromInt(strict_mode())));
2716 // Push the start position of the scope the calls resides in.
2717 __ push(Immediate(Smi::FromInt(scope()->start_position())));
2719 // Do the runtime call.
2720 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 5);
2724 void FullCodeGenerator::VisitCall(Call* expr) {
2726 // We want to verify that RecordJSReturnSite gets called on all paths
2727 // through this function. Avoid early returns.
2728 expr->return_is_recorded_ = false;
2731 Comment cmnt(masm_, "[ Call");
2732 Expression* callee = expr->expression();
2733 Call::CallType call_type = expr->GetCallType(isolate());
2735 if (call_type == Call::POSSIBLY_EVAL_CALL) {
2736 // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
2737 // to resolve the function we need to call and the receiver of the call.
2738 // Then we call the resolved function using the given arguments.
2739 ZoneList<Expression*>* args = expr->arguments();
2740 int arg_count = args->length();
2741 { PreservePositionScope pos_scope(masm()->positions_recorder());
2742 VisitForStackValue(callee);
2743 // Reserved receiver slot.
2744 __ push(Immediate(isolate()->factory()->undefined_value()));
2745 // Push the arguments.
2746 for (int i = 0; i < arg_count; i++) {
2747 VisitForStackValue(args->at(i));
2750 // Push a copy of the function (found below the arguments) and
2752 __ push(Operand(esp, (arg_count + 1) * kPointerSize));
2753 EmitResolvePossiblyDirectEval(arg_count);
2755 // The runtime call returns a pair of values in eax (function) and
2756 // edx (receiver). Touch up the stack with the right values.
2757 __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
2758 __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
2760 // Record source position for debugger.
2761 SetSourcePosition(expr->position());
2762 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
2763 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2765 RecordJSReturnSite(expr);
2766 // Restore context register.
2767 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2768 context()->DropAndPlug(1, eax);
2770 } else if (call_type == Call::GLOBAL_CALL) {
2771 EmitCallWithLoadIC(expr);
2773 } else if (call_type == Call::LOOKUP_SLOT_CALL) {
2774 // Call to a lookup slot (dynamically introduced variable).
2775 VariableProxy* proxy = callee->AsVariableProxy();
2777 { PreservePositionScope scope(masm()->positions_recorder());
2778 // Generate code for loading from variables potentially shadowed by
2779 // eval-introduced variables.
2780 EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
2783 // Call the runtime to find the function to call (returned in eax) and
2784 // the object holding it (returned in edx).
2785 __ push(context_register());
2786 __ push(Immediate(proxy->name()));
2787 __ CallRuntime(Runtime::kLoadLookupSlot, 2);
2788 __ push(eax); // Function.
2789 __ push(edx); // Receiver.
2791 // If fast case code has been generated, emit code to push the function
2792 // and receiver and have the slow path jump around this code.
2793 if (done.is_linked()) {
2795 __ jmp(&call, Label::kNear);
2799 // The receiver is implicitly the global receiver. Indicate this by
2800 // passing the hole to the call function stub.
2801 __ push(Immediate(isolate()->factory()->undefined_value()));
2805 // The receiver is either the global receiver or an object found by
2809 } else if (call_type == Call::PROPERTY_CALL) {
2810 Property* property = callee->AsProperty();
2811 bool is_named_call = property->key()->IsPropertyName();
2812 // super.x() is handled in EmitCallWithLoadIC.
2813 if (property->IsSuperAccess() && is_named_call) {
2814 EmitSuperCallWithLoadIC(expr);
2817 PreservePositionScope scope(masm()->positions_recorder());
2818 VisitForStackValue(property->obj());
2820 if (is_named_call) {
2821 EmitCallWithLoadIC(expr);
2823 EmitKeyedCallWithLoadIC(expr, property->key());
2827 DCHECK(call_type == Call::OTHER_CALL);
2828 // Call to an arbitrary expression not handled specially above.
2829 { PreservePositionScope scope(masm()->positions_recorder());
2830 VisitForStackValue(callee);
2832 __ push(Immediate(isolate()->factory()->undefined_value()));
2833 // Emit function call.
2838 // RecordJSReturnSite should have been called.
2839 DCHECK(expr->return_is_recorded_);
2844 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
2845 Comment cmnt(masm_, "[ CallNew");
2846 // According to ECMA-262, section 11.2.2, page 44, the function
2847 // expression in new calls must be evaluated before the
2850 // Push constructor on the stack. If it's not a function it's used as
2851 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
2853 VisitForStackValue(expr->expression());
2855 // Push the arguments ("left-to-right") on the stack.
2856 ZoneList<Expression*>* args = expr->arguments();
2857 int arg_count = args->length();
2858 for (int i = 0; i < arg_count; i++) {
2859 VisitForStackValue(args->at(i));
2862 // Call the construct call builtin that handles allocation and
2863 // constructor invocation.
2864 SetSourcePosition(expr->position());
2866 // Load function and argument count into edi and eax.
2867 __ Move(eax, Immediate(arg_count));
2868 __ mov(edi, Operand(esp, arg_count * kPointerSize));
2870 // Record call targets in unoptimized code.
2871 if (FLAG_pretenuring_call_new) {
2872 EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
2873 DCHECK(expr->AllocationSiteFeedbackSlot() ==
2874 expr->CallNewFeedbackSlot() + 1);
2877 __ LoadHeapObject(ebx, FeedbackVector());
2878 __ mov(edx, Immediate(Smi::FromInt(expr->CallNewFeedbackSlot())));
2880 CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
2881 __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
2882 PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
2883 context()->Plug(eax);
2887 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
2888 ZoneList<Expression*>* args = expr->arguments();
2889 DCHECK(args->length() == 1);
2891 VisitForAccumulatorValue(args->at(0));
2893 Label materialize_true, materialize_false;
2894 Label* if_true = NULL;
2895 Label* if_false = NULL;
2896 Label* fall_through = NULL;
2897 context()->PrepareTest(&materialize_true, &materialize_false,
2898 &if_true, &if_false, &fall_through);
2900 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2901 __ test(eax, Immediate(kSmiTagMask));
2902 Split(zero, if_true, if_false, fall_through);
2904 context()->Plug(if_true, if_false);
2908 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
2909 ZoneList<Expression*>* args = expr->arguments();
2910 DCHECK(args->length() == 1);
2912 VisitForAccumulatorValue(args->at(0));
2914 Label materialize_true, materialize_false;
2915 Label* if_true = NULL;
2916 Label* if_false = NULL;
2917 Label* fall_through = NULL;
2918 context()->PrepareTest(&materialize_true, &materialize_false,
2919 &if_true, &if_false, &fall_through);
2921 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2922 __ test(eax, Immediate(kSmiTagMask | 0x80000000));
2923 Split(zero, if_true, if_false, fall_through);
2925 context()->Plug(if_true, if_false);
2929 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
2930 ZoneList<Expression*>* args = expr->arguments();
2931 DCHECK(args->length() == 1);
2933 VisitForAccumulatorValue(args->at(0));
2935 Label materialize_true, materialize_false;
2936 Label* if_true = NULL;
2937 Label* if_false = NULL;
2938 Label* fall_through = NULL;
2939 context()->PrepareTest(&materialize_true, &materialize_false,
2940 &if_true, &if_false, &fall_through);
2942 __ JumpIfSmi(eax, if_false);
2943 __ cmp(eax, isolate()->factory()->null_value());
2944 __ j(equal, if_true);
2945 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
2946 // Undetectable objects behave like undefined when tested with typeof.
2947 __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
2948 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
2949 __ j(not_zero, if_false);
2950 __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
2951 __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2952 __ j(below, if_false);
2953 __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2954 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2955 Split(below_equal, if_true, if_false, fall_through);
2957 context()->Plug(if_true, if_false);
2961 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
2962 ZoneList<Expression*>* args = expr->arguments();
2963 DCHECK(args->length() == 1);
2965 VisitForAccumulatorValue(args->at(0));
2967 Label materialize_true, materialize_false;
2968 Label* if_true = NULL;
2969 Label* if_false = NULL;
2970 Label* fall_through = NULL;
2971 context()->PrepareTest(&materialize_true, &materialize_false,
2972 &if_true, &if_false, &fall_through);
2974 __ JumpIfSmi(eax, if_false);
2975 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
2976 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2977 Split(above_equal, if_true, if_false, fall_through);
2979 context()->Plug(if_true, if_false);
2983 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
2984 ZoneList<Expression*>* args = expr->arguments();
2985 DCHECK(args->length() == 1);
2987 VisitForAccumulatorValue(args->at(0));
2989 Label materialize_true, materialize_false;
2990 Label* if_true = NULL;
2991 Label* if_false = NULL;
2992 Label* fall_through = NULL;
2993 context()->PrepareTest(&materialize_true, &materialize_false,
2994 &if_true, &if_false, &fall_through);
2996 __ JumpIfSmi(eax, if_false);
2997 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
2998 __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
2999 __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3000 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3001 Split(not_zero, if_true, if_false, fall_through);
3003 context()->Plug(if_true, if_false);
3007 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3008 CallRuntime* expr) {
3009 ZoneList<Expression*>* args = expr->arguments();
3010 DCHECK(args->length() == 1);
3012 VisitForAccumulatorValue(args->at(0));
3014 Label materialize_true, materialize_false, skip_lookup;
3015 Label* if_true = NULL;
3016 Label* if_false = NULL;
3017 Label* fall_through = NULL;
3018 context()->PrepareTest(&materialize_true, &materialize_false,
3019 &if_true, &if_false, &fall_through);
3021 __ AssertNotSmi(eax);
3023 // Check whether this map has already been checked to be safe for default
3025 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3026 __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3027 1 << Map::kStringWrapperSafeForDefaultValueOf);
3028 __ j(not_zero, &skip_lookup);
3030 // Check for fast case object. Return false for slow case objects.
3031 __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3032 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3033 __ cmp(ecx, isolate()->factory()->hash_table_map());
3034 __ j(equal, if_false);
3036 // Look for valueOf string in the descriptor array, and indicate false if
3037 // found. Since we omit an enumeration index check, if it is added via a
3038 // transition that shares its descriptor array, this is a false positive.
3039 Label entry, loop, done;
3041 // Skip loop if no descriptors are valid.
3042 __ NumberOfOwnDescriptors(ecx, ebx);
3046 __ LoadInstanceDescriptors(ebx, ebx);
3047 // ebx: descriptor array.
3048 // ecx: valid entries in the descriptor array.
3049 // Calculate the end of the descriptor array.
3050 STATIC_ASSERT(kSmiTag == 0);
3051 STATIC_ASSERT(kSmiTagSize == 1);
3052 STATIC_ASSERT(kPointerSize == 4);
3053 __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3054 __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3055 // Calculate location of the first key name.
3056 __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3057 // Loop through all the keys in the descriptor array. If one of these is the
3058 // internalized string "valueOf" the result is false.
3061 __ mov(edx, FieldOperand(ebx, 0));
3062 __ cmp(edx, isolate()->factory()->value_of_string());
3063 __ j(equal, if_false);
3064 __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3067 __ j(not_equal, &loop);
3071 // Reload map as register ebx was used as temporary above.
3072 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3074 // Set the bit in the map to indicate that there is no local valueOf field.
3075 __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3076 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3078 __ bind(&skip_lookup);
3080 // If a valueOf property is not found on the object check that its
3081 // prototype is the un-modified String prototype. If not result is false.
3082 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3083 __ JumpIfSmi(ecx, if_false);
3084 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3085 __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3087 FieldOperand(edx, GlobalObject::kNativeContextOffset));
3090 Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3091 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3092 Split(equal, if_true, if_false, fall_through);
3094 context()->Plug(if_true, if_false);
3098 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3099 ZoneList<Expression*>* args = expr->arguments();
3100 DCHECK(args->length() == 1);
3102 VisitForAccumulatorValue(args->at(0));
3104 Label materialize_true, materialize_false;
3105 Label* if_true = NULL;
3106 Label* if_false = NULL;
3107 Label* fall_through = NULL;
3108 context()->PrepareTest(&materialize_true, &materialize_false,
3109 &if_true, &if_false, &fall_through);
3111 __ JumpIfSmi(eax, if_false);
3112 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3113 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3114 Split(equal, if_true, if_false, fall_through);
3116 context()->Plug(if_true, if_false);
3120 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3121 ZoneList<Expression*>* args = expr->arguments();
3122 DCHECK(args->length() == 1);
3124 VisitForAccumulatorValue(args->at(0));
3126 Label materialize_true, materialize_false;
3127 Label* if_true = NULL;
3128 Label* if_false = NULL;
3129 Label* fall_through = NULL;
3130 context()->PrepareTest(&materialize_true, &materialize_false,
3131 &if_true, &if_false, &fall_through);
3133 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3134 __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3135 // Check if the exponent half is 0x80000000. Comparing against 1 and
3136 // checking for overflow is the shortest possible encoding.
3137 __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3138 __ j(no_overflow, if_false);
3139 __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3140 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3141 Split(equal, if_true, if_false, fall_through);
3143 context()->Plug(if_true, if_false);
3148 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3149 ZoneList<Expression*>* args = expr->arguments();
3150 DCHECK(args->length() == 1);
3152 VisitForAccumulatorValue(args->at(0));
3154 Label materialize_true, materialize_false;
3155 Label* if_true = NULL;
3156 Label* if_false = NULL;
3157 Label* fall_through = NULL;
3158 context()->PrepareTest(&materialize_true, &materialize_false,
3159 &if_true, &if_false, &fall_through);
3161 __ JumpIfSmi(eax, if_false);
3162 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3163 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3164 Split(equal, if_true, if_false, fall_through);
3166 context()->Plug(if_true, if_false);
3170 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3171 ZoneList<Expression*>* args = expr->arguments();
3172 DCHECK(args->length() == 1);
3174 VisitForAccumulatorValue(args->at(0));
3176 Label materialize_true, materialize_false;
3177 Label* if_true = NULL;
3178 Label* if_false = NULL;
3179 Label* fall_through = NULL;
3180 context()->PrepareTest(&materialize_true, &materialize_false,
3181 &if_true, &if_false, &fall_through);
3183 __ JumpIfSmi(eax, if_false);
3184 __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3185 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3186 Split(equal, if_true, if_false, fall_through);
3188 context()->Plug(if_true, if_false);
3193 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3194 DCHECK(expr->arguments()->length() == 0);
3196 Label materialize_true, materialize_false;
3197 Label* if_true = NULL;
3198 Label* if_false = NULL;
3199 Label* fall_through = NULL;
3200 context()->PrepareTest(&materialize_true, &materialize_false,
3201 &if_true, &if_false, &fall_through);
3203 // Get the frame pointer for the calling frame.
3204 __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3206 // Skip the arguments adaptor frame if it exists.
3207 Label check_frame_marker;
3208 __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3209 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3210 __ j(not_equal, &check_frame_marker);
3211 __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3213 // Check the marker in the calling frame.
3214 __ bind(&check_frame_marker);
3215 __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3216 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3217 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3218 Split(equal, if_true, if_false, fall_through);
3220 context()->Plug(if_true, if_false);
3224 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3225 ZoneList<Expression*>* args = expr->arguments();
3226 DCHECK(args->length() == 2);
3228 // Load the two objects into registers and perform the comparison.
3229 VisitForStackValue(args->at(0));
3230 VisitForAccumulatorValue(args->at(1));
3232 Label materialize_true, materialize_false;
3233 Label* if_true = NULL;
3234 Label* if_false = NULL;
3235 Label* fall_through = NULL;
3236 context()->PrepareTest(&materialize_true, &materialize_false,
3237 &if_true, &if_false, &fall_through);
3241 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3242 Split(equal, if_true, if_false, fall_through);
3244 context()->Plug(if_true, if_false);
3248 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3249 ZoneList<Expression*>* args = expr->arguments();
3250 DCHECK(args->length() == 1);
3252 // ArgumentsAccessStub expects the key in edx and the formal
3253 // parameter count in eax.
3254 VisitForAccumulatorValue(args->at(0));
3256 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3257 ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3259 context()->Plug(eax);
3263 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3264 DCHECK(expr->arguments()->length() == 0);
3267 // Get the number of formal parameters.
3268 __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3270 // Check if the calling frame is an arguments adaptor frame.
3271 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3272 __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3273 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3274 __ j(not_equal, &exit);
3276 // Arguments adaptor case: Read the arguments length from the
3278 __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3282 context()->Plug(eax);
3286 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3287 ZoneList<Expression*>* args = expr->arguments();
3288 DCHECK(args->length() == 1);
3289 Label done, null, function, non_function_constructor;
3291 VisitForAccumulatorValue(args->at(0));
3293 // If the object is a smi, we return null.
3294 __ JumpIfSmi(eax, &null);
3296 // Check that the object is a JS object but take special care of JS
3297 // functions to make sure they have 'Function' as their class.
3298 // Assume that there are only two callable types, and one of them is at
3299 // either end of the type range for JS object types. Saves extra comparisons.
3300 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3301 __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3302 // Map is now in eax.
3304 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3305 FIRST_SPEC_OBJECT_TYPE + 1);
3306 __ j(equal, &function);
3308 __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3309 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3310 LAST_SPEC_OBJECT_TYPE - 1);
3311 __ j(equal, &function);
3312 // Assume that there is no larger type.
3313 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3315 // Check if the constructor in the map is a JS function.
3316 __ mov(eax, FieldOperand(eax, Map::kConstructorOffset));
3317 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3318 __ j(not_equal, &non_function_constructor);
3320 // eax now contains the constructor function. Grab the
3321 // instance class name from there.
3322 __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3323 __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3326 // Functions have class 'Function'.
3328 __ mov(eax, isolate()->factory()->Function_string());
3331 // Objects with a non-function constructor have class 'Object'.
3332 __ bind(&non_function_constructor);
3333 __ mov(eax, isolate()->factory()->Object_string());
3336 // Non-JS objects have class null.
3338 __ mov(eax, isolate()->factory()->null_value());
3343 context()->Plug(eax);
3347 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3348 // Load the arguments on the stack and call the stub.
3349 SubStringStub stub(isolate());
3350 ZoneList<Expression*>* args = expr->arguments();
3351 DCHECK(args->length() == 3);
3352 VisitForStackValue(args->at(0));
3353 VisitForStackValue(args->at(1));
3354 VisitForStackValue(args->at(2));
3356 context()->Plug(eax);
3360 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3361 // Load the arguments on the stack and call the stub.
3362 RegExpExecStub stub(isolate());
3363 ZoneList<Expression*>* args = expr->arguments();
3364 DCHECK(args->length() == 4);
3365 VisitForStackValue(args->at(0));
3366 VisitForStackValue(args->at(1));
3367 VisitForStackValue(args->at(2));
3368 VisitForStackValue(args->at(3));
3370 context()->Plug(eax);
3374 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3375 ZoneList<Expression*>* args = expr->arguments();
3376 DCHECK(args->length() == 1);
3378 VisitForAccumulatorValue(args->at(0)); // Load the object.
3381 // If the object is a smi return the object.
3382 __ JumpIfSmi(eax, &done, Label::kNear);
3383 // If the object is not a value type, return the object.
3384 __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3385 __ j(not_equal, &done, Label::kNear);
3386 __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3389 context()->Plug(eax);
3393 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3394 ZoneList<Expression*>* args = expr->arguments();
3395 DCHECK(args->length() == 2);
3396 DCHECK_NE(NULL, args->at(1)->AsLiteral());
3397 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3399 VisitForAccumulatorValue(args->at(0)); // Load the object.
3401 Label runtime, done, not_date_object;
3402 Register object = eax;
3403 Register result = eax;
3404 Register scratch = ecx;
3406 __ JumpIfSmi(object, ¬_date_object);
3407 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3408 __ j(not_equal, ¬_date_object);
3410 if (index->value() == 0) {
3411 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3414 if (index->value() < JSDate::kFirstUncachedField) {
3415 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3416 __ mov(scratch, Operand::StaticVariable(stamp));
3417 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3418 __ j(not_equal, &runtime, Label::kNear);
3419 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3420 kPointerSize * index->value()));
3424 __ PrepareCallCFunction(2, scratch);
3425 __ mov(Operand(esp, 0), object);
3426 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3427 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3431 __ bind(¬_date_object);
3432 __ CallRuntime(Runtime::kThrowNotDateError, 0);
3434 context()->Plug(result);
3438 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3439 ZoneList<Expression*>* args = expr->arguments();
3440 DCHECK_EQ(3, args->length());
3442 Register string = eax;
3443 Register index = ebx;
3444 Register value = ecx;
3446 VisitForStackValue(args->at(0)); // index
3447 VisitForStackValue(args->at(1)); // value
3448 VisitForAccumulatorValue(args->at(2)); // string
3453 if (FLAG_debug_code) {
3454 __ test(value, Immediate(kSmiTagMask));
3455 __ Check(zero, kNonSmiValue);
3456 __ test(index, Immediate(kSmiTagMask));
3457 __ Check(zero, kNonSmiValue);
3463 if (FLAG_debug_code) {
3464 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3465 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3468 __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3470 context()->Plug(string);
3474 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3475 ZoneList<Expression*>* args = expr->arguments();
3476 DCHECK_EQ(3, args->length());
3478 Register string = eax;
3479 Register index = ebx;
3480 Register value = ecx;
3482 VisitForStackValue(args->at(0)); // index
3483 VisitForStackValue(args->at(1)); // value
3484 VisitForAccumulatorValue(args->at(2)); // string
3488 if (FLAG_debug_code) {
3489 __ test(value, Immediate(kSmiTagMask));
3490 __ Check(zero, kNonSmiValue);
3491 __ test(index, Immediate(kSmiTagMask));
3492 __ Check(zero, kNonSmiValue);
3494 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3495 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3500 // No need to untag a smi for two-byte addressing.
3501 __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3503 context()->Plug(string);
3507 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3508 // Load the arguments on the stack and call the runtime function.
3509 ZoneList<Expression*>* args = expr->arguments();
3510 DCHECK(args->length() == 2);
3511 VisitForStackValue(args->at(0));
3512 VisitForStackValue(args->at(1));
3514 MathPowStub stub(isolate(), MathPowStub::ON_STACK);
3516 context()->Plug(eax);
3520 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3521 ZoneList<Expression*>* args = expr->arguments();
3522 DCHECK(args->length() == 2);
3524 VisitForStackValue(args->at(0)); // Load the object.
3525 VisitForAccumulatorValue(args->at(1)); // Load the value.
3526 __ pop(ebx); // eax = value. ebx = object.
3529 // If the object is a smi, return the value.
3530 __ JumpIfSmi(ebx, &done, Label::kNear);
3532 // If the object is not a value type, return the value.
3533 __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3534 __ j(not_equal, &done, Label::kNear);
3537 __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3539 // Update the write barrier. Save the value as it will be
3540 // overwritten by the write barrier code and is needed afterward.
3542 __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3545 context()->Plug(eax);
3549 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3550 ZoneList<Expression*>* args = expr->arguments();
3551 DCHECK_EQ(args->length(), 1);
3553 // Load the argument into eax and call the stub.
3554 VisitForAccumulatorValue(args->at(0));
3556 NumberToStringStub stub(isolate());
3558 context()->Plug(eax);
3562 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3563 ZoneList<Expression*>* args = expr->arguments();
3564 DCHECK(args->length() == 1);
3566 VisitForAccumulatorValue(args->at(0));
3569 StringCharFromCodeGenerator generator(eax, ebx);
3570 generator.GenerateFast(masm_);
3573 NopRuntimeCallHelper call_helper;
3574 generator.GenerateSlow(masm_, call_helper);
3577 context()->Plug(ebx);
3581 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3582 ZoneList<Expression*>* args = expr->arguments();
3583 DCHECK(args->length() == 2);
3585 VisitForStackValue(args->at(0));
3586 VisitForAccumulatorValue(args->at(1));
3588 Register object = ebx;
3589 Register index = eax;
3590 Register result = edx;
3594 Label need_conversion;
3595 Label index_out_of_range;
3597 StringCharCodeAtGenerator generator(object,
3602 &index_out_of_range,
3603 STRING_INDEX_IS_NUMBER);
3604 generator.GenerateFast(masm_);
3607 __ bind(&index_out_of_range);
3608 // When the index is out of range, the spec requires us to return
3610 __ Move(result, Immediate(isolate()->factory()->nan_value()));
3613 __ bind(&need_conversion);
3614 // Move the undefined value into the result register, which will
3615 // trigger conversion.
3616 __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3619 NopRuntimeCallHelper call_helper;
3620 generator.GenerateSlow(masm_, call_helper);
3623 context()->Plug(result);
3627 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3628 ZoneList<Expression*>* args = expr->arguments();
3629 DCHECK(args->length() == 2);
3631 VisitForStackValue(args->at(0));
3632 VisitForAccumulatorValue(args->at(1));
3634 Register object = ebx;
3635 Register index = eax;
3636 Register scratch = edx;
3637 Register result = eax;
3641 Label need_conversion;
3642 Label index_out_of_range;
3644 StringCharAtGenerator generator(object,
3650 &index_out_of_range,
3651 STRING_INDEX_IS_NUMBER);
3652 generator.GenerateFast(masm_);
3655 __ bind(&index_out_of_range);
3656 // When the index is out of range, the spec requires us to return
3657 // the empty string.
3658 __ Move(result, Immediate(isolate()->factory()->empty_string()));
3661 __ bind(&need_conversion);
3662 // Move smi zero into the result register, which will trigger
3664 __ Move(result, Immediate(Smi::FromInt(0)));
3667 NopRuntimeCallHelper call_helper;
3668 generator.GenerateSlow(masm_, call_helper);
3671 context()->Plug(result);
3675 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
3676 ZoneList<Expression*>* args = expr->arguments();
3677 DCHECK_EQ(2, args->length());
3678 VisitForStackValue(args->at(0));
3679 VisitForAccumulatorValue(args->at(1));
3682 StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
3684 context()->Plug(eax);
3688 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
3689 ZoneList<Expression*>* args = expr->arguments();
3690 DCHECK_EQ(2, args->length());
3692 VisitForStackValue(args->at(0));
3693 VisitForStackValue(args->at(1));
3695 StringCompareStub stub(isolate());
3697 context()->Plug(eax);
3701 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
3702 ZoneList<Expression*>* args = expr->arguments();
3703 DCHECK(args->length() >= 2);
3705 int arg_count = args->length() - 2; // 2 ~ receiver and function.
3706 for (int i = 0; i < arg_count + 1; ++i) {
3707 VisitForStackValue(args->at(i));
3709 VisitForAccumulatorValue(args->last()); // Function.
3711 Label runtime, done;
3712 // Check for non-function argument (including proxy).
3713 __ JumpIfSmi(eax, &runtime);
3714 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3715 __ j(not_equal, &runtime);
3717 // InvokeFunction requires the function in edi. Move it in there.
3718 __ mov(edi, result_register());
3719 ParameterCount count(arg_count);
3720 __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
3721 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3726 __ CallRuntime(Runtime::kCall, args->length());
3729 context()->Plug(eax);
3733 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
3734 // Load the arguments on the stack and call the stub.
3735 RegExpConstructResultStub stub(isolate());
3736 ZoneList<Expression*>* args = expr->arguments();
3737 DCHECK(args->length() == 3);
3738 VisitForStackValue(args->at(0));
3739 VisitForStackValue(args->at(1));
3740 VisitForAccumulatorValue(args->at(2));
3744 context()->Plug(eax);
3748 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
3749 ZoneList<Expression*>* args = expr->arguments();
3750 DCHECK_EQ(2, args->length());
3752 DCHECK_NE(NULL, args->at(0)->AsLiteral());
3753 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
3755 Handle<FixedArray> jsfunction_result_caches(
3756 isolate()->native_context()->jsfunction_result_caches());
3757 if (jsfunction_result_caches->length() <= cache_id) {
3758 __ Abort(kAttemptToUseUndefinedCache);
3759 __ mov(eax, isolate()->factory()->undefined_value());
3760 context()->Plug(eax);
3764 VisitForAccumulatorValue(args->at(1));
3767 Register cache = ebx;
3769 __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
3771 FieldOperand(cache, GlobalObject::kNativeContextOffset));
3772 __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
3774 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
3776 Label done, not_found;
3777 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
3778 __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
3779 // tmp now holds finger offset as a smi.
3780 __ cmp(key, FixedArrayElementOperand(cache, tmp));
3781 __ j(not_equal, ¬_found);
3783 __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
3786 __ bind(¬_found);
3787 // Call runtime to perform the lookup.
3790 __ CallRuntime(Runtime::kGetFromCache, 2);
3793 context()->Plug(eax);
3797 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
3798 ZoneList<Expression*>* args = expr->arguments();
3799 DCHECK(args->length() == 1);
3801 VisitForAccumulatorValue(args->at(0));
3803 __ AssertString(eax);
3805 Label materialize_true, materialize_false;
3806 Label* if_true = NULL;
3807 Label* if_false = NULL;
3808 Label* fall_through = NULL;
3809 context()->PrepareTest(&materialize_true, &materialize_false,
3810 &if_true, &if_false, &fall_through);
3812 __ test(FieldOperand(eax, String::kHashFieldOffset),
3813 Immediate(String::kContainsCachedArrayIndexMask));
3814 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3815 Split(zero, if_true, if_false, fall_through);
3817 context()->Plug(if_true, if_false);
3821 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
3822 ZoneList<Expression*>* args = expr->arguments();
3823 DCHECK(args->length() == 1);
3824 VisitForAccumulatorValue(args->at(0));
3826 __ AssertString(eax);
3828 __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
3829 __ IndexFromHash(eax, eax);
3831 context()->Plug(eax);
3835 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
3836 Label bailout, done, one_char_separator, long_separator,
3837 non_trivial_array, not_size_one_array, loop,
3838 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
3840 ZoneList<Expression*>* args = expr->arguments();
3841 DCHECK(args->length() == 2);
3842 // We will leave the separator on the stack until the end of the function.
3843 VisitForStackValue(args->at(1));
3844 // Load this to eax (= array)
3845 VisitForAccumulatorValue(args->at(0));
3846 // All aliases of the same register have disjoint lifetimes.
3847 Register array = eax;
3848 Register elements = no_reg; // Will be eax.
3850 Register index = edx;
3852 Register string_length = ecx;
3854 Register string = esi;
3856 Register scratch = ebx;
3858 Register array_length = edi;
3859 Register result_pos = no_reg; // Will be edi.
3861 // Separator operand is already pushed.
3862 Operand separator_operand = Operand(esp, 2 * kPointerSize);
3863 Operand result_operand = Operand(esp, 1 * kPointerSize);
3864 Operand array_length_operand = Operand(esp, 0);
3865 __ sub(esp, Immediate(2 * kPointerSize));
3867 // Check that the array is a JSArray
3868 __ JumpIfSmi(array, &bailout);
3869 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
3870 __ j(not_equal, &bailout);
3872 // Check that the array has fast elements.
3873 __ CheckFastElements(scratch, &bailout);
3875 // If the array has length zero, return the empty string.
3876 __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
3877 __ SmiUntag(array_length);
3878 __ j(not_zero, &non_trivial_array);
3879 __ mov(result_operand, isolate()->factory()->empty_string());
3882 // Save the array length.
3883 __ bind(&non_trivial_array);
3884 __ mov(array_length_operand, array_length);
3886 // Save the FixedArray containing array's elements.
3887 // End of array's live range.
3889 __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
3893 // Check that all array elements are sequential one-byte strings, and
3894 // accumulate the sum of their lengths, as a smi-encoded value.
3895 __ Move(index, Immediate(0));
3896 __ Move(string_length, Immediate(0));
3897 // Loop condition: while (index < length).
3898 // Live loop registers: index, array_length, string,
3899 // scratch, string_length, elements.
3900 if (generate_debug_code_) {
3901 __ cmp(index, array_length);
3902 __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
3905 __ mov(string, FieldOperand(elements,
3908 FixedArray::kHeaderSize));
3909 __ JumpIfSmi(string, &bailout);
3910 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
3911 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
3912 __ and_(scratch, Immediate(
3913 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
3914 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
3915 __ j(not_equal, &bailout);
3916 __ add(string_length,
3917 FieldOperand(string, SeqOneByteString::kLengthOffset));
3918 __ j(overflow, &bailout);
3919 __ add(index, Immediate(1));
3920 __ cmp(index, array_length);
3923 // If array_length is 1, return elements[0], a string.
3924 __ cmp(array_length, 1);
3925 __ j(not_equal, ¬_size_one_array);
3926 __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
3927 __ mov(result_operand, scratch);
3930 __ bind(¬_size_one_array);
3932 // End of array_length live range.
3933 result_pos = array_length;
3934 array_length = no_reg;
3937 // string_length: Sum of string lengths, as a smi.
3938 // elements: FixedArray of strings.
3940 // Check that the separator is a flat one-byte string.
3941 __ mov(string, separator_operand);
3942 __ JumpIfSmi(string, &bailout);
3943 __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
3944 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
3945 __ and_(scratch, Immediate(
3946 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
3947 __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
3948 __ j(not_equal, &bailout);
3950 // Add (separator length times array_length) - separator length
3951 // to string_length.
3952 __ mov(scratch, separator_operand);
3953 __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
3954 __ sub(string_length, scratch); // May be negative, temporarily.
3955 __ imul(scratch, array_length_operand);
3956 __ j(overflow, &bailout);
3957 __ add(string_length, scratch);
3958 __ j(overflow, &bailout);
3960 __ shr(string_length, 1);
3961 // Live registers and stack values:
3964 __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
3966 __ mov(result_operand, result_pos);
3967 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
3970 __ mov(string, separator_operand);
3971 __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
3972 Immediate(Smi::FromInt(1)));
3973 __ j(equal, &one_char_separator);
3974 __ j(greater, &long_separator);
3977 // Empty separator case
3978 __ mov(index, Immediate(0));
3979 __ jmp(&loop_1_condition);
3980 // Loop condition: while (index < length).
3982 // Each iteration of the loop concatenates one string to the result.
3983 // Live values in registers:
3984 // index: which element of the elements array we are adding to the result.
3985 // result_pos: the position to which we are currently copying characters.
3986 // elements: the FixedArray of strings we are joining.
3988 // Get string = array[index].
3989 __ mov(string, FieldOperand(elements, index,
3991 FixedArray::kHeaderSize));
3992 __ mov(string_length,
3993 FieldOperand(string, String::kLengthOffset));
3994 __ shr(string_length, 1);
3996 FieldOperand(string, SeqOneByteString::kHeaderSize));
3997 __ CopyBytes(string, result_pos, string_length, scratch);
3998 __ add(index, Immediate(1));
3999 __ bind(&loop_1_condition);
4000 __ cmp(index, array_length_operand);
4001 __ j(less, &loop_1); // End while (index < length).
4006 // One-character separator case
4007 __ bind(&one_char_separator);
4008 // Replace separator with its one-byte character value.
4009 __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4010 __ mov_b(separator_operand, scratch);
4012 __ Move(index, Immediate(0));
4013 // Jump into the loop after the code that copies the separator, so the first
4014 // element is not preceded by a separator
4015 __ jmp(&loop_2_entry);
4016 // Loop condition: while (index < length).
4018 // Each iteration of the loop concatenates one string to the result.
4019 // Live values in registers:
4020 // index: which element of the elements array we are adding to the result.
4021 // result_pos: the position to which we are currently copying characters.
4023 // Copy the separator character to the result.
4024 __ mov_b(scratch, separator_operand);
4025 __ mov_b(Operand(result_pos, 0), scratch);
4028 __ bind(&loop_2_entry);
4029 // Get string = array[index].
4030 __ mov(string, FieldOperand(elements, index,
4032 FixedArray::kHeaderSize));
4033 __ mov(string_length,
4034 FieldOperand(string, String::kLengthOffset));
4035 __ shr(string_length, 1);
4037 FieldOperand(string, SeqOneByteString::kHeaderSize));
4038 __ CopyBytes(string, result_pos, string_length, scratch);
4039 __ add(index, Immediate(1));
4041 __ cmp(index, array_length_operand);
4042 __ j(less, &loop_2); // End while (index < length).
4046 // Long separator case (separator is more than one character).
4047 __ bind(&long_separator);
4049 __ Move(index, Immediate(0));
4050 // Jump into the loop after the code that copies the separator, so the first
4051 // element is not preceded by a separator
4052 __ jmp(&loop_3_entry);
4053 // Loop condition: while (index < length).
4055 // Each iteration of the loop concatenates one string to the result.
4056 // Live values in registers:
4057 // index: which element of the elements array we are adding to the result.
4058 // result_pos: the position to which we are currently copying characters.
4060 // Copy the separator to the result.
4061 __ mov(string, separator_operand);
4062 __ mov(string_length,
4063 FieldOperand(string, String::kLengthOffset));
4064 __ shr(string_length, 1);
4066 FieldOperand(string, SeqOneByteString::kHeaderSize));
4067 __ CopyBytes(string, result_pos, string_length, scratch);
4069 __ bind(&loop_3_entry);
4070 // Get string = array[index].
4071 __ mov(string, FieldOperand(elements, index,
4073 FixedArray::kHeaderSize));
4074 __ mov(string_length,
4075 FieldOperand(string, String::kLengthOffset));
4076 __ shr(string_length, 1);
4078 FieldOperand(string, SeqOneByteString::kHeaderSize));
4079 __ CopyBytes(string, result_pos, string_length, scratch);
4080 __ add(index, Immediate(1));
4082 __ cmp(index, array_length_operand);
4083 __ j(less, &loop_3); // End while (index < length).
4088 __ mov(result_operand, isolate()->factory()->undefined_value());
4090 __ mov(eax, result_operand);
4091 // Drop temp values from the stack, and restore context register.
4092 __ add(esp, Immediate(3 * kPointerSize));
4094 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4095 context()->Plug(eax);
4099 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4100 DCHECK(expr->arguments()->length() == 0);
4101 ExternalReference debug_is_active =
4102 ExternalReference::debug_is_active_address(isolate());
4103 __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4105 context()->Plug(eax);
4109 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4110 if (expr->function() != NULL &&
4111 expr->function()->intrinsic_type == Runtime::INLINE) {
4112 Comment cmnt(masm_, "[ InlineRuntimeCall");
4113 EmitInlineRuntimeCall(expr);
4117 Comment cmnt(masm_, "[ CallRuntime");
4118 ZoneList<Expression*>* args = expr->arguments();
4120 if (expr->is_jsruntime()) {
4121 // Push the builtins object as receiver.
4122 __ mov(eax, GlobalObjectOperand());
4123 __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4125 // Load the function from the receiver.
4126 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4127 __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4128 if (FLAG_vector_ics) {
4129 __ mov(VectorLoadICDescriptor::SlotRegister(),
4130 Immediate(Smi::FromInt(expr->CallRuntimeFeedbackSlot())));
4131 CallLoadIC(NOT_CONTEXTUAL);
4133 CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4136 // Push the target function under the receiver.
4137 __ push(Operand(esp, 0));
4138 __ mov(Operand(esp, kPointerSize), eax);
4140 // Code common for calls using the IC.
4141 ZoneList<Expression*>* args = expr->arguments();
4142 int arg_count = args->length();
4143 for (int i = 0; i < arg_count; i++) {
4144 VisitForStackValue(args->at(i));
4147 // Record source position of the IC call.
4148 SetSourcePosition(expr->position());
4149 CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4150 __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4152 // Restore context register.
4153 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4154 context()->DropAndPlug(1, eax);
4157 // Push the arguments ("left-to-right").
4158 int arg_count = args->length();
4159 for (int i = 0; i < arg_count; i++) {
4160 VisitForStackValue(args->at(i));
4163 // Call the C runtime function.
4164 __ CallRuntime(expr->function(), arg_count);
4166 context()->Plug(eax);
4171 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4172 switch (expr->op()) {
4173 case Token::DELETE: {
4174 Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4175 Property* property = expr->expression()->AsProperty();
4176 VariableProxy* proxy = expr->expression()->AsVariableProxy();
4178 if (property != NULL) {
4179 VisitForStackValue(property->obj());
4180 VisitForStackValue(property->key());
4181 __ push(Immediate(Smi::FromInt(strict_mode())));
4182 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4183 context()->Plug(eax);
4184 } else if (proxy != NULL) {
4185 Variable* var = proxy->var();
4186 // Delete of an unqualified identifier is disallowed in strict mode
4187 // but "delete this" is allowed.
4188 DCHECK(strict_mode() == SLOPPY || var->is_this());
4189 if (var->IsUnallocated()) {
4190 __ push(GlobalObjectOperand());
4191 __ push(Immediate(var->name()));
4192 __ push(Immediate(Smi::FromInt(SLOPPY)));
4193 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4194 context()->Plug(eax);
4195 } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4196 // Result of deleting non-global variables is false. 'this' is
4197 // not really a variable, though we implement it as one. The
4198 // subexpression does not have side effects.
4199 context()->Plug(var->is_this());
4201 // Non-global variable. Call the runtime to try to delete from the
4202 // context where the variable was introduced.
4203 __ push(context_register());
4204 __ push(Immediate(var->name()));
4205 __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4206 context()->Plug(eax);
4209 // Result of deleting non-property, non-variable reference is true.
4210 // The subexpression may have side effects.
4211 VisitForEffect(expr->expression());
4212 context()->Plug(true);
4218 Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4219 VisitForEffect(expr->expression());
4220 context()->Plug(isolate()->factory()->undefined_value());
4225 Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4226 if (context()->IsEffect()) {
4227 // Unary NOT has no side effects so it's only necessary to visit the
4228 // subexpression. Match the optimizing compiler by not branching.
4229 VisitForEffect(expr->expression());
4230 } else if (context()->IsTest()) {
4231 const TestContext* test = TestContext::cast(context());
4232 // The labels are swapped for the recursive call.
4233 VisitForControl(expr->expression(),
4234 test->false_label(),
4236 test->fall_through());
4237 context()->Plug(test->true_label(), test->false_label());
4239 // We handle value contexts explicitly rather than simply visiting
4240 // for control and plugging the control flow into the context,
4241 // because we need to prepare a pair of extra administrative AST ids
4242 // for the optimizing compiler.
4243 DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4244 Label materialize_true, materialize_false, done;
4245 VisitForControl(expr->expression(),
4249 __ bind(&materialize_true);
4250 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4251 if (context()->IsAccumulatorValue()) {
4252 __ mov(eax, isolate()->factory()->true_value());
4254 __ Push(isolate()->factory()->true_value());
4256 __ jmp(&done, Label::kNear);
4257 __ bind(&materialize_false);
4258 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4259 if (context()->IsAccumulatorValue()) {
4260 __ mov(eax, isolate()->factory()->false_value());
4262 __ Push(isolate()->factory()->false_value());
4269 case Token::TYPEOF: {
4270 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4271 { StackValueContext context(this);
4272 VisitForTypeofValue(expr->expression());
4274 __ CallRuntime(Runtime::kTypeof, 1);
4275 context()->Plug(eax);
4285 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4286 DCHECK(expr->expression()->IsValidReferenceExpression());
4288 Comment cmnt(masm_, "[ CountOperation");
4289 SetSourcePosition(expr->position());
4291 // Expression can only be a property, a global or a (parameter or local)
4293 enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY };
4294 LhsKind assign_type = VARIABLE;
4295 Property* prop = expr->expression()->AsProperty();
4296 // In case of a property we use the uninitialized expression context
4297 // of the key to detect a named property.
4300 (prop->key()->IsPropertyName()) ? NAMED_PROPERTY : KEYED_PROPERTY;
4303 // Evaluate expression and get value.
4304 if (assign_type == VARIABLE) {
4305 DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4306 AccumulatorValueContext context(this);
4307 EmitVariableLoad(expr->expression()->AsVariableProxy());
4309 // Reserve space for result of postfix operation.
4310 if (expr->is_postfix() && !context()->IsEffect()) {
4311 __ push(Immediate(Smi::FromInt(0)));
4313 if (assign_type == NAMED_PROPERTY) {
4314 // Put the object both on the stack and in the register.
4315 VisitForStackValue(prop->obj());
4316 __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4317 EmitNamedPropertyLoad(prop);
4319 VisitForStackValue(prop->obj());
4320 VisitForStackValue(prop->key());
4321 __ mov(LoadDescriptor::ReceiverRegister(),
4322 Operand(esp, kPointerSize)); // Object.
4323 __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0)); // Key.
4324 EmitKeyedPropertyLoad(prop);
4328 // We need a second deoptimization point after loading the value
4329 // in case evaluating the property load my have a side effect.
4330 if (assign_type == VARIABLE) {
4331 PrepareForBailout(expr->expression(), TOS_REG);
4333 PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4336 // Inline smi case if we are in a loop.
4337 Label done, stub_call;
4338 JumpPatchSite patch_site(masm_);
4339 if (ShouldInlineSmiCase(expr->op())) {
4341 patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4343 // Save result for postfix expressions.
4344 if (expr->is_postfix()) {
4345 if (!context()->IsEffect()) {
4346 // Save the result on the stack. If we have a named or keyed property
4347 // we store the result under the receiver that is currently on top
4349 switch (assign_type) {
4353 case NAMED_PROPERTY:
4354 __ mov(Operand(esp, kPointerSize), eax);
4356 case KEYED_PROPERTY:
4357 __ mov(Operand(esp, 2 * kPointerSize), eax);
4363 if (expr->op() == Token::INC) {
4364 __ add(eax, Immediate(Smi::FromInt(1)));
4366 __ sub(eax, Immediate(Smi::FromInt(1)));
4368 __ j(no_overflow, &done, Label::kNear);
4369 // Call stub. Undo operation first.
4370 if (expr->op() == Token::INC) {
4371 __ sub(eax, Immediate(Smi::FromInt(1)));
4373 __ add(eax, Immediate(Smi::FromInt(1)));
4375 __ jmp(&stub_call, Label::kNear);
4378 ToNumberStub convert_stub(isolate());
4379 __ CallStub(&convert_stub);
4381 // Save result for postfix expressions.
4382 if (expr->is_postfix()) {
4383 if (!context()->IsEffect()) {
4384 // Save the result on the stack. If we have a named or keyed property
4385 // we store the result under the receiver that is currently on top
4387 switch (assign_type) {
4391 case NAMED_PROPERTY:
4392 __ mov(Operand(esp, kPointerSize), eax);
4394 case KEYED_PROPERTY:
4395 __ mov(Operand(esp, 2 * kPointerSize), eax);
4401 // Record position before stub call.
4402 SetSourcePosition(expr->position());
4404 // Call stub for +1/-1.
4405 __ bind(&stub_call);
4407 __ mov(eax, Immediate(Smi::FromInt(1)));
4408 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
4409 NO_OVERWRITE).code();
4410 CallIC(code, expr->CountBinOpFeedbackId());
4411 patch_site.EmitPatchInfo();
4414 // Store the value returned in eax.
4415 switch (assign_type) {
4417 if (expr->is_postfix()) {
4418 // Perform the assignment as if via '='.
4419 { EffectContext context(this);
4420 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4422 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4425 // For all contexts except EffectContext We have the result on
4426 // top of the stack.
4427 if (!context()->IsEffect()) {
4428 context()->PlugTOS();
4431 // Perform the assignment as if via '='.
4432 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4434 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4435 context()->Plug(eax);
4438 case NAMED_PROPERTY: {
4439 __ mov(StoreDescriptor::NameRegister(),
4440 prop->key()->AsLiteral()->value());
4441 __ pop(StoreDescriptor::ReceiverRegister());
4442 CallStoreIC(expr->CountStoreFeedbackId());
4443 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4444 if (expr->is_postfix()) {
4445 if (!context()->IsEffect()) {
4446 context()->PlugTOS();
4449 context()->Plug(eax);
4453 case KEYED_PROPERTY: {
4454 __ pop(StoreDescriptor::NameRegister());
4455 __ pop(StoreDescriptor::ReceiverRegister());
4457 CodeFactory::KeyedStoreIC(isolate(), strict_mode()).code();
4458 CallIC(ic, expr->CountStoreFeedbackId());
4459 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4460 if (expr->is_postfix()) {
4461 // Result is on the stack
4462 if (!context()->IsEffect()) {
4463 context()->PlugTOS();
4466 context()->Plug(eax);
4474 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4475 VariableProxy* proxy = expr->AsVariableProxy();
4476 DCHECK(!context()->IsEffect());
4477 DCHECK(!context()->IsTest());
4479 if (proxy != NULL && proxy->var()->IsUnallocated()) {
4480 Comment cmnt(masm_, "[ Global variable");
4481 __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4482 __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4483 if (FLAG_vector_ics) {
4484 __ mov(VectorLoadICDescriptor::SlotRegister(),
4485 Immediate(Smi::FromInt(proxy->VariableFeedbackSlot())));
4487 // Use a regular load, not a contextual load, to avoid a reference
4489 CallLoadIC(NOT_CONTEXTUAL);
4490 PrepareForBailout(expr, TOS_REG);
4491 context()->Plug(eax);
4492 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4493 Comment cmnt(masm_, "[ Lookup slot");
4496 // Generate code for loading from variables potentially shadowed
4497 // by eval-introduced variables.
4498 EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4502 __ push(Immediate(proxy->name()));
4503 __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4504 PrepareForBailout(expr, TOS_REG);
4507 context()->Plug(eax);
4509 // This expression cannot throw a reference error at the top level.
4510 VisitInDuplicateContext(expr);
4515 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4516 Expression* sub_expr,
4517 Handle<String> check) {
4518 Label materialize_true, materialize_false;
4519 Label* if_true = NULL;
4520 Label* if_false = NULL;
4521 Label* fall_through = NULL;
4522 context()->PrepareTest(&materialize_true, &materialize_false,
4523 &if_true, &if_false, &fall_through);
4525 { AccumulatorValueContext context(this);
4526 VisitForTypeofValue(sub_expr);
4528 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4530 Factory* factory = isolate()->factory();
4531 if (String::Equals(check, factory->number_string())) {
4532 __ JumpIfSmi(eax, if_true);
4533 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
4534 isolate()->factory()->heap_number_map());
4535 Split(equal, if_true, if_false, fall_through);
4536 } else if (String::Equals(check, factory->string_string())) {
4537 __ JumpIfSmi(eax, if_false);
4538 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
4539 __ j(above_equal, if_false);
4540 // Check for undetectable objects => false.
4541 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4542 1 << Map::kIsUndetectable);
4543 Split(zero, if_true, if_false, fall_through);
4544 } else if (String::Equals(check, factory->symbol_string())) {
4545 __ JumpIfSmi(eax, if_false);
4546 __ CmpObjectType(eax, SYMBOL_TYPE, edx);
4547 Split(equal, if_true, if_false, fall_through);
4548 } else if (String::Equals(check, factory->boolean_string())) {
4549 __ cmp(eax, isolate()->factory()->true_value());
4550 __ j(equal, if_true);
4551 __ cmp(eax, isolate()->factory()->false_value());
4552 Split(equal, if_true, if_false, fall_through);
4553 } else if (String::Equals(check, factory->undefined_string())) {
4554 __ cmp(eax, isolate()->factory()->undefined_value());
4555 __ j(equal, if_true);
4556 __ JumpIfSmi(eax, if_false);
4557 // Check for undetectable objects => true.
4558 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
4559 __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
4560 __ test(ecx, Immediate(1 << Map::kIsUndetectable));
4561 Split(not_zero, if_true, if_false, fall_through);
4562 } else if (String::Equals(check, factory->function_string())) {
4563 __ JumpIfSmi(eax, if_false);
4564 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
4565 __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
4566 __ j(equal, if_true);
4567 __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
4568 Split(equal, if_true, if_false, fall_through);
4569 } else if (String::Equals(check, factory->object_string())) {
4570 __ JumpIfSmi(eax, if_false);
4571 __ cmp(eax, isolate()->factory()->null_value());
4572 __ j(equal, if_true);
4573 __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
4574 __ j(below, if_false);
4575 __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
4576 __ j(above, if_false);
4577 // Check for undetectable objects => false.
4578 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4579 1 << Map::kIsUndetectable);
4580 Split(zero, if_true, if_false, fall_through);
4582 if (if_false != fall_through) __ jmp(if_false);
4584 context()->Plug(if_true, if_false);
4588 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
4589 Comment cmnt(masm_, "[ CompareOperation");
4590 SetSourcePosition(expr->position());
4592 // First we try a fast inlined version of the compare when one of
4593 // the operands is a literal.
4594 if (TryLiteralCompare(expr)) return;
4596 // Always perform the comparison for its control flow. Pack the result
4597 // into the expression's context after the comparison is performed.
4598 Label materialize_true, materialize_false;
4599 Label* if_true = NULL;
4600 Label* if_false = NULL;
4601 Label* fall_through = NULL;
4602 context()->PrepareTest(&materialize_true, &materialize_false,
4603 &if_true, &if_false, &fall_through);
4605 Token::Value op = expr->op();
4606 VisitForStackValue(expr->left());
4609 VisitForStackValue(expr->right());
4610 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
4611 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
4612 __ cmp(eax, isolate()->factory()->true_value());
4613 Split(equal, if_true, if_false, fall_through);
4616 case Token::INSTANCEOF: {
4617 VisitForStackValue(expr->right());
4618 InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
4620 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4622 // The stub returns 0 for true.
4623 Split(zero, if_true, if_false, fall_through);
4628 VisitForAccumulatorValue(expr->right());
4629 Condition cc = CompareIC::ComputeCondition(op);
4632 bool inline_smi_code = ShouldInlineSmiCase(op);
4633 JumpPatchSite patch_site(masm_);
4634 if (inline_smi_code) {
4638 patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
4640 Split(cc, if_true, if_false, NULL);
4641 __ bind(&slow_case);
4644 // Record position and call the compare IC.
4645 SetSourcePosition(expr->position());
4646 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
4647 CallIC(ic, expr->CompareOperationFeedbackId());
4648 patch_site.EmitPatchInfo();
4650 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4652 Split(cc, if_true, if_false, fall_through);
4656 // Convert the result of the comparison into one expected for this
4657 // expression's context.
4658 context()->Plug(if_true, if_false);
4662 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
4663 Expression* sub_expr,
4665 Label materialize_true, materialize_false;
4666 Label* if_true = NULL;
4667 Label* if_false = NULL;
4668 Label* fall_through = NULL;
4669 context()->PrepareTest(&materialize_true, &materialize_false,
4670 &if_true, &if_false, &fall_through);
4672 VisitForAccumulatorValue(sub_expr);
4673 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4675 Handle<Object> nil_value = nil == kNullValue
4676 ? isolate()->factory()->null_value()
4677 : isolate()->factory()->undefined_value();
4678 if (expr->op() == Token::EQ_STRICT) {
4679 __ cmp(eax, nil_value);
4680 Split(equal, if_true, if_false, fall_through);
4682 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
4683 CallIC(ic, expr->CompareOperationFeedbackId());
4685 Split(not_zero, if_true, if_false, fall_through);
4687 context()->Plug(if_true, if_false);
4691 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
4692 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
4693 context()->Plug(eax);
4697 Register FullCodeGenerator::result_register() {
4702 Register FullCodeGenerator::context_register() {
4707 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
4708 DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
4709 __ mov(Operand(ebp, frame_offset), value);
4713 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
4714 __ mov(dst, ContextOperand(esi, context_index));
4718 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
4719 Scope* declaration_scope = scope()->DeclarationScope();
4720 if (declaration_scope->is_global_scope() ||
4721 declaration_scope->is_module_scope()) {
4722 // Contexts nested in the native context have a canonical empty function
4723 // as their closure, not the anonymous closure containing the global
4724 // code. Pass a smi sentinel and let the runtime look up the empty
4726 __ push(Immediate(Smi::FromInt(0)));
4727 } else if (declaration_scope->is_eval_scope()) {
4728 // Contexts nested inside eval code have the same closure as the context
4729 // calling eval, not the anonymous closure containing the eval code.
4730 // Fetch it from the context.
4731 __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
4733 DCHECK(declaration_scope->is_function_scope());
4734 __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
4739 // ----------------------------------------------------------------------------
4740 // Non-local control flow support.
4742 void FullCodeGenerator::EnterFinallyBlock() {
4743 // Cook return address on top of stack (smi encoded Code* delta)
4744 DCHECK(!result_register().is(edx));
4746 __ sub(edx, Immediate(masm_->CodeObject()));
4747 STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
4748 STATIC_ASSERT(kSmiTag == 0);
4752 // Store result register while executing finally block.
4753 __ push(result_register());
4755 // Store pending message while executing finally block.
4756 ExternalReference pending_message_obj =
4757 ExternalReference::address_of_pending_message_obj(isolate());
4758 __ mov(edx, Operand::StaticVariable(pending_message_obj));
4761 ExternalReference has_pending_message =
4762 ExternalReference::address_of_has_pending_message(isolate());
4763 __ mov(edx, Operand::StaticVariable(has_pending_message));
4767 ExternalReference pending_message_script =
4768 ExternalReference::address_of_pending_message_script(isolate());
4769 __ mov(edx, Operand::StaticVariable(pending_message_script));
4774 void FullCodeGenerator::ExitFinallyBlock() {
4775 DCHECK(!result_register().is(edx));
4776 // Restore pending message from stack.
4778 ExternalReference pending_message_script =
4779 ExternalReference::address_of_pending_message_script(isolate());
4780 __ mov(Operand::StaticVariable(pending_message_script), edx);
4784 ExternalReference has_pending_message =
4785 ExternalReference::address_of_has_pending_message(isolate());
4786 __ mov(Operand::StaticVariable(has_pending_message), edx);
4789 ExternalReference pending_message_obj =
4790 ExternalReference::address_of_pending_message_obj(isolate());
4791 __ mov(Operand::StaticVariable(pending_message_obj), edx);
4793 // Restore result register from stack.
4794 __ pop(result_register());
4796 // Uncook return address.
4799 __ add(edx, Immediate(masm_->CodeObject()));
4806 #define __ ACCESS_MASM(masm())
4808 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
4810 int* context_length) {
4811 // The macros used here must preserve the result register.
4813 // Because the handler block contains the context of the finally
4814 // code, we can restore it directly from there for the finally code
4815 // rather than iteratively unwinding contexts via their previous
4817 __ Drop(*stack_depth); // Down to the handler block.
4818 if (*context_length > 0) {
4819 // Restore the context to its dedicated register and the stack.
4820 __ mov(esi, Operand(esp, StackHandlerConstants::kContextOffset));
4821 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
4824 __ call(finally_entry_);
4827 *context_length = 0;
4834 static const byte kJnsInstruction = 0x79;
4835 static const byte kJnsOffset = 0x11;
4836 static const byte kNopByteOne = 0x66;
4837 static const byte kNopByteTwo = 0x90;
4839 static const byte kCallInstruction = 0xe8;
4843 void BackEdgeTable::PatchAt(Code* unoptimized_code,
4845 BackEdgeState target_state,
4846 Code* replacement_code) {
4847 Address call_target_address = pc - kIntSize;
4848 Address jns_instr_address = call_target_address - 3;
4849 Address jns_offset_address = call_target_address - 2;
4851 switch (target_state) {
4853 // sub <profiling_counter>, <delta> ;; Not changed
4855 // call <interrupt stub>
4857 *jns_instr_address = kJnsInstruction;
4858 *jns_offset_address = kJnsOffset;
4860 case ON_STACK_REPLACEMENT:
4861 case OSR_AFTER_STACK_CHECK:
4862 // sub <profiling_counter>, <delta> ;; Not changed
4865 // call <on-stack replacment>
4867 *jns_instr_address = kNopByteOne;
4868 *jns_offset_address = kNopByteTwo;
4872 Assembler::set_target_address_at(call_target_address,
4874 replacement_code->entry());
4875 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
4876 unoptimized_code, call_target_address, replacement_code);
4880 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
4882 Code* unoptimized_code,
4884 Address call_target_address = pc - kIntSize;
4885 Address jns_instr_address = call_target_address - 3;
4886 DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
4888 if (*jns_instr_address == kJnsInstruction) {
4889 DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
4890 DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
4891 Assembler::target_address_at(call_target_address,
4896 DCHECK_EQ(kNopByteOne, *jns_instr_address);
4897 DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
4899 if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
4900 isolate->builtins()->OnStackReplacement()->entry()) {
4901 return ON_STACK_REPLACEMENT;
4904 DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
4905 Assembler::target_address_at(call_target_address,
4907 return OSR_AFTER_STACK_CHECK;
4911 } } // namespace v8::internal
4913 #endif // V8_TARGET_ARCH_IA32