4ec21ae09c3067d14cbafc246659f2576bfc1f62
[platform/upstream/nodejs.git] / deps / v8 / src / x87 / full-codegen-x87.cc
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.
4
5 #include "src/v8.h"
6
7 #if V8_TARGET_ARCH_X87
8
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"
19
20 namespace v8 {
21 namespace internal {
22
23 #define __ ACCESS_MASM(masm_)
24
25
26 class JumpPatchSite BASE_EMBEDDED {
27  public:
28   explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
29 #ifdef DEBUG
30     info_emitted_ = false;
31 #endif
32   }
33
34   ~JumpPatchSite() {
35     DCHECK(patch_site_.is_bound() == info_emitted_);
36   }
37
38   void EmitJumpIfNotSmi(Register reg,
39                         Label* target,
40                         Label::Distance distance = Label::kFar) {
41     __ test(reg, Immediate(kSmiTagMask));
42     EmitJump(not_carry, target, distance);  // Always taken before patched.
43   }
44
45   void EmitJumpIfSmi(Register reg,
46                      Label* target,
47                      Label::Distance distance = Label::kFar) {
48     __ test(reg, Immediate(kSmiTagMask));
49     EmitJump(carry, target, distance);  // Never taken before patched.
50   }
51
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));
57 #ifdef DEBUG
58       info_emitted_ = true;
59 #endif
60     } else {
61       __ nop();  // Signals no inlined code.
62     }
63   }
64
65  private:
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);
72   }
73
74   MacroAssembler* masm_;
75   Label patch_site_;
76 #ifdef DEBUG
77   bool info_emitted_;
78 #endif
79 };
80
81
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.
86 //
87 // The live registers are:
88 //   o edi: the JS function object being called (i.e. ourselves)
89 //   o esi: our context
90 //   o ebp: our caller's frame pointer
91 //   o esp: stack pointer (pointing to return address)
92 //
93 // The function builds a JS frame.  Please see JavaScriptFrameConstants in
94 // frames-x87.h for its layout.
95 void FullCodeGenerator::Generate() {
96   CompilationInfo* info = info_;
97   handler_table_ =
98       isolate()->factory()->NewFixedArray(function()->handler_count(), TENURED);
99
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");
104
105   ProfileEntryHookStub::MaybeCallEntryHook(masm_);
106
107 #ifdef DEBUG
108   if (strlen(FLAG_stop_at) > 0 &&
109       info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
110     __ int3();
111   }
112 #endif
113
114   // Sloppy mode functions and builtins need to replace the receiver with the
115   // global proxy when called as functions (without an explicit receiver
116   // object).
117   if (is_sloppy(info->language_mode()) && !info->is_native()) {
118     Label ok;
119     // +1 for return address.
120     int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
121     __ mov(ecx, Operand(esp, receiver_offset));
122
123     __ cmp(ecx, isolate()->factory()->undefined_value());
124     __ j(not_equal, &ok, Label::kNear);
125
126     __ mov(ecx, GlobalObjectOperand());
127     __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
128
129     __ mov(Operand(esp, receiver_offset), ecx);
130
131     __ bind(&ok);
132   }
133
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);
138
139   info->set_prologue_offset(masm_->pc_offset());
140   __ Prologue(info->IsCodePreAgingActive());
141   info->AddNoFrameRange(0, masm_->pc_offset());
142
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(!IsGeneratorFunction(info->function()->kind()) || 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) {
151         Label ok;
152         __ mov(ecx, esp);
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);
159         __ bind(&ok);
160       }
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);
166         Label loop_header;
167         __ bind(&loop_header);
168         // Do pushes.
169         for (int i = 0; i < kMaxPushes; i++) {
170           __ push(eax);
171         }
172         __ dec(ecx);
173         __ j(not_zero, &loop_header, Label::kNear);
174       }
175       int remaining = locals_count % kMaxPushes;
176       // Emit the remaining pushes.
177       for (int i  = 0; i < remaining; i++) {
178         __ push(eax);
179       }
180     }
181   }
182
183   bool function_in_register = true;
184
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_script_scope()) {
192       __ push(edi);
193       __ Push(info->scope()->GetScopeInfo(info->isolate()));
194       __ CallRuntime(Runtime::kNewScriptContext, 2);
195     } else if (heap_slots <= FastNewContextStub::kMaximumSlots) {
196       FastNewContextStub stub(isolate(), heap_slots);
197       __ CallStub(&stub);
198       // Result of FastNewContextStub is always in new space.
199       need_write_barrier = false;
200     } else {
201       __ push(edi);
202       __ CallRuntime(Runtime::kNewFunctionContext, 1);
203     }
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.
207     __ mov(esi, eax);
208     __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
209
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, context_offset, eax, ebx,
225                                     kDontSaveFPRegs);
226         } else if (FLAG_debug_code) {
227           Label done;
228           __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
229           __ Abort(kExpectedNewSpaceObject);
230           __ bind(&done);
231         }
232       }
233     }
234   }
235
236   // Possibly allocate RestParameters
237   int rest_index;
238   Variable* rest_param = scope()->rest_parameter(&rest_index);
239   if (rest_param) {
240     Comment cmnt(masm_, "[ Allocate rest parameter array");
241
242     int num_parameters = info->scope()->num_parameters();
243     int offset = num_parameters * kPointerSize;
244     __ lea(edx,
245            Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
246     __ push(edx);
247     __ push(Immediate(Smi::FromInt(num_parameters)));
248     __ push(Immediate(Smi::FromInt(rest_index)));
249
250     RestParamAccessStub stub(isolate());
251     __ CallStub(&stub);
252
253     SetVar(rest_param, eax, ebx, edx);
254   }
255
256   Variable* arguments = scope()->arguments();
257   if (arguments != NULL) {
258     // Function uses arguments object.
259     Comment cmnt(masm_, "[ Allocate arguments object");
260     if (function_in_register) {
261       __ push(edi);
262     } else {
263       __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
264     }
265     // Receiver is just before the parameters on the caller's stack.
266     int num_parameters = info->scope()->num_parameters();
267     int offset = num_parameters * kPointerSize;
268     __ lea(edx,
269            Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
270     __ push(edx);
271     __ push(Immediate(Smi::FromInt(num_parameters)));
272     // Arguments to ArgumentsAccessStub:
273     //   function, receiver address, parameter count.
274     // The stub will rewrite receiver and parameter count if the previous
275     // stack frame was an arguments adapter frame.
276     ArgumentsAccessStub::Type type;
277     if (is_strict(language_mode()) || !is_simple_parameter_list()) {
278       type = ArgumentsAccessStub::NEW_STRICT;
279     } else if (function()->has_duplicate_parameters()) {
280       type = ArgumentsAccessStub::NEW_SLOPPY_SLOW;
281     } else {
282       type = ArgumentsAccessStub::NEW_SLOPPY_FAST;
283     }
284     ArgumentsAccessStub::HasNewTarget has_new_target =
285         IsSubclassConstructor(info->function()->kind())
286             ? ArgumentsAccessStub::HAS_NEW_TARGET
287             : ArgumentsAccessStub::NO_NEW_TARGET;
288     ArgumentsAccessStub stub(isolate(), type, has_new_target);
289     __ CallStub(&stub);
290
291     SetVar(arguments, eax, ebx, edx);
292   }
293
294   if (FLAG_trace) {
295     __ CallRuntime(Runtime::kTraceEnter, 0);
296   }
297
298   // Visit the declarations and body unless there is an illegal
299   // redeclaration.
300   if (scope()->HasIllegalRedeclaration()) {
301     Comment cmnt(masm_, "[ Declarations");
302     scope()->VisitIllegalRedeclaration(this);
303
304   } else {
305     PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
306     { Comment cmnt(masm_, "[ Declarations");
307       // For named function expressions, declare the function name as a
308       // constant.
309       if (scope()->is_function_scope() && scope()->function() != NULL) {
310         VariableDeclaration* function = scope()->function();
311         DCHECK(function->proxy()->var()->mode() == CONST ||
312                function->proxy()->var()->mode() == CONST_LEGACY);
313         DCHECK(function->proxy()->var()->location() != Variable::UNALLOCATED);
314         VisitVariableDeclaration(function);
315       }
316       VisitDeclarations(scope()->declarations());
317     }
318
319     { Comment cmnt(masm_, "[ Stack check");
320       PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
321       Label ok;
322       ExternalReference stack_limit
323           = ExternalReference::address_of_stack_limit(isolate());
324       __ cmp(esp, Operand::StaticVariable(stack_limit));
325       __ j(above_equal, &ok, Label::kNear);
326       __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
327       __ bind(&ok);
328     }
329
330     { Comment cmnt(masm_, "[ Body");
331       DCHECK(loop_depth() == 0);
332       VisitStatements(function()->body());
333       DCHECK(loop_depth() == 0);
334     }
335   }
336
337   // Always emit a 'return undefined' in case control fell off the end of
338   // the body.
339   { Comment cmnt(masm_, "[ return <undefined>;");
340     __ mov(eax, isolate()->factory()->undefined_value());
341     EmitReturnSequence();
342   }
343 }
344
345
346 void FullCodeGenerator::ClearAccumulator() {
347   __ Move(eax, Immediate(Smi::FromInt(0)));
348 }
349
350
351 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
352   __ mov(ebx, Immediate(profiling_counter_));
353   __ sub(FieldOperand(ebx, Cell::kValueOffset),
354          Immediate(Smi::FromInt(delta)));
355 }
356
357
358 void FullCodeGenerator::EmitProfilingCounterReset() {
359   int reset_value = FLAG_interrupt_budget;
360   __ mov(ebx, Immediate(profiling_counter_));
361   __ mov(FieldOperand(ebx, Cell::kValueOffset),
362          Immediate(Smi::FromInt(reset_value)));
363 }
364
365
366 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
367                                                 Label* back_edge_target) {
368   Comment cmnt(masm_, "[ Back edge bookkeeping");
369   Label ok;
370
371   DCHECK(back_edge_target->is_bound());
372   int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
373   int weight = Min(kMaxBackEdgeWeight,
374                    Max(1, distance / kCodeSizeMultiplier));
375   EmitProfilingCounterDecrement(weight);
376   __ j(positive, &ok, Label::kNear);
377   __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
378
379   // Record a mapping of this PC offset to the OSR id.  This is used to find
380   // the AST id from the unoptimized code in order to use it as a key into
381   // the deoptimization input data found in the optimized code.
382   RecordBackEdge(stmt->OsrEntryId());
383
384   EmitProfilingCounterReset();
385
386   __ bind(&ok);
387   PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
388   // Record a mapping of the OSR id to this PC.  This is used if the OSR
389   // entry becomes the target of a bailout.  We don't expect it to be, but
390   // we want it to work if it is.
391   PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
392 }
393
394
395 void FullCodeGenerator::EmitReturnSequence() {
396   Comment cmnt(masm_, "[ Return sequence");
397   if (return_label_.is_bound()) {
398     __ jmp(&return_label_);
399   } else {
400     // Common return label
401     __ bind(&return_label_);
402     if (FLAG_trace) {
403       __ push(eax);
404       __ CallRuntime(Runtime::kTraceExit, 1);
405     }
406     // Pretend that the exit is a backwards jump to the entry.
407     int weight = 1;
408     if (info_->ShouldSelfOptimize()) {
409       weight = FLAG_interrupt_budget / FLAG_self_opt_count;
410     } else {
411       int distance = masm_->pc_offset();
412       weight = Min(kMaxBackEdgeWeight,
413                    Max(1, distance / kCodeSizeMultiplier));
414     }
415     EmitProfilingCounterDecrement(weight);
416     Label ok;
417     __ j(positive, &ok, Label::kNear);
418     __ push(eax);
419     __ call(isolate()->builtins()->InterruptCheck(),
420             RelocInfo::CODE_TARGET);
421     __ pop(eax);
422     EmitProfilingCounterReset();
423     __ bind(&ok);
424 #ifdef DEBUG
425     // Add a label for checking the size of the code used for returning.
426     Label check_exit_codesize;
427     masm_->bind(&check_exit_codesize);
428 #endif
429     SetSourcePosition(function()->end_position() - 1);
430     __ RecordJSReturn();
431     // Do not use the leave instruction here because it is too short to
432     // patch with the code required by the debugger.
433     __ mov(esp, ebp);
434     int no_frame_start = masm_->pc_offset();
435     __ pop(ebp);
436
437     int arg_count = info_->scope()->num_parameters() + 1;
438     if (IsSubclassConstructor(info_->function()->kind())) {
439       arg_count++;
440     }
441     int arguments_bytes = arg_count * kPointerSize;
442     __ Ret(arguments_bytes, ecx);
443     // Check that the size of the code used for returning is large enough
444     // for the debugger's requirements.
445     DCHECK(Assembler::kJSReturnSequenceLength <=
446            masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
447     info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
448   }
449 }
450
451
452 void FullCodeGenerator::EffectContext::Plug(Variable* var) const {
453   DCHECK(var->IsStackAllocated() || var->IsContextSlot());
454 }
455
456
457 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const {
458   DCHECK(var->IsStackAllocated() || var->IsContextSlot());
459   codegen()->GetVar(result_register(), var);
460 }
461
462
463 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
464   DCHECK(var->IsStackAllocated() || var->IsContextSlot());
465   MemOperand operand = codegen()->VarOperand(var, result_register());
466   // Memory operands can be pushed directly.
467   __ push(operand);
468 }
469
470
471 void FullCodeGenerator::TestContext::Plug(Variable* var) const {
472   // For simplicity we always test the accumulator register.
473   codegen()->GetVar(result_register(), var);
474   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
475   codegen()->DoTest(this);
476 }
477
478
479 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
480   UNREACHABLE();  // Not used on X87.
481 }
482
483
484 void FullCodeGenerator::AccumulatorValueContext::Plug(
485     Heap::RootListIndex index) const {
486   UNREACHABLE();  // Not used on X87.
487 }
488
489
490 void FullCodeGenerator::StackValueContext::Plug(
491     Heap::RootListIndex index) const {
492   UNREACHABLE();  // Not used on X87.
493 }
494
495
496 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
497   UNREACHABLE();  // Not used on X87.
498 }
499
500
501 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
502 }
503
504
505 void FullCodeGenerator::AccumulatorValueContext::Plug(
506     Handle<Object> lit) const {
507   if (lit->IsSmi()) {
508     __ SafeMove(result_register(), Immediate(lit));
509   } else {
510     __ Move(result_register(), Immediate(lit));
511   }
512 }
513
514
515 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
516   if (lit->IsSmi()) {
517     __ SafePush(Immediate(lit));
518   } else {
519     __ push(Immediate(lit));
520   }
521 }
522
523
524 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
525   codegen()->PrepareForBailoutBeforeSplit(condition(),
526                                           true,
527                                           true_label_,
528                                           false_label_);
529   DCHECK(!lit->IsUndetectableObject());  // There are no undetectable literals.
530   if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
531     if (false_label_ != fall_through_) __ jmp(false_label_);
532   } else if (lit->IsTrue() || lit->IsJSObject()) {
533     if (true_label_ != fall_through_) __ jmp(true_label_);
534   } else if (lit->IsString()) {
535     if (String::cast(*lit)->length() == 0) {
536       if (false_label_ != fall_through_) __ jmp(false_label_);
537     } else {
538       if (true_label_ != fall_through_) __ jmp(true_label_);
539     }
540   } else if (lit->IsSmi()) {
541     if (Smi::cast(*lit)->value() == 0) {
542       if (false_label_ != fall_through_) __ jmp(false_label_);
543     } else {
544       if (true_label_ != fall_through_) __ jmp(true_label_);
545     }
546   } else {
547     // For simplicity we always test the accumulator register.
548     __ mov(result_register(), lit);
549     codegen()->DoTest(this);
550   }
551 }
552
553
554 void FullCodeGenerator::EffectContext::DropAndPlug(int count,
555                                                    Register reg) const {
556   DCHECK(count > 0);
557   __ Drop(count);
558 }
559
560
561 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
562     int count,
563     Register reg) const {
564   DCHECK(count > 0);
565   __ Drop(count);
566   __ Move(result_register(), reg);
567 }
568
569
570 void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
571                                                        Register reg) const {
572   DCHECK(count > 0);
573   if (count > 1) __ Drop(count - 1);
574   __ mov(Operand(esp, 0), reg);
575 }
576
577
578 void FullCodeGenerator::TestContext::DropAndPlug(int count,
579                                                  Register reg) const {
580   DCHECK(count > 0);
581   // For simplicity we always test the accumulator register.
582   __ Drop(count);
583   __ Move(result_register(), reg);
584   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
585   codegen()->DoTest(this);
586 }
587
588
589 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
590                                             Label* materialize_false) const {
591   DCHECK(materialize_true == materialize_false);
592   __ bind(materialize_true);
593 }
594
595
596 void FullCodeGenerator::AccumulatorValueContext::Plug(
597     Label* materialize_true,
598     Label* materialize_false) const {
599   Label done;
600   __ bind(materialize_true);
601   __ mov(result_register(), isolate()->factory()->true_value());
602   __ jmp(&done, Label::kNear);
603   __ bind(materialize_false);
604   __ mov(result_register(), isolate()->factory()->false_value());
605   __ bind(&done);
606 }
607
608
609 void FullCodeGenerator::StackValueContext::Plug(
610     Label* materialize_true,
611     Label* materialize_false) const {
612   Label done;
613   __ bind(materialize_true);
614   __ push(Immediate(isolate()->factory()->true_value()));
615   __ jmp(&done, Label::kNear);
616   __ bind(materialize_false);
617   __ push(Immediate(isolate()->factory()->false_value()));
618   __ bind(&done);
619 }
620
621
622 void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
623                                           Label* materialize_false) const {
624   DCHECK(materialize_true == true_label_);
625   DCHECK(materialize_false == false_label_);
626 }
627
628
629 void FullCodeGenerator::EffectContext::Plug(bool flag) const {
630 }
631
632
633 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
634   Handle<Object> value = flag
635       ? isolate()->factory()->true_value()
636       : isolate()->factory()->false_value();
637   __ mov(result_register(), value);
638 }
639
640
641 void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
642   Handle<Object> value = flag
643       ? isolate()->factory()->true_value()
644       : isolate()->factory()->false_value();
645   __ push(Immediate(value));
646 }
647
648
649 void FullCodeGenerator::TestContext::Plug(bool flag) const {
650   codegen()->PrepareForBailoutBeforeSplit(condition(),
651                                           true,
652                                           true_label_,
653                                           false_label_);
654   if (flag) {
655     if (true_label_ != fall_through_) __ jmp(true_label_);
656   } else {
657     if (false_label_ != fall_through_) __ jmp(false_label_);
658   }
659 }
660
661
662 void FullCodeGenerator::DoTest(Expression* condition,
663                                Label* if_true,
664                                Label* if_false,
665                                Label* fall_through) {
666   Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
667   CallIC(ic, condition->test_id());
668   __ test(result_register(), result_register());
669   // The stub returns nonzero for true.
670   Split(not_zero, if_true, if_false, fall_through);
671 }
672
673
674 void FullCodeGenerator::Split(Condition cc,
675                               Label* if_true,
676                               Label* if_false,
677                               Label* fall_through) {
678   if (if_false == fall_through) {
679     __ j(cc, if_true);
680   } else if (if_true == fall_through) {
681     __ j(NegateCondition(cc), if_false);
682   } else {
683     __ j(cc, if_true);
684     __ jmp(if_false);
685   }
686 }
687
688
689 MemOperand FullCodeGenerator::StackOperand(Variable* var) {
690   DCHECK(var->IsStackAllocated());
691   // Offset is negative because higher indexes are at lower addresses.
692   int offset = -var->index() * kPointerSize;
693   // Adjust by a (parameter or local) base offset.
694   if (var->IsParameter()) {
695     offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
696   } else {
697     offset += JavaScriptFrameConstants::kLocal0Offset;
698   }
699   return Operand(ebp, offset);
700 }
701
702
703 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
704   DCHECK(var->IsContextSlot() || var->IsStackAllocated());
705   if (var->IsContextSlot()) {
706     int context_chain_length = scope()->ContextChainLength(var->scope());
707     __ LoadContext(scratch, context_chain_length);
708     return ContextOperand(scratch, var->index());
709   } else {
710     return StackOperand(var);
711   }
712 }
713
714
715 void FullCodeGenerator::GetVar(Register dest, Variable* var) {
716   DCHECK(var->IsContextSlot() || var->IsStackAllocated());
717   MemOperand location = VarOperand(var, dest);
718   __ mov(dest, location);
719 }
720
721
722 void FullCodeGenerator::SetVar(Variable* var,
723                                Register src,
724                                Register scratch0,
725                                Register scratch1) {
726   DCHECK(var->IsContextSlot() || var->IsStackAllocated());
727   DCHECK(!scratch0.is(src));
728   DCHECK(!scratch0.is(scratch1));
729   DCHECK(!scratch1.is(src));
730   MemOperand location = VarOperand(var, scratch0);
731   __ mov(location, src);
732
733   // Emit the write barrier code if the location is in the heap.
734   if (var->IsContextSlot()) {
735     int offset = Context::SlotOffset(var->index());
736     DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
737     __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
738   }
739 }
740
741
742 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
743                                                      bool should_normalize,
744                                                      Label* if_true,
745                                                      Label* if_false) {
746   // Only prepare for bailouts before splits if we're in a test
747   // context. Otherwise, we let the Visit function deal with the
748   // preparation to avoid preparing with the same AST id twice.
749   if (!context()->IsTest() || !info_->IsOptimizable()) return;
750
751   Label skip;
752   if (should_normalize) __ jmp(&skip, Label::kNear);
753   PrepareForBailout(expr, TOS_REG);
754   if (should_normalize) {
755     __ cmp(eax, isolate()->factory()->true_value());
756     Split(equal, if_true, if_false, NULL);
757     __ bind(&skip);
758   }
759 }
760
761
762 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
763   // The variable in the declaration always resides in the current context.
764   DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
765   if (generate_debug_code_) {
766     // Check that we're not inside a with or catch context.
767     __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
768     __ cmp(ebx, isolate()->factory()->with_context_map());
769     __ Check(not_equal, kDeclarationInWithContext);
770     __ cmp(ebx, isolate()->factory()->catch_context_map());
771     __ Check(not_equal, kDeclarationInCatchContext);
772   }
773 }
774
775
776 void FullCodeGenerator::VisitVariableDeclaration(
777     VariableDeclaration* declaration) {
778   // If it was not possible to allocate the variable at compile time, we
779   // need to "declare" it at runtime to make sure it actually exists in the
780   // local context.
781   VariableProxy* proxy = declaration->proxy();
782   VariableMode mode = declaration->mode();
783   Variable* variable = proxy->var();
784   bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
785   switch (variable->location()) {
786     case Variable::UNALLOCATED:
787       globals_->Add(variable->name(), zone());
788       globals_->Add(variable->binding_needs_init()
789                         ? isolate()->factory()->the_hole_value()
790                         : isolate()->factory()->undefined_value(), zone());
791       break;
792
793     case Variable::PARAMETER:
794     case Variable::LOCAL:
795       if (hole_init) {
796         Comment cmnt(masm_, "[ VariableDeclaration");
797         __ mov(StackOperand(variable),
798                Immediate(isolate()->factory()->the_hole_value()));
799       }
800       break;
801
802     case Variable::CONTEXT:
803       if (hole_init) {
804         Comment cmnt(masm_, "[ VariableDeclaration");
805         EmitDebugCheckDeclarationContext(variable);
806         __ mov(ContextOperand(esi, variable->index()),
807                Immediate(isolate()->factory()->the_hole_value()));
808         // No write barrier since the hole value is in old space.
809         PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
810       }
811       break;
812
813     case Variable::LOOKUP: {
814       Comment cmnt(masm_, "[ VariableDeclaration");
815       __ push(esi);
816       __ push(Immediate(variable->name()));
817       // VariableDeclaration nodes are always introduced in one of four modes.
818       DCHECK(IsDeclaredVariableMode(mode));
819       PropertyAttributes attr =
820           IsImmutableVariableMode(mode) ? READ_ONLY : NONE;
821       __ push(Immediate(Smi::FromInt(attr)));
822       // Push initial value, if any.
823       // Note: For variables we must not push an initial value (such as
824       // 'undefined') because we may have a (legal) redeclaration and we
825       // must not destroy the current value.
826       if (hole_init) {
827         __ push(Immediate(isolate()->factory()->the_hole_value()));
828       } else {
829         __ push(Immediate(Smi::FromInt(0)));  // Indicates no initial value.
830       }
831       __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
832       break;
833     }
834   }
835 }
836
837
838 void FullCodeGenerator::VisitFunctionDeclaration(
839     FunctionDeclaration* declaration) {
840   VariableProxy* proxy = declaration->proxy();
841   Variable* variable = proxy->var();
842   switch (variable->location()) {
843     case Variable::UNALLOCATED: {
844       globals_->Add(variable->name(), zone());
845       Handle<SharedFunctionInfo> function =
846           Compiler::BuildFunctionInfo(declaration->fun(), script(), info_);
847       // Check for stack-overflow exception.
848       if (function.is_null()) return SetStackOverflow();
849       globals_->Add(function, zone());
850       break;
851     }
852
853     case Variable::PARAMETER:
854     case Variable::LOCAL: {
855       Comment cmnt(masm_, "[ FunctionDeclaration");
856       VisitForAccumulatorValue(declaration->fun());
857       __ mov(StackOperand(variable), result_register());
858       break;
859     }
860
861     case Variable::CONTEXT: {
862       Comment cmnt(masm_, "[ FunctionDeclaration");
863       EmitDebugCheckDeclarationContext(variable);
864       VisitForAccumulatorValue(declaration->fun());
865       __ mov(ContextOperand(esi, variable->index()), result_register());
866       // We know that we have written a function, which is not a smi.
867       __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()),
868                                 result_register(), ecx, kDontSaveFPRegs,
869                                 EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
870       PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
871       break;
872     }
873
874     case Variable::LOOKUP: {
875       Comment cmnt(masm_, "[ FunctionDeclaration");
876       __ push(esi);
877       __ push(Immediate(variable->name()));
878       __ push(Immediate(Smi::FromInt(NONE)));
879       VisitForStackValue(declaration->fun());
880       __ CallRuntime(Runtime::kDeclareLookupSlot, 4);
881       break;
882     }
883   }
884 }
885
886
887 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) {
888   Variable* variable = declaration->proxy()->var();
889   ModuleDescriptor* descriptor = declaration->module()->descriptor();
890   DCHECK(variable->location() == Variable::CONTEXT);
891   DCHECK(descriptor->IsFrozen());
892
893   Comment cmnt(masm_, "[ ModuleDeclaration");
894   EmitDebugCheckDeclarationContext(variable);
895
896   // Load instance object.
897   __ LoadContext(eax, scope_->ContextChainLength(scope_->ScriptScope()));
898   __ mov(eax, ContextOperand(eax, descriptor->Index()));
899   __ mov(eax, ContextOperand(eax, Context::EXTENSION_INDEX));
900
901   // Assign it.
902   __ mov(ContextOperand(esi, variable->index()), eax);
903   // We know that we have written a module, which is not a smi.
904   __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()), eax,
905                             ecx, kDontSaveFPRegs, EMIT_REMEMBERED_SET,
906                             OMIT_SMI_CHECK);
907   PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS);
908
909   // Traverse into body.
910   Visit(declaration->module());
911 }
912
913
914 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) {
915   VariableProxy* proxy = declaration->proxy();
916   Variable* variable = proxy->var();
917   switch (variable->location()) {
918     case Variable::UNALLOCATED:
919       // TODO(rossberg)
920       break;
921
922     case Variable::CONTEXT: {
923       Comment cmnt(masm_, "[ ImportDeclaration");
924       EmitDebugCheckDeclarationContext(variable);
925       // TODO(rossberg)
926       break;
927     }
928
929     case Variable::PARAMETER:
930     case Variable::LOCAL:
931     case Variable::LOOKUP:
932       UNREACHABLE();
933   }
934 }
935
936
937 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) {
938   // TODO(rossberg)
939 }
940
941
942 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
943   // Call the runtime to declare the globals.
944   __ push(esi);  // The context is the first argument.
945   __ Push(pairs);
946   __ Push(Smi::FromInt(DeclareGlobalsFlags()));
947   __ CallRuntime(Runtime::kDeclareGlobals, 3);
948   // Return value is ignored.
949 }
950
951
952 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
953   // Call the runtime to declare the modules.
954   __ Push(descriptions);
955   __ CallRuntime(Runtime::kDeclareModules, 1);
956   // Return value is ignored.
957 }
958
959
960 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
961   Comment cmnt(masm_, "[ SwitchStatement");
962   Breakable nested_statement(this, stmt);
963   SetStatementPosition(stmt);
964
965   // Keep the switch value on the stack until a case matches.
966   VisitForStackValue(stmt->tag());
967   PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
968
969   ZoneList<CaseClause*>* clauses = stmt->cases();
970   CaseClause* default_clause = NULL;  // Can occur anywhere in the list.
971
972   Label next_test;  // Recycled for each test.
973   // Compile all the tests with branches to their bodies.
974   for (int i = 0; i < clauses->length(); i++) {
975     CaseClause* clause = clauses->at(i);
976     clause->body_target()->Unuse();
977
978     // The default is not a test, but remember it as final fall through.
979     if (clause->is_default()) {
980       default_clause = clause;
981       continue;
982     }
983
984     Comment cmnt(masm_, "[ Case comparison");
985     __ bind(&next_test);
986     next_test.Unuse();
987
988     // Compile the label expression.
989     VisitForAccumulatorValue(clause->label());
990
991     // Perform the comparison as if via '==='.
992     __ mov(edx, Operand(esp, 0));  // Switch value.
993     bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
994     JumpPatchSite patch_site(masm_);
995     if (inline_smi_code) {
996       Label slow_case;
997       __ mov(ecx, edx);
998       __ or_(ecx, eax);
999       patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
1000
1001       __ cmp(edx, eax);
1002       __ j(not_equal, &next_test);
1003       __ Drop(1);  // Switch value is no longer needed.
1004       __ jmp(clause->body_target());
1005       __ bind(&slow_case);
1006     }
1007
1008     // Record position before stub call for type feedback.
1009     SetSourcePosition(clause->position());
1010     Handle<Code> ic =
1011         CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
1012     CallIC(ic, clause->CompareId());
1013     patch_site.EmitPatchInfo();
1014
1015     Label skip;
1016     __ jmp(&skip, Label::kNear);
1017     PrepareForBailout(clause, TOS_REG);
1018     __ cmp(eax, isolate()->factory()->true_value());
1019     __ j(not_equal, &next_test);
1020     __ Drop(1);
1021     __ jmp(clause->body_target());
1022     __ bind(&skip);
1023
1024     __ test(eax, eax);
1025     __ j(not_equal, &next_test);
1026     __ Drop(1);  // Switch value is no longer needed.
1027     __ jmp(clause->body_target());
1028   }
1029
1030   // Discard the test value and jump to the default if present, otherwise to
1031   // the end of the statement.
1032   __ bind(&next_test);
1033   __ Drop(1);  // Switch value is no longer needed.
1034   if (default_clause == NULL) {
1035     __ jmp(nested_statement.break_label());
1036   } else {
1037     __ jmp(default_clause->body_target());
1038   }
1039
1040   // Compile all the case bodies.
1041   for (int i = 0; i < clauses->length(); i++) {
1042     Comment cmnt(masm_, "[ Case body");
1043     CaseClause* clause = clauses->at(i);
1044     __ bind(clause->body_target());
1045     PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
1046     VisitStatements(clause->statements());
1047   }
1048
1049   __ bind(nested_statement.break_label());
1050   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1051 }
1052
1053
1054 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
1055   Comment cmnt(masm_, "[ ForInStatement");
1056   FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
1057
1058   SetStatementPosition(stmt);
1059
1060   Label loop, exit;
1061   ForIn loop_statement(this, stmt);
1062   increment_loop_depth();
1063
1064   // Get the object to enumerate over. If the object is null or undefined, skip
1065   // over the loop.  See ECMA-262 version 5, section 12.6.4.
1066   SetExpressionPosition(stmt->enumerable());
1067   VisitForAccumulatorValue(stmt->enumerable());
1068   __ cmp(eax, isolate()->factory()->undefined_value());
1069   __ j(equal, &exit);
1070   __ cmp(eax, isolate()->factory()->null_value());
1071   __ j(equal, &exit);
1072
1073   PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);
1074
1075   // Convert the object to a JS object.
1076   Label convert, done_convert;
1077   __ JumpIfSmi(eax, &convert, Label::kNear);
1078   __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
1079   __ j(above_equal, &done_convert, Label::kNear);
1080   __ bind(&convert);
1081   __ push(eax);
1082   __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1083   __ bind(&done_convert);
1084   PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
1085   __ push(eax);
1086
1087   // Check for proxies.
1088   Label call_runtime, use_cache, fixed_array;
1089   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1090   __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
1091   __ j(below_equal, &call_runtime);
1092
1093   // Check cache validity in generated code. This is a fast case for
1094   // the JSObject::IsSimpleEnum cache validity checks. If we cannot
1095   // guarantee cache validity, call the runtime system to check cache
1096   // validity or get the property names in a fixed array.
1097   __ CheckEnumCache(&call_runtime);
1098
1099   __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
1100   __ jmp(&use_cache, Label::kNear);
1101
1102   // Get the set of properties to enumerate.
1103   __ bind(&call_runtime);
1104   __ push(eax);
1105   __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1106   PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
1107   __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
1108          isolate()->factory()->meta_map());
1109   __ j(not_equal, &fixed_array);
1110
1111
1112   // We got a map in register eax. Get the enumeration cache from it.
1113   Label no_descriptors;
1114   __ bind(&use_cache);
1115
1116   __ EnumLength(edx, eax);
1117   __ cmp(edx, Immediate(Smi::FromInt(0)));
1118   __ j(equal, &no_descriptors);
1119
1120   __ LoadInstanceDescriptors(eax, ecx);
1121   __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
1122   __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1123
1124   // Set up the four remaining stack slots.
1125   __ push(eax);  // Map.
1126   __ push(ecx);  // Enumeration cache.
1127   __ push(edx);  // Number of valid entries for the map in the enum cache.
1128   __ push(Immediate(Smi::FromInt(0)));  // Initial index.
1129   __ jmp(&loop);
1130
1131   __ bind(&no_descriptors);
1132   __ add(esp, Immediate(kPointerSize));
1133   __ jmp(&exit);
1134
1135   // We got a fixed array in register eax. Iterate through that.
1136   Label non_proxy;
1137   __ bind(&fixed_array);
1138
1139   // No need for a write barrier, we are storing a Smi in the feedback vector.
1140   __ LoadHeapObject(ebx, FeedbackVector());
1141   int vector_index = FeedbackVector()->GetIndex(slot);
1142   __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1143          Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
1144
1145   __ mov(ebx, Immediate(Smi::FromInt(1)));  // Smi indicates slow check
1146   __ mov(ecx, Operand(esp, 0 * kPointerSize));  // Get enumerated object
1147   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
1148   __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
1149   __ j(above, &non_proxy);
1150   __ Move(ebx, Immediate(Smi::FromInt(0)));  // Zero indicates proxy
1151   __ bind(&non_proxy);
1152   __ push(ebx);  // Smi
1153   __ push(eax);  // Array
1154   __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
1155   __ push(eax);  // Fixed array length (as smi).
1156   __ push(Immediate(Smi::FromInt(0)));  // Initial index.
1157
1158   // Generate code for doing the condition check.
1159   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1160   __ bind(&loop);
1161   SetExpressionPosition(stmt->each());
1162
1163   __ mov(eax, Operand(esp, 0 * kPointerSize));  // Get the current index.
1164   __ cmp(eax, Operand(esp, 1 * kPointerSize));  // Compare to the array length.
1165   __ j(above_equal, loop_statement.break_label());
1166
1167   // Get the current entry of the array into register ebx.
1168   __ mov(ebx, Operand(esp, 2 * kPointerSize));
1169   __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));
1170
1171   // Get the expected map from the stack or a smi in the
1172   // permanent slow case into register edx.
1173   __ mov(edx, Operand(esp, 3 * kPointerSize));
1174
1175   // Check if the expected map still matches that of the enumerable.
1176   // If not, we may have to filter the key.
1177   Label update_each;
1178   __ mov(ecx, Operand(esp, 4 * kPointerSize));
1179   __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
1180   __ j(equal, &update_each, Label::kNear);
1181
1182   // For proxies, no filtering is done.
1183   // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1184   DCHECK(Smi::FromInt(0) == 0);
1185   __ test(edx, edx);
1186   __ j(zero, &update_each);
1187
1188   // Convert the entry to a string or null if it isn't a property
1189   // anymore. If the property has been removed while iterating, we
1190   // just skip it.
1191   __ push(ecx);  // Enumerable.
1192   __ push(ebx);  // Current entry.
1193   __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION);
1194   __ test(eax, eax);
1195   __ j(equal, loop_statement.continue_label());
1196   __ mov(ebx, eax);
1197
1198   // Update the 'each' property or variable from the possibly filtered
1199   // entry in register ebx.
1200   __ bind(&update_each);
1201   __ mov(result_register(), ebx);
1202   // Perform the assignment as if via '='.
1203   { EffectContext context(this);
1204     EmitAssignment(stmt->each());
1205     PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
1206   }
1207
1208   // Generate code for the body of the loop.
1209   Visit(stmt->body());
1210
1211   // Generate code for going to the next element by incrementing the
1212   // index (smi) stored on top of the stack.
1213   __ bind(loop_statement.continue_label());
1214   __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));
1215
1216   EmitBackEdgeBookkeeping(stmt, &loop);
1217   __ jmp(&loop);
1218
1219   // Remove the pointers stored on the stack.
1220   __ bind(loop_statement.break_label());
1221   __ add(esp, Immediate(5 * kPointerSize));
1222
1223   // Exit and decrement the loop depth.
1224   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1225   __ bind(&exit);
1226   decrement_loop_depth();
1227 }
1228
1229
1230 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
1231                                        bool pretenure) {
1232   // Use the fast case closure allocation code that allocates in new
1233   // space for nested functions that don't need literals cloning. If
1234   // we're running with the --always-opt or the --prepare-always-opt
1235   // flag, we need to use the runtime function so that the new function
1236   // we are creating here gets a chance to have its code optimized and
1237   // doesn't just get a copy of the existing unoptimized code.
1238   if (!FLAG_always_opt &&
1239       !FLAG_prepare_always_opt &&
1240       !pretenure &&
1241       scope()->is_function_scope() &&
1242       info->num_literals() == 0) {
1243     FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
1244     __ mov(ebx, Immediate(info));
1245     __ CallStub(&stub);
1246   } else {
1247     __ push(esi);
1248     __ push(Immediate(info));
1249     __ push(Immediate(pretenure
1250                       ? isolate()->factory()->true_value()
1251                       : isolate()->factory()->false_value()));
1252     __ CallRuntime(Runtime::kNewClosure, 3);
1253   }
1254   context()->Plug(eax);
1255 }
1256
1257
1258 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) {
1259   Comment cmnt(masm_, "[ VariableProxy");
1260   EmitVariableLoad(expr);
1261 }
1262
1263
1264 void FullCodeGenerator::EmitLoadHomeObject(SuperReference* expr) {
1265   Comment cnmt(masm_, "[ SuperReference ");
1266
1267   __ mov(LoadDescriptor::ReceiverRegister(),
1268          Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1269
1270   Handle<Symbol> home_object_symbol(isolate()->heap()->home_object_symbol());
1271   __ mov(LoadDescriptor::NameRegister(), home_object_symbol);
1272
1273   if (FLAG_vector_ics) {
1274     __ mov(VectorLoadICDescriptor::SlotRegister(),
1275            Immediate(SmiFromSlot(expr->HomeObjectFeedbackSlot())));
1276     CallLoadIC(NOT_CONTEXTUAL);
1277   } else {
1278     CallLoadIC(NOT_CONTEXTUAL, expr->HomeObjectFeedbackId());
1279   }
1280
1281   __ cmp(eax, isolate()->factory()->undefined_value());
1282   Label done;
1283   __ j(not_equal, &done);
1284   __ CallRuntime(Runtime::kThrowNonMethodError, 0);
1285   __ bind(&done);
1286 }
1287
1288
1289 void FullCodeGenerator::EmitSetHomeObjectIfNeeded(Expression* initializer,
1290                                                   int offset) {
1291   if (NeedsHomeObject(initializer)) {
1292     __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1293     __ mov(StoreDescriptor::NameRegister(),
1294            Immediate(isolate()->factory()->home_object_symbol()));
1295     __ mov(StoreDescriptor::ValueRegister(),
1296            Operand(esp, offset * kPointerSize));
1297     CallStoreIC();
1298   }
1299 }
1300
1301
1302 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1303                                                       TypeofState typeof_state,
1304                                                       Label* slow) {
1305   Register context = esi;
1306   Register temp = edx;
1307
1308   Scope* s = scope();
1309   while (s != NULL) {
1310     if (s->num_heap_slots() > 0) {
1311       if (s->calls_sloppy_eval()) {
1312         // Check that extension is NULL.
1313         __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1314                Immediate(0));
1315         __ j(not_equal, slow);
1316       }
1317       // Load next context in chain.
1318       __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1319       // Walk the rest of the chain without clobbering esi.
1320       context = temp;
1321     }
1322     // If no outer scope calls eval, we do not need to check more
1323     // context extensions.  If we have reached an eval scope, we check
1324     // all extensions from this point.
1325     if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
1326     s = s->outer_scope();
1327   }
1328
1329   if (s != NULL && s->is_eval_scope()) {
1330     // Loop up the context chain.  There is no frame effect so it is
1331     // safe to use raw labels here.
1332     Label next, fast;
1333     if (!context.is(temp)) {
1334       __ mov(temp, context);
1335     }
1336     __ bind(&next);
1337     // Terminate at native context.
1338     __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
1339            Immediate(isolate()->factory()->native_context_map()));
1340     __ j(equal, &fast, Label::kNear);
1341     // Check that extension is NULL.
1342     __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
1343     __ j(not_equal, slow);
1344     // Load next context in chain.
1345     __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
1346     __ jmp(&next);
1347     __ bind(&fast);
1348   }
1349
1350   // All extension objects were empty and it is safe to use a global
1351   // load IC call.
1352   __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1353   __ mov(LoadDescriptor::NameRegister(), proxy->var()->name());
1354   if (FLAG_vector_ics) {
1355     __ mov(VectorLoadICDescriptor::SlotRegister(),
1356            Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1357   }
1358
1359   ContextualMode mode = (typeof_state == INSIDE_TYPEOF)
1360       ? NOT_CONTEXTUAL
1361       : CONTEXTUAL;
1362
1363   CallLoadIC(mode);
1364 }
1365
1366
1367 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
1368                                                                 Label* slow) {
1369   DCHECK(var->IsContextSlot());
1370   Register context = esi;
1371   Register temp = ebx;
1372
1373   for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1374     if (s->num_heap_slots() > 0) {
1375       if (s->calls_sloppy_eval()) {
1376         // Check that extension is NULL.
1377         __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
1378                Immediate(0));
1379         __ j(not_equal, slow);
1380       }
1381       __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1382       // Walk the rest of the chain without clobbering esi.
1383       context = temp;
1384     }
1385   }
1386   // Check that last extension is NULL.
1387   __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
1388   __ j(not_equal, slow);
1389
1390   // This function is used only for loads, not stores, so it's safe to
1391   // return an esi-based operand (the write barrier cannot be allowed to
1392   // destroy the esi register).
1393   return ContextOperand(context, var->index());
1394 }
1395
1396
1397 void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1398                                                   TypeofState typeof_state,
1399                                                   Label* slow,
1400                                                   Label* done) {
1401   // Generate fast-case code for variables that might be shadowed by
1402   // eval-introduced variables.  Eval is used a lot without
1403   // introducing variables.  In those cases, we do not want to
1404   // perform a runtime call for all variables in the scope
1405   // containing the eval.
1406   Variable* var = proxy->var();
1407   if (var->mode() == DYNAMIC_GLOBAL) {
1408     EmitLoadGlobalCheckExtensions(proxy, typeof_state, slow);
1409     __ jmp(done);
1410   } else if (var->mode() == DYNAMIC_LOCAL) {
1411     Variable* local = var->local_if_not_shadowed();
1412     __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
1413     if (local->mode() == LET || local->mode() == CONST ||
1414         local->mode() == CONST_LEGACY) {
1415       __ cmp(eax, isolate()->factory()->the_hole_value());
1416       __ j(not_equal, done);
1417       if (local->mode() == CONST_LEGACY) {
1418         __ mov(eax, isolate()->factory()->undefined_value());
1419       } else {  // LET || CONST
1420         __ push(Immediate(var->name()));
1421         __ CallRuntime(Runtime::kThrowReferenceError, 1);
1422       }
1423     }
1424     __ jmp(done);
1425   }
1426 }
1427
1428
1429 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) {
1430   // Record position before possible IC call.
1431   SetSourcePosition(proxy->position());
1432   Variable* var = proxy->var();
1433
1434   // Three cases: global variables, lookup variables, and all other types of
1435   // variables.
1436   switch (var->location()) {
1437     case Variable::UNALLOCATED: {
1438       Comment cmnt(masm_, "[ Global variable");
1439       __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
1440       __ mov(LoadDescriptor::NameRegister(), var->name());
1441       if (FLAG_vector_ics) {
1442         __ mov(VectorLoadICDescriptor::SlotRegister(),
1443                Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1444       }
1445       CallLoadIC(CONTEXTUAL);
1446       context()->Plug(eax);
1447       break;
1448     }
1449
1450     case Variable::PARAMETER:
1451     case Variable::LOCAL:
1452     case Variable::CONTEXT: {
1453       Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
1454                                                : "[ Stack variable");
1455       if (var->binding_needs_init()) {
1456         // var->scope() may be NULL when the proxy is located in eval code and
1457         // refers to a potential outside binding. Currently those bindings are
1458         // always looked up dynamically, i.e. in that case
1459         //     var->location() == LOOKUP.
1460         // always holds.
1461         DCHECK(var->scope() != NULL);
1462
1463         // Check if the binding really needs an initialization check. The check
1464         // can be skipped in the following situation: we have a LET or CONST
1465         // binding in harmony mode, both the Variable and the VariableProxy have
1466         // the same declaration scope (i.e. they are both in global code, in the
1467         // same function or in the same eval code) and the VariableProxy is in
1468         // the source physically located after the initializer of the variable.
1469         //
1470         // We cannot skip any initialization checks for CONST in non-harmony
1471         // mode because const variables may be declared but never initialized:
1472         //   if (false) { const x; }; var y = x;
1473         //
1474         // The condition on the declaration scopes is a conservative check for
1475         // nested functions that access a binding and are called before the
1476         // binding is initialized:
1477         //   function() { f(); let x = 1; function f() { x = 2; } }
1478         //
1479         bool skip_init_check;
1480         if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) {
1481           skip_init_check = false;
1482         } else if (var->is_this()) {
1483           CHECK(info_->function() != nullptr &&
1484                 (info_->function()->kind() & kSubclassConstructor) != 0);
1485           // TODO(dslomov): implement 'this' hole check elimination.
1486           skip_init_check = false;
1487         } else {
1488           // Check that we always have valid source position.
1489           DCHECK(var->initializer_position() != RelocInfo::kNoPosition);
1490           DCHECK(proxy->position() != RelocInfo::kNoPosition);
1491           skip_init_check = var->mode() != CONST_LEGACY &&
1492               var->initializer_position() < proxy->position();
1493         }
1494
1495         if (!skip_init_check) {
1496           // Let and const need a read barrier.
1497           Label done;
1498           GetVar(eax, var);
1499           __ cmp(eax, isolate()->factory()->the_hole_value());
1500           __ j(not_equal, &done, Label::kNear);
1501           if (var->mode() == LET || var->mode() == CONST) {
1502             // Throw a reference error when using an uninitialized let/const
1503             // binding in harmony mode.
1504             __ push(Immediate(var->name()));
1505             __ CallRuntime(Runtime::kThrowReferenceError, 1);
1506           } else {
1507             // Uninitalized const bindings outside of harmony mode are unholed.
1508             DCHECK(var->mode() == CONST_LEGACY);
1509             __ mov(eax, isolate()->factory()->undefined_value());
1510           }
1511           __ bind(&done);
1512           context()->Plug(eax);
1513           break;
1514         }
1515       }
1516       context()->Plug(var);
1517       break;
1518     }
1519
1520     case Variable::LOOKUP: {
1521       Comment cmnt(masm_, "[ Lookup variable");
1522       Label done, slow;
1523       // Generate code for loading from variables potentially shadowed
1524       // by eval-introduced variables.
1525       EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
1526       __ bind(&slow);
1527       __ push(esi);  // Context.
1528       __ push(Immediate(var->name()));
1529       __ CallRuntime(Runtime::kLoadLookupSlot, 2);
1530       __ bind(&done);
1531       context()->Plug(eax);
1532       break;
1533     }
1534   }
1535 }
1536
1537
1538 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
1539   Comment cmnt(masm_, "[ RegExpLiteral");
1540   Label materialized;
1541   // Registers will be used as follows:
1542   // edi = JS function.
1543   // ecx = literals array.
1544   // ebx = regexp literal.
1545   // eax = regexp literal clone.
1546   __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1547   __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1548   int literal_offset =
1549       FixedArray::kHeaderSize + expr->literal_index() * kPointerSize;
1550   __ mov(ebx, FieldOperand(ecx, literal_offset));
1551   __ cmp(ebx, isolate()->factory()->undefined_value());
1552   __ j(not_equal, &materialized, Label::kNear);
1553
1554   // Create regexp literal using runtime function
1555   // Result will be in eax.
1556   __ push(ecx);
1557   __ push(Immediate(Smi::FromInt(expr->literal_index())));
1558   __ push(Immediate(expr->pattern()));
1559   __ push(Immediate(expr->flags()));
1560   __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
1561   __ mov(ebx, eax);
1562
1563   __ bind(&materialized);
1564   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
1565   Label allocated, runtime_allocate;
1566   __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
1567   __ jmp(&allocated);
1568
1569   __ bind(&runtime_allocate);
1570   __ push(ebx);
1571   __ push(Immediate(Smi::FromInt(size)));
1572   __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
1573   __ pop(ebx);
1574
1575   __ bind(&allocated);
1576   // Copy the content into the newly allocated memory.
1577   // (Unroll copy loop once for better throughput).
1578   for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
1579     __ mov(edx, FieldOperand(ebx, i));
1580     __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
1581     __ mov(FieldOperand(eax, i), edx);
1582     __ mov(FieldOperand(eax, i + kPointerSize), ecx);
1583   }
1584   if ((size % (2 * kPointerSize)) != 0) {
1585     __ mov(edx, FieldOperand(ebx, size - kPointerSize));
1586     __ mov(FieldOperand(eax, size - kPointerSize), edx);
1587   }
1588   context()->Plug(eax);
1589 }
1590
1591
1592 void FullCodeGenerator::EmitAccessor(Expression* expression) {
1593   if (expression == NULL) {
1594     __ push(Immediate(isolate()->factory()->null_value()));
1595   } else {
1596     VisitForStackValue(expression);
1597   }
1598 }
1599
1600
1601 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1602   Comment cmnt(masm_, "[ ObjectLiteral");
1603
1604   expr->BuildConstantProperties(isolate());
1605   Handle<FixedArray> constant_properties = expr->constant_properties();
1606   int flags = expr->fast_elements()
1607       ? ObjectLiteral::kFastElements
1608       : ObjectLiteral::kNoFlags;
1609   flags |= expr->has_function()
1610       ? ObjectLiteral::kHasFunction
1611       : ObjectLiteral::kNoFlags;
1612   int properties_count = constant_properties->length() / 2;
1613   if (expr->may_store_doubles() || expr->depth() > 1 ||
1614       masm()->serializer_enabled() ||
1615       flags != ObjectLiteral::kFastElements ||
1616       properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
1617     __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1618     __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
1619     __ push(Immediate(Smi::FromInt(expr->literal_index())));
1620     __ push(Immediate(constant_properties));
1621     __ push(Immediate(Smi::FromInt(flags)));
1622     __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
1623   } else {
1624     __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1625     __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
1626     __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1627     __ mov(ecx, Immediate(constant_properties));
1628     __ mov(edx, Immediate(Smi::FromInt(flags)));
1629     FastCloneShallowObjectStub stub(isolate(), properties_count);
1630     __ CallStub(&stub);
1631   }
1632   PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1633
1634   // If result_saved is true the result is on top of the stack.  If
1635   // result_saved is false the result is in eax.
1636   bool result_saved = false;
1637
1638   // Mark all computed expressions that are bound to a key that
1639   // is shadowed by a later occurrence of the same key. For the
1640   // marked expressions, no store code is emitted.
1641   expr->CalculateEmitStore(zone());
1642
1643   AccessorTable accessor_table(zone());
1644   int property_index = 0;
1645   for (; property_index < expr->properties()->length(); property_index++) {
1646     ObjectLiteral::Property* property = expr->properties()->at(property_index);
1647     if (property->is_computed_name()) break;
1648     if (property->IsCompileTimeValue()) continue;
1649
1650     Literal* key = property->key()->AsLiteral();
1651     Expression* value = property->value();
1652     if (!result_saved) {
1653       __ push(eax);  // Save result on the stack
1654       result_saved = true;
1655     }
1656     switch (property->kind()) {
1657       case ObjectLiteral::Property::CONSTANT:
1658         UNREACHABLE();
1659       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1660         DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1661         // Fall through.
1662       case ObjectLiteral::Property::COMPUTED:
1663         // It is safe to use [[Put]] here because the boilerplate already
1664         // contains computed properties with an uninitialized value.
1665         if (key->value()->IsInternalizedString()) {
1666           if (property->emit_store()) {
1667             VisitForAccumulatorValue(value);
1668             DCHECK(StoreDescriptor::ValueRegister().is(eax));
1669             __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
1670             __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1671             CallStoreIC(key->LiteralFeedbackId());
1672             PrepareForBailoutForId(key->id(), NO_REGISTERS);
1673
1674             if (NeedsHomeObject(value)) {
1675               __ mov(StoreDescriptor::ReceiverRegister(), eax);
1676               __ mov(StoreDescriptor::NameRegister(),
1677                      Immediate(isolate()->factory()->home_object_symbol()));
1678               __ mov(StoreDescriptor::ValueRegister(), Operand(esp, 0));
1679               CallStoreIC();
1680             }
1681           } else {
1682             VisitForEffect(value);
1683           }
1684           break;
1685         }
1686         __ push(Operand(esp, 0));  // Duplicate receiver.
1687         VisitForStackValue(key);
1688         VisitForStackValue(value);
1689         if (property->emit_store()) {
1690           EmitSetHomeObjectIfNeeded(value, 2);
1691           __ push(Immediate(Smi::FromInt(SLOPPY)));  // Language mode
1692           __ CallRuntime(Runtime::kSetProperty, 4);
1693         } else {
1694           __ Drop(3);
1695         }
1696         break;
1697       case ObjectLiteral::Property::PROTOTYPE:
1698         __ push(Operand(esp, 0));  // Duplicate receiver.
1699         VisitForStackValue(value);
1700         DCHECK(property->emit_store());
1701         __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1702         break;
1703       case ObjectLiteral::Property::GETTER:
1704         if (property->emit_store()) {
1705           accessor_table.lookup(key)->second->getter = value;
1706         }
1707         break;
1708       case ObjectLiteral::Property::SETTER:
1709         if (property->emit_store()) {
1710           accessor_table.lookup(key)->second->setter = value;
1711         }
1712         break;
1713     }
1714   }
1715
1716   // Emit code to define accessors, using only a single call to the runtime for
1717   // each pair of corresponding getters and setters.
1718   for (AccessorTable::Iterator it = accessor_table.begin();
1719        it != accessor_table.end();
1720        ++it) {
1721     __ push(Operand(esp, 0));  // Duplicate receiver.
1722     VisitForStackValue(it->first);
1723     EmitAccessor(it->second->getter);
1724     EmitSetHomeObjectIfNeeded(it->second->getter, 2);
1725     EmitAccessor(it->second->setter);
1726     EmitSetHomeObjectIfNeeded(it->second->setter, 3);
1727     __ push(Immediate(Smi::FromInt(NONE)));
1728     __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
1729   }
1730
1731   // Object literals have two parts. The "static" part on the left contains no
1732   // computed property names, and so we can compute its map ahead of time; see
1733   // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
1734   // starts with the first computed property name, and continues with all
1735   // properties to its right.  All the code from above initializes the static
1736   // component of the object literal, and arranges for the map of the result to
1737   // reflect the static order in which the keys appear. For the dynamic
1738   // properties, we compile them into a series of "SetOwnProperty" runtime
1739   // calls. This will preserve insertion order.
1740   for (; property_index < expr->properties()->length(); property_index++) {
1741     ObjectLiteral::Property* property = expr->properties()->at(property_index);
1742
1743     Expression* value = property->value();
1744     if (!result_saved) {
1745       __ push(eax);  // Save result on the stack
1746       result_saved = true;
1747     }
1748
1749     __ push(Operand(esp, 0));  // Duplicate receiver.
1750
1751     if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
1752       DCHECK(!property->is_computed_name());
1753       VisitForStackValue(value);
1754       DCHECK(property->emit_store());
1755       __ CallRuntime(Runtime::kInternalSetPrototype, 2);
1756     } else {
1757       EmitPropertyKey(property, expr->GetIdForProperty(property_index));
1758       VisitForStackValue(value);
1759       EmitSetHomeObjectIfNeeded(value, 2);
1760
1761       switch (property->kind()) {
1762         case ObjectLiteral::Property::CONSTANT:
1763         case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1764         case ObjectLiteral::Property::COMPUTED:
1765           if (property->emit_store()) {
1766             __ push(Immediate(Smi::FromInt(NONE)));
1767             __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
1768           } else {
1769             __ Drop(3);
1770           }
1771           break;
1772
1773         case ObjectLiteral::Property::PROTOTYPE:
1774           UNREACHABLE();
1775           break;
1776
1777         case ObjectLiteral::Property::GETTER:
1778           __ push(Immediate(Smi::FromInt(NONE)));
1779           __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
1780           break;
1781
1782         case ObjectLiteral::Property::SETTER:
1783           __ push(Immediate(Smi::FromInt(NONE)));
1784           __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
1785           break;
1786       }
1787     }
1788   }
1789
1790   if (expr->has_function()) {
1791     DCHECK(result_saved);
1792     __ push(Operand(esp, 0));
1793     __ CallRuntime(Runtime::kToFastProperties, 1);
1794   }
1795
1796   if (result_saved) {
1797     context()->PlugTOS();
1798   } else {
1799     context()->Plug(eax);
1800   }
1801 }
1802
1803
1804 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1805   Comment cmnt(masm_, "[ ArrayLiteral");
1806
1807   expr->BuildConstantElements(isolate());
1808   int flags = expr->depth() == 1
1809       ? ArrayLiteral::kShallowElements
1810       : ArrayLiteral::kNoFlags;
1811
1812   ZoneList<Expression*>* subexprs = expr->values();
1813   int length = subexprs->length();
1814   Handle<FixedArray> constant_elements = expr->constant_elements();
1815   DCHECK_EQ(2, constant_elements->length());
1816   ElementsKind constant_elements_kind =
1817       static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value());
1818   bool has_constant_fast_elements =
1819       IsFastObjectElementsKind(constant_elements_kind);
1820   Handle<FixedArrayBase> constant_elements_values(
1821       FixedArrayBase::cast(constant_elements->get(1)));
1822
1823   AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1824   if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
1825     // If the only customer of allocation sites is transitioning, then
1826     // we can turn it off if we don't have anywhere else to transition to.
1827     allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
1828   }
1829
1830   if (expr->depth() > 1 || length > JSObject::kInitialMaxFastElementArray) {
1831     __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1832     __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
1833     __ push(Immediate(Smi::FromInt(expr->literal_index())));
1834     __ push(Immediate(constant_elements));
1835     __ push(Immediate(Smi::FromInt(flags)));
1836     __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
1837   } else {
1838     __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1839     __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
1840     __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
1841     __ mov(ecx, Immediate(constant_elements));
1842     FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1843     __ CallStub(&stub);
1844   }
1845   PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
1846
1847   bool result_saved = false;  // Is the result saved to the stack?
1848
1849   // Emit code to evaluate all the non-constant subexpressions and to store
1850   // them into the newly cloned array.
1851   for (int i = 0; i < length; i++) {
1852     Expression* subexpr = subexprs->at(i);
1853     // If the subexpression is a literal or a simple materialized literal it
1854     // is already set in the cloned array.
1855     if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1856
1857     if (!result_saved) {
1858       __ push(eax);  // array literal.
1859       __ push(Immediate(Smi::FromInt(expr->literal_index())));
1860       result_saved = true;
1861     }
1862     VisitForAccumulatorValue(subexpr);
1863
1864     if (IsFastObjectElementsKind(constant_elements_kind)) {
1865       // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
1866       // cannot transition and don't need to call the runtime stub.
1867       int offset = FixedArray::kHeaderSize + (i * kPointerSize);
1868       __ mov(ebx, Operand(esp, kPointerSize));  // Copy of array literal.
1869       __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
1870       // Store the subexpression value in the array's elements.
1871       __ mov(FieldOperand(ebx, offset), result_register());
1872       // Update the write barrier for the array store.
1873       __ RecordWriteField(ebx, offset, result_register(), ecx, kDontSaveFPRegs,
1874                           EMIT_REMEMBERED_SET, INLINE_SMI_CHECK);
1875     } else {
1876       // Store the subexpression value in the array's elements.
1877       __ mov(ecx, Immediate(Smi::FromInt(i)));
1878       StoreArrayLiteralElementStub stub(isolate());
1879       __ CallStub(&stub);
1880     }
1881
1882     PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS);
1883   }
1884
1885   if (result_saved) {
1886     __ add(esp, Immediate(kPointerSize));  // literal index
1887     context()->PlugTOS();
1888   } else {
1889     context()->Plug(eax);
1890   }
1891 }
1892
1893
1894 void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1895   DCHECK(expr->target()->IsValidReferenceExpression());
1896
1897   Comment cmnt(masm_, "[ Assignment");
1898
1899   Property* property = expr->target()->AsProperty();
1900   LhsKind assign_type = GetAssignType(property);
1901
1902   // Evaluate LHS expression.
1903   switch (assign_type) {
1904     case VARIABLE:
1905       // Nothing to do here.
1906       break;
1907     case NAMED_SUPER_PROPERTY:
1908       VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1909       EmitLoadHomeObject(property->obj()->AsSuperReference());
1910       __ push(result_register());
1911       if (expr->is_compound()) {
1912         __ push(MemOperand(esp, kPointerSize));
1913         __ push(result_register());
1914       }
1915       break;
1916     case NAMED_PROPERTY:
1917       if (expr->is_compound()) {
1918         // We need the receiver both on the stack and in the register.
1919         VisitForStackValue(property->obj());
1920         __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
1921       } else {
1922         VisitForStackValue(property->obj());
1923       }
1924       break;
1925     case KEYED_SUPER_PROPERTY:
1926       VisitForStackValue(property->obj()->AsSuperReference()->this_var());
1927       EmitLoadHomeObject(property->obj()->AsSuperReference());
1928       __ Push(result_register());
1929       VisitForAccumulatorValue(property->key());
1930       __ Push(result_register());
1931       if (expr->is_compound()) {
1932         __ push(MemOperand(esp, 2 * kPointerSize));
1933         __ push(MemOperand(esp, 2 * kPointerSize));
1934         __ push(result_register());
1935       }
1936       break;
1937     case KEYED_PROPERTY: {
1938       if (expr->is_compound()) {
1939         VisitForStackValue(property->obj());
1940         VisitForStackValue(property->key());
1941         __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
1942         __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
1943       } else {
1944         VisitForStackValue(property->obj());
1945         VisitForStackValue(property->key());
1946       }
1947       break;
1948     }
1949   }
1950
1951   // For compound assignments we need another deoptimization point after the
1952   // variable/property load.
1953   if (expr->is_compound()) {
1954     AccumulatorValueContext result_context(this);
1955     { AccumulatorValueContext left_operand_context(this);
1956       switch (assign_type) {
1957         case VARIABLE:
1958           EmitVariableLoad(expr->target()->AsVariableProxy());
1959           PrepareForBailout(expr->target(), TOS_REG);
1960           break;
1961         case NAMED_SUPER_PROPERTY:
1962           EmitNamedSuperPropertyLoad(property);
1963           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1964           break;
1965         case NAMED_PROPERTY:
1966           EmitNamedPropertyLoad(property);
1967           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1968           break;
1969         case KEYED_SUPER_PROPERTY:
1970           EmitKeyedSuperPropertyLoad(property);
1971           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1972           break;
1973         case KEYED_PROPERTY:
1974           EmitKeyedPropertyLoad(property);
1975           PrepareForBailoutForId(property->LoadId(), TOS_REG);
1976           break;
1977       }
1978     }
1979
1980     Token::Value op = expr->binary_op();
1981     __ push(eax);  // Left operand goes on the stack.
1982     VisitForAccumulatorValue(expr->value());
1983
1984     SetSourcePosition(expr->position() + 1);
1985     if (ShouldInlineSmiCase(op)) {
1986       EmitInlineSmiBinaryOp(expr->binary_operation(),
1987                             op,
1988                             expr->target(),
1989                             expr->value());
1990     } else {
1991       EmitBinaryOp(expr->binary_operation(), op);
1992     }
1993
1994     // Deoptimization point in case the binary operation may have side effects.
1995     PrepareForBailout(expr->binary_operation(), TOS_REG);
1996   } else {
1997     VisitForAccumulatorValue(expr->value());
1998   }
1999
2000   // Record source position before possible IC call.
2001   SetSourcePosition(expr->position());
2002
2003   // Store the value.
2004   switch (assign_type) {
2005     case VARIABLE:
2006       EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
2007                              expr->op());
2008       PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2009       context()->Plug(eax);
2010       break;
2011     case NAMED_PROPERTY:
2012       EmitNamedPropertyAssignment(expr);
2013       break;
2014     case NAMED_SUPER_PROPERTY:
2015       EmitNamedSuperPropertyStore(property);
2016       context()->Plug(result_register());
2017       break;
2018     case KEYED_SUPER_PROPERTY:
2019       EmitKeyedSuperPropertyStore(property);
2020       context()->Plug(result_register());
2021       break;
2022     case KEYED_PROPERTY:
2023       EmitKeyedPropertyAssignment(expr);
2024       break;
2025   }
2026 }
2027
2028
2029 void FullCodeGenerator::VisitYield(Yield* expr) {
2030   Comment cmnt(masm_, "[ Yield");
2031   // Evaluate yielded value first; the initial iterator definition depends on
2032   // this.  It stays on the stack while we update the iterator.
2033   VisitForStackValue(expr->expression());
2034
2035   switch (expr->yield_kind()) {
2036     case Yield::kSuspend:
2037       // Pop value from top-of-stack slot; box result into result register.
2038       EmitCreateIteratorResult(false);
2039       __ push(result_register());
2040       // Fall through.
2041     case Yield::kInitial: {
2042       Label suspend, continuation, post_runtime, resume;
2043
2044       __ jmp(&suspend);
2045
2046       __ bind(&continuation);
2047       __ jmp(&resume);
2048
2049       __ bind(&suspend);
2050       VisitForAccumulatorValue(expr->generator_object());
2051       DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
2052       __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2053              Immediate(Smi::FromInt(continuation.pos())));
2054       __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2055       __ mov(ecx, esi);
2056       __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2057                           kDontSaveFPRegs);
2058       __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
2059       __ cmp(esp, ebx);
2060       __ j(equal, &post_runtime);
2061       __ push(eax);  // generator object
2062       __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2063       __ mov(context_register(),
2064              Operand(ebp, StandardFrameConstants::kContextOffset));
2065       __ bind(&post_runtime);
2066       __ pop(result_register());
2067       EmitReturnSequence();
2068
2069       __ bind(&resume);
2070       context()->Plug(result_register());
2071       break;
2072     }
2073
2074     case Yield::kFinal: {
2075       VisitForAccumulatorValue(expr->generator_object());
2076       __ mov(FieldOperand(result_register(),
2077                           JSGeneratorObject::kContinuationOffset),
2078              Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
2079       // Pop value from top-of-stack slot, box result into result register.
2080       EmitCreateIteratorResult(true);
2081       EmitUnwindBeforeReturn();
2082       EmitReturnSequence();
2083       break;
2084     }
2085
2086     case Yield::kDelegating: {
2087       VisitForStackValue(expr->generator_object());
2088
2089       // Initial stack layout is as follows:
2090       // [sp + 1 * kPointerSize] iter
2091       // [sp + 0 * kPointerSize] g
2092
2093       Label l_catch, l_try, l_suspend, l_continuation, l_resume;
2094       Label l_next, l_call, l_loop;
2095       Register load_receiver = LoadDescriptor::ReceiverRegister();
2096       Register load_name = LoadDescriptor::NameRegister();
2097
2098       // Initial send value is undefined.
2099       __ mov(eax, isolate()->factory()->undefined_value());
2100       __ jmp(&l_next);
2101
2102       // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
2103       __ bind(&l_catch);
2104       handler_table()->set(expr->index(), Smi::FromInt(l_catch.pos()));
2105       __ mov(load_name, isolate()->factory()->throw_string());  // "throw"
2106       __ push(load_name);                                       // "throw"
2107       __ push(Operand(esp, 2 * kPointerSize));                  // iter
2108       __ push(eax);                                             // exception
2109       __ jmp(&l_call);
2110
2111       // try { received = %yield result }
2112       // Shuffle the received result above a try handler and yield it without
2113       // re-boxing.
2114       __ bind(&l_try);
2115       __ pop(eax);                                       // result
2116       __ PushTryHandler(StackHandler::CATCH, expr->index());
2117       const int handler_size = StackHandlerConstants::kSize;
2118       __ push(eax);                                      // result
2119       __ jmp(&l_suspend);
2120       __ bind(&l_continuation);
2121       __ jmp(&l_resume);
2122       __ bind(&l_suspend);
2123       const int generator_object_depth = kPointerSize + handler_size;
2124       __ mov(eax, Operand(esp, generator_object_depth));
2125       __ push(eax);                                      // g
2126       DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
2127       __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
2128              Immediate(Smi::FromInt(l_continuation.pos())));
2129       __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
2130       __ mov(ecx, esi);
2131       __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
2132                           kDontSaveFPRegs);
2133       __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
2134       __ mov(context_register(),
2135              Operand(ebp, StandardFrameConstants::kContextOffset));
2136       __ pop(eax);                                       // result
2137       EmitReturnSequence();
2138       __ bind(&l_resume);                                // received in eax
2139       __ PopTryHandler();
2140
2141       // receiver = iter; f = iter.next; arg = received;
2142       __ bind(&l_next);
2143
2144       __ mov(load_name, isolate()->factory()->next_string());
2145       __ push(load_name);                           // "next"
2146       __ push(Operand(esp, 2 * kPointerSize));      // iter
2147       __ push(eax);                                 // received
2148
2149       // result = receiver[f](arg);
2150       __ bind(&l_call);
2151       __ mov(load_receiver, Operand(esp, kPointerSize));
2152       if (FLAG_vector_ics) {
2153         __ mov(VectorLoadICDescriptor::SlotRegister(),
2154                Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2155       }
2156       Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2157       CallIC(ic, TypeFeedbackId::None());
2158       __ mov(edi, eax);
2159       __ mov(Operand(esp, 2 * kPointerSize), edi);
2160       CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
2161       __ CallStub(&stub);
2162
2163       __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2164       __ Drop(1);  // The function is still on the stack; drop it.
2165
2166       // if (!result.done) goto l_try;
2167       __ bind(&l_loop);
2168       __ push(eax);                                      // save result
2169       __ Move(load_receiver, eax);                       // result
2170       __ mov(load_name,
2171              isolate()->factory()->done_string());       // "done"
2172       if (FLAG_vector_ics) {
2173         __ mov(VectorLoadICDescriptor::SlotRegister(),
2174                Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2175       }
2176       CallLoadIC(NOT_CONTEXTUAL);                        // result.done in eax
2177       Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
2178       CallIC(bool_ic);
2179       __ test(eax, eax);
2180       __ j(zero, &l_try);
2181
2182       // result.value
2183       __ pop(load_receiver);                              // result
2184       __ mov(load_name,
2185              isolate()->factory()->value_string());       // "value"
2186       if (FLAG_vector_ics) {
2187         __ mov(VectorLoadICDescriptor::SlotRegister(),
2188                Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2189       }
2190       CallLoadIC(NOT_CONTEXTUAL);                         // result.value in eax
2191       context()->DropAndPlug(2, eax);                     // drop iter and g
2192       break;
2193     }
2194   }
2195 }
2196
2197
2198 void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
2199     Expression *value,
2200     JSGeneratorObject::ResumeMode resume_mode) {
2201   // The value stays in eax, and is ultimately read by the resumed generator, as
2202   // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
2203   // is read to throw the value when the resumed generator is already closed.
2204   // ebx will hold the generator object until the activation has been resumed.
2205   VisitForStackValue(generator);
2206   VisitForAccumulatorValue(value);
2207   __ pop(ebx);
2208
2209   // Load suspended function and context.
2210   __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
2211   __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));
2212
2213   // Push receiver.
2214   __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));
2215
2216   // Push holes for arguments to generator function.
2217   __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2218   __ mov(edx,
2219          FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2220   __ mov(ecx, isolate()->factory()->the_hole_value());
2221   Label push_argument_holes, push_frame;
2222   __ bind(&push_argument_holes);
2223   __ sub(edx, Immediate(Smi::FromInt(1)));
2224   __ j(carry, &push_frame);
2225   __ push(ecx);
2226   __ jmp(&push_argument_holes);
2227
2228   // Enter a new JavaScript frame, and initialize its slots as they were when
2229   // the generator was suspended.
2230   Label resume_frame, done;
2231   __ bind(&push_frame);
2232   __ call(&resume_frame);
2233   __ jmp(&done);
2234   __ bind(&resume_frame);
2235   __ push(ebp);  // Caller's frame pointer.
2236   __ mov(ebp, esp);
2237   __ push(esi);  // Callee's context.
2238   __ push(edi);  // Callee's JS Function.
2239
2240   // Load the operand stack size.
2241   __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
2242   __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
2243   __ SmiUntag(edx);
2244
2245   // If we are sending a value and there is no operand stack, we can jump back
2246   // in directly.
2247   if (resume_mode == JSGeneratorObject::NEXT) {
2248     Label slow_resume;
2249     __ cmp(edx, Immediate(0));
2250     __ j(not_zero, &slow_resume);
2251     __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2252     __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
2253     __ SmiUntag(ecx);
2254     __ add(edx, ecx);
2255     __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
2256            Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
2257     __ jmp(edx);
2258     __ bind(&slow_resume);
2259   }
2260
2261   // Otherwise, we push holes for the operand stack and call the runtime to fix
2262   // up the stack and the handlers.
2263   Label push_operand_holes, call_resume;
2264   __ bind(&push_operand_holes);
2265   __ sub(edx, Immediate(1));
2266   __ j(carry, &call_resume);
2267   __ push(ecx);
2268   __ jmp(&push_operand_holes);
2269   __ bind(&call_resume);
2270   __ push(ebx);
2271   __ push(result_register());
2272   __ Push(Smi::FromInt(resume_mode));
2273   __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
2274   // Not reached: the runtime call returns elsewhere.
2275   __ Abort(kGeneratorFailedToResume);
2276
2277   __ bind(&done);
2278   context()->Plug(result_register());
2279 }
2280
2281
2282 void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2283   Label gc_required;
2284   Label allocated;
2285
2286   const int instance_size = 5 * kPointerSize;
2287   DCHECK_EQ(isolate()->native_context()->iterator_result_map()->instance_size(),
2288             instance_size);
2289
2290   __ Allocate(instance_size, eax, ecx, edx, &gc_required, TAG_OBJECT);
2291   __ jmp(&allocated);
2292
2293   __ bind(&gc_required);
2294   __ Push(Smi::FromInt(instance_size));
2295   __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
2296   __ mov(context_register(),
2297          Operand(ebp, StandardFrameConstants::kContextOffset));
2298
2299   __ bind(&allocated);
2300   __ mov(ebx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2301   __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
2302   __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
2303   __ pop(ecx);
2304   __ mov(edx, isolate()->factory()->ToBoolean(done));
2305   __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
2306   __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
2307          isolate()->factory()->empty_fixed_array());
2308   __ mov(FieldOperand(eax, JSObject::kElementsOffset),
2309          isolate()->factory()->empty_fixed_array());
2310   __ mov(FieldOperand(eax, JSGeneratorObject::kResultValuePropertyOffset), ecx);
2311   __ mov(FieldOperand(eax, JSGeneratorObject::kResultDonePropertyOffset), edx);
2312
2313   // Only the value field needs a write barrier, as the other values are in the
2314   // root set.
2315   __ RecordWriteField(eax, JSGeneratorObject::kResultValuePropertyOffset, ecx,
2316                       edx, kDontSaveFPRegs);
2317 }
2318
2319
2320 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2321   SetSourcePosition(prop->position());
2322   Literal* key = prop->key()->AsLiteral();
2323   DCHECK(!key->value()->IsSmi());
2324   DCHECK(!prop->IsSuperAccess());
2325
2326   __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2327   if (FLAG_vector_ics) {
2328     __ mov(VectorLoadICDescriptor::SlotRegister(),
2329            Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2330     CallLoadIC(NOT_CONTEXTUAL);
2331   } else {
2332     CallLoadIC(NOT_CONTEXTUAL, prop->PropertyFeedbackId());
2333   }
2334 }
2335
2336
2337 void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2338   // Stack: receiver, home_object.
2339   SetSourcePosition(prop->position());
2340   Literal* key = prop->key()->AsLiteral();
2341   DCHECK(!key->value()->IsSmi());
2342   DCHECK(prop->IsSuperAccess());
2343
2344   __ push(Immediate(key->value()));
2345   __ CallRuntime(Runtime::kLoadFromSuper, 3);
2346 }
2347
2348
2349 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2350   SetSourcePosition(prop->position());
2351   Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate()).code();
2352   if (FLAG_vector_ics) {
2353     __ mov(VectorLoadICDescriptor::SlotRegister(),
2354            Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2355     CallIC(ic);
2356   } else {
2357     CallIC(ic, prop->PropertyFeedbackId());
2358   }
2359 }
2360
2361
2362 void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
2363   // Stack: receiver, home_object, key.
2364   SetSourcePosition(prop->position());
2365
2366   __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2367 }
2368
2369
2370 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
2371                                               Token::Value op,
2372                                               Expression* left,
2373                                               Expression* right) {
2374   // Do combined smi check of the operands. Left operand is on the
2375   // stack. Right operand is in eax.
2376   Label smi_case, done, stub_call;
2377   __ pop(edx);
2378   __ mov(ecx, eax);
2379   __ or_(eax, edx);
2380   JumpPatchSite patch_site(masm_);
2381   patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);
2382
2383   __ bind(&stub_call);
2384   __ mov(eax, ecx);
2385   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2386   CallIC(code, expr->BinaryOperationFeedbackId());
2387   patch_site.EmitPatchInfo();
2388   __ jmp(&done, Label::kNear);
2389
2390   // Smi case.
2391   __ bind(&smi_case);
2392   __ mov(eax, edx);  // Copy left operand in case of a stub call.
2393
2394   switch (op) {
2395     case Token::SAR:
2396       __ SmiUntag(ecx);
2397       __ sar_cl(eax);  // No checks of result necessary
2398       __ and_(eax, Immediate(~kSmiTagMask));
2399       break;
2400     case Token::SHL: {
2401       Label result_ok;
2402       __ SmiUntag(eax);
2403       __ SmiUntag(ecx);
2404       __ shl_cl(eax);
2405       // Check that the *signed* result fits in a smi.
2406       __ cmp(eax, 0xc0000000);
2407       __ j(positive, &result_ok);
2408       __ SmiTag(ecx);
2409       __ jmp(&stub_call);
2410       __ bind(&result_ok);
2411       __ SmiTag(eax);
2412       break;
2413     }
2414     case Token::SHR: {
2415       Label result_ok;
2416       __ SmiUntag(eax);
2417       __ SmiUntag(ecx);
2418       __ shr_cl(eax);
2419       __ test(eax, Immediate(0xc0000000));
2420       __ j(zero, &result_ok);
2421       __ SmiTag(ecx);
2422       __ jmp(&stub_call);
2423       __ bind(&result_ok);
2424       __ SmiTag(eax);
2425       break;
2426     }
2427     case Token::ADD:
2428       __ add(eax, ecx);
2429       __ j(overflow, &stub_call);
2430       break;
2431     case Token::SUB:
2432       __ sub(eax, ecx);
2433       __ j(overflow, &stub_call);
2434       break;
2435     case Token::MUL: {
2436       __ SmiUntag(eax);
2437       __ imul(eax, ecx);
2438       __ j(overflow, &stub_call);
2439       __ test(eax, eax);
2440       __ j(not_zero, &done, Label::kNear);
2441       __ mov(ebx, edx);
2442       __ or_(ebx, ecx);
2443       __ j(negative, &stub_call);
2444       break;
2445     }
2446     case Token::BIT_OR:
2447       __ or_(eax, ecx);
2448       break;
2449     case Token::BIT_AND:
2450       __ and_(eax, ecx);
2451       break;
2452     case Token::BIT_XOR:
2453       __ xor_(eax, ecx);
2454       break;
2455     default:
2456       UNREACHABLE();
2457   }
2458
2459   __ bind(&done);
2460   context()->Plug(eax);
2461 }
2462
2463
2464 void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2465   // Constructor is in eax.
2466   DCHECK(lit != NULL);
2467   __ push(eax);
2468
2469   // No access check is needed here since the constructor is created by the
2470   // class literal.
2471   Register scratch = ebx;
2472   __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
2473   __ Push(scratch);
2474
2475   for (int i = 0; i < lit->properties()->length(); i++) {
2476     ObjectLiteral::Property* property = lit->properties()->at(i);
2477     Expression* value = property->value();
2478
2479     if (property->is_static()) {
2480       __ push(Operand(esp, kPointerSize));  // constructor
2481     } else {
2482       __ push(Operand(esp, 0));  // prototype
2483     }
2484     EmitPropertyKey(property, lit->GetIdForProperty(i));
2485     VisitForStackValue(value);
2486     EmitSetHomeObjectIfNeeded(value, 2);
2487
2488     switch (property->kind()) {
2489       case ObjectLiteral::Property::CONSTANT:
2490       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2491       case ObjectLiteral::Property::PROTOTYPE:
2492         UNREACHABLE();
2493       case ObjectLiteral::Property::COMPUTED:
2494         __ CallRuntime(Runtime::kDefineClassMethod, 3);
2495         break;
2496
2497       case ObjectLiteral::Property::GETTER:
2498         __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2499         __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2500         break;
2501
2502       case ObjectLiteral::Property::SETTER:
2503         __ push(Immediate(Smi::FromInt(DONT_ENUM)));
2504         __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2505         break;
2506     }
2507   }
2508
2509   // prototype
2510   __ CallRuntime(Runtime::kToFastProperties, 1);
2511
2512   // constructor
2513   __ CallRuntime(Runtime::kToFastProperties, 1);
2514 }
2515
2516
2517 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
2518   __ pop(edx);
2519   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
2520   JumpPatchSite patch_site(masm_);    // unbound, signals no inlined smi code.
2521   CallIC(code, expr->BinaryOperationFeedbackId());
2522   patch_site.EmitPatchInfo();
2523   context()->Plug(eax);
2524 }
2525
2526
2527 void FullCodeGenerator::EmitAssignment(Expression* expr) {
2528   DCHECK(expr->IsValidReferenceExpression());
2529
2530   Property* prop = expr->AsProperty();
2531   LhsKind assign_type = GetAssignType(prop);
2532
2533   switch (assign_type) {
2534     case VARIABLE: {
2535       Variable* var = expr->AsVariableProxy()->var();
2536       EffectContext context(this);
2537       EmitVariableAssignment(var, Token::ASSIGN);
2538       break;
2539     }
2540     case NAMED_PROPERTY: {
2541       __ push(eax);  // Preserve value.
2542       VisitForAccumulatorValue(prop->obj());
2543       __ Move(StoreDescriptor::ReceiverRegister(), eax);
2544       __ pop(StoreDescriptor::ValueRegister());  // Restore value.
2545       __ mov(StoreDescriptor::NameRegister(),
2546              prop->key()->AsLiteral()->value());
2547       CallStoreIC();
2548       break;
2549     }
2550     case NAMED_SUPER_PROPERTY: {
2551       __ push(eax);
2552       VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2553       EmitLoadHomeObject(prop->obj()->AsSuperReference());
2554       // stack: value, this; eax: home_object
2555       Register scratch = ecx;
2556       Register scratch2 = edx;
2557       __ mov(scratch, result_register());               // home_object
2558       __ mov(eax, MemOperand(esp, kPointerSize));       // value
2559       __ mov(scratch2, MemOperand(esp, 0));             // this
2560       __ mov(MemOperand(esp, kPointerSize), scratch2);  // this
2561       __ mov(MemOperand(esp, 0), scratch);              // home_object
2562       // stack: this, home_object. eax: value
2563       EmitNamedSuperPropertyStore(prop);
2564       break;
2565     }
2566     case KEYED_SUPER_PROPERTY: {
2567       __ push(eax);
2568       VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
2569       EmitLoadHomeObject(prop->obj()->AsSuperReference());
2570       __ push(result_register());
2571       VisitForAccumulatorValue(prop->key());
2572       Register scratch = ecx;
2573       Register scratch2 = edx;
2574       __ mov(scratch2, MemOperand(esp, 2 * kPointerSize));  // value
2575       // stack: value, this, home_object; eax: key, edx: value
2576       __ mov(scratch, MemOperand(esp, kPointerSize));  // this
2577       __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
2578       __ mov(scratch, MemOperand(esp, 0));  // home_object
2579       __ mov(MemOperand(esp, kPointerSize), scratch);
2580       __ mov(MemOperand(esp, 0), eax);
2581       __ mov(eax, scratch2);
2582       // stack: this, home_object, key; eax: value.
2583       EmitKeyedSuperPropertyStore(prop);
2584       break;
2585     }
2586     case KEYED_PROPERTY: {
2587       __ push(eax);  // Preserve value.
2588       VisitForStackValue(prop->obj());
2589       VisitForAccumulatorValue(prop->key());
2590       __ Move(StoreDescriptor::NameRegister(), eax);
2591       __ pop(StoreDescriptor::ReceiverRegister());  // Receiver.
2592       __ pop(StoreDescriptor::ValueRegister());     // Restore value.
2593       Handle<Code> ic =
2594           CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2595       CallIC(ic);
2596       break;
2597     }
2598   }
2599   context()->Plug(eax);
2600 }
2601
2602
2603 void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
2604     Variable* var, MemOperand location) {
2605   __ mov(location, eax);
2606   if (var->IsContextSlot()) {
2607     __ mov(edx, eax);
2608     int offset = Context::SlotOffset(var->index());
2609     __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
2610   }
2611 }
2612
2613
2614 void FullCodeGenerator::EmitVariableAssignment(Variable* var,
2615                                                Token::Value op) {
2616   if (var->IsUnallocated()) {
2617     // Global var, const, or let.
2618     __ mov(StoreDescriptor::NameRegister(), var->name());
2619     __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2620     CallStoreIC();
2621
2622   } else if (op == Token::INIT_CONST_LEGACY) {
2623     // Const initializers need a write barrier.
2624     DCHECK(!var->IsParameter());  // No const parameters.
2625     if (var->IsLookupSlot()) {
2626       __ push(eax);
2627       __ push(esi);
2628       __ push(Immediate(var->name()));
2629       __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
2630     } else {
2631       DCHECK(var->IsStackLocal() || var->IsContextSlot());
2632       Label skip;
2633       MemOperand location = VarOperand(var, ecx);
2634       __ mov(edx, location);
2635       __ cmp(edx, isolate()->factory()->the_hole_value());
2636       __ j(not_equal, &skip, Label::kNear);
2637       EmitStoreToStackLocalOrContextSlot(var, location);
2638       __ bind(&skip);
2639     }
2640
2641   } else if (var->mode() == LET && op != Token::INIT_LET) {
2642     // Non-initializing assignment to let variable needs a write barrier.
2643     DCHECK(!var->IsLookupSlot());
2644     DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2645     Label assign;
2646     MemOperand location = VarOperand(var, ecx);
2647     __ mov(edx, location);
2648     __ cmp(edx, isolate()->factory()->the_hole_value());
2649     __ j(not_equal, &assign, Label::kNear);
2650     __ push(Immediate(var->name()));
2651     __ CallRuntime(Runtime::kThrowReferenceError, 1);
2652     __ bind(&assign);
2653     EmitStoreToStackLocalOrContextSlot(var, location);
2654   } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
2655     if (var->IsLookupSlot()) {
2656       // Assignment to var.
2657       __ push(eax);  // Value.
2658       __ push(esi);  // Context.
2659       __ push(Immediate(var->name()));
2660       __ push(Immediate(Smi::FromInt(language_mode())));
2661       __ CallRuntime(Runtime::kStoreLookupSlot, 4);
2662     } else {
2663       // Assignment to var or initializing assignment to let/const in harmony
2664       // mode.
2665       DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2666       MemOperand location = VarOperand(var, ecx);
2667       if (generate_debug_code_ && op == Token::INIT_LET) {
2668         // Check for an uninitialized let binding.
2669         __ mov(edx, location);
2670         __ cmp(edx, isolate()->factory()->the_hole_value());
2671         __ Check(equal, kLetBindingReInitialization);
2672       }
2673       EmitStoreToStackLocalOrContextSlot(var, location);
2674     }
2675   } else if (IsSignallingAssignmentToConst(var, op, language_mode())) {
2676     __ CallRuntime(Runtime::kThrowConstAssignError, 0);
2677   }
2678 }
2679
2680
2681 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2682   // Assignment to a property, using a named store IC.
2683   // eax    : value
2684   // esp[0] : receiver
2685
2686   Property* prop = expr->target()->AsProperty();
2687   DCHECK(prop != NULL);
2688   DCHECK(prop->key()->IsLiteral());
2689
2690   // Record source code position before IC call.
2691   SetSourcePosition(expr->position());
2692   __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
2693   __ pop(StoreDescriptor::ReceiverRegister());
2694   CallStoreIC(expr->AssignmentFeedbackId());
2695   PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2696   context()->Plug(eax);
2697 }
2698
2699
2700 void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2701   // Assignment to named property of super.
2702   // eax : value
2703   // stack : receiver ('this'), home_object
2704   DCHECK(prop != NULL);
2705   Literal* key = prop->key()->AsLiteral();
2706   DCHECK(key != NULL);
2707
2708   __ push(Immediate(key->value()));
2709   __ push(eax);
2710   __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
2711                                              : Runtime::kStoreToSuper_Sloppy),
2712                  4);
2713 }
2714
2715
2716 void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
2717   // Assignment to named property of super.
2718   // eax : value
2719   // stack : receiver ('this'), home_object, key
2720
2721   __ push(eax);
2722   __ CallRuntime(
2723       (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
2724                                   : Runtime::kStoreKeyedToSuper_Sloppy),
2725       4);
2726 }
2727
2728
2729 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2730   // Assignment to a property, using a keyed store IC.
2731   // eax               : value
2732   // esp[0]            : key
2733   // esp[kPointerSize] : receiver
2734
2735   __ pop(StoreDescriptor::NameRegister());  // Key.
2736   __ pop(StoreDescriptor::ReceiverRegister());
2737   DCHECK(StoreDescriptor::ValueRegister().is(eax));
2738   // Record source code position before IC call.
2739   SetSourcePosition(expr->position());
2740   Handle<Code> ic =
2741       CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2742   CallIC(ic, expr->AssignmentFeedbackId());
2743
2744   PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
2745   context()->Plug(eax);
2746 }
2747
2748
2749 void FullCodeGenerator::VisitProperty(Property* expr) {
2750   Comment cmnt(masm_, "[ Property");
2751   Expression* key = expr->key();
2752
2753   if (key->IsPropertyName()) {
2754     if (!expr->IsSuperAccess()) {
2755       VisitForAccumulatorValue(expr->obj());
2756       __ Move(LoadDescriptor::ReceiverRegister(), result_register());
2757       EmitNamedPropertyLoad(expr);
2758     } else {
2759       VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2760       EmitLoadHomeObject(expr->obj()->AsSuperReference());
2761       __ push(result_register());
2762       EmitNamedSuperPropertyLoad(expr);
2763     }
2764   } else {
2765     if (!expr->IsSuperAccess()) {
2766       VisitForStackValue(expr->obj());
2767       VisitForAccumulatorValue(expr->key());
2768       __ pop(LoadDescriptor::ReceiverRegister());                  // Object.
2769       __ Move(LoadDescriptor::NameRegister(), result_register());  // Key.
2770       EmitKeyedPropertyLoad(expr);
2771     } else {
2772       VisitForStackValue(expr->obj()->AsSuperReference()->this_var());
2773       EmitLoadHomeObject(expr->obj()->AsSuperReference());
2774       __ push(result_register());
2775       VisitForStackValue(expr->key());
2776       EmitKeyedSuperPropertyLoad(expr);
2777     }
2778   }
2779   PrepareForBailoutForId(expr->LoadId(), TOS_REG);
2780   context()->Plug(eax);
2781 }
2782
2783
2784 void FullCodeGenerator::CallIC(Handle<Code> code,
2785                                TypeFeedbackId ast_id) {
2786   ic_total_count_++;
2787   __ call(code, RelocInfo::CODE_TARGET, ast_id);
2788 }
2789
2790
2791 // Code common for calls using the IC.
2792 void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
2793   Expression* callee = expr->expression();
2794
2795   CallICState::CallType call_type =
2796       callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
2797   // Get the target function.
2798   if (call_type == CallICState::FUNCTION) {
2799     { StackValueContext context(this);
2800       EmitVariableLoad(callee->AsVariableProxy());
2801       PrepareForBailout(callee, NO_REGISTERS);
2802     }
2803     // Push undefined as receiver. This is patched in the method prologue if it
2804     // is a sloppy mode method.
2805     __ push(Immediate(isolate()->factory()->undefined_value()));
2806   } else {
2807     // Load the function from the receiver.
2808     DCHECK(callee->IsProperty());
2809     DCHECK(!callee->AsProperty()->IsSuperAccess());
2810     __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2811     EmitNamedPropertyLoad(callee->AsProperty());
2812     PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2813     // Push the target function under the receiver.
2814     __ push(Operand(esp, 0));
2815     __ mov(Operand(esp, kPointerSize), eax);
2816   }
2817
2818   EmitCall(expr, call_type);
2819 }
2820
2821
2822 void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2823   Expression* callee = expr->expression();
2824   DCHECK(callee->IsProperty());
2825   Property* prop = callee->AsProperty();
2826   DCHECK(prop->IsSuperAccess());
2827
2828   SetSourcePosition(prop->position());
2829   Literal* key = prop->key()->AsLiteral();
2830   DCHECK(!key->value()->IsSmi());
2831   // Load the function from the receiver.
2832   SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2833   EmitLoadHomeObject(super_ref);
2834   __ push(eax);
2835   VisitForAccumulatorValue(super_ref->this_var());
2836   __ push(eax);
2837   __ push(eax);
2838   __ push(Operand(esp, kPointerSize * 2));
2839   __ push(Immediate(key->value()));
2840   // Stack here:
2841   //  - home_object
2842   //  - this (receiver)
2843   //  - this (receiver) <-- LoadFromSuper will pop here and below.
2844   //  - home_object
2845   //  - key
2846   __ CallRuntime(Runtime::kLoadFromSuper, 3);
2847
2848   // Replace home_object with target function.
2849   __ mov(Operand(esp, kPointerSize), eax);
2850
2851   // Stack here:
2852   // - target function
2853   // - this (receiver)
2854   EmitCall(expr, CallICState::METHOD);
2855 }
2856
2857
2858 // Code common for calls using the IC.
2859 void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
2860                                                 Expression* key) {
2861   // Load the key.
2862   VisitForAccumulatorValue(key);
2863
2864   Expression* callee = expr->expression();
2865
2866   // Load the function from the receiver.
2867   DCHECK(callee->IsProperty());
2868   __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
2869   __ mov(LoadDescriptor::NameRegister(), eax);
2870   EmitKeyedPropertyLoad(callee->AsProperty());
2871   PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
2872
2873   // Push the target function under the receiver.
2874   __ push(Operand(esp, 0));
2875   __ mov(Operand(esp, kPointerSize), eax);
2876
2877   EmitCall(expr, CallICState::METHOD);
2878 }
2879
2880
2881 void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
2882   Expression* callee = expr->expression();
2883   DCHECK(callee->IsProperty());
2884   Property* prop = callee->AsProperty();
2885   DCHECK(prop->IsSuperAccess());
2886
2887   SetSourcePosition(prop->position());
2888   // Load the function from the receiver.
2889   SuperReference* super_ref = callee->AsProperty()->obj()->AsSuperReference();
2890   EmitLoadHomeObject(super_ref);
2891   __ push(eax);
2892   VisitForAccumulatorValue(super_ref->this_var());
2893   __ push(eax);
2894   __ push(eax);
2895   __ push(Operand(esp, kPointerSize * 2));
2896   VisitForStackValue(prop->key());
2897   // Stack here:
2898   //  - home_object
2899   //  - this (receiver)
2900   //  - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
2901   //  - home_object
2902   //  - key
2903   __ CallRuntime(Runtime::kLoadKeyedFromSuper, 3);
2904
2905   // Replace home_object with target function.
2906   __ mov(Operand(esp, kPointerSize), eax);
2907
2908   // Stack here:
2909   // - target function
2910   // - this (receiver)
2911   EmitCall(expr, CallICState::METHOD);
2912 }
2913
2914
2915 void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
2916   // Load the arguments.
2917   ZoneList<Expression*>* args = expr->arguments();
2918   int arg_count = args->length();
2919   { PreservePositionScope scope(masm()->positions_recorder());
2920     for (int i = 0; i < arg_count; i++) {
2921       VisitForStackValue(args->at(i));
2922     }
2923   }
2924
2925   // Record source position of the IC call.
2926   SetSourcePosition(expr->position());
2927   Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2928   __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackICSlot())));
2929   __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
2930   // Don't assign a type feedback id to the IC, since type feedback is provided
2931   // by the vector above.
2932   CallIC(ic);
2933
2934   RecordJSReturnSite(expr);
2935
2936   // Restore context register.
2937   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2938
2939   context()->DropAndPlug(1, eax);
2940 }
2941
2942
2943 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
2944   // Push copy of the first argument or undefined if it doesn't exist.
2945   if (arg_count > 0) {
2946     __ push(Operand(esp, arg_count * kPointerSize));
2947   } else {
2948     __ push(Immediate(isolate()->factory()->undefined_value()));
2949   }
2950
2951   // Push the enclosing function.
2952   __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2953   // Push the receiver of the enclosing function.
2954   __ push(Operand(ebp, (2 + info_->scope()->num_parameters()) * kPointerSize));
2955   // Push the language mode.
2956   __ push(Immediate(Smi::FromInt(language_mode())));
2957
2958   // Push the start position of the scope the calls resides in.
2959   __ push(Immediate(Smi::FromInt(scope()->start_position())));
2960
2961   // Do the runtime call.
2962   __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 6);
2963 }
2964
2965
2966 void FullCodeGenerator::EmitLoadSuperConstructor() {
2967   __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2968   __ CallRuntime(Runtime::kGetPrototype, 1);
2969 }
2970
2971
2972 void FullCodeGenerator::VisitCall(Call* expr) {
2973 #ifdef DEBUG
2974   // We want to verify that RecordJSReturnSite gets called on all paths
2975   // through this function.  Avoid early returns.
2976   expr->return_is_recorded_ = false;
2977 #endif
2978
2979   Comment cmnt(masm_, "[ Call");
2980   Expression* callee = expr->expression();
2981   Call::CallType call_type = expr->GetCallType(isolate());
2982
2983   if (call_type == Call::POSSIBLY_EVAL_CALL) {
2984     // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
2985     // to resolve the function we need to call and the receiver of the call.
2986     // Then we call the resolved function using the given arguments.
2987     ZoneList<Expression*>* args = expr->arguments();
2988     int arg_count = args->length();
2989     { PreservePositionScope pos_scope(masm()->positions_recorder());
2990       VisitForStackValue(callee);
2991       // Reserved receiver slot.
2992       __ push(Immediate(isolate()->factory()->undefined_value()));
2993       // Push the arguments.
2994       for (int i = 0; i < arg_count; i++) {
2995         VisitForStackValue(args->at(i));
2996       }
2997
2998       // Push a copy of the function (found below the arguments) and
2999       // resolve eval.
3000       __ push(Operand(esp, (arg_count + 1) * kPointerSize));
3001       EmitResolvePossiblyDirectEval(arg_count);
3002
3003       // The runtime call returns a pair of values in eax (function) and
3004       // edx (receiver). Touch up the stack with the right values.
3005       __ mov(Operand(esp, (arg_count + 0) * kPointerSize), edx);
3006       __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);
3007
3008       PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3009     }
3010     // Record source position for debugger.
3011     SetSourcePosition(expr->position());
3012     CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
3013     __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
3014     __ CallStub(&stub);
3015     RecordJSReturnSite(expr);
3016     // Restore context register.
3017     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3018     context()->DropAndPlug(1, eax);
3019
3020   } else if (call_type == Call::GLOBAL_CALL) {
3021     EmitCallWithLoadIC(expr);
3022   } else if (call_type == Call::LOOKUP_SLOT_CALL) {
3023     // Call to a lookup slot (dynamically introduced variable).
3024     VariableProxy* proxy = callee->AsVariableProxy();
3025     Label slow, done;
3026     { PreservePositionScope scope(masm()->positions_recorder());
3027       // Generate code for loading from variables potentially shadowed by
3028       // eval-introduced variables.
3029       EmitDynamicLookupFastCase(proxy, NOT_INSIDE_TYPEOF, &slow, &done);
3030     }
3031     __ bind(&slow);
3032     // Call the runtime to find the function to call (returned in eax) and
3033     // the object holding it (returned in edx).
3034     __ push(context_register());
3035     __ push(Immediate(proxy->name()));
3036     __ CallRuntime(Runtime::kLoadLookupSlot, 2);
3037     __ push(eax);  // Function.
3038     __ push(edx);  // Receiver.
3039     PrepareForBailoutForId(expr->EvalOrLookupId(), NO_REGISTERS);
3040
3041     // If fast case code has been generated, emit code to push the function
3042     // and receiver and have the slow path jump around this code.
3043     if (done.is_linked()) {
3044       Label call;
3045       __ jmp(&call, Label::kNear);
3046       __ bind(&done);
3047       // Push function.
3048       __ push(eax);
3049       // The receiver is implicitly the global receiver. Indicate this by
3050       // passing the hole to the call function stub.
3051       __ push(Immediate(isolate()->factory()->undefined_value()));
3052       __ bind(&call);
3053     }
3054
3055     // The receiver is either the global receiver or an object found by
3056     // LoadContextSlot.
3057     EmitCall(expr);
3058
3059   } else if (call_type == Call::PROPERTY_CALL) {
3060     Property* property = callee->AsProperty();
3061     bool is_named_call = property->key()->IsPropertyName();
3062     if (property->IsSuperAccess()) {
3063       if (is_named_call) {
3064         EmitSuperCallWithLoadIC(expr);
3065       } else {
3066         EmitKeyedSuperCallWithLoadIC(expr);
3067       }
3068     } else {
3069       {
3070         PreservePositionScope scope(masm()->positions_recorder());
3071         VisitForStackValue(property->obj());
3072       }
3073       if (is_named_call) {
3074         EmitCallWithLoadIC(expr);
3075       } else {
3076         EmitKeyedCallWithLoadIC(expr, property->key());
3077       }
3078     }
3079   } else if (call_type == Call::SUPER_CALL) {
3080     EmitSuperConstructorCall(expr);
3081   } else {
3082     DCHECK(call_type == Call::OTHER_CALL);
3083     // Call to an arbitrary expression not handled specially above.
3084     { PreservePositionScope scope(masm()->positions_recorder());
3085       VisitForStackValue(callee);
3086     }
3087     __ push(Immediate(isolate()->factory()->undefined_value()));
3088     // Emit function call.
3089     EmitCall(expr);
3090   }
3091
3092 #ifdef DEBUG
3093   // RecordJSReturnSite should have been called.
3094   DCHECK(expr->return_is_recorded_);
3095 #endif
3096 }
3097
3098
3099 void FullCodeGenerator::VisitCallNew(CallNew* expr) {
3100   Comment cmnt(masm_, "[ CallNew");
3101   // According to ECMA-262, section 11.2.2, page 44, the function
3102   // expression in new calls must be evaluated before the
3103   // arguments.
3104
3105   // Push constructor on the stack.  If it's not a function it's used as
3106   // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
3107   // ignored.
3108   DCHECK(!expr->expression()->IsSuperReference());
3109   VisitForStackValue(expr->expression());
3110
3111   // Push the arguments ("left-to-right") on the stack.
3112   ZoneList<Expression*>* args = expr->arguments();
3113   int arg_count = args->length();
3114   for (int i = 0; i < arg_count; i++) {
3115     VisitForStackValue(args->at(i));
3116   }
3117
3118   // Call the construct call builtin that handles allocation and
3119   // constructor invocation.
3120   SetSourcePosition(expr->position());
3121
3122   // Load function and argument count into edi and eax.
3123   __ Move(eax, Immediate(arg_count));
3124   __ mov(edi, Operand(esp, arg_count * kPointerSize));
3125
3126   // Record call targets in unoptimized code.
3127   if (FLAG_pretenuring_call_new) {
3128     EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3129     DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3130            expr->CallNewFeedbackSlot().ToInt() + 1);
3131   }
3132
3133   __ LoadHeapObject(ebx, FeedbackVector());
3134   __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
3135
3136   CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
3137   __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3138   PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3139   context()->Plug(eax);
3140 }
3141
3142
3143 void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3144   if (!ValidateSuperCall(expr)) return;
3145
3146   Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
3147   GetVar(eax, new_target_var);
3148   __ push(eax);
3149
3150   EmitLoadSuperConstructor();
3151   __ push(result_register());
3152
3153   // Push the arguments ("left-to-right") on the stack.
3154   ZoneList<Expression*>* args = expr->arguments();
3155   int arg_count = args->length();
3156   for (int i = 0; i < arg_count; i++) {
3157     VisitForStackValue(args->at(i));
3158   }
3159
3160   // Call the construct call builtin that handles allocation and
3161   // constructor invocation.
3162   SetSourcePosition(expr->position());
3163
3164   // Load function and argument count into edi and eax.
3165   __ Move(eax, Immediate(arg_count));
3166   __ mov(edi, Operand(esp, arg_count * kPointerSize));
3167
3168   // Record call targets in unoptimized code.
3169   if (FLAG_pretenuring_call_new) {
3170     UNREACHABLE();
3171     /* TODO(dslomov): support pretenuring.
3172     EnsureSlotContainsAllocationSite(expr->AllocationSiteFeedbackSlot());
3173     DCHECK(expr->AllocationSiteFeedbackSlot().ToInt() ==
3174            expr->CallNewFeedbackSlot().ToInt() + 1);
3175     */
3176   }
3177
3178   __ LoadHeapObject(ebx, FeedbackVector());
3179   __ mov(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));
3180
3181   CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3182   __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
3183
3184   __ Drop(1);
3185
3186   RecordJSReturnSite(expr);
3187
3188   SuperReference* super_ref = expr->expression()->AsSuperReference();
3189   Variable* this_var = super_ref->this_var()->var();
3190   GetVar(ecx, this_var);
3191   __ cmp(ecx, isolate()->factory()->the_hole_value());
3192   Label uninitialized_this;
3193   __ j(equal, &uninitialized_this);
3194   __ push(Immediate(this_var->name()));
3195   __ CallRuntime(Runtime::kThrowReferenceError, 1);
3196   __ bind(&uninitialized_this);
3197
3198   EmitVariableAssignment(this_var, Token::INIT_CONST);
3199   context()->Plug(eax);
3200 }
3201
3202
3203 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
3204   ZoneList<Expression*>* args = expr->arguments();
3205   DCHECK(args->length() == 1);
3206
3207   VisitForAccumulatorValue(args->at(0));
3208
3209   Label materialize_true, materialize_false;
3210   Label* if_true = NULL;
3211   Label* if_false = NULL;
3212   Label* fall_through = NULL;
3213   context()->PrepareTest(&materialize_true, &materialize_false,
3214                          &if_true, &if_false, &fall_through);
3215
3216   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3217   __ test(eax, Immediate(kSmiTagMask));
3218   Split(zero, if_true, if_false, fall_through);
3219
3220   context()->Plug(if_true, if_false);
3221 }
3222
3223
3224 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) {
3225   ZoneList<Expression*>* args = expr->arguments();
3226   DCHECK(args->length() == 1);
3227
3228   VisitForAccumulatorValue(args->at(0));
3229
3230   Label materialize_true, materialize_false;
3231   Label* if_true = NULL;
3232   Label* if_false = NULL;
3233   Label* fall_through = NULL;
3234   context()->PrepareTest(&materialize_true, &materialize_false,
3235                          &if_true, &if_false, &fall_through);
3236
3237   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3238   __ test(eax, Immediate(kSmiTagMask | 0x80000000));
3239   Split(zero, if_true, if_false, fall_through);
3240
3241   context()->Plug(if_true, if_false);
3242 }
3243
3244
3245 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) {
3246   ZoneList<Expression*>* args = expr->arguments();
3247   DCHECK(args->length() == 1);
3248
3249   VisitForAccumulatorValue(args->at(0));
3250
3251   Label materialize_true, materialize_false;
3252   Label* if_true = NULL;
3253   Label* if_false = NULL;
3254   Label* fall_through = NULL;
3255   context()->PrepareTest(&materialize_true, &materialize_false,
3256                          &if_true, &if_false, &fall_through);
3257
3258   __ JumpIfSmi(eax, if_false);
3259   __ cmp(eax, isolate()->factory()->null_value());
3260   __ j(equal, if_true);
3261   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3262   // Undetectable objects behave like undefined when tested with typeof.
3263   __ movzx_b(ecx, FieldOperand(ebx, Map::kBitFieldOffset));
3264   __ test(ecx, Immediate(1 << Map::kIsUndetectable));
3265   __ j(not_zero, if_false);
3266   __ movzx_b(ecx, FieldOperand(ebx, Map::kInstanceTypeOffset));
3267   __ cmp(ecx, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
3268   __ j(below, if_false);
3269   __ cmp(ecx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3270   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3271   Split(below_equal, if_true, if_false, fall_through);
3272
3273   context()->Plug(if_true, if_false);
3274 }
3275
3276
3277 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
3278   ZoneList<Expression*>* args = expr->arguments();
3279   DCHECK(args->length() == 1);
3280
3281   VisitForAccumulatorValue(args->at(0));
3282
3283   Label materialize_true, materialize_false;
3284   Label* if_true = NULL;
3285   Label* if_false = NULL;
3286   Label* fall_through = NULL;
3287   context()->PrepareTest(&materialize_true, &materialize_false,
3288                          &if_true, &if_false, &fall_through);
3289
3290   __ JumpIfSmi(eax, if_false);
3291   __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
3292   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3293   Split(above_equal, if_true, if_false, fall_through);
3294
3295   context()->Plug(if_true, if_false);
3296 }
3297
3298
3299 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) {
3300   ZoneList<Expression*>* args = expr->arguments();
3301   DCHECK(args->length() == 1);
3302
3303   VisitForAccumulatorValue(args->at(0));
3304
3305   Label materialize_true, materialize_false;
3306   Label* if_true = NULL;
3307   Label* if_false = NULL;
3308   Label* fall_through = NULL;
3309   context()->PrepareTest(&materialize_true, &materialize_false,
3310                          &if_true, &if_false, &fall_through);
3311
3312   __ JumpIfSmi(eax, if_false);
3313   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3314   __ movzx_b(ebx, FieldOperand(ebx, Map::kBitFieldOffset));
3315   __ test(ebx, Immediate(1 << Map::kIsUndetectable));
3316   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3317   Split(not_zero, if_true, if_false, fall_through);
3318
3319   context()->Plug(if_true, if_false);
3320 }
3321
3322
3323 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf(
3324     CallRuntime* expr) {
3325   ZoneList<Expression*>* args = expr->arguments();
3326   DCHECK(args->length() == 1);
3327
3328   VisitForAccumulatorValue(args->at(0));
3329
3330   Label materialize_true, materialize_false, skip_lookup;
3331   Label* if_true = NULL;
3332   Label* if_false = NULL;
3333   Label* fall_through = NULL;
3334   context()->PrepareTest(&materialize_true, &materialize_false,
3335                          &if_true, &if_false, &fall_through);
3336
3337   __ AssertNotSmi(eax);
3338
3339   // Check whether this map has already been checked to be safe for default
3340   // valueOf.
3341   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3342   __ test_b(FieldOperand(ebx, Map::kBitField2Offset),
3343             1 << Map::kStringWrapperSafeForDefaultValueOf);
3344   __ j(not_zero, &skip_lookup);
3345
3346   // Check for fast case object. Return false for slow case objects.
3347   __ mov(ecx, FieldOperand(eax, JSObject::kPropertiesOffset));
3348   __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3349   __ cmp(ecx, isolate()->factory()->hash_table_map());
3350   __ j(equal, if_false);
3351
3352   // Look for valueOf string in the descriptor array, and indicate false if
3353   // found. Since we omit an enumeration index check, if it is added via a
3354   // transition that shares its descriptor array, this is a false positive.
3355   Label entry, loop, done;
3356
3357   // Skip loop if no descriptors are valid.
3358   __ NumberOfOwnDescriptors(ecx, ebx);
3359   __ cmp(ecx, 0);
3360   __ j(equal, &done);
3361
3362   __ LoadInstanceDescriptors(ebx, ebx);
3363   // ebx: descriptor array.
3364   // ecx: valid entries in the descriptor array.
3365   // Calculate the end of the descriptor array.
3366   STATIC_ASSERT(kSmiTag == 0);
3367   STATIC_ASSERT(kSmiTagSize == 1);
3368   STATIC_ASSERT(kPointerSize == 4);
3369   __ imul(ecx, ecx, DescriptorArray::kDescriptorSize);
3370   __ lea(ecx, Operand(ebx, ecx, times_4, DescriptorArray::kFirstOffset));
3371   // Calculate location of the first key name.
3372   __ add(ebx, Immediate(DescriptorArray::kFirstOffset));
3373   // Loop through all the keys in the descriptor array. If one of these is the
3374   // internalized string "valueOf" the result is false.
3375   __ jmp(&entry);
3376   __ bind(&loop);
3377   __ mov(edx, FieldOperand(ebx, 0));
3378   __ cmp(edx, isolate()->factory()->value_of_string());
3379   __ j(equal, if_false);
3380   __ add(ebx, Immediate(DescriptorArray::kDescriptorSize * kPointerSize));
3381   __ bind(&entry);
3382   __ cmp(ebx, ecx);
3383   __ j(not_equal, &loop);
3384
3385   __ bind(&done);
3386
3387   // Reload map as register ebx was used as temporary above.
3388   __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
3389
3390   // Set the bit in the map to indicate that there is no local valueOf field.
3391   __ or_(FieldOperand(ebx, Map::kBitField2Offset),
3392          Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf));
3393
3394   __ bind(&skip_lookup);
3395
3396   // If a valueOf property is not found on the object check that its
3397   // prototype is the un-modified String prototype. If not result is false.
3398   __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3399   __ JumpIfSmi(ecx, if_false);
3400   __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
3401   __ mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3402   __ mov(edx,
3403          FieldOperand(edx, GlobalObject::kNativeContextOffset));
3404   __ cmp(ecx,
3405          ContextOperand(edx,
3406                         Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX));
3407   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3408   Split(equal, if_true, if_false, fall_through);
3409
3410   context()->Plug(if_true, if_false);
3411 }
3412
3413
3414 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
3415   ZoneList<Expression*>* args = expr->arguments();
3416   DCHECK(args->length() == 1);
3417
3418   VisitForAccumulatorValue(args->at(0));
3419
3420   Label materialize_true, materialize_false;
3421   Label* if_true = NULL;
3422   Label* if_false = NULL;
3423   Label* fall_through = NULL;
3424   context()->PrepareTest(&materialize_true, &materialize_false,
3425                          &if_true, &if_false, &fall_through);
3426
3427   __ JumpIfSmi(eax, if_false);
3428   __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3429   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3430   Split(equal, if_true, if_false, fall_through);
3431
3432   context()->Plug(if_true, if_false);
3433 }
3434
3435
3436 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
3437   ZoneList<Expression*>* args = expr->arguments();
3438   DCHECK(args->length() == 1);
3439
3440   VisitForAccumulatorValue(args->at(0));
3441
3442   Label materialize_true, materialize_false;
3443   Label* if_true = NULL;
3444   Label* if_false = NULL;
3445   Label* fall_through = NULL;
3446   context()->PrepareTest(&materialize_true, &materialize_false,
3447                          &if_true, &if_false, &fall_through);
3448
3449   Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
3450   __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
3451   // Check if the exponent half is 0x80000000. Comparing against 1 and
3452   // checking for overflow is the shortest possible encoding.
3453   __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
3454   __ j(no_overflow, if_false);
3455   __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
3456   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3457   Split(equal, if_true, if_false, fall_through);
3458
3459   context()->Plug(if_true, if_false);
3460 }
3461
3462
3463
3464 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
3465   ZoneList<Expression*>* args = expr->arguments();
3466   DCHECK(args->length() == 1);
3467
3468   VisitForAccumulatorValue(args->at(0));
3469
3470   Label materialize_true, materialize_false;
3471   Label* if_true = NULL;
3472   Label* if_false = NULL;
3473   Label* fall_through = NULL;
3474   context()->PrepareTest(&materialize_true, &materialize_false,
3475                          &if_true, &if_false, &fall_through);
3476
3477   __ JumpIfSmi(eax, if_false);
3478   __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
3479   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3480   Split(equal, if_true, if_false, fall_through);
3481
3482   context()->Plug(if_true, if_false);
3483 }
3484
3485
3486 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
3487   ZoneList<Expression*>* args = expr->arguments();
3488   DCHECK(args->length() == 1);
3489
3490   VisitForAccumulatorValue(args->at(0));
3491
3492   Label materialize_true, materialize_false;
3493   Label* if_true = NULL;
3494   Label* if_false = NULL;
3495   Label* fall_through = NULL;
3496   context()->PrepareTest(&materialize_true, &materialize_false,
3497                          &if_true, &if_false, &fall_through);
3498
3499   __ JumpIfSmi(eax, if_false);
3500   __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
3501   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3502   Split(equal, if_true, if_false, fall_through);
3503
3504   context()->Plug(if_true, if_false);
3505 }
3506
3507
3508 void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
3509   ZoneList<Expression*>* args = expr->arguments();
3510   DCHECK(args->length() == 1);
3511
3512   VisitForAccumulatorValue(args->at(0));
3513
3514   Label materialize_true, materialize_false;
3515   Label* if_true = NULL;
3516   Label* if_false = NULL;
3517   Label* fall_through = NULL;
3518   context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
3519                          &if_false, &fall_through);
3520
3521   __ JumpIfSmi(eax, if_false);
3522   Register map = ebx;
3523   __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
3524   __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
3525   __ j(less, if_false);
3526   __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
3527   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3528   Split(less_equal, if_true, if_false, fall_through);
3529
3530   context()->Plug(if_true, if_false);
3531 }
3532
3533
3534 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3535   DCHECK(expr->arguments()->length() == 0);
3536
3537   Label materialize_true, materialize_false;
3538   Label* if_true = NULL;
3539   Label* if_false = NULL;
3540   Label* fall_through = NULL;
3541   context()->PrepareTest(&materialize_true, &materialize_false,
3542                          &if_true, &if_false, &fall_through);
3543
3544   // Get the frame pointer for the calling frame.
3545   __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3546
3547   // Skip the arguments adaptor frame if it exists.
3548   Label check_frame_marker;
3549   __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
3550          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3551   __ j(not_equal, &check_frame_marker);
3552   __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));
3553
3554   // Check the marker in the calling frame.
3555   __ bind(&check_frame_marker);
3556   __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
3557          Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
3558   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3559   Split(equal, if_true, if_false, fall_through);
3560
3561   context()->Plug(if_true, if_false);
3562 }
3563
3564
3565 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
3566   ZoneList<Expression*>* args = expr->arguments();
3567   DCHECK(args->length() == 2);
3568
3569   // Load the two objects into registers and perform the comparison.
3570   VisitForStackValue(args->at(0));
3571   VisitForAccumulatorValue(args->at(1));
3572
3573   Label materialize_true, materialize_false;
3574   Label* if_true = NULL;
3575   Label* if_false = NULL;
3576   Label* fall_through = NULL;
3577   context()->PrepareTest(&materialize_true, &materialize_false,
3578                          &if_true, &if_false, &fall_through);
3579
3580   __ pop(ebx);
3581   __ cmp(eax, ebx);
3582   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3583   Split(equal, if_true, if_false, fall_through);
3584
3585   context()->Plug(if_true, if_false);
3586 }
3587
3588
3589 void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
3590   ZoneList<Expression*>* args = expr->arguments();
3591   DCHECK(args->length() == 1);
3592
3593   // ArgumentsAccessStub expects the key in edx and the formal
3594   // parameter count in eax.
3595   VisitForAccumulatorValue(args->at(0));
3596   __ mov(edx, eax);
3597   __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3598   ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
3599   __ CallStub(&stub);
3600   context()->Plug(eax);
3601 }
3602
3603
3604 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3605   DCHECK(expr->arguments()->length() == 0);
3606
3607   Label exit;
3608   // Get the number of formal parameters.
3609   __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
3610
3611   // Check if the calling frame is an arguments adaptor frame.
3612   __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3613   __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
3614          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3615   __ j(not_equal, &exit);
3616
3617   // Arguments adaptor case: Read the arguments length from the
3618   // adaptor frame.
3619   __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3620
3621   __ bind(&exit);
3622   __ AssertSmi(eax);
3623   context()->Plug(eax);
3624 }
3625
3626
3627 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
3628   ZoneList<Expression*>* args = expr->arguments();
3629   DCHECK(args->length() == 1);
3630   Label done, null, function, non_function_constructor;
3631
3632   VisitForAccumulatorValue(args->at(0));
3633
3634   // If the object is a smi, we return null.
3635   __ JumpIfSmi(eax, &null);
3636
3637   // Check that the object is a JS object but take special care of JS
3638   // functions to make sure they have 'Function' as their class.
3639   // Assume that there are only two callable types, and one of them is at
3640   // either end of the type range for JS object types. Saves extra comparisons.
3641   STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
3642   __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
3643   // Map is now in eax.
3644   __ j(below, &null);
3645   STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3646                 FIRST_SPEC_OBJECT_TYPE + 1);
3647   __ j(equal, &function);
3648
3649   __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
3650   STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
3651                 LAST_SPEC_OBJECT_TYPE - 1);
3652   __ j(equal, &function);
3653   // Assume that there is no larger type.
3654   STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);
3655
3656   // Check if the constructor in the map is a JS function.
3657   __ mov(eax, FieldOperand(eax, Map::kConstructorOffset));
3658   __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
3659   __ j(not_equal, &non_function_constructor);
3660
3661   // eax now contains the constructor function. Grab the
3662   // instance class name from there.
3663   __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
3664   __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
3665   __ jmp(&done);
3666
3667   // Functions have class 'Function'.
3668   __ bind(&function);
3669   __ mov(eax, isolate()->factory()->Function_string());
3670   __ jmp(&done);
3671
3672   // Objects with a non-function constructor have class 'Object'.
3673   __ bind(&non_function_constructor);
3674   __ mov(eax, isolate()->factory()->Object_string());
3675   __ jmp(&done);
3676
3677   // Non-JS objects have class null.
3678   __ bind(&null);
3679   __ mov(eax, isolate()->factory()->null_value());
3680
3681   // All done.
3682   __ bind(&done);
3683
3684   context()->Plug(eax);
3685 }
3686
3687
3688 void FullCodeGenerator::EmitSubString(CallRuntime* expr) {
3689   // Load the arguments on the stack and call the stub.
3690   SubStringStub stub(isolate());
3691   ZoneList<Expression*>* args = expr->arguments();
3692   DCHECK(args->length() == 3);
3693   VisitForStackValue(args->at(0));
3694   VisitForStackValue(args->at(1));
3695   VisitForStackValue(args->at(2));
3696   __ CallStub(&stub);
3697   context()->Plug(eax);
3698 }
3699
3700
3701 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) {
3702   // Load the arguments on the stack and call the stub.
3703   RegExpExecStub stub(isolate());
3704   ZoneList<Expression*>* args = expr->arguments();
3705   DCHECK(args->length() == 4);
3706   VisitForStackValue(args->at(0));
3707   VisitForStackValue(args->at(1));
3708   VisitForStackValue(args->at(2));
3709   VisitForStackValue(args->at(3));
3710   __ CallStub(&stub);
3711   context()->Plug(eax);
3712 }
3713
3714
3715 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
3716   ZoneList<Expression*>* args = expr->arguments();
3717   DCHECK(args->length() == 1);
3718
3719   VisitForAccumulatorValue(args->at(0));  // Load the object.
3720
3721   Label done;
3722   // If the object is a smi return the object.
3723   __ JumpIfSmi(eax, &done, Label::kNear);
3724   // If the object is not a value type, return the object.
3725   __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
3726   __ j(not_equal, &done, Label::kNear);
3727   __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));
3728
3729   __ bind(&done);
3730   context()->Plug(eax);
3731 }
3732
3733
3734 void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
3735   ZoneList<Expression*>* args = expr->arguments();
3736   DCHECK(args->length() == 2);
3737   DCHECK_NOT_NULL(args->at(1)->AsLiteral());
3738   Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));
3739
3740   VisitForAccumulatorValue(args->at(0));  // Load the object.
3741
3742   Label runtime, done, not_date_object;
3743   Register object = eax;
3744   Register result = eax;
3745   Register scratch = ecx;
3746
3747   __ JumpIfSmi(object, &not_date_object);
3748   __ CmpObjectType(object, JS_DATE_TYPE, scratch);
3749   __ j(not_equal, &not_date_object);
3750
3751   if (index->value() == 0) {
3752     __ mov(result, FieldOperand(object, JSDate::kValueOffset));
3753     __ jmp(&done);
3754   } else {
3755     if (index->value() < JSDate::kFirstUncachedField) {
3756       ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
3757       __ mov(scratch, Operand::StaticVariable(stamp));
3758       __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
3759       __ j(not_equal, &runtime, Label::kNear);
3760       __ mov(result, FieldOperand(object, JSDate::kValueOffset +
3761                                           kPointerSize * index->value()));
3762       __ jmp(&done);
3763     }
3764     __ bind(&runtime);
3765     __ PrepareCallCFunction(2, scratch);
3766     __ mov(Operand(esp, 0), object);
3767     __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
3768     __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3769     __ jmp(&done);
3770   }
3771
3772   __ bind(&not_date_object);
3773   __ CallRuntime(Runtime::kThrowNotDateError, 0);
3774   __ bind(&done);
3775   context()->Plug(result);
3776 }
3777
3778
3779 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
3780   ZoneList<Expression*>* args = expr->arguments();
3781   DCHECK_EQ(3, args->length());
3782
3783   Register string = eax;
3784   Register index = ebx;
3785   Register value = ecx;
3786
3787   VisitForStackValue(args->at(0));        // index
3788   VisitForStackValue(args->at(1));        // value
3789   VisitForAccumulatorValue(args->at(2));  // string
3790
3791   __ pop(value);
3792   __ pop(index);
3793
3794   if (FLAG_debug_code) {
3795     __ test(value, Immediate(kSmiTagMask));
3796     __ Check(zero, kNonSmiValue);
3797     __ test(index, Immediate(kSmiTagMask));
3798     __ Check(zero, kNonSmiValue);
3799   }
3800
3801   __ SmiUntag(value);
3802   __ SmiUntag(index);
3803
3804   if (FLAG_debug_code) {
3805     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
3806     __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
3807   }
3808
3809   __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
3810            value);
3811   context()->Plug(string);
3812 }
3813
3814
3815 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
3816   ZoneList<Expression*>* args = expr->arguments();
3817   DCHECK_EQ(3, args->length());
3818
3819   Register string = eax;
3820   Register index = ebx;
3821   Register value = ecx;
3822
3823   VisitForStackValue(args->at(0));        // index
3824   VisitForStackValue(args->at(1));        // value
3825   VisitForAccumulatorValue(args->at(2));  // string
3826   __ pop(value);
3827   __ pop(index);
3828
3829   if (FLAG_debug_code) {
3830     __ test(value, Immediate(kSmiTagMask));
3831     __ Check(zero, kNonSmiValue);
3832     __ test(index, Immediate(kSmiTagMask));
3833     __ Check(zero, kNonSmiValue);
3834     __ SmiUntag(index);
3835     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
3836     __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
3837     __ SmiTag(index);
3838   }
3839
3840   __ SmiUntag(value);
3841   // No need to untag a smi for two-byte addressing.
3842   __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
3843            value);
3844   context()->Plug(string);
3845 }
3846
3847
3848 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) {
3849   // Load the arguments on the stack and call the runtime function.
3850   ZoneList<Expression*>* args = expr->arguments();
3851   DCHECK(args->length() == 2);
3852   VisitForStackValue(args->at(0));
3853   VisitForStackValue(args->at(1));
3854
3855   __ CallRuntime(Runtime::kMathPowSlow, 2);
3856   context()->Plug(eax);
3857 }
3858
3859
3860 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
3861   ZoneList<Expression*>* args = expr->arguments();
3862   DCHECK(args->length() == 2);
3863
3864   VisitForStackValue(args->at(0));  // Load the object.
3865   VisitForAccumulatorValue(args->at(1));  // Load the value.
3866   __ pop(ebx);  // eax = value. ebx = object.
3867
3868   Label done;
3869   // If the object is a smi, return the value.
3870   __ JumpIfSmi(ebx, &done, Label::kNear);
3871
3872   // If the object is not a value type, return the value.
3873   __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
3874   __ j(not_equal, &done, Label::kNear);
3875
3876   // Store the value.
3877   __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);
3878
3879   // Update the write barrier.  Save the value as it will be
3880   // overwritten by the write barrier code and is needed afterward.
3881   __ mov(edx, eax);
3882   __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
3883
3884   __ bind(&done);
3885   context()->Plug(eax);
3886 }
3887
3888
3889 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
3890   ZoneList<Expression*>* args = expr->arguments();
3891   DCHECK_EQ(args->length(), 1);
3892
3893   // Load the argument into eax and call the stub.
3894   VisitForAccumulatorValue(args->at(0));
3895
3896   NumberToStringStub stub(isolate());
3897   __ CallStub(&stub);
3898   context()->Plug(eax);
3899 }
3900
3901
3902 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
3903   ZoneList<Expression*>* args = expr->arguments();
3904   DCHECK(args->length() == 1);
3905
3906   VisitForAccumulatorValue(args->at(0));
3907
3908   Label done;
3909   StringCharFromCodeGenerator generator(eax, ebx);
3910   generator.GenerateFast(masm_);
3911   __ jmp(&done);
3912
3913   NopRuntimeCallHelper call_helper;
3914   generator.GenerateSlow(masm_, call_helper);
3915
3916   __ bind(&done);
3917   context()->Plug(ebx);
3918 }
3919
3920
3921 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
3922   ZoneList<Expression*>* args = expr->arguments();
3923   DCHECK(args->length() == 2);
3924
3925   VisitForStackValue(args->at(0));
3926   VisitForAccumulatorValue(args->at(1));
3927
3928   Register object = ebx;
3929   Register index = eax;
3930   Register result = edx;
3931
3932   __ pop(object);
3933
3934   Label need_conversion;
3935   Label index_out_of_range;
3936   Label done;
3937   StringCharCodeAtGenerator generator(object,
3938                                       index,
3939                                       result,
3940                                       &need_conversion,
3941                                       &need_conversion,
3942                                       &index_out_of_range,
3943                                       STRING_INDEX_IS_NUMBER);
3944   generator.GenerateFast(masm_);
3945   __ jmp(&done);
3946
3947   __ bind(&index_out_of_range);
3948   // When the index is out of range, the spec requires us to return
3949   // NaN.
3950   __ Move(result, Immediate(isolate()->factory()->nan_value()));
3951   __ jmp(&done);
3952
3953   __ bind(&need_conversion);
3954   // Move the undefined value into the result register, which will
3955   // trigger conversion.
3956   __ Move(result, Immediate(isolate()->factory()->undefined_value()));
3957   __ jmp(&done);
3958
3959   NopRuntimeCallHelper call_helper;
3960   generator.GenerateSlow(masm_, call_helper);
3961
3962   __ bind(&done);
3963   context()->Plug(result);
3964 }
3965
3966
3967 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
3968   ZoneList<Expression*>* args = expr->arguments();
3969   DCHECK(args->length() == 2);
3970
3971   VisitForStackValue(args->at(0));
3972   VisitForAccumulatorValue(args->at(1));
3973
3974   Register object = ebx;
3975   Register index = eax;
3976   Register scratch = edx;
3977   Register result = eax;
3978
3979   __ pop(object);
3980
3981   Label need_conversion;
3982   Label index_out_of_range;
3983   Label done;
3984   StringCharAtGenerator generator(object,
3985                                   index,
3986                                   scratch,
3987                                   result,
3988                                   &need_conversion,
3989                                   &need_conversion,
3990                                   &index_out_of_range,
3991                                   STRING_INDEX_IS_NUMBER);
3992   generator.GenerateFast(masm_);
3993   __ jmp(&done);
3994
3995   __ bind(&index_out_of_range);
3996   // When the index is out of range, the spec requires us to return
3997   // the empty string.
3998   __ Move(result, Immediate(isolate()->factory()->empty_string()));
3999   __ jmp(&done);
4000
4001   __ bind(&need_conversion);
4002   // Move smi zero into the result register, which will trigger
4003   // conversion.
4004   __ Move(result, Immediate(Smi::FromInt(0)));
4005   __ jmp(&done);
4006
4007   NopRuntimeCallHelper call_helper;
4008   generator.GenerateSlow(masm_, call_helper);
4009
4010   __ bind(&done);
4011   context()->Plug(result);
4012 }
4013
4014
4015 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
4016   ZoneList<Expression*>* args = expr->arguments();
4017   DCHECK_EQ(2, args->length());
4018   VisitForStackValue(args->at(0));
4019   VisitForAccumulatorValue(args->at(1));
4020
4021   __ pop(edx);
4022   StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
4023   __ CallStub(&stub);
4024   context()->Plug(eax);
4025 }
4026
4027
4028 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) {
4029   ZoneList<Expression*>* args = expr->arguments();
4030   DCHECK_EQ(2, args->length());
4031
4032   VisitForStackValue(args->at(0));
4033   VisitForStackValue(args->at(1));
4034
4035   StringCompareStub stub(isolate());
4036   __ CallStub(&stub);
4037   context()->Plug(eax);
4038 }
4039
4040
4041 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
4042   ZoneList<Expression*>* args = expr->arguments();
4043   DCHECK(args->length() >= 2);
4044
4045   int arg_count = args->length() - 2;  // 2 ~ receiver and function.
4046   for (int i = 0; i < arg_count + 1; ++i) {
4047     VisitForStackValue(args->at(i));
4048   }
4049   VisitForAccumulatorValue(args->last());  // Function.
4050
4051   Label runtime, done;
4052   // Check for non-function argument (including proxy).
4053   __ JumpIfSmi(eax, &runtime);
4054   __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
4055   __ j(not_equal, &runtime);
4056
4057   // InvokeFunction requires the function in edi. Move it in there.
4058   __ mov(edi, result_register());
4059   ParameterCount count(arg_count);
4060   __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
4061   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4062   __ jmp(&done);
4063
4064   __ bind(&runtime);
4065   __ push(eax);
4066   __ CallRuntime(Runtime::kCall, args->length());
4067   __ bind(&done);
4068
4069   context()->Plug(eax);
4070 }
4071
4072
4073 void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
4074   Variable* new_target_var = scope()->DeclarationScope()->new_target_var();
4075   GetVar(eax, new_target_var);
4076   __ push(eax);
4077
4078   EmitLoadSuperConstructor();
4079   __ push(result_register());
4080
4081   // Check if the calling frame is an arguments adaptor frame.
4082   Label adaptor_frame, args_set_up, runtime;
4083   __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
4084   __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
4085   __ cmp(ecx, Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4086   __ j(equal, &adaptor_frame);
4087   // default constructor has no arguments, so no adaptor frame means no args.
4088   __ mov(eax, Immediate(0));
4089   __ jmp(&args_set_up);
4090
4091   // Copy arguments from adaptor frame.
4092   {
4093     __ bind(&adaptor_frame);
4094     __ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
4095     __ SmiUntag(ecx);
4096
4097     // Subtract 1 from arguments count, for new.target.
4098     __ sub(ecx, Immediate(1));
4099     __ mov(eax, ecx);
4100     __ lea(edx, Operand(edx, ecx, times_pointer_size,
4101                         StandardFrameConstants::kCallerSPOffset));
4102     Label loop;
4103     __ bind(&loop);
4104     __ push(Operand(edx, -1 * kPointerSize));
4105     __ sub(edx, Immediate(kPointerSize));
4106     __ dec(ecx);
4107     __ j(not_zero, &loop);
4108   }
4109
4110   __ bind(&args_set_up);
4111
4112   __ mov(edi, Operand(esp, eax, times_pointer_size, 0));
4113   __ mov(ebx, Immediate(isolate()->factory()->undefined_value()));
4114   CallConstructStub stub(isolate(), SUPER_CONSTRUCTOR_CALL);
4115   __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
4116
4117   __ Drop(1);
4118
4119   context()->Plug(eax);
4120 }
4121
4122
4123 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
4124   // Load the arguments on the stack and call the stub.
4125   RegExpConstructResultStub stub(isolate());
4126   ZoneList<Expression*>* args = expr->arguments();
4127   DCHECK(args->length() == 3);
4128   VisitForStackValue(args->at(0));
4129   VisitForStackValue(args->at(1));
4130   VisitForAccumulatorValue(args->at(2));
4131   __ pop(ebx);
4132   __ pop(ecx);
4133   __ CallStub(&stub);
4134   context()->Plug(eax);
4135 }
4136
4137
4138 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) {
4139   ZoneList<Expression*>* args = expr->arguments();
4140   DCHECK_EQ(2, args->length());
4141
4142   DCHECK_NOT_NULL(args->at(0)->AsLiteral());
4143   int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value();
4144
4145   Handle<FixedArray> jsfunction_result_caches(
4146       isolate()->native_context()->jsfunction_result_caches());
4147   if (jsfunction_result_caches->length() <= cache_id) {
4148     __ Abort(kAttemptToUseUndefinedCache);
4149     __ mov(eax, isolate()->factory()->undefined_value());
4150     context()->Plug(eax);
4151     return;
4152   }
4153
4154   VisitForAccumulatorValue(args->at(1));
4155
4156   Register key = eax;
4157   Register cache = ebx;
4158   Register tmp = ecx;
4159   __ mov(cache, ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX));
4160   __ mov(cache,
4161          FieldOperand(cache, GlobalObject::kNativeContextOffset));
4162   __ mov(cache, ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4163   __ mov(cache,
4164          FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id)));
4165
4166   Label done, not_found;
4167   STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4168   __ mov(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset));
4169   // tmp now holds finger offset as a smi.
4170   __ cmp(key, FixedArrayElementOperand(cache, tmp));
4171   __ j(not_equal, &not_found);
4172
4173   __ mov(eax, FixedArrayElementOperand(cache, tmp, 1));
4174   __ jmp(&done);
4175
4176   __ bind(&not_found);
4177   // Call runtime to perform the lookup.
4178   __ push(cache);
4179   __ push(key);
4180   __ CallRuntime(Runtime::kGetFromCache, 2);
4181
4182   __ bind(&done);
4183   context()->Plug(eax);
4184 }
4185
4186
4187 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
4188   ZoneList<Expression*>* args = expr->arguments();
4189   DCHECK(args->length() == 1);
4190
4191   VisitForAccumulatorValue(args->at(0));
4192
4193   __ AssertString(eax);
4194
4195   Label materialize_true, materialize_false;
4196   Label* if_true = NULL;
4197   Label* if_false = NULL;
4198   Label* fall_through = NULL;
4199   context()->PrepareTest(&materialize_true, &materialize_false,
4200                          &if_true, &if_false, &fall_through);
4201
4202   __ test(FieldOperand(eax, String::kHashFieldOffset),
4203           Immediate(String::kContainsCachedArrayIndexMask));
4204   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4205   Split(zero, if_true, if_false, fall_through);
4206
4207   context()->Plug(if_true, if_false);
4208 }
4209
4210
4211 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
4212   ZoneList<Expression*>* args = expr->arguments();
4213   DCHECK(args->length() == 1);
4214   VisitForAccumulatorValue(args->at(0));
4215
4216   __ AssertString(eax);
4217
4218   __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
4219   __ IndexFromHash(eax, eax);
4220
4221   context()->Plug(eax);
4222 }
4223
4224
4225 void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
4226   Label bailout, done, one_char_separator, long_separator,
4227       non_trivial_array, not_size_one_array, loop,
4228       loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;
4229
4230   ZoneList<Expression*>* args = expr->arguments();
4231   DCHECK(args->length() == 2);
4232   // We will leave the separator on the stack until the end of the function.
4233   VisitForStackValue(args->at(1));
4234   // Load this to eax (= array)
4235   VisitForAccumulatorValue(args->at(0));
4236   // All aliases of the same register have disjoint lifetimes.
4237   Register array = eax;
4238   Register elements = no_reg;  // Will be eax.
4239
4240   Register index = edx;
4241
4242   Register string_length = ecx;
4243
4244   Register string = esi;
4245
4246   Register scratch = ebx;
4247
4248   Register array_length = edi;
4249   Register result_pos = no_reg;  // Will be edi.
4250
4251   // Separator operand is already pushed.
4252   Operand separator_operand = Operand(esp, 2 * kPointerSize);
4253   Operand result_operand = Operand(esp, 1 * kPointerSize);
4254   Operand array_length_operand = Operand(esp, 0);
4255   __ sub(esp, Immediate(2 * kPointerSize));
4256   __ cld();
4257   // Check that the array is a JSArray
4258   __ JumpIfSmi(array, &bailout);
4259   __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
4260   __ j(not_equal, &bailout);
4261
4262   // Check that the array has fast elements.
4263   __ CheckFastElements(scratch, &bailout);
4264
4265   // If the array has length zero, return the empty string.
4266   __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
4267   __ SmiUntag(array_length);
4268   __ j(not_zero, &non_trivial_array);
4269   __ mov(result_operand, isolate()->factory()->empty_string());
4270   __ jmp(&done);
4271
4272   // Save the array length.
4273   __ bind(&non_trivial_array);
4274   __ mov(array_length_operand, array_length);
4275
4276   // Save the FixedArray containing array's elements.
4277   // End of array's live range.
4278   elements = array;
4279   __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
4280   array = no_reg;
4281
4282
4283   // Check that all array elements are sequential one-byte strings, and
4284   // accumulate the sum of their lengths, as a smi-encoded value.
4285   __ Move(index, Immediate(0));
4286   __ Move(string_length, Immediate(0));
4287   // Loop condition: while (index < length).
4288   // Live loop registers: index, array_length, string,
4289   //                      scratch, string_length, elements.
4290   if (generate_debug_code_) {
4291     __ cmp(index, array_length);
4292     __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
4293   }
4294   __ bind(&loop);
4295   __ mov(string, FieldOperand(elements,
4296                               index,
4297                               times_pointer_size,
4298                               FixedArray::kHeaderSize));
4299   __ JumpIfSmi(string, &bailout);
4300   __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4301   __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4302   __ and_(scratch, Immediate(
4303       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4304   __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4305   __ j(not_equal, &bailout);
4306   __ add(string_length,
4307          FieldOperand(string, SeqOneByteString::kLengthOffset));
4308   __ j(overflow, &bailout);
4309   __ add(index, Immediate(1));
4310   __ cmp(index, array_length);
4311   __ j(less, &loop);
4312
4313   // If array_length is 1, return elements[0], a string.
4314   __ cmp(array_length, 1);
4315   __ j(not_equal, &not_size_one_array);
4316   __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
4317   __ mov(result_operand, scratch);
4318   __ jmp(&done);
4319
4320   __ bind(&not_size_one_array);
4321
4322   // End of array_length live range.
4323   result_pos = array_length;
4324   array_length = no_reg;
4325
4326   // Live registers:
4327   // string_length: Sum of string lengths, as a smi.
4328   // elements: FixedArray of strings.
4329
4330   // Check that the separator is a flat one-byte string.
4331   __ mov(string, separator_operand);
4332   __ JumpIfSmi(string, &bailout);
4333   __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
4334   __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
4335   __ and_(scratch, Immediate(
4336       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
4337   __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
4338   __ j(not_equal, &bailout);
4339
4340   // Add (separator length times array_length) - separator length
4341   // to string_length.
4342   __ mov(scratch, separator_operand);
4343   __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
4344   __ sub(string_length, scratch);  // May be negative, temporarily.
4345   __ imul(scratch, array_length_operand);
4346   __ j(overflow, &bailout);
4347   __ add(string_length, scratch);
4348   __ j(overflow, &bailout);
4349
4350   __ shr(string_length, 1);
4351   // Live registers and stack values:
4352   //   string_length
4353   //   elements
4354   __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
4355                            &bailout);
4356   __ mov(result_operand, result_pos);
4357   __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));
4358
4359
4360   __ mov(string, separator_operand);
4361   __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
4362          Immediate(Smi::FromInt(1)));
4363   __ j(equal, &one_char_separator);
4364   __ j(greater, &long_separator);
4365
4366
4367   // Empty separator case
4368   __ mov(index, Immediate(0));
4369   __ jmp(&loop_1_condition);
4370   // Loop condition: while (index < length).
4371   __ bind(&loop_1);
4372   // Each iteration of the loop concatenates one string to the result.
4373   // Live values in registers:
4374   //   index: which element of the elements array we are adding to the result.
4375   //   result_pos: the position to which we are currently copying characters.
4376   //   elements: the FixedArray of strings we are joining.
4377
4378   // Get string = array[index].
4379   __ mov(string, FieldOperand(elements, index,
4380                               times_pointer_size,
4381                               FixedArray::kHeaderSize));
4382   __ mov(string_length,
4383          FieldOperand(string, String::kLengthOffset));
4384   __ shr(string_length, 1);
4385   __ lea(string,
4386          FieldOperand(string, SeqOneByteString::kHeaderSize));
4387   __ CopyBytes(string, result_pos, string_length, scratch);
4388   __ add(index, Immediate(1));
4389   __ bind(&loop_1_condition);
4390   __ cmp(index, array_length_operand);
4391   __ j(less, &loop_1);  // End while (index < length).
4392   __ jmp(&done);
4393
4394
4395
4396   // One-character separator case
4397   __ bind(&one_char_separator);
4398   // Replace separator with its one-byte character value.
4399   __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
4400   __ mov_b(separator_operand, scratch);
4401
4402   __ Move(index, Immediate(0));
4403   // Jump into the loop after the code that copies the separator, so the first
4404   // element is not preceded by a separator
4405   __ jmp(&loop_2_entry);
4406   // Loop condition: while (index < length).
4407   __ bind(&loop_2);
4408   // Each iteration of the loop concatenates one string to the result.
4409   // Live values in registers:
4410   //   index: which element of the elements array we are adding to the result.
4411   //   result_pos: the position to which we are currently copying characters.
4412
4413   // Copy the separator character to the result.
4414   __ mov_b(scratch, separator_operand);
4415   __ mov_b(Operand(result_pos, 0), scratch);
4416   __ inc(result_pos);
4417
4418   __ bind(&loop_2_entry);
4419   // Get string = array[index].
4420   __ mov(string, FieldOperand(elements, index,
4421                               times_pointer_size,
4422                               FixedArray::kHeaderSize));
4423   __ mov(string_length,
4424          FieldOperand(string, String::kLengthOffset));
4425   __ shr(string_length, 1);
4426   __ lea(string,
4427          FieldOperand(string, SeqOneByteString::kHeaderSize));
4428   __ CopyBytes(string, result_pos, string_length, scratch);
4429   __ add(index, Immediate(1));
4430
4431   __ cmp(index, array_length_operand);
4432   __ j(less, &loop_2);  // End while (index < length).
4433   __ jmp(&done);
4434
4435
4436   // Long separator case (separator is more than one character).
4437   __ bind(&long_separator);
4438
4439   __ Move(index, Immediate(0));
4440   // Jump into the loop after the code that copies the separator, so the first
4441   // element is not preceded by a separator
4442   __ jmp(&loop_3_entry);
4443   // Loop condition: while (index < length).
4444   __ bind(&loop_3);
4445   // Each iteration of the loop concatenates one string to the result.
4446   // Live values in registers:
4447   //   index: which element of the elements array we are adding to the result.
4448   //   result_pos: the position to which we are currently copying characters.
4449
4450   // Copy the separator to the result.
4451   __ mov(string, separator_operand);
4452   __ mov(string_length,
4453          FieldOperand(string, String::kLengthOffset));
4454   __ shr(string_length, 1);
4455   __ lea(string,
4456          FieldOperand(string, SeqOneByteString::kHeaderSize));
4457   __ CopyBytes(string, result_pos, string_length, scratch);
4458
4459   __ bind(&loop_3_entry);
4460   // Get string = array[index].
4461   __ mov(string, FieldOperand(elements, index,
4462                               times_pointer_size,
4463                               FixedArray::kHeaderSize));
4464   __ mov(string_length,
4465          FieldOperand(string, String::kLengthOffset));
4466   __ shr(string_length, 1);
4467   __ lea(string,
4468          FieldOperand(string, SeqOneByteString::kHeaderSize));
4469   __ CopyBytes(string, result_pos, string_length, scratch);
4470   __ add(index, Immediate(1));
4471
4472   __ cmp(index, array_length_operand);
4473   __ j(less, &loop_3);  // End while (index < length).
4474   __ jmp(&done);
4475
4476
4477   __ bind(&bailout);
4478   __ mov(result_operand, isolate()->factory()->undefined_value());
4479   __ bind(&done);
4480   __ mov(eax, result_operand);
4481   // Drop temp values from the stack, and restore context register.
4482   __ add(esp, Immediate(3 * kPointerSize));
4483
4484   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4485   context()->Plug(eax);
4486 }
4487
4488
4489 void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4490   DCHECK(expr->arguments()->length() == 0);
4491   ExternalReference debug_is_active =
4492       ExternalReference::debug_is_active_address(isolate());
4493   __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
4494   __ SmiTag(eax);
4495   context()->Plug(eax);
4496 }
4497
4498
4499 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
4500   if (expr->function() != NULL &&
4501       expr->function()->intrinsic_type == Runtime::INLINE) {
4502     Comment cmnt(masm_, "[ InlineRuntimeCall");
4503     EmitInlineRuntimeCall(expr);
4504     return;
4505   }
4506
4507   Comment cmnt(masm_, "[ CallRuntime");
4508   ZoneList<Expression*>* args = expr->arguments();
4509
4510   if (expr->is_jsruntime()) {
4511     // Push the builtins object as receiver.
4512     __ mov(eax, GlobalObjectOperand());
4513     __ push(FieldOperand(eax, GlobalObject::kBuiltinsOffset));
4514
4515     // Load the function from the receiver.
4516     __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4517     __ mov(LoadDescriptor::NameRegister(), Immediate(expr->name()));
4518     if (FLAG_vector_ics) {
4519       __ mov(VectorLoadICDescriptor::SlotRegister(),
4520              Immediate(SmiFromSlot(expr->CallRuntimeFeedbackSlot())));
4521       CallLoadIC(NOT_CONTEXTUAL);
4522     } else {
4523       CallLoadIC(NOT_CONTEXTUAL, expr->CallRuntimeFeedbackId());
4524     }
4525
4526     // Push the target function under the receiver.
4527     __ push(Operand(esp, 0));
4528     __ mov(Operand(esp, kPointerSize), eax);
4529
4530     // Code common for calls using the IC.
4531     ZoneList<Expression*>* args = expr->arguments();
4532     int arg_count = args->length();
4533     for (int i = 0; i < arg_count; i++) {
4534       VisitForStackValue(args->at(i));
4535     }
4536
4537     // Record source position of the IC call.
4538     SetSourcePosition(expr->position());
4539     CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
4540     __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
4541     __ CallStub(&stub);
4542     // Restore context register.
4543     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4544     context()->DropAndPlug(1, eax);
4545
4546   } else {
4547     // Push the arguments ("left-to-right").
4548     int arg_count = args->length();
4549     for (int i = 0; i < arg_count; i++) {
4550       VisitForStackValue(args->at(i));
4551     }
4552
4553     // Call the C runtime function.
4554     __ CallRuntime(expr->function(), arg_count);
4555
4556     context()->Plug(eax);
4557   }
4558 }
4559
4560
4561 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
4562   switch (expr->op()) {
4563     case Token::DELETE: {
4564       Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
4565       Property* property = expr->expression()->AsProperty();
4566       VariableProxy* proxy = expr->expression()->AsVariableProxy();
4567
4568       if (property != NULL) {
4569         VisitForStackValue(property->obj());
4570         VisitForStackValue(property->key());
4571         __ push(Immediate(Smi::FromInt(language_mode())));
4572         __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4573         context()->Plug(eax);
4574       } else if (proxy != NULL) {
4575         Variable* var = proxy->var();
4576         // Delete of an unqualified identifier is disallowed in strict mode
4577         // but "delete this" is allowed.
4578         DCHECK(is_sloppy(language_mode()) || var->is_this());
4579         if (var->IsUnallocated()) {
4580           __ push(GlobalObjectOperand());
4581           __ push(Immediate(var->name()));
4582           __ push(Immediate(Smi::FromInt(SLOPPY)));
4583           __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION);
4584           context()->Plug(eax);
4585         } else if (var->IsStackAllocated() || var->IsContextSlot()) {
4586           // Result of deleting non-global variables is false.  'this' is
4587           // not really a variable, though we implement it as one.  The
4588           // subexpression does not have side effects.
4589           context()->Plug(var->is_this());
4590         } else {
4591           // Non-global variable.  Call the runtime to try to delete from the
4592           // context where the variable was introduced.
4593           __ push(context_register());
4594           __ push(Immediate(var->name()));
4595           __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
4596           context()->Plug(eax);
4597         }
4598       } else {
4599         // Result of deleting non-property, non-variable reference is true.
4600         // The subexpression may have side effects.
4601         VisitForEffect(expr->expression());
4602         context()->Plug(true);
4603       }
4604       break;
4605     }
4606
4607     case Token::VOID: {
4608       Comment cmnt(masm_, "[ UnaryOperation (VOID)");
4609       VisitForEffect(expr->expression());
4610       context()->Plug(isolate()->factory()->undefined_value());
4611       break;
4612     }
4613
4614     case Token::NOT: {
4615       Comment cmnt(masm_, "[ UnaryOperation (NOT)");
4616       if (context()->IsEffect()) {
4617         // Unary NOT has no side effects so it's only necessary to visit the
4618         // subexpression.  Match the optimizing compiler by not branching.
4619         VisitForEffect(expr->expression());
4620       } else if (context()->IsTest()) {
4621         const TestContext* test = TestContext::cast(context());
4622         // The labels are swapped for the recursive call.
4623         VisitForControl(expr->expression(),
4624                         test->false_label(),
4625                         test->true_label(),
4626                         test->fall_through());
4627         context()->Plug(test->true_label(), test->false_label());
4628       } else {
4629         // We handle value contexts explicitly rather than simply visiting
4630         // for control and plugging the control flow into the context,
4631         // because we need to prepare a pair of extra administrative AST ids
4632         // for the optimizing compiler.
4633         DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
4634         Label materialize_true, materialize_false, done;
4635         VisitForControl(expr->expression(),
4636                         &materialize_false,
4637                         &materialize_true,
4638                         &materialize_true);
4639         __ bind(&materialize_true);
4640         PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
4641         if (context()->IsAccumulatorValue()) {
4642           __ mov(eax, isolate()->factory()->true_value());
4643         } else {
4644           __ Push(isolate()->factory()->true_value());
4645         }
4646         __ jmp(&done, Label::kNear);
4647         __ bind(&materialize_false);
4648         PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
4649         if (context()->IsAccumulatorValue()) {
4650           __ mov(eax, isolate()->factory()->false_value());
4651         } else {
4652           __ Push(isolate()->factory()->false_value());
4653         }
4654         __ bind(&done);
4655       }
4656       break;
4657     }
4658
4659     case Token::TYPEOF: {
4660       Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4661       { StackValueContext context(this);
4662         VisitForTypeofValue(expr->expression());
4663       }
4664       __ CallRuntime(Runtime::kTypeof, 1);
4665       context()->Plug(eax);
4666       break;
4667     }
4668
4669     default:
4670       UNREACHABLE();
4671   }
4672 }
4673
4674
4675 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4676   DCHECK(expr->expression()->IsValidReferenceExpression());
4677
4678   Comment cmnt(masm_, "[ CountOperation");
4679   SetSourcePosition(expr->position());
4680
4681   Property* prop = expr->expression()->AsProperty();
4682   LhsKind assign_type = GetAssignType(prop);
4683
4684   // Evaluate expression and get value.
4685   if (assign_type == VARIABLE) {
4686     DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
4687     AccumulatorValueContext context(this);
4688     EmitVariableLoad(expr->expression()->AsVariableProxy());
4689   } else {
4690     // Reserve space for result of postfix operation.
4691     if (expr->is_postfix() && !context()->IsEffect()) {
4692       __ push(Immediate(Smi::FromInt(0)));
4693     }
4694     switch (assign_type) {
4695       case NAMED_PROPERTY: {
4696         // Put the object both on the stack and in the register.
4697         VisitForStackValue(prop->obj());
4698         __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
4699         EmitNamedPropertyLoad(prop);
4700         break;
4701       }
4702
4703       case NAMED_SUPER_PROPERTY: {
4704         VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4705         EmitLoadHomeObject(prop->obj()->AsSuperReference());
4706         __ push(result_register());
4707         __ push(MemOperand(esp, kPointerSize));
4708         __ push(result_register());
4709         EmitNamedSuperPropertyLoad(prop);
4710         break;
4711       }
4712
4713       case KEYED_SUPER_PROPERTY: {
4714         VisitForStackValue(prop->obj()->AsSuperReference()->this_var());
4715         EmitLoadHomeObject(prop->obj()->AsSuperReference());
4716         __ push(result_register());
4717         VisitForAccumulatorValue(prop->key());
4718         __ push(result_register());
4719         __ push(MemOperand(esp, 2 * kPointerSize));
4720         __ push(MemOperand(esp, 2 * kPointerSize));
4721         __ push(result_register());
4722         EmitKeyedSuperPropertyLoad(prop);
4723         break;
4724       }
4725
4726       case KEYED_PROPERTY: {
4727         VisitForStackValue(prop->obj());
4728         VisitForStackValue(prop->key());
4729         __ mov(LoadDescriptor::ReceiverRegister(),
4730                Operand(esp, kPointerSize));                       // Object.
4731         __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));  // Key.
4732         EmitKeyedPropertyLoad(prop);
4733         break;
4734       }
4735
4736       case VARIABLE:
4737         UNREACHABLE();
4738     }
4739   }
4740
4741   // We need a second deoptimization point after loading the value
4742   // in case evaluating the property load my have a side effect.
4743   if (assign_type == VARIABLE) {
4744     PrepareForBailout(expr->expression(), TOS_REG);
4745   } else {
4746     PrepareForBailoutForId(prop->LoadId(), TOS_REG);
4747   }
4748
4749   // Inline smi case if we are in a loop.
4750   Label done, stub_call;
4751   JumpPatchSite patch_site(masm_);
4752   if (ShouldInlineSmiCase(expr->op())) {
4753     Label slow;
4754     patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);
4755
4756     // Save result for postfix expressions.
4757     if (expr->is_postfix()) {
4758       if (!context()->IsEffect()) {
4759         // Save the result on the stack. If we have a named or keyed property
4760         // we store the result under the receiver that is currently on top
4761         // of the stack.
4762         switch (assign_type) {
4763           case VARIABLE:
4764             __ push(eax);
4765             break;
4766           case NAMED_PROPERTY:
4767             __ mov(Operand(esp, kPointerSize), eax);
4768             break;
4769           case NAMED_SUPER_PROPERTY:
4770             __ mov(Operand(esp, 2 * kPointerSize), eax);
4771             break;
4772           case KEYED_PROPERTY:
4773             __ mov(Operand(esp, 2 * kPointerSize), eax);
4774             break;
4775           case KEYED_SUPER_PROPERTY:
4776             __ mov(Operand(esp, 3 * kPointerSize), eax);
4777             break;
4778         }
4779       }
4780     }
4781
4782     if (expr->op() == Token::INC) {
4783       __ add(eax, Immediate(Smi::FromInt(1)));
4784     } else {
4785       __ sub(eax, Immediate(Smi::FromInt(1)));
4786     }
4787     __ j(no_overflow, &done, Label::kNear);
4788     // Call stub. Undo operation first.
4789     if (expr->op() == Token::INC) {
4790       __ sub(eax, Immediate(Smi::FromInt(1)));
4791     } else {
4792       __ add(eax, Immediate(Smi::FromInt(1)));
4793     }
4794     __ jmp(&stub_call, Label::kNear);
4795     __ bind(&slow);
4796   }
4797   ToNumberStub convert_stub(isolate());
4798   __ CallStub(&convert_stub);
4799   PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
4800
4801   // Save result for postfix expressions.
4802   if (expr->is_postfix()) {
4803     if (!context()->IsEffect()) {
4804       // Save the result on the stack. If we have a named or keyed property
4805       // we store the result under the receiver that is currently on top
4806       // of the stack.
4807       switch (assign_type) {
4808         case VARIABLE:
4809           __ push(eax);
4810           break;
4811         case NAMED_PROPERTY:
4812           __ mov(Operand(esp, kPointerSize), eax);
4813           break;
4814         case NAMED_SUPER_PROPERTY:
4815           __ mov(Operand(esp, 2 * kPointerSize), eax);
4816           break;
4817         case KEYED_PROPERTY:
4818           __ mov(Operand(esp, 2 * kPointerSize), eax);
4819           break;
4820         case KEYED_SUPER_PROPERTY:
4821           __ mov(Operand(esp, 3 * kPointerSize), eax);
4822           break;
4823       }
4824     }
4825   }
4826
4827   // Record position before stub call.
4828   SetSourcePosition(expr->position());
4829
4830   // Call stub for +1/-1.
4831   __ bind(&stub_call);
4832   __ mov(edx, eax);
4833   __ mov(eax, Immediate(Smi::FromInt(1)));
4834   Handle<Code> code =
4835       CodeFactory::BinaryOpIC(isolate(), expr->binary_op()).code();
4836   CallIC(code, expr->CountBinOpFeedbackId());
4837   patch_site.EmitPatchInfo();
4838   __ bind(&done);
4839
4840   // Store the value returned in eax.
4841   switch (assign_type) {
4842     case VARIABLE:
4843       if (expr->is_postfix()) {
4844         // Perform the assignment as if via '='.
4845         { EffectContext context(this);
4846           EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4847                                  Token::ASSIGN);
4848           PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4849           context.Plug(eax);
4850         }
4851         // For all contexts except EffectContext We have the result on
4852         // top of the stack.
4853         if (!context()->IsEffect()) {
4854           context()->PlugTOS();
4855         }
4856       } else {
4857         // Perform the assignment as if via '='.
4858         EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4859                                Token::ASSIGN);
4860         PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4861         context()->Plug(eax);
4862       }
4863       break;
4864     case NAMED_PROPERTY: {
4865       __ mov(StoreDescriptor::NameRegister(),
4866              prop->key()->AsLiteral()->value());
4867       __ pop(StoreDescriptor::ReceiverRegister());
4868       CallStoreIC(expr->CountStoreFeedbackId());
4869       PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4870       if (expr->is_postfix()) {
4871         if (!context()->IsEffect()) {
4872           context()->PlugTOS();
4873         }
4874       } else {
4875         context()->Plug(eax);
4876       }
4877       break;
4878     }
4879     case NAMED_SUPER_PROPERTY: {
4880       EmitNamedSuperPropertyStore(prop);
4881       if (expr->is_postfix()) {
4882         if (!context()->IsEffect()) {
4883           context()->PlugTOS();
4884         }
4885       } else {
4886         context()->Plug(eax);
4887       }
4888       break;
4889     }
4890     case KEYED_SUPER_PROPERTY: {
4891       EmitKeyedSuperPropertyStore(prop);
4892       if (expr->is_postfix()) {
4893         if (!context()->IsEffect()) {
4894           context()->PlugTOS();
4895         }
4896       } else {
4897         context()->Plug(eax);
4898       }
4899       break;
4900     }
4901     case KEYED_PROPERTY: {
4902       __ pop(StoreDescriptor::NameRegister());
4903       __ pop(StoreDescriptor::ReceiverRegister());
4904       Handle<Code> ic =
4905           CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4906       CallIC(ic, expr->CountStoreFeedbackId());
4907       PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
4908       if (expr->is_postfix()) {
4909         // Result is on the stack
4910         if (!context()->IsEffect()) {
4911           context()->PlugTOS();
4912         }
4913       } else {
4914         context()->Plug(eax);
4915       }
4916       break;
4917     }
4918   }
4919 }
4920
4921
4922 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) {
4923   VariableProxy* proxy = expr->AsVariableProxy();
4924   DCHECK(!context()->IsEffect());
4925   DCHECK(!context()->IsTest());
4926
4927   if (proxy != NULL && proxy->var()->IsUnallocated()) {
4928     Comment cmnt(masm_, "[ Global variable");
4929     __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
4930     __ mov(LoadDescriptor::NameRegister(), Immediate(proxy->name()));
4931     if (FLAG_vector_ics) {
4932       __ mov(VectorLoadICDescriptor::SlotRegister(),
4933              Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
4934     }
4935     // Use a regular load, not a contextual load, to avoid a reference
4936     // error.
4937     CallLoadIC(NOT_CONTEXTUAL);
4938     PrepareForBailout(expr, TOS_REG);
4939     context()->Plug(eax);
4940   } else if (proxy != NULL && proxy->var()->IsLookupSlot()) {
4941     Comment cmnt(masm_, "[ Lookup slot");
4942     Label done, slow;
4943
4944     // Generate code for loading from variables potentially shadowed
4945     // by eval-introduced variables.
4946     EmitDynamicLookupFastCase(proxy, INSIDE_TYPEOF, &slow, &done);
4947
4948     __ bind(&slow);
4949     __ push(esi);
4950     __ push(Immediate(proxy->name()));
4951     __ CallRuntime(Runtime::kLoadLookupSlotNoReferenceError, 2);
4952     PrepareForBailout(expr, TOS_REG);
4953     __ bind(&done);
4954
4955     context()->Plug(eax);
4956   } else {
4957     // This expression cannot throw a reference error at the top level.
4958     VisitInDuplicateContext(expr);
4959   }
4960 }
4961
4962
4963 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
4964                                                  Expression* sub_expr,
4965                                                  Handle<String> check) {
4966   Label materialize_true, materialize_false;
4967   Label* if_true = NULL;
4968   Label* if_false = NULL;
4969   Label* fall_through = NULL;
4970   context()->PrepareTest(&materialize_true, &materialize_false,
4971                          &if_true, &if_false, &fall_through);
4972
4973   { AccumulatorValueContext context(this);
4974     VisitForTypeofValue(sub_expr);
4975   }
4976   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
4977
4978   Factory* factory = isolate()->factory();
4979   if (String::Equals(check, factory->number_string())) {
4980     __ JumpIfSmi(eax, if_true);
4981     __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
4982            isolate()->factory()->heap_number_map());
4983     Split(equal, if_true, if_false, fall_through);
4984   } else if (String::Equals(check, factory->string_string())) {
4985     __ JumpIfSmi(eax, if_false);
4986     __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
4987     __ j(above_equal, if_false);
4988     // Check for undetectable objects => false.
4989     __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4990               1 << Map::kIsUndetectable);
4991     Split(zero, if_true, if_false, fall_through);
4992   } else if (String::Equals(check, factory->symbol_string())) {
4993     __ JumpIfSmi(eax, if_false);
4994     __ CmpObjectType(eax, SYMBOL_TYPE, edx);
4995     Split(equal, if_true, if_false, fall_through);
4996   } else if (String::Equals(check, factory->boolean_string())) {
4997     __ cmp(eax, isolate()->factory()->true_value());
4998     __ j(equal, if_true);
4999     __ cmp(eax, isolate()->factory()->false_value());
5000     Split(equal, if_true, if_false, fall_through);
5001   } else if (String::Equals(check, factory->undefined_string())) {
5002     __ cmp(eax, isolate()->factory()->undefined_value());
5003     __ j(equal, if_true);
5004     __ JumpIfSmi(eax, if_false);
5005     // Check for undetectable objects => true.
5006     __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
5007     __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
5008     __ test(ecx, Immediate(1 << Map::kIsUndetectable));
5009     Split(not_zero, if_true, if_false, fall_through);
5010   } else if (String::Equals(check, factory->function_string())) {
5011     __ JumpIfSmi(eax, if_false);
5012     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5013     __ CmpObjectType(eax, JS_FUNCTION_TYPE, edx);
5014     __ j(equal, if_true);
5015     __ CmpInstanceType(edx, JS_FUNCTION_PROXY_TYPE);
5016     Split(equal, if_true, if_false, fall_through);
5017   } else if (String::Equals(check, factory->object_string())) {
5018     __ JumpIfSmi(eax, if_false);
5019     __ cmp(eax, isolate()->factory()->null_value());
5020     __ j(equal, if_true);
5021     __ CmpObjectType(eax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, edx);
5022     __ j(below, if_false);
5023     __ CmpInstanceType(edx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5024     __ j(above, if_false);
5025     // Check for undetectable objects => false.
5026     __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
5027               1 << Map::kIsUndetectable);
5028     Split(zero, if_true, if_false, fall_through);
5029   } else {
5030     if (if_false != fall_through) __ jmp(if_false);
5031   }
5032   context()->Plug(if_true, if_false);
5033 }
5034
5035
5036 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
5037   Comment cmnt(masm_, "[ CompareOperation");
5038   SetSourcePosition(expr->position());
5039
5040   // First we try a fast inlined version of the compare when one of
5041   // the operands is a literal.
5042   if (TryLiteralCompare(expr)) return;
5043
5044   // Always perform the comparison for its control flow.  Pack the result
5045   // into the expression's context after the comparison is performed.
5046   Label materialize_true, materialize_false;
5047   Label* if_true = NULL;
5048   Label* if_false = NULL;
5049   Label* fall_through = NULL;
5050   context()->PrepareTest(&materialize_true, &materialize_false,
5051                          &if_true, &if_false, &fall_through);
5052
5053   Token::Value op = expr->op();
5054   VisitForStackValue(expr->left());
5055   switch (op) {
5056     case Token::IN:
5057       VisitForStackValue(expr->right());
5058       __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION);
5059       PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
5060       __ cmp(eax, isolate()->factory()->true_value());
5061       Split(equal, if_true, if_false, fall_through);
5062       break;
5063
5064     case Token::INSTANCEOF: {
5065       VisitForStackValue(expr->right());
5066       InstanceofStub stub(isolate(), InstanceofStub::kNoFlags);
5067       __ CallStub(&stub);
5068       PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5069       __ test(eax, eax);
5070       // The stub returns 0 for true.
5071       Split(zero, if_true, if_false, fall_through);
5072       break;
5073     }
5074
5075     default: {
5076       VisitForAccumulatorValue(expr->right());
5077       Condition cc = CompareIC::ComputeCondition(op);
5078       __ pop(edx);
5079
5080       bool inline_smi_code = ShouldInlineSmiCase(op);
5081       JumpPatchSite patch_site(masm_);
5082       if (inline_smi_code) {
5083         Label slow_case;
5084         __ mov(ecx, edx);
5085         __ or_(ecx, eax);
5086         patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
5087         __ cmp(edx, eax);
5088         Split(cc, if_true, if_false, NULL);
5089         __ bind(&slow_case);
5090       }
5091
5092       // Record position and call the compare IC.
5093       SetSourcePosition(expr->position());
5094       Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
5095       CallIC(ic, expr->CompareOperationFeedbackId());
5096       patch_site.EmitPatchInfo();
5097
5098       PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5099       __ test(eax, eax);
5100       Split(cc, if_true, if_false, fall_through);
5101     }
5102   }
5103
5104   // Convert the result of the comparison into one expected for this
5105   // expression's context.
5106   context()->Plug(if_true, if_false);
5107 }
5108
5109
5110 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
5111                                               Expression* sub_expr,
5112                                               NilValue nil) {
5113   Label materialize_true, materialize_false;
5114   Label* if_true = NULL;
5115   Label* if_false = NULL;
5116   Label* fall_through = NULL;
5117   context()->PrepareTest(&materialize_true, &materialize_false,
5118                          &if_true, &if_false, &fall_through);
5119
5120   VisitForAccumulatorValue(sub_expr);
5121   PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
5122
5123   Handle<Object> nil_value = nil == kNullValue
5124       ? isolate()->factory()->null_value()
5125       : isolate()->factory()->undefined_value();
5126   if (expr->op() == Token::EQ_STRICT) {
5127     __ cmp(eax, nil_value);
5128     Split(equal, if_true, if_false, fall_through);
5129   } else {
5130     Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
5131     CallIC(ic, expr->CompareOperationFeedbackId());
5132     __ test(eax, eax);
5133     Split(not_zero, if_true, if_false, fall_through);
5134   }
5135   context()->Plug(if_true, if_false);
5136 }
5137
5138
5139 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
5140   __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5141   context()->Plug(eax);
5142 }
5143
5144
5145 Register FullCodeGenerator::result_register() {
5146   return eax;
5147 }
5148
5149
5150 Register FullCodeGenerator::context_register() {
5151   return esi;
5152 }
5153
5154
5155 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
5156   DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
5157   __ mov(Operand(ebp, frame_offset), value);
5158 }
5159
5160
5161 void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
5162   __ mov(dst, ContextOperand(esi, context_index));
5163 }
5164
5165
5166 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
5167   Scope* declaration_scope = scope()->DeclarationScope();
5168   if (declaration_scope->is_script_scope() ||
5169       declaration_scope->is_module_scope()) {
5170     // Contexts nested in the native context have a canonical empty function
5171     // as their closure, not the anonymous closure containing the global
5172     // code.  Pass a smi sentinel and let the runtime look up the empty
5173     // function.
5174     __ push(Immediate(Smi::FromInt(0)));
5175   } else if (declaration_scope->is_eval_scope()) {
5176     // Contexts nested inside eval code have the same closure as the context
5177     // calling eval, not the anonymous closure containing the eval code.
5178     // Fetch it from the context.
5179     __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
5180   } else {
5181     DCHECK(declaration_scope->is_function_scope());
5182     __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
5183   }
5184 }
5185
5186
5187 // ----------------------------------------------------------------------------
5188 // Non-local control flow support.
5189
5190 void FullCodeGenerator::EnterFinallyBlock() {
5191   // Cook return address on top of stack (smi encoded Code* delta)
5192   DCHECK(!result_register().is(edx));
5193   __ pop(edx);
5194   __ sub(edx, Immediate(masm_->CodeObject()));
5195   STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
5196   STATIC_ASSERT(kSmiTag == 0);
5197   __ SmiTag(edx);
5198   __ push(edx);
5199
5200   // Store result register while executing finally block.
5201   __ push(result_register());
5202
5203   // Store pending message while executing finally block.
5204   ExternalReference pending_message_obj =
5205       ExternalReference::address_of_pending_message_obj(isolate());
5206   __ mov(edx, Operand::StaticVariable(pending_message_obj));
5207   __ push(edx);
5208
5209   ExternalReference has_pending_message =
5210       ExternalReference::address_of_has_pending_message(isolate());
5211   __ mov(edx, Operand::StaticVariable(has_pending_message));
5212   __ SmiTag(edx);
5213   __ push(edx);
5214
5215   ExternalReference pending_message_script =
5216       ExternalReference::address_of_pending_message_script(isolate());
5217   __ mov(edx, Operand::StaticVariable(pending_message_script));
5218   __ push(edx);
5219 }
5220
5221
5222 void FullCodeGenerator::ExitFinallyBlock() {
5223   DCHECK(!result_register().is(edx));
5224   // Restore pending message from stack.
5225   __ pop(edx);
5226   ExternalReference pending_message_script =
5227       ExternalReference::address_of_pending_message_script(isolate());
5228   __ mov(Operand::StaticVariable(pending_message_script), edx);
5229
5230   __ pop(edx);
5231   __ SmiUntag(edx);
5232   ExternalReference has_pending_message =
5233       ExternalReference::address_of_has_pending_message(isolate());
5234   __ mov(Operand::StaticVariable(has_pending_message), edx);
5235
5236   __ pop(edx);
5237   ExternalReference pending_message_obj =
5238       ExternalReference::address_of_pending_message_obj(isolate());
5239   __ mov(Operand::StaticVariable(pending_message_obj), edx);
5240
5241   // Restore result register from stack.
5242   __ pop(result_register());
5243
5244   // Uncook return address.
5245   __ pop(edx);
5246   __ SmiUntag(edx);
5247   __ add(edx, Immediate(masm_->CodeObject()));
5248   __ jmp(edx);
5249 }
5250
5251
5252 #undef __
5253
5254 #define __ ACCESS_MASM(masm())
5255
5256 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
5257     int* stack_depth,
5258     int* context_length) {
5259   // The macros used here must preserve the result register.
5260
5261   // Because the handler block contains the context of the finally
5262   // code, we can restore it directly from there for the finally code
5263   // rather than iteratively unwinding contexts via their previous
5264   // links.
5265   __ Drop(*stack_depth);  // Down to the handler block.
5266   if (*context_length > 0) {
5267     // Restore the context to its dedicated register and the stack.
5268     __ mov(esi, Operand(esp, StackHandlerConstants::kContextOffset));
5269     __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
5270   }
5271   __ PopTryHandler();
5272   __ call(finally_entry_);
5273
5274   *stack_depth = 0;
5275   *context_length = 0;
5276   return previous_;
5277 }
5278
5279 #undef __
5280
5281
5282 static const byte kJnsInstruction = 0x79;
5283 static const byte kJnsOffset = 0x11;
5284 static const byte kNopByteOne = 0x66;
5285 static const byte kNopByteTwo = 0x90;
5286 #ifdef DEBUG
5287 static const byte kCallInstruction = 0xe8;
5288 #endif
5289
5290
5291 void BackEdgeTable::PatchAt(Code* unoptimized_code,
5292                             Address pc,
5293                             BackEdgeState target_state,
5294                             Code* replacement_code) {
5295   Address call_target_address = pc - kIntSize;
5296   Address jns_instr_address = call_target_address - 3;
5297   Address jns_offset_address = call_target_address - 2;
5298
5299   switch (target_state) {
5300     case INTERRUPT:
5301       //     sub <profiling_counter>, <delta>  ;; Not changed
5302       //     jns ok
5303       //     call <interrupt stub>
5304       //   ok:
5305       *jns_instr_address = kJnsInstruction;
5306       *jns_offset_address = kJnsOffset;
5307       break;
5308     case ON_STACK_REPLACEMENT:
5309     case OSR_AFTER_STACK_CHECK:
5310       //     sub <profiling_counter>, <delta>  ;; Not changed
5311       //     nop
5312       //     nop
5313       //     call <on-stack replacment>
5314       //   ok:
5315       *jns_instr_address = kNopByteOne;
5316       *jns_offset_address = kNopByteTwo;
5317       break;
5318   }
5319
5320   Assembler::set_target_address_at(call_target_address,
5321                                    unoptimized_code,
5322                                    replacement_code->entry());
5323   unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
5324       unoptimized_code, call_target_address, replacement_code);
5325 }
5326
5327
5328 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
5329     Isolate* isolate,
5330     Code* unoptimized_code,
5331     Address pc) {
5332   Address call_target_address = pc - kIntSize;
5333   Address jns_instr_address = call_target_address - 3;
5334   DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
5335
5336   if (*jns_instr_address == kJnsInstruction) {
5337     DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
5338     DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
5339               Assembler::target_address_at(call_target_address,
5340                                            unoptimized_code));
5341     return INTERRUPT;
5342   }
5343
5344   DCHECK_EQ(kNopByteOne, *jns_instr_address);
5345   DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
5346
5347   if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
5348       isolate->builtins()->OnStackReplacement()->entry()) {
5349     return ON_STACK_REPLACEMENT;
5350   }
5351
5352   DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
5353             Assembler::target_address_at(call_target_address,
5354                                          unoptimized_code));
5355   return OSR_AFTER_STACK_CHECK;
5356 }
5357
5358
5359 } }  // namespace v8::internal
5360
5361 #endif  // V8_TARGET_ARCH_X87