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