07be757ed5d5cf238808b9765e66da4e17409747
[platform/upstream/nodejs.git] / deps / v8 / src / x87 / lithium-codegen-x87.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/v8.h"
6
7 #if V8_TARGET_ARCH_X87
8
9 #include "src/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/deoptimizer.h"
14 #include "src/hydrogen-osr.h"
15 #include "src/ic/ic.h"
16 #include "src/ic/stub-cache.h"
17 #include "src/x87/lithium-codegen-x87.h"
18
19 namespace v8 {
20 namespace internal {
21
22
23 // When invoking builtins, we need to record the safepoint in the middle of
24 // the invoke instruction sequence generated by the macro assembler.
25 class SafepointGenerator FINAL : public CallWrapper {
26  public:
27   SafepointGenerator(LCodeGen* codegen,
28                      LPointerMap* pointers,
29                      Safepoint::DeoptMode mode)
30       : codegen_(codegen),
31         pointers_(pointers),
32         deopt_mode_(mode) {}
33   virtual ~SafepointGenerator() {}
34
35   void BeforeCall(int call_size) const OVERRIDE {}
36
37   void AfterCall() const OVERRIDE {
38     codegen_->RecordSafepoint(pointers_, deopt_mode_);
39   }
40
41  private:
42   LCodeGen* codegen_;
43   LPointerMap* pointers_;
44   Safepoint::DeoptMode deopt_mode_;
45 };
46
47
48 #define __ masm()->
49
50 bool LCodeGen::GenerateCode() {
51   LPhase phase("Z_Code generation", chunk());
52   DCHECK(is_unused());
53   status_ = GENERATING;
54
55   // Open a frame scope to indicate that there is a frame on the stack.  The
56   // MANUAL indicates that the scope shouldn't actually generate code to set up
57   // the frame (that is done in GeneratePrologue).
58   FrameScope frame_scope(masm_, StackFrame::MANUAL);
59
60   support_aligned_spilled_doubles_ = info()->IsOptimizing();
61
62   dynamic_frame_alignment_ = info()->IsOptimizing() &&
63       ((chunk()->num_double_slots() > 2 &&
64         !chunk()->graph()->is_recursive()) ||
65        !info()->osr_ast_id().IsNone());
66
67   return GeneratePrologue() &&
68       GenerateBody() &&
69       GenerateDeferredCode() &&
70       GenerateJumpTable() &&
71       GenerateSafepointTable();
72 }
73
74
75 void LCodeGen::FinishCode(Handle<Code> code) {
76   DCHECK(is_done());
77   code->set_stack_slots(GetStackSlotCount());
78   code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
79   PopulateDeoptimizationData(code);
80   if (!info()->IsStub()) {
81     Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
82   }
83 }
84
85
86 #ifdef _MSC_VER
87 void LCodeGen::MakeSureStackPagesMapped(int offset) {
88   const int kPageSize = 4 * KB;
89   for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
90     __ mov(Operand(esp, offset), eax);
91   }
92 }
93 #endif
94
95
96 bool LCodeGen::GeneratePrologue() {
97   DCHECK(is_generating());
98
99   if (info()->IsOptimizing()) {
100     ProfileEntryHookStub::MaybeCallEntryHook(masm_);
101
102 #ifdef DEBUG
103     if (strlen(FLAG_stop_at) > 0 &&
104         info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
105       __ int3();
106     }
107 #endif
108
109     // Sloppy mode functions and builtins need to replace the receiver with the
110     // global proxy when called as functions (without an explicit receiver
111     // object).
112     if (info_->this_has_uses() && is_sloppy(info_->language_mode()) &&
113         !info_->is_native()) {
114       Label ok;
115       // +1 for return address.
116       int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
117       __ mov(ecx, Operand(esp, receiver_offset));
118
119       __ cmp(ecx, isolate()->factory()->undefined_value());
120       __ j(not_equal, &ok, Label::kNear);
121
122       __ mov(ecx, GlobalObjectOperand());
123       __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
124
125       __ mov(Operand(esp, receiver_offset), ecx);
126
127       __ bind(&ok);
128     }
129
130     if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
131       // Move state of dynamic frame alignment into edx.
132       __ Move(edx, Immediate(kNoAlignmentPadding));
133
134       Label do_not_pad, align_loop;
135       STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
136       // Align esp + 4 to a multiple of 2 * kPointerSize.
137       __ test(esp, Immediate(kPointerSize));
138       __ j(not_zero, &do_not_pad, Label::kNear);
139       __ push(Immediate(0));
140       __ mov(ebx, esp);
141       __ mov(edx, Immediate(kAlignmentPaddingPushed));
142       // Copy arguments, receiver, and return address.
143       __ mov(ecx, Immediate(scope()->num_parameters() + 2));
144
145       __ bind(&align_loop);
146       __ mov(eax, Operand(ebx, 1 * kPointerSize));
147       __ mov(Operand(ebx, 0), eax);
148       __ add(Operand(ebx), Immediate(kPointerSize));
149       __ dec(ecx);
150       __ j(not_zero, &align_loop, Label::kNear);
151       __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
152       __ bind(&do_not_pad);
153     }
154   }
155
156   info()->set_prologue_offset(masm_->pc_offset());
157   if (NeedsEagerFrame()) {
158     DCHECK(!frame_is_built_);
159     frame_is_built_ = true;
160     if (info()->IsStub()) {
161       __ StubPrologue();
162     } else {
163       __ Prologue(info()->IsCodePreAgingActive());
164     }
165     info()->AddNoFrameRange(0, masm_->pc_offset());
166   }
167
168   if (info()->IsOptimizing() &&
169       dynamic_frame_alignment_ &&
170       FLAG_debug_code) {
171     __ test(esp, Immediate(kPointerSize));
172     __ Assert(zero, kFrameIsExpectedToBeAligned);
173   }
174
175   // Reserve space for the stack slots needed by the code.
176   int slots = GetStackSlotCount();
177   DCHECK(slots != 0 || !info()->IsOptimizing());
178   if (slots > 0) {
179     if (slots == 1) {
180       if (dynamic_frame_alignment_) {
181         __ push(edx);
182       } else {
183         __ push(Immediate(kNoAlignmentPadding));
184       }
185     } else {
186       if (FLAG_debug_code) {
187         __ sub(Operand(esp), Immediate(slots * kPointerSize));
188 #ifdef _MSC_VER
189         MakeSureStackPagesMapped(slots * kPointerSize);
190 #endif
191         __ push(eax);
192         __ mov(Operand(eax), Immediate(slots));
193         Label loop;
194         __ bind(&loop);
195         __ mov(MemOperand(esp, eax, times_4, 0),
196                Immediate(kSlotsZapValue));
197         __ dec(eax);
198         __ j(not_zero, &loop);
199         __ pop(eax);
200       } else {
201         __ sub(Operand(esp), Immediate(slots * kPointerSize));
202 #ifdef _MSC_VER
203         MakeSureStackPagesMapped(slots * kPointerSize);
204 #endif
205       }
206
207       if (support_aligned_spilled_doubles_) {
208         Comment(";;; Store dynamic frame alignment tag for spilled doubles");
209         // Store dynamic frame alignment state in the first local.
210         int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
211         if (dynamic_frame_alignment_) {
212           __ mov(Operand(ebp, offset), edx);
213         } else {
214           __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
215         }
216       }
217     }
218   }
219
220   // Possibly allocate a local context.
221   int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
222   if (heap_slots > 0) {
223     Comment(";;; Allocate local context");
224     bool need_write_barrier = true;
225     // Argument to NewContext is the function, which is still in edi.
226     if (heap_slots <= FastNewContextStub::kMaximumSlots) {
227       FastNewContextStub stub(isolate(), heap_slots);
228       __ CallStub(&stub);
229       // Result of FastNewContextStub is always in new space.
230       need_write_barrier = false;
231     } else {
232       __ push(edi);
233       __ CallRuntime(Runtime::kNewFunctionContext, 1);
234     }
235     RecordSafepoint(Safepoint::kNoLazyDeopt);
236     // Context is returned in eax.  It replaces the context passed to us.
237     // It's saved in the stack and kept live in esi.
238     __ mov(esi, eax);
239     __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
240
241     // Copy parameters into context if necessary.
242     int num_parameters = scope()->num_parameters();
243     for (int i = 0; i < num_parameters; i++) {
244       Variable* var = scope()->parameter(i);
245       if (var->IsContextSlot()) {
246         int parameter_offset = StandardFrameConstants::kCallerSPOffset +
247             (num_parameters - 1 - i) * kPointerSize;
248         // Load parameter from stack.
249         __ mov(eax, Operand(ebp, parameter_offset));
250         // Store it in the context.
251         int context_offset = Context::SlotOffset(var->index());
252         __ mov(Operand(esi, context_offset), eax);
253         // Update the write barrier. This clobbers eax and ebx.
254         if (need_write_barrier) {
255           __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
256                                     kDontSaveFPRegs);
257         } else if (FLAG_debug_code) {
258           Label done;
259           __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
260           __ Abort(kExpectedNewSpaceObject);
261           __ bind(&done);
262         }
263       }
264     }
265     Comment(";;; End allocate local context");
266   }
267
268   // Initailize FPU state.
269   __ fninit();
270   // Trace the call.
271   if (FLAG_trace && info()->IsOptimizing()) {
272     // We have not executed any compiled code yet, so esi still holds the
273     // incoming context.
274     __ CallRuntime(Runtime::kTraceEnter, 0);
275   }
276   return !is_aborted();
277 }
278
279
280 void LCodeGen::GenerateOsrPrologue() {
281   // Generate the OSR entry prologue at the first unknown OSR value, or if there
282   // are none, at the OSR entrypoint instruction.
283   if (osr_pc_offset_ >= 0) return;
284
285   osr_pc_offset_ = masm()->pc_offset();
286
287     // Move state of dynamic frame alignment into edx.
288   __ Move(edx, Immediate(kNoAlignmentPadding));
289
290   if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
291     Label do_not_pad, align_loop;
292     // Align ebp + 4 to a multiple of 2 * kPointerSize.
293     __ test(ebp, Immediate(kPointerSize));
294     __ j(zero, &do_not_pad, Label::kNear);
295     __ push(Immediate(0));
296     __ mov(ebx, esp);
297     __ mov(edx, Immediate(kAlignmentPaddingPushed));
298
299     // Move all parts of the frame over one word. The frame consists of:
300     // unoptimized frame slots, alignment state, context, frame pointer, return
301     // address, receiver, and the arguments.
302     __ mov(ecx, Immediate(scope()->num_parameters() +
303            5 + graph()->osr()->UnoptimizedFrameSlots()));
304
305     __ bind(&align_loop);
306     __ mov(eax, Operand(ebx, 1 * kPointerSize));
307     __ mov(Operand(ebx, 0), eax);
308     __ add(Operand(ebx), Immediate(kPointerSize));
309     __ dec(ecx);
310     __ j(not_zero, &align_loop, Label::kNear);
311     __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
312     __ sub(Operand(ebp), Immediate(kPointerSize));
313     __ bind(&do_not_pad);
314   }
315
316   // Save the first local, which is overwritten by the alignment state.
317   Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
318   __ push(alignment_loc);
319
320   // Set the dynamic frame alignment state.
321   __ mov(alignment_loc, edx);
322
323   // Adjust the frame size, subsuming the unoptimized frame into the
324   // optimized frame.
325   int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
326   DCHECK(slots >= 1);
327   __ sub(esp, Immediate((slots - 1) * kPointerSize));
328
329   // Initailize FPU state.
330   __ fninit();
331 }
332
333
334 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
335   if (instr->IsCall()) {
336     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
337   }
338   if (!instr->IsLazyBailout() && !instr->IsGap()) {
339     safepoints_.BumpLastLazySafepointIndex();
340   }
341   FlushX87StackIfNecessary(instr);
342 }
343
344
345 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) {
346   // When return from function call, FPU should be initialized again.
347   if (instr->IsCall() && instr->ClobbersDoubleRegisters(isolate())) {
348     bool double_result = instr->HasDoubleRegisterResult();
349     if (double_result) {
350       __ lea(esp, Operand(esp, -kDoubleSize));
351       __ fstp_d(Operand(esp, 0));
352     }
353     __ fninit();
354     if (double_result) {
355       __ fld_d(Operand(esp, 0));
356       __ lea(esp, Operand(esp, kDoubleSize));
357     }
358   }
359   if (instr->IsGoto()) {
360     x87_stack_.LeavingBlock(current_block_, LGoto::cast(instr), this);
361   } else if (FLAG_debug_code && FLAG_enable_slow_asserts &&
362              !instr->IsGap() && !instr->IsReturn()) {
363     if (instr->ClobbersDoubleRegisters(isolate())) {
364       if (instr->HasDoubleRegisterResult()) {
365         DCHECK_EQ(1, x87_stack_.depth());
366       } else {
367         DCHECK_EQ(0, x87_stack_.depth());
368       }
369     }
370     __ VerifyX87StackDepth(x87_stack_.depth());
371   }
372 }
373
374
375 bool LCodeGen::GenerateJumpTable() {
376   Label needs_frame;
377   if (jump_table_.length() > 0) {
378     Comment(";;; -------------------- Jump table --------------------");
379   }
380   for (int i = 0; i < jump_table_.length(); i++) {
381     Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
382     __ bind(&table_entry->label);
383     Address entry = table_entry->address;
384     DeoptComment(table_entry->deopt_info);
385     if (table_entry->needs_frame) {
386       DCHECK(!info()->saves_caller_doubles());
387       __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
388       if (needs_frame.is_bound()) {
389         __ jmp(&needs_frame);
390       } else {
391         __ bind(&needs_frame);
392         __ push(MemOperand(ebp, StandardFrameConstants::kContextOffset));
393         // This variant of deopt can only be used with stubs. Since we don't
394         // have a function pointer to install in the stack frame that we're
395         // building, install a special marker there instead.
396         DCHECK(info()->IsStub());
397         __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
398         // Push a PC inside the function so that the deopt code can find where
399         // the deopt comes from. It doesn't have to be the precise return
400         // address of a "calling" LAZY deopt, it only has to be somewhere
401         // inside the code body.
402         Label push_approx_pc;
403         __ call(&push_approx_pc);
404         __ bind(&push_approx_pc);
405         // Push the continuation which was stashed were the ebp should
406         // be. Replace it with the saved ebp.
407         __ push(MemOperand(esp, 3 * kPointerSize));
408         __ mov(MemOperand(esp, 4 * kPointerSize), ebp);
409         __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
410         __ ret(0);  // Call the continuation without clobbering registers.
411       }
412     } else {
413       __ call(entry, RelocInfo::RUNTIME_ENTRY);
414     }
415   }
416   return !is_aborted();
417 }
418
419
420 bool LCodeGen::GenerateDeferredCode() {
421   DCHECK(is_generating());
422   if (deferred_.length() > 0) {
423     for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
424       LDeferredCode* code = deferred_[i];
425       X87Stack copy(code->x87_stack());
426       x87_stack_ = copy;
427
428       HValue* value =
429           instructions_->at(code->instruction_index())->hydrogen_value();
430       RecordAndWritePosition(
431           chunk()->graph()->SourcePositionToScriptPosition(value->position()));
432
433       Comment(";;; <@%d,#%d> "
434               "-------------------- Deferred %s --------------------",
435               code->instruction_index(),
436               code->instr()->hydrogen_value()->id(),
437               code->instr()->Mnemonic());
438       __ bind(code->entry());
439       if (NeedsDeferredFrame()) {
440         Comment(";;; Build frame");
441         DCHECK(!frame_is_built_);
442         DCHECK(info()->IsStub());
443         frame_is_built_ = true;
444         // Build the frame in such a way that esi isn't trashed.
445         __ push(ebp);  // Caller's frame pointer.
446         __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
447         __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
448         __ lea(ebp, Operand(esp, 2 * kPointerSize));
449         Comment(";;; Deferred code");
450       }
451       code->Generate();
452       if (NeedsDeferredFrame()) {
453         __ bind(code->done());
454         Comment(";;; Destroy frame");
455         DCHECK(frame_is_built_);
456         frame_is_built_ = false;
457         __ mov(esp, ebp);
458         __ pop(ebp);
459       }
460       __ jmp(code->exit());
461     }
462   }
463
464   // Deferred code is the last part of the instruction sequence. Mark
465   // the generated code as done unless we bailed out.
466   if (!is_aborted()) status_ = DONE;
467   return !is_aborted();
468 }
469
470
471 bool LCodeGen::GenerateSafepointTable() {
472   DCHECK(is_done());
473   if (!info()->IsStub()) {
474     // For lazy deoptimization we need space to patch a call after every call.
475     // Ensure there is always space for such patching, even if the code ends
476     // in a call.
477     int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
478     while (masm()->pc_offset() < target_offset) {
479       masm()->nop();
480     }
481   }
482   safepoints_.Emit(masm(), GetStackSlotCount());
483   return !is_aborted();
484 }
485
486
487 Register LCodeGen::ToRegister(int index) const {
488   return Register::FromAllocationIndex(index);
489 }
490
491
492 X87Register LCodeGen::ToX87Register(int index) const {
493   return X87Register::FromAllocationIndex(index);
494 }
495
496
497 void LCodeGen::X87LoadForUsage(X87Register reg) {
498   DCHECK(x87_stack_.Contains(reg));
499   x87_stack_.Fxch(reg);
500   x87_stack_.pop();
501 }
502
503
504 void LCodeGen::X87LoadForUsage(X87Register reg1, X87Register reg2) {
505   DCHECK(x87_stack_.Contains(reg1));
506   DCHECK(x87_stack_.Contains(reg2));
507   if (reg1.is(reg2) && x87_stack_.depth() == 1) {
508     __ fld(x87_stack_.st(reg1));
509     x87_stack_.push(reg1);
510     x87_stack_.pop();
511     x87_stack_.pop();
512   } else {
513     x87_stack_.Fxch(reg1, 1);
514     x87_stack_.Fxch(reg2);
515     x87_stack_.pop();
516     x87_stack_.pop();
517   }
518 }
519
520
521 int LCodeGen::X87Stack::GetLayout() {
522   int layout = stack_depth_;
523   for (int i = 0; i < stack_depth_; i++) {
524     layout |= (stack_[stack_depth_ - 1 - i].code() << ((i + 1) * 3));
525   }
526
527   return layout;
528 }
529
530
531 void LCodeGen::X87Stack::Fxch(X87Register reg, int other_slot) {
532   DCHECK(is_mutable_);
533   DCHECK(Contains(reg) && stack_depth_ > other_slot);
534   int i  = ArrayIndex(reg);
535   int st = st2idx(i);
536   if (st != other_slot) {
537     int other_i = st2idx(other_slot);
538     X87Register other = stack_[other_i];
539     stack_[other_i]   = reg;
540     stack_[i]         = other;
541     if (st == 0) {
542       __ fxch(other_slot);
543     } else if (other_slot == 0) {
544       __ fxch(st);
545     } else {
546       __ fxch(st);
547       __ fxch(other_slot);
548       __ fxch(st);
549     }
550   }
551 }
552
553
554 int LCodeGen::X87Stack::st2idx(int pos) {
555   return stack_depth_ - pos - 1;
556 }
557
558
559 int LCodeGen::X87Stack::ArrayIndex(X87Register reg) {
560   for (int i = 0; i < stack_depth_; i++) {
561     if (stack_[i].is(reg)) return i;
562   }
563   UNREACHABLE();
564   return -1;
565 }
566
567
568 bool LCodeGen::X87Stack::Contains(X87Register reg) {
569   for (int i = 0; i < stack_depth_; i++) {
570     if (stack_[i].is(reg)) return true;
571   }
572   return false;
573 }
574
575
576 void LCodeGen::X87Stack::Free(X87Register reg) {
577   DCHECK(is_mutable_);
578   DCHECK(Contains(reg));
579   int i  = ArrayIndex(reg);
580   int st = st2idx(i);
581   if (st > 0) {
582     // keep track of how fstp(i) changes the order of elements
583     int tos_i = st2idx(0);
584     stack_[i] = stack_[tos_i];
585   }
586   pop();
587   __ fstp(st);
588 }
589
590
591 void LCodeGen::X87Mov(X87Register dst, Operand src, X87OperandType opts) {
592   if (x87_stack_.Contains(dst)) {
593     x87_stack_.Fxch(dst);
594     __ fstp(0);
595   } else {
596     x87_stack_.push(dst);
597   }
598   X87Fld(src, opts);
599 }
600
601
602 void LCodeGen::X87Mov(X87Register dst, X87Register src, X87OperandType opts) {
603   if (x87_stack_.Contains(dst)) {
604     x87_stack_.Fxch(dst);
605     __ fstp(0);
606     x87_stack_.pop();
607     // Push ST(i) onto the FPU register stack
608     __ fld(x87_stack_.st(src));
609     x87_stack_.push(dst);
610   } else {
611     // Push ST(i) onto the FPU register stack
612     __ fld(x87_stack_.st(src));
613     x87_stack_.push(dst);
614   }
615 }
616
617
618 void LCodeGen::X87Fld(Operand src, X87OperandType opts) {
619   DCHECK(!src.is_reg_only());
620   switch (opts) {
621     case kX87DoubleOperand:
622       __ fld_d(src);
623       break;
624     case kX87FloatOperand:
625       __ fld_s(src);
626       break;
627     case kX87IntOperand:
628       __ fild_s(src);
629       break;
630     default:
631       UNREACHABLE();
632   }
633 }
634
635
636 void LCodeGen::X87Mov(Operand dst, X87Register src, X87OperandType opts) {
637   DCHECK(!dst.is_reg_only());
638   x87_stack_.Fxch(src);
639   switch (opts) {
640     case kX87DoubleOperand:
641       __ fst_d(dst);
642       break;
643     case kX87FloatOperand:
644       __ fst_s(dst);
645       break;
646     case kX87IntOperand:
647       __ fist_s(dst);
648       break;
649     default:
650       UNREACHABLE();
651   }
652 }
653
654
655 void LCodeGen::X87Stack::PrepareToWrite(X87Register reg) {
656   DCHECK(is_mutable_);
657   if (Contains(reg)) {
658     Free(reg);
659   }
660   // Mark this register as the next register to write to
661   stack_[stack_depth_] = reg;
662 }
663
664
665 void LCodeGen::X87Stack::CommitWrite(X87Register reg) {
666   DCHECK(is_mutable_);
667   // Assert the reg is prepared to write, but not on the virtual stack yet
668   DCHECK(!Contains(reg) && stack_[stack_depth_].is(reg) &&
669       stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
670   stack_depth_++;
671 }
672
673
674 void LCodeGen::X87PrepareBinaryOp(
675     X87Register left, X87Register right, X87Register result) {
676   // You need to use DefineSameAsFirst for x87 instructions
677   DCHECK(result.is(left));
678   x87_stack_.Fxch(right, 1);
679   x87_stack_.Fxch(left);
680 }
681
682
683 void LCodeGen::X87Stack::FlushIfNecessary(LInstruction* instr, LCodeGen* cgen) {
684   if (stack_depth_ > 0 && instr->ClobbersDoubleRegisters(isolate())) {
685     bool double_inputs = instr->HasDoubleRegisterInput();
686
687     // Flush stack from tos down, since FreeX87() will mess with tos
688     for (int i = stack_depth_-1; i >= 0; i--) {
689       X87Register reg = stack_[i];
690       // Skip registers which contain the inputs for the next instruction
691       // when flushing the stack
692       if (double_inputs && instr->IsDoubleInput(reg, cgen)) {
693         continue;
694       }
695       Free(reg);
696       if (i < stack_depth_-1) i++;
697     }
698   }
699   if (instr->IsReturn()) {
700     while (stack_depth_ > 0) {
701       __ fstp(0);
702       stack_depth_--;
703     }
704     if (FLAG_debug_code && FLAG_enable_slow_asserts) __ VerifyX87StackDepth(0);
705   }
706 }
707
708
709 void LCodeGen::X87Stack::LeavingBlock(int current_block_id, LGoto* goto_instr,
710                                       LCodeGen* cgen) {
711   // For going to a joined block, an explicit LClobberDoubles is inserted before
712   // LGoto. Because all used x87 registers are spilled to stack slots. The
713   // ResolvePhis phase of register allocator could guarantee the two input's x87
714   // stacks have the same layout. So don't check stack_depth_ <= 1 here.
715   int goto_block_id = goto_instr->block_id();
716   if (current_block_id + 1 != goto_block_id) {
717     // If we have a value on the x87 stack on leaving a block, it must be a
718     // phi input. If the next block we compile is not the join block, we have
719     // to discard the stack state.
720     // Before discarding the stack state, we need to save it if the "goto block"
721     // has unreachable last predecessor when FLAG_unreachable_code_elimination.
722     if (FLAG_unreachable_code_elimination) {
723       int length = goto_instr->block()->predecessors()->length();
724       bool has_unreachable_last_predecessor = false;
725       for (int i = 0; i < length; i++) {
726         HBasicBlock* block = goto_instr->block()->predecessors()->at(i);
727         if (block->IsUnreachable() &&
728             (block->block_id() + 1) == goto_block_id) {
729           has_unreachable_last_predecessor = true;
730         }
731       }
732       if (has_unreachable_last_predecessor) {
733         if (cgen->x87_stack_map_.find(goto_block_id) ==
734             cgen->x87_stack_map_.end()) {
735           X87Stack* stack = new (cgen->zone()) X87Stack(*this);
736           cgen->x87_stack_map_.insert(std::make_pair(goto_block_id, stack));
737         }
738       }
739     }
740
741     // Discard the stack state.
742     stack_depth_ = 0;
743   }
744 }
745
746
747 void LCodeGen::EmitFlushX87ForDeopt() {
748   // The deoptimizer does not support X87 Registers. But as long as we
749   // deopt from a stub its not a problem, since we will re-materialize the
750   // original stub inputs, which can't be double registers.
751   // DCHECK(info()->IsStub());
752   if (FLAG_debug_code && FLAG_enable_slow_asserts) {
753     __ pushfd();
754     __ VerifyX87StackDepth(x87_stack_.depth());
755     __ popfd();
756   }
757
758   // Flush X87 stack in the deoptimizer entry.
759 }
760
761
762 Register LCodeGen::ToRegister(LOperand* op) const {
763   DCHECK(op->IsRegister());
764   return ToRegister(op->index());
765 }
766
767
768 X87Register LCodeGen::ToX87Register(LOperand* op) const {
769   DCHECK(op->IsDoubleRegister());
770   return ToX87Register(op->index());
771 }
772
773
774 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
775   return ToRepresentation(op, Representation::Integer32());
776 }
777
778
779 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
780                                    const Representation& r) const {
781   HConstant* constant = chunk_->LookupConstant(op);
782   int32_t value = constant->Integer32Value();
783   if (r.IsInteger32()) return value;
784   DCHECK(r.IsSmiOrTagged());
785   return reinterpret_cast<int32_t>(Smi::FromInt(value));
786 }
787
788
789 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
790   HConstant* constant = chunk_->LookupConstant(op);
791   DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
792   return constant->handle(isolate());
793 }
794
795
796 double LCodeGen::ToDouble(LConstantOperand* op) const {
797   HConstant* constant = chunk_->LookupConstant(op);
798   DCHECK(constant->HasDoubleValue());
799   return constant->DoubleValue();
800 }
801
802
803 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
804   HConstant* constant = chunk_->LookupConstant(op);
805   DCHECK(constant->HasExternalReferenceValue());
806   return constant->ExternalReferenceValue();
807 }
808
809
810 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
811   return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
812 }
813
814
815 bool LCodeGen::IsSmi(LConstantOperand* op) const {
816   return chunk_->LookupLiteralRepresentation(op).IsSmi();
817 }
818
819
820 static int ArgumentsOffsetWithoutFrame(int index) {
821   DCHECK(index < 0);
822   return -(index + 1) * kPointerSize + kPCOnStackSize;
823 }
824
825
826 Operand LCodeGen::ToOperand(LOperand* op) const {
827   if (op->IsRegister()) return Operand(ToRegister(op));
828   DCHECK(!op->IsDoubleRegister());
829   DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
830   if (NeedsEagerFrame()) {
831     return Operand(ebp, StackSlotOffset(op->index()));
832   } else {
833     // Retrieve parameter without eager stack-frame relative to the
834     // stack-pointer.
835     return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
836   }
837 }
838
839
840 Operand LCodeGen::HighOperand(LOperand* op) {
841   DCHECK(op->IsDoubleStackSlot());
842   if (NeedsEagerFrame()) {
843     return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
844   } else {
845     // Retrieve parameter without eager stack-frame relative to the
846     // stack-pointer.
847     return Operand(
848         esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
849   }
850 }
851
852
853 void LCodeGen::WriteTranslation(LEnvironment* environment,
854                                 Translation* translation) {
855   if (environment == NULL) return;
856
857   // The translation includes one command per value in the environment.
858   int translation_size = environment->translation_size();
859   // The output frame height does not include the parameters.
860   int height = translation_size - environment->parameter_count();
861
862   WriteTranslation(environment->outer(), translation);
863   bool has_closure_id = !info()->closure().is_null() &&
864       !info()->closure().is_identical_to(environment->closure());
865   int closure_id = has_closure_id
866       ? DefineDeoptimizationLiteral(environment->closure())
867       : Translation::kSelfLiteralId;
868   switch (environment->frame_type()) {
869     case JS_FUNCTION:
870       translation->BeginJSFrame(environment->ast_id(), closure_id, height);
871       break;
872     case JS_CONSTRUCT:
873       translation->BeginConstructStubFrame(closure_id, translation_size);
874       break;
875     case JS_GETTER:
876       DCHECK(translation_size == 1);
877       DCHECK(height == 0);
878       translation->BeginGetterStubFrame(closure_id);
879       break;
880     case JS_SETTER:
881       DCHECK(translation_size == 2);
882       DCHECK(height == 0);
883       translation->BeginSetterStubFrame(closure_id);
884       break;
885     case ARGUMENTS_ADAPTOR:
886       translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
887       break;
888     case STUB:
889       translation->BeginCompiledStubFrame();
890       break;
891     default:
892       UNREACHABLE();
893   }
894
895   int object_index = 0;
896   int dematerialized_index = 0;
897   for (int i = 0; i < translation_size; ++i) {
898     LOperand* value = environment->values()->at(i);
899     AddToTranslation(environment,
900                      translation,
901                      value,
902                      environment->HasTaggedValueAt(i),
903                      environment->HasUint32ValueAt(i),
904                      &object_index,
905                      &dematerialized_index);
906   }
907 }
908
909
910 void LCodeGen::AddToTranslation(LEnvironment* environment,
911                                 Translation* translation,
912                                 LOperand* op,
913                                 bool is_tagged,
914                                 bool is_uint32,
915                                 int* object_index_pointer,
916                                 int* dematerialized_index_pointer) {
917   if (op == LEnvironment::materialization_marker()) {
918     int object_index = (*object_index_pointer)++;
919     if (environment->ObjectIsDuplicateAt(object_index)) {
920       int dupe_of = environment->ObjectDuplicateOfAt(object_index);
921       translation->DuplicateObject(dupe_of);
922       return;
923     }
924     int object_length = environment->ObjectLengthAt(object_index);
925     if (environment->ObjectIsArgumentsAt(object_index)) {
926       translation->BeginArgumentsObject(object_length);
927     } else {
928       translation->BeginCapturedObject(object_length);
929     }
930     int dematerialized_index = *dematerialized_index_pointer;
931     int env_offset = environment->translation_size() + dematerialized_index;
932     *dematerialized_index_pointer += object_length;
933     for (int i = 0; i < object_length; ++i) {
934       LOperand* value = environment->values()->at(env_offset + i);
935       AddToTranslation(environment,
936                        translation,
937                        value,
938                        environment->HasTaggedValueAt(env_offset + i),
939                        environment->HasUint32ValueAt(env_offset + i),
940                        object_index_pointer,
941                        dematerialized_index_pointer);
942     }
943     return;
944   }
945
946   if (op->IsStackSlot()) {
947     if (is_tagged) {
948       translation->StoreStackSlot(op->index());
949     } else if (is_uint32) {
950       translation->StoreUint32StackSlot(op->index());
951     } else {
952       translation->StoreInt32StackSlot(op->index());
953     }
954   } else if (op->IsDoubleStackSlot()) {
955     translation->StoreDoubleStackSlot(op->index());
956   } else if (op->IsRegister()) {
957     Register reg = ToRegister(op);
958     if (is_tagged) {
959       translation->StoreRegister(reg);
960     } else if (is_uint32) {
961       translation->StoreUint32Register(reg);
962     } else {
963       translation->StoreInt32Register(reg);
964     }
965   } else if (op->IsDoubleRegister()) {
966     X87Register reg = ToX87Register(op);
967     translation->StoreDoubleRegister(reg);
968   } else if (op->IsConstantOperand()) {
969     HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
970     int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
971     translation->StoreLiteral(src_index);
972   } else {
973     UNREACHABLE();
974   }
975 }
976
977
978 void LCodeGen::CallCodeGeneric(Handle<Code> code,
979                                RelocInfo::Mode mode,
980                                LInstruction* instr,
981                                SafepointMode safepoint_mode) {
982   DCHECK(instr != NULL);
983   __ call(code, mode);
984   RecordSafepointWithLazyDeopt(instr, safepoint_mode);
985
986   // Signal that we don't inline smi code before these stubs in the
987   // optimizing code generator.
988   if (code->kind() == Code::BINARY_OP_IC ||
989       code->kind() == Code::COMPARE_IC) {
990     __ nop();
991   }
992 }
993
994
995 void LCodeGen::CallCode(Handle<Code> code,
996                         RelocInfo::Mode mode,
997                         LInstruction* instr) {
998   CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
999 }
1000
1001
1002 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
1003                            LInstruction* instr, SaveFPRegsMode save_doubles) {
1004   DCHECK(instr != NULL);
1005   DCHECK(instr->HasPointerMap());
1006
1007   __ CallRuntime(fun, argc, save_doubles);
1008
1009   RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1010
1011   DCHECK(info()->is_calling());
1012 }
1013
1014
1015 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1016   if (context->IsRegister()) {
1017     if (!ToRegister(context).is(esi)) {
1018       __ mov(esi, ToRegister(context));
1019     }
1020   } else if (context->IsStackSlot()) {
1021     __ mov(esi, ToOperand(context));
1022   } else if (context->IsConstantOperand()) {
1023     HConstant* constant =
1024         chunk_->LookupConstant(LConstantOperand::cast(context));
1025     __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1026   } else {
1027     UNREACHABLE();
1028   }
1029 }
1030
1031 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1032                                        int argc,
1033                                        LInstruction* instr,
1034                                        LOperand* context) {
1035   LoadContextFromDeferred(context);
1036
1037   __ CallRuntimeSaveDoubles(id);
1038   RecordSafepointWithRegisters(
1039       instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1040
1041   DCHECK(info()->is_calling());
1042 }
1043
1044
1045 void LCodeGen::RegisterEnvironmentForDeoptimization(
1046     LEnvironment* environment, Safepoint::DeoptMode mode) {
1047   environment->set_has_been_used();
1048   if (!environment->HasBeenRegistered()) {
1049     // Physical stack frame layout:
1050     // -x ............. -4  0 ..................................... y
1051     // [incoming arguments] [spill slots] [pushed outgoing arguments]
1052
1053     // Layout of the environment:
1054     // 0 ..................................................... size-1
1055     // [parameters] [locals] [expression stack including arguments]
1056
1057     // Layout of the translation:
1058     // 0 ........................................................ size - 1 + 4
1059     // [expression stack including arguments] [locals] [4 words] [parameters]
1060     // |>------------  translation_size ------------<|
1061
1062     int frame_count = 0;
1063     int jsframe_count = 0;
1064     for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1065       ++frame_count;
1066       if (e->frame_type() == JS_FUNCTION) {
1067         ++jsframe_count;
1068       }
1069     }
1070     Translation translation(&translations_, frame_count, jsframe_count, zone());
1071     WriteTranslation(environment, &translation);
1072     int deoptimization_index = deoptimizations_.length();
1073     int pc_offset = masm()->pc_offset();
1074     environment->Register(deoptimization_index,
1075                           translation.index(),
1076                           (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1077     deoptimizations_.Add(environment, zone());
1078   }
1079 }
1080
1081
1082 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1083                             Deoptimizer::DeoptReason deopt_reason,
1084                             Deoptimizer::BailoutType bailout_type) {
1085   LEnvironment* environment = instr->environment();
1086   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1087   DCHECK(environment->HasBeenRegistered());
1088   int id = environment->deoptimization_index();
1089   DCHECK(info()->IsOptimizing() || info()->IsStub());
1090   Address entry =
1091       Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1092   if (entry == NULL) {
1093     Abort(kBailoutWasNotPrepared);
1094     return;
1095   }
1096
1097   if (DeoptEveryNTimes()) {
1098     ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1099     Label no_deopt;
1100     __ pushfd();
1101     __ push(eax);
1102     __ mov(eax, Operand::StaticVariable(count));
1103     __ sub(eax, Immediate(1));
1104     __ j(not_zero, &no_deopt, Label::kNear);
1105     if (FLAG_trap_on_deopt) __ int3();
1106     __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1107     __ mov(Operand::StaticVariable(count), eax);
1108     __ pop(eax);
1109     __ popfd();
1110     DCHECK(frame_is_built_);
1111     // Put the x87 stack layout in TOS.
1112     if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1113     __ push(Immediate(x87_stack_.GetLayout()));
1114     __ fild_s(MemOperand(esp, 0));
1115     // Don't touch eflags.
1116     __ lea(esp, Operand(esp, kPointerSize));
1117     __ call(entry, RelocInfo::RUNTIME_ENTRY);
1118     __ bind(&no_deopt);
1119     __ mov(Operand::StaticVariable(count), eax);
1120     __ pop(eax);
1121     __ popfd();
1122   }
1123
1124   // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1125   // the correct location.
1126   {
1127     Label done;
1128     if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1129     if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1130
1131     int x87_stack_layout = x87_stack_.GetLayout();
1132     __ push(Immediate(x87_stack_layout));
1133     __ fild_s(MemOperand(esp, 0));
1134     // Don't touch eflags.
1135     __ lea(esp, Operand(esp, kPointerSize));
1136     __ bind(&done);
1137   }
1138
1139   if (info()->ShouldTrapOnDeopt()) {
1140     Label done;
1141     if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1142     __ int3();
1143     __ bind(&done);
1144   }
1145
1146   Deoptimizer::DeoptInfo deopt_info(instr->hydrogen_value()->position().raw(),
1147                                     instr->Mnemonic(), deopt_reason);
1148   DCHECK(info()->IsStub() || frame_is_built_);
1149   if (cc == no_condition && frame_is_built_) {
1150     DeoptComment(deopt_info);
1151     __ call(entry, RelocInfo::RUNTIME_ENTRY);
1152   } else {
1153     Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1154                                             !frame_is_built_);
1155     // We often have several deopts to the same entry, reuse the last
1156     // jump entry if this is the case.
1157     if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1158         jump_table_.is_empty() ||
1159         !table_entry.IsEquivalentTo(jump_table_.last())) {
1160       jump_table_.Add(table_entry, zone());
1161     }
1162     if (cc == no_condition) {
1163       __ jmp(&jump_table_.last().label);
1164     } else {
1165       __ j(cc, &jump_table_.last().label);
1166     }
1167   }
1168 }
1169
1170
1171 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1172                             Deoptimizer::DeoptReason deopt_reason) {
1173   Deoptimizer::BailoutType bailout_type = info()->IsStub()
1174       ? Deoptimizer::LAZY
1175       : Deoptimizer::EAGER;
1176   DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
1177 }
1178
1179
1180 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1181   int length = deoptimizations_.length();
1182   if (length == 0) return;
1183   Handle<DeoptimizationInputData> data =
1184       DeoptimizationInputData::New(isolate(), length, TENURED);
1185
1186   Handle<ByteArray> translations =
1187       translations_.CreateByteArray(isolate()->factory());
1188   data->SetTranslationByteArray(*translations);
1189   data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1190   data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1191   if (info_->IsOptimizing()) {
1192     // Reference to shared function info does not change between phases.
1193     AllowDeferredHandleDereference allow_handle_dereference;
1194     data->SetSharedFunctionInfo(*info_->shared_info());
1195   } else {
1196     data->SetSharedFunctionInfo(Smi::FromInt(0));
1197   }
1198   data->SetWeakCellCache(Smi::FromInt(0));
1199
1200   Handle<FixedArray> literals =
1201       factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1202   { AllowDeferredHandleDereference copy_handles;
1203     for (int i = 0; i < deoptimization_literals_.length(); i++) {
1204       literals->set(i, *deoptimization_literals_[i]);
1205     }
1206     data->SetLiteralArray(*literals);
1207   }
1208
1209   data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1210   data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1211
1212   // Populate the deoptimization entries.
1213   for (int i = 0; i < length; i++) {
1214     LEnvironment* env = deoptimizations_[i];
1215     data->SetAstId(i, env->ast_id());
1216     data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1217     data->SetArgumentsStackHeight(i,
1218                                   Smi::FromInt(env->arguments_stack_height()));
1219     data->SetPc(i, Smi::FromInt(env->pc_offset()));
1220   }
1221   code->set_deoptimization_data(*data);
1222 }
1223
1224
1225 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
1226   int result = deoptimization_literals_.length();
1227   for (int i = 0; i < deoptimization_literals_.length(); ++i) {
1228     if (deoptimization_literals_[i].is_identical_to(literal)) return i;
1229   }
1230   deoptimization_literals_.Add(literal, zone());
1231   return result;
1232 }
1233
1234
1235 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1236   DCHECK(deoptimization_literals_.length() == 0);
1237
1238   const ZoneList<Handle<JSFunction> >* inlined_closures =
1239       chunk()->inlined_closures();
1240
1241   for (int i = 0, length = inlined_closures->length();
1242        i < length;
1243        i++) {
1244     DefineDeoptimizationLiteral(inlined_closures->at(i));
1245   }
1246
1247   inlined_function_count_ = deoptimization_literals_.length();
1248 }
1249
1250
1251 void LCodeGen::RecordSafepointWithLazyDeopt(
1252     LInstruction* instr, SafepointMode safepoint_mode) {
1253   if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1254     RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1255   } else {
1256     DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1257     RecordSafepointWithRegisters(
1258         instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1259   }
1260 }
1261
1262
1263 void LCodeGen::RecordSafepoint(
1264     LPointerMap* pointers,
1265     Safepoint::Kind kind,
1266     int arguments,
1267     Safepoint::DeoptMode deopt_mode) {
1268   DCHECK(kind == expected_safepoint_kind_);
1269   const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1270   Safepoint safepoint =
1271       safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1272   for (int i = 0; i < operands->length(); i++) {
1273     LOperand* pointer = operands->at(i);
1274     if (pointer->IsStackSlot()) {
1275       safepoint.DefinePointerSlot(pointer->index(), zone());
1276     } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1277       safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1278     }
1279   }
1280 }
1281
1282
1283 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1284                                Safepoint::DeoptMode mode) {
1285   RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1286 }
1287
1288
1289 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1290   LPointerMap empty_pointers(zone());
1291   RecordSafepoint(&empty_pointers, mode);
1292 }
1293
1294
1295 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1296                                             int arguments,
1297                                             Safepoint::DeoptMode mode) {
1298   RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1299 }
1300
1301
1302 void LCodeGen::RecordAndWritePosition(int position) {
1303   if (position == RelocInfo::kNoPosition) return;
1304   masm()->positions_recorder()->RecordPosition(position);
1305   masm()->positions_recorder()->WriteRecordedPositions();
1306 }
1307
1308
1309 static const char* LabelType(LLabel* label) {
1310   if (label->is_loop_header()) return " (loop header)";
1311   if (label->is_osr_entry()) return " (OSR entry)";
1312   return "";
1313 }
1314
1315
1316 void LCodeGen::DoLabel(LLabel* label) {
1317   Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1318           current_instruction_,
1319           label->hydrogen_value()->id(),
1320           label->block_id(),
1321           LabelType(label));
1322   __ bind(label->label());
1323   current_block_ = label->block_id();
1324   if (label->block()->predecessors()->length() > 1) {
1325     // A join block's x87 stack is that of its last visited predecessor.
1326     // If the last visited predecessor block is unreachable, the stack state
1327     // will be wrong. In such case, use the x87 stack of reachable predecessor.
1328     X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1329     // Restore x87 stack.
1330     if (it != x87_stack_map_.end()) {
1331       x87_stack_ = *(it->second);
1332     }
1333   }
1334   DoGap(label);
1335 }
1336
1337
1338 void LCodeGen::DoParallelMove(LParallelMove* move) {
1339   resolver_.Resolve(move);
1340 }
1341
1342
1343 void LCodeGen::DoGap(LGap* gap) {
1344   for (int i = LGap::FIRST_INNER_POSITION;
1345        i <= LGap::LAST_INNER_POSITION;
1346        i++) {
1347     LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1348     LParallelMove* move = gap->GetParallelMove(inner_pos);
1349     if (move != NULL) DoParallelMove(move);
1350   }
1351 }
1352
1353
1354 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1355   DoGap(instr);
1356 }
1357
1358
1359 void LCodeGen::DoParameter(LParameter* instr) {
1360   // Nothing to do.
1361 }
1362
1363
1364 void LCodeGen::DoCallStub(LCallStub* instr) {
1365   DCHECK(ToRegister(instr->context()).is(esi));
1366   DCHECK(ToRegister(instr->result()).is(eax));
1367   switch (instr->hydrogen()->major_key()) {
1368     case CodeStub::RegExpExec: {
1369       RegExpExecStub stub(isolate());
1370       CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1371       break;
1372     }
1373     case CodeStub::SubString: {
1374       SubStringStub stub(isolate());
1375       CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1376       break;
1377     }
1378     case CodeStub::StringCompare: {
1379       StringCompareStub stub(isolate());
1380       CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1381       break;
1382     }
1383     default:
1384       UNREACHABLE();
1385   }
1386 }
1387
1388
1389 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1390   GenerateOsrPrologue();
1391 }
1392
1393
1394 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1395   Register dividend = ToRegister(instr->dividend());
1396   int32_t divisor = instr->divisor();
1397   DCHECK(dividend.is(ToRegister(instr->result())));
1398
1399   // Theoretically, a variation of the branch-free code for integer division by
1400   // a power of 2 (calculating the remainder via an additional multiplication
1401   // (which gets simplified to an 'and') and subtraction) should be faster, and
1402   // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1403   // indicate that positive dividends are heavily favored, so the branching
1404   // version performs better.
1405   HMod* hmod = instr->hydrogen();
1406   int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1407   Label dividend_is_not_negative, done;
1408   if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1409     __ test(dividend, dividend);
1410     __ j(not_sign, &dividend_is_not_negative, Label::kNear);
1411     // Note that this is correct even for kMinInt operands.
1412     __ neg(dividend);
1413     __ and_(dividend, mask);
1414     __ neg(dividend);
1415     if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1416       DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1417     }
1418     __ jmp(&done, Label::kNear);
1419   }
1420
1421   __ bind(&dividend_is_not_negative);
1422   __ and_(dividend, mask);
1423   __ bind(&done);
1424 }
1425
1426
1427 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1428   Register dividend = ToRegister(instr->dividend());
1429   int32_t divisor = instr->divisor();
1430   DCHECK(ToRegister(instr->result()).is(eax));
1431
1432   if (divisor == 0) {
1433     DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1434     return;
1435   }
1436
1437   __ TruncatingDiv(dividend, Abs(divisor));
1438   __ imul(edx, edx, Abs(divisor));
1439   __ mov(eax, dividend);
1440   __ sub(eax, edx);
1441
1442   // Check for negative zero.
1443   HMod* hmod = instr->hydrogen();
1444   if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1445     Label remainder_not_zero;
1446     __ j(not_zero, &remainder_not_zero, Label::kNear);
1447     __ cmp(dividend, Immediate(0));
1448     DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1449     __ bind(&remainder_not_zero);
1450   }
1451 }
1452
1453
1454 void LCodeGen::DoModI(LModI* instr) {
1455   HMod* hmod = instr->hydrogen();
1456
1457   Register left_reg = ToRegister(instr->left());
1458   DCHECK(left_reg.is(eax));
1459   Register right_reg = ToRegister(instr->right());
1460   DCHECK(!right_reg.is(eax));
1461   DCHECK(!right_reg.is(edx));
1462   Register result_reg = ToRegister(instr->result());
1463   DCHECK(result_reg.is(edx));
1464
1465   Label done;
1466   // Check for x % 0, idiv would signal a divide error. We have to
1467   // deopt in this case because we can't return a NaN.
1468   if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1469     __ test(right_reg, Operand(right_reg));
1470     DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1471   }
1472
1473   // Check for kMinInt % -1, idiv would signal a divide error. We
1474   // have to deopt if we care about -0, because we can't return that.
1475   if (hmod->CheckFlag(HValue::kCanOverflow)) {
1476     Label no_overflow_possible;
1477     __ cmp(left_reg, kMinInt);
1478     __ j(not_equal, &no_overflow_possible, Label::kNear);
1479     __ cmp(right_reg, -1);
1480     if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1481       DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1482     } else {
1483       __ j(not_equal, &no_overflow_possible, Label::kNear);
1484       __ Move(result_reg, Immediate(0));
1485       __ jmp(&done, Label::kNear);
1486     }
1487     __ bind(&no_overflow_possible);
1488   }
1489
1490   // Sign extend dividend in eax into edx:eax.
1491   __ cdq();
1492
1493   // If we care about -0, test if the dividend is <0 and the result is 0.
1494   if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1495     Label positive_left;
1496     __ test(left_reg, Operand(left_reg));
1497     __ j(not_sign, &positive_left, Label::kNear);
1498     __ idiv(right_reg);
1499     __ test(result_reg, Operand(result_reg));
1500     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1501     __ jmp(&done, Label::kNear);
1502     __ bind(&positive_left);
1503   }
1504   __ idiv(right_reg);
1505   __ bind(&done);
1506 }
1507
1508
1509 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1510   Register dividend = ToRegister(instr->dividend());
1511   int32_t divisor = instr->divisor();
1512   Register result = ToRegister(instr->result());
1513   DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1514   DCHECK(!result.is(dividend));
1515
1516   // Check for (0 / -x) that will produce negative zero.
1517   HDiv* hdiv = instr->hydrogen();
1518   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1519     __ test(dividend, dividend);
1520     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1521   }
1522   // Check for (kMinInt / -1).
1523   if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1524     __ cmp(dividend, kMinInt);
1525     DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1526   }
1527   // Deoptimize if remainder will not be 0.
1528   if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1529       divisor != 1 && divisor != -1) {
1530     int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1531     __ test(dividend, Immediate(mask));
1532     DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1533   }
1534   __ Move(result, dividend);
1535   int32_t shift = WhichPowerOf2Abs(divisor);
1536   if (shift > 0) {
1537     // The arithmetic shift is always OK, the 'if' is an optimization only.
1538     if (shift > 1) __ sar(result, 31);
1539     __ shr(result, 32 - shift);
1540     __ add(result, dividend);
1541     __ sar(result, shift);
1542   }
1543   if (divisor < 0) __ neg(result);
1544 }
1545
1546
1547 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1548   Register dividend = ToRegister(instr->dividend());
1549   int32_t divisor = instr->divisor();
1550   DCHECK(ToRegister(instr->result()).is(edx));
1551
1552   if (divisor == 0) {
1553     DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1554     return;
1555   }
1556
1557   // Check for (0 / -x) that will produce negative zero.
1558   HDiv* hdiv = instr->hydrogen();
1559   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1560     __ test(dividend, dividend);
1561     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1562   }
1563
1564   __ TruncatingDiv(dividend, Abs(divisor));
1565   if (divisor < 0) __ neg(edx);
1566
1567   if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1568     __ mov(eax, edx);
1569     __ imul(eax, eax, divisor);
1570     __ sub(eax, dividend);
1571     DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1572   }
1573 }
1574
1575
1576 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1577 void LCodeGen::DoDivI(LDivI* instr) {
1578   HBinaryOperation* hdiv = instr->hydrogen();
1579   Register dividend = ToRegister(instr->dividend());
1580   Register divisor = ToRegister(instr->divisor());
1581   Register remainder = ToRegister(instr->temp());
1582   DCHECK(dividend.is(eax));
1583   DCHECK(remainder.is(edx));
1584   DCHECK(ToRegister(instr->result()).is(eax));
1585   DCHECK(!divisor.is(eax));
1586   DCHECK(!divisor.is(edx));
1587
1588   // Check for x / 0.
1589   if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1590     __ test(divisor, divisor);
1591     DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1592   }
1593
1594   // Check for (0 / -x) that will produce negative zero.
1595   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1596     Label dividend_not_zero;
1597     __ test(dividend, dividend);
1598     __ j(not_zero, &dividend_not_zero, Label::kNear);
1599     __ test(divisor, divisor);
1600     DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1601     __ bind(&dividend_not_zero);
1602   }
1603
1604   // Check for (kMinInt / -1).
1605   if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1606     Label dividend_not_min_int;
1607     __ cmp(dividend, kMinInt);
1608     __ j(not_zero, &dividend_not_min_int, Label::kNear);
1609     __ cmp(divisor, -1);
1610     DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1611     __ bind(&dividend_not_min_int);
1612   }
1613
1614   // Sign extend to edx (= remainder).
1615   __ cdq();
1616   __ idiv(divisor);
1617
1618   if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1619     // Deoptimize if remainder is not 0.
1620     __ test(remainder, remainder);
1621     DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1622   }
1623 }
1624
1625
1626 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1627   Register dividend = ToRegister(instr->dividend());
1628   int32_t divisor = instr->divisor();
1629   DCHECK(dividend.is(ToRegister(instr->result())));
1630
1631   // If the divisor is positive, things are easy: There can be no deopts and we
1632   // can simply do an arithmetic right shift.
1633   if (divisor == 1) return;
1634   int32_t shift = WhichPowerOf2Abs(divisor);
1635   if (divisor > 1) {
1636     __ sar(dividend, shift);
1637     return;
1638   }
1639
1640   // If the divisor is negative, we have to negate and handle edge cases.
1641   __ neg(dividend);
1642   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1643     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1644   }
1645
1646   // Dividing by -1 is basically negation, unless we overflow.
1647   if (divisor == -1) {
1648     if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1649       DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1650     }
1651     return;
1652   }
1653
1654   // If the negation could not overflow, simply shifting is OK.
1655   if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1656     __ sar(dividend, shift);
1657     return;
1658   }
1659
1660   Label not_kmin_int, done;
1661   __ j(no_overflow, &not_kmin_int, Label::kNear);
1662   __ mov(dividend, Immediate(kMinInt / divisor));
1663   __ jmp(&done, Label::kNear);
1664   __ bind(&not_kmin_int);
1665   __ sar(dividend, shift);
1666   __ bind(&done);
1667 }
1668
1669
1670 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1671   Register dividend = ToRegister(instr->dividend());
1672   int32_t divisor = instr->divisor();
1673   DCHECK(ToRegister(instr->result()).is(edx));
1674
1675   if (divisor == 0) {
1676     DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1677     return;
1678   }
1679
1680   // Check for (0 / -x) that will produce negative zero.
1681   HMathFloorOfDiv* hdiv = instr->hydrogen();
1682   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1683     __ test(dividend, dividend);
1684     DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1685   }
1686
1687   // Easy case: We need no dynamic check for the dividend and the flooring
1688   // division is the same as the truncating division.
1689   if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1690       (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1691     __ TruncatingDiv(dividend, Abs(divisor));
1692     if (divisor < 0) __ neg(edx);
1693     return;
1694   }
1695
1696   // In the general case we may need to adjust before and after the truncating
1697   // division to get a flooring division.
1698   Register temp = ToRegister(instr->temp3());
1699   DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1700   Label needs_adjustment, done;
1701   __ cmp(dividend, Immediate(0));
1702   __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1703   __ TruncatingDiv(dividend, Abs(divisor));
1704   if (divisor < 0) __ neg(edx);
1705   __ jmp(&done, Label::kNear);
1706   __ bind(&needs_adjustment);
1707   __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1708   __ TruncatingDiv(temp, Abs(divisor));
1709   if (divisor < 0) __ neg(edx);
1710   __ dec(edx);
1711   __ bind(&done);
1712 }
1713
1714
1715 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1716 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1717   HBinaryOperation* hdiv = instr->hydrogen();
1718   Register dividend = ToRegister(instr->dividend());
1719   Register divisor = ToRegister(instr->divisor());
1720   Register remainder = ToRegister(instr->temp());
1721   Register result = ToRegister(instr->result());
1722   DCHECK(dividend.is(eax));
1723   DCHECK(remainder.is(edx));
1724   DCHECK(result.is(eax));
1725   DCHECK(!divisor.is(eax));
1726   DCHECK(!divisor.is(edx));
1727
1728   // Check for x / 0.
1729   if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1730     __ test(divisor, divisor);
1731     DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1732   }
1733
1734   // Check for (0 / -x) that will produce negative zero.
1735   if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1736     Label dividend_not_zero;
1737     __ test(dividend, dividend);
1738     __ j(not_zero, &dividend_not_zero, Label::kNear);
1739     __ test(divisor, divisor);
1740     DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1741     __ bind(&dividend_not_zero);
1742   }
1743
1744   // Check for (kMinInt / -1).
1745   if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1746     Label dividend_not_min_int;
1747     __ cmp(dividend, kMinInt);
1748     __ j(not_zero, &dividend_not_min_int, Label::kNear);
1749     __ cmp(divisor, -1);
1750     DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1751     __ bind(&dividend_not_min_int);
1752   }
1753
1754   // Sign extend to edx (= remainder).
1755   __ cdq();
1756   __ idiv(divisor);
1757
1758   Label done;
1759   __ test(remainder, remainder);
1760   __ j(zero, &done, Label::kNear);
1761   __ xor_(remainder, divisor);
1762   __ sar(remainder, 31);
1763   __ add(result, remainder);
1764   __ bind(&done);
1765 }
1766
1767
1768 void LCodeGen::DoMulI(LMulI* instr) {
1769   Register left = ToRegister(instr->left());
1770   LOperand* right = instr->right();
1771
1772   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1773     __ mov(ToRegister(instr->temp()), left);
1774   }
1775
1776   if (right->IsConstantOperand()) {
1777     // Try strength reductions on the multiplication.
1778     // All replacement instructions are at most as long as the imul
1779     // and have better latency.
1780     int constant = ToInteger32(LConstantOperand::cast(right));
1781     if (constant == -1) {
1782       __ neg(left);
1783     } else if (constant == 0) {
1784       __ xor_(left, Operand(left));
1785     } else if (constant == 2) {
1786       __ add(left, Operand(left));
1787     } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1788       // If we know that the multiplication can't overflow, it's safe to
1789       // use instructions that don't set the overflow flag for the
1790       // multiplication.
1791       switch (constant) {
1792         case 1:
1793           // Do nothing.
1794           break;
1795         case 3:
1796           __ lea(left, Operand(left, left, times_2, 0));
1797           break;
1798         case 4:
1799           __ shl(left, 2);
1800           break;
1801         case 5:
1802           __ lea(left, Operand(left, left, times_4, 0));
1803           break;
1804         case 8:
1805           __ shl(left, 3);
1806           break;
1807         case 9:
1808           __ lea(left, Operand(left, left, times_8, 0));
1809           break;
1810         case 16:
1811           __ shl(left, 4);
1812           break;
1813         default:
1814           __ imul(left, left, constant);
1815           break;
1816       }
1817     } else {
1818       __ imul(left, left, constant);
1819     }
1820   } else {
1821     if (instr->hydrogen()->representation().IsSmi()) {
1822       __ SmiUntag(left);
1823     }
1824     __ imul(left, ToOperand(right));
1825   }
1826
1827   if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1828     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1829   }
1830
1831   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1832     // Bail out if the result is supposed to be negative zero.
1833     Label done;
1834     __ test(left, Operand(left));
1835     __ j(not_zero, &done);
1836     if (right->IsConstantOperand()) {
1837       if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1838         DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1839       } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1840         __ cmp(ToRegister(instr->temp()), Immediate(0));
1841         DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1842       }
1843     } else {
1844       // Test the non-zero operand for negative sign.
1845       __ or_(ToRegister(instr->temp()), ToOperand(right));
1846       DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1847     }
1848     __ bind(&done);
1849   }
1850 }
1851
1852
1853 void LCodeGen::DoBitI(LBitI* instr) {
1854   LOperand* left = instr->left();
1855   LOperand* right = instr->right();
1856   DCHECK(left->Equals(instr->result()));
1857   DCHECK(left->IsRegister());
1858
1859   if (right->IsConstantOperand()) {
1860     int32_t right_operand =
1861         ToRepresentation(LConstantOperand::cast(right),
1862                          instr->hydrogen()->representation());
1863     switch (instr->op()) {
1864       case Token::BIT_AND:
1865         __ and_(ToRegister(left), right_operand);
1866         break;
1867       case Token::BIT_OR:
1868         __ or_(ToRegister(left), right_operand);
1869         break;
1870       case Token::BIT_XOR:
1871         if (right_operand == int32_t(~0)) {
1872           __ not_(ToRegister(left));
1873         } else {
1874           __ xor_(ToRegister(left), right_operand);
1875         }
1876         break;
1877       default:
1878         UNREACHABLE();
1879         break;
1880     }
1881   } else {
1882     switch (instr->op()) {
1883       case Token::BIT_AND:
1884         __ and_(ToRegister(left), ToOperand(right));
1885         break;
1886       case Token::BIT_OR:
1887         __ or_(ToRegister(left), ToOperand(right));
1888         break;
1889       case Token::BIT_XOR:
1890         __ xor_(ToRegister(left), ToOperand(right));
1891         break;
1892       default:
1893         UNREACHABLE();
1894         break;
1895     }
1896   }
1897 }
1898
1899
1900 void LCodeGen::DoShiftI(LShiftI* instr) {
1901   LOperand* left = instr->left();
1902   LOperand* right = instr->right();
1903   DCHECK(left->Equals(instr->result()));
1904   DCHECK(left->IsRegister());
1905   if (right->IsRegister()) {
1906     DCHECK(ToRegister(right).is(ecx));
1907
1908     switch (instr->op()) {
1909       case Token::ROR:
1910         __ ror_cl(ToRegister(left));
1911         break;
1912       case Token::SAR:
1913         __ sar_cl(ToRegister(left));
1914         break;
1915       case Token::SHR:
1916         __ shr_cl(ToRegister(left));
1917         if (instr->can_deopt()) {
1918           __ test(ToRegister(left), ToRegister(left));
1919           DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1920         }
1921         break;
1922       case Token::SHL:
1923         __ shl_cl(ToRegister(left));
1924         break;
1925       default:
1926         UNREACHABLE();
1927         break;
1928     }
1929   } else {
1930     int value = ToInteger32(LConstantOperand::cast(right));
1931     uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1932     switch (instr->op()) {
1933       case Token::ROR:
1934         if (shift_count == 0 && instr->can_deopt()) {
1935           __ test(ToRegister(left), ToRegister(left));
1936           DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1937         } else {
1938           __ ror(ToRegister(left), shift_count);
1939         }
1940         break;
1941       case Token::SAR:
1942         if (shift_count != 0) {
1943           __ sar(ToRegister(left), shift_count);
1944         }
1945         break;
1946       case Token::SHR:
1947         if (shift_count != 0) {
1948           __ shr(ToRegister(left), shift_count);
1949         } else if (instr->can_deopt()) {
1950           __ test(ToRegister(left), ToRegister(left));
1951           DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1952         }
1953         break;
1954       case Token::SHL:
1955         if (shift_count != 0) {
1956           if (instr->hydrogen_value()->representation().IsSmi() &&
1957               instr->can_deopt()) {
1958             if (shift_count != 1) {
1959               __ shl(ToRegister(left), shift_count - 1);
1960             }
1961             __ SmiTag(ToRegister(left));
1962             DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1963           } else {
1964             __ shl(ToRegister(left), shift_count);
1965           }
1966         }
1967         break;
1968       default:
1969         UNREACHABLE();
1970         break;
1971     }
1972   }
1973 }
1974
1975
1976 void LCodeGen::DoSubI(LSubI* instr) {
1977   LOperand* left = instr->left();
1978   LOperand* right = instr->right();
1979   DCHECK(left->Equals(instr->result()));
1980
1981   if (right->IsConstantOperand()) {
1982     __ sub(ToOperand(left),
1983            ToImmediate(right, instr->hydrogen()->representation()));
1984   } else {
1985     __ sub(ToRegister(left), ToOperand(right));
1986   }
1987   if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1988     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1989   }
1990 }
1991
1992
1993 void LCodeGen::DoConstantI(LConstantI* instr) {
1994   __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1995 }
1996
1997
1998 void LCodeGen::DoConstantS(LConstantS* instr) {
1999   __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2000 }
2001
2002
2003 void LCodeGen::DoConstantD(LConstantD* instr) {
2004   uint64_t const bits = instr->bits();
2005   uint32_t const lower = static_cast<uint32_t>(bits);
2006   uint32_t const upper = static_cast<uint32_t>(bits >> 32);
2007   DCHECK(instr->result()->IsDoubleRegister());
2008
2009   __ push(Immediate(upper));
2010   __ push(Immediate(lower));
2011   X87Register reg = ToX87Register(instr->result());
2012   X87Mov(reg, Operand(esp, 0));
2013   __ add(Operand(esp), Immediate(kDoubleSize));
2014 }
2015
2016
2017 void LCodeGen::DoConstantE(LConstantE* instr) {
2018   __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2019 }
2020
2021
2022 void LCodeGen::DoConstantT(LConstantT* instr) {
2023   Register reg = ToRegister(instr->result());
2024   Handle<Object> object = instr->value(isolate());
2025   AllowDeferredHandleDereference smi_check;
2026   __ LoadObject(reg, object);
2027 }
2028
2029
2030 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2031   Register result = ToRegister(instr->result());
2032   Register map = ToRegister(instr->value());
2033   __ EnumLength(result, map);
2034 }
2035
2036
2037 void LCodeGen::DoDateField(LDateField* instr) {
2038   Register object = ToRegister(instr->date());
2039   Register result = ToRegister(instr->result());
2040   Register scratch = ToRegister(instr->temp());
2041   Smi* index = instr->index();
2042   Label runtime, done;
2043   DCHECK(object.is(result));
2044   DCHECK(object.is(eax));
2045
2046   __ test(object, Immediate(kSmiTagMask));
2047   DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2048   __ CmpObjectType(object, JS_DATE_TYPE, scratch);
2049   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
2050
2051   if (index->value() == 0) {
2052     __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2053   } else {
2054     if (index->value() < JSDate::kFirstUncachedField) {
2055       ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2056       __ mov(scratch, Operand::StaticVariable(stamp));
2057       __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2058       __ j(not_equal, &runtime, Label::kNear);
2059       __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2060                                           kPointerSize * index->value()));
2061       __ jmp(&done, Label::kNear);
2062     }
2063     __ bind(&runtime);
2064     __ PrepareCallCFunction(2, scratch);
2065     __ mov(Operand(esp, 0), object);
2066     __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2067     __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2068     __ bind(&done);
2069   }
2070 }
2071
2072
2073 Operand LCodeGen::BuildSeqStringOperand(Register string,
2074                                         LOperand* index,
2075                                         String::Encoding encoding) {
2076   if (index->IsConstantOperand()) {
2077     int offset = ToRepresentation(LConstantOperand::cast(index),
2078                                   Representation::Integer32());
2079     if (encoding == String::TWO_BYTE_ENCODING) {
2080       offset *= kUC16Size;
2081     }
2082     STATIC_ASSERT(kCharSize == 1);
2083     return FieldOperand(string, SeqString::kHeaderSize + offset);
2084   }
2085   return FieldOperand(
2086       string, ToRegister(index),
2087       encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2088       SeqString::kHeaderSize);
2089 }
2090
2091
2092 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2093   String::Encoding encoding = instr->hydrogen()->encoding();
2094   Register result = ToRegister(instr->result());
2095   Register string = ToRegister(instr->string());
2096
2097   if (FLAG_debug_code) {
2098     __ push(string);
2099     __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2100     __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2101
2102     __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2103     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2104     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2105     __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2106                              ? one_byte_seq_type : two_byte_seq_type));
2107     __ Check(equal, kUnexpectedStringType);
2108     __ pop(string);
2109   }
2110
2111   Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2112   if (encoding == String::ONE_BYTE_ENCODING) {
2113     __ movzx_b(result, operand);
2114   } else {
2115     __ movzx_w(result, operand);
2116   }
2117 }
2118
2119
2120 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2121   String::Encoding encoding = instr->hydrogen()->encoding();
2122   Register string = ToRegister(instr->string());
2123
2124   if (FLAG_debug_code) {
2125     Register value = ToRegister(instr->value());
2126     Register index = ToRegister(instr->index());
2127     static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2128     static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2129     int encoding_mask =
2130         instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2131         ? one_byte_seq_type : two_byte_seq_type;
2132     __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2133   }
2134
2135   Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2136   if (instr->value()->IsConstantOperand()) {
2137     int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2138                                  Representation::Integer32());
2139     DCHECK_LE(0, value);
2140     if (encoding == String::ONE_BYTE_ENCODING) {
2141       DCHECK_LE(value, String::kMaxOneByteCharCode);
2142       __ mov_b(operand, static_cast<int8_t>(value));
2143     } else {
2144       DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2145       __ mov_w(operand, static_cast<int16_t>(value));
2146     }
2147   } else {
2148     Register value = ToRegister(instr->value());
2149     if (encoding == String::ONE_BYTE_ENCODING) {
2150       __ mov_b(operand, value);
2151     } else {
2152       __ mov_w(operand, value);
2153     }
2154   }
2155 }
2156
2157
2158 void LCodeGen::DoAddI(LAddI* instr) {
2159   LOperand* left = instr->left();
2160   LOperand* right = instr->right();
2161
2162   if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2163     if (right->IsConstantOperand()) {
2164       int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2165                                         instr->hydrogen()->representation());
2166       __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2167     } else {
2168       Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2169       __ lea(ToRegister(instr->result()), address);
2170     }
2171   } else {
2172     if (right->IsConstantOperand()) {
2173       __ add(ToOperand(left),
2174              ToImmediate(right, instr->hydrogen()->representation()));
2175     } else {
2176       __ add(ToRegister(left), ToOperand(right));
2177     }
2178     if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2179       DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2180     }
2181   }
2182 }
2183
2184
2185 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2186   LOperand* left = instr->left();
2187   LOperand* right = instr->right();
2188   DCHECK(left->Equals(instr->result()));
2189   HMathMinMax::Operation operation = instr->hydrogen()->operation();
2190   if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2191     Label return_left;
2192     Condition condition = (operation == HMathMinMax::kMathMin)
2193         ? less_equal
2194         : greater_equal;
2195     if (right->IsConstantOperand()) {
2196       Operand left_op = ToOperand(left);
2197       Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2198                                         instr->hydrogen()->representation());
2199       __ cmp(left_op, immediate);
2200       __ j(condition, &return_left, Label::kNear);
2201       __ mov(left_op, immediate);
2202     } else {
2203       Register left_reg = ToRegister(left);
2204       Operand right_op = ToOperand(right);
2205       __ cmp(left_reg, right_op);
2206       __ j(condition, &return_left, Label::kNear);
2207       __ mov(left_reg, right_op);
2208     }
2209     __ bind(&return_left);
2210   } else {
2211     DCHECK(instr->hydrogen()->representation().IsDouble());
2212     Label check_nan_left, check_zero, return_left, return_right;
2213     Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2214     X87Register left_reg = ToX87Register(left);
2215     X87Register right_reg = ToX87Register(right);
2216
2217     X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2218     __ fld(1);
2219     __ fld(1);
2220     __ FCmp();
2221     __ j(parity_even, &check_nan_left, Label::kNear);  // At least one NaN.
2222     __ j(equal, &check_zero, Label::kNear);            // left == right.
2223     __ j(condition, &return_left, Label::kNear);
2224     __ jmp(&return_right, Label::kNear);
2225
2226     __ bind(&check_zero);
2227     __ fld(0);
2228     __ fldz();
2229     __ FCmp();
2230     __ j(not_equal, &return_left, Label::kNear);  // left == right != 0.
2231     // At this point, both left and right are either 0 or -0.
2232     if (operation == HMathMinMax::kMathMin) {
2233       // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2234       // load it to left.
2235       Register scratch_reg = ToRegister(instr->temp());
2236       __ fld(1);
2237       __ fld(1);
2238       __ sub(esp, Immediate(2 * kPointerSize));
2239       __ fstp_s(MemOperand(esp, 0));
2240       __ fstp_s(MemOperand(esp, kPointerSize));
2241       __ pop(scratch_reg);
2242       __ xor_(MemOperand(esp, 0), scratch_reg);
2243       X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2244       __ pop(scratch_reg);  // restore esp
2245     } else {
2246       // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2247       X87Fxch(left_reg);
2248       __ fadd(1);
2249     }
2250     __ jmp(&return_left, Label::kNear);
2251
2252     __ bind(&check_nan_left);
2253     __ fld(0);
2254     __ fld(0);
2255     __ FCmp();                                      // NaN check.
2256     __ j(parity_even, &return_left, Label::kNear);  // left == NaN.
2257
2258     __ bind(&return_right);
2259     X87Fxch(left_reg);
2260     X87Mov(left_reg, right_reg);
2261
2262     __ bind(&return_left);
2263   }
2264 }
2265
2266
2267 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2268   X87Register left = ToX87Register(instr->left());
2269   X87Register right = ToX87Register(instr->right());
2270   X87Register result = ToX87Register(instr->result());
2271   if (instr->op() != Token::MOD) {
2272     X87PrepareBinaryOp(left, right, result);
2273   }
2274   // Set the precision control to double-precision.
2275   __ X87SetFPUCW(0x027F);
2276   switch (instr->op()) {
2277     case Token::ADD:
2278       __ fadd_i(1);
2279       break;
2280     case Token::SUB:
2281       __ fsub_i(1);
2282       break;
2283     case Token::MUL:
2284       __ fmul_i(1);
2285       break;
2286     case Token::DIV:
2287       __ fdiv_i(1);
2288       break;
2289     case Token::MOD: {
2290       // Pass two doubles as arguments on the stack.
2291       __ PrepareCallCFunction(4, eax);
2292       X87Mov(Operand(esp, 1 * kDoubleSize), right);
2293       X87Mov(Operand(esp, 0), left);
2294       X87Free(right);
2295       DCHECK(left.is(result));
2296       X87PrepareToWrite(result);
2297       __ CallCFunction(
2298           ExternalReference::mod_two_doubles_operation(isolate()),
2299           4);
2300
2301       // Return value is in st(0) on ia32.
2302       X87CommitWrite(result);
2303       break;
2304     }
2305     default:
2306       UNREACHABLE();
2307       break;
2308   }
2309
2310   // Restore the default value of control word.
2311   __ X87SetFPUCW(0x037F);
2312 }
2313
2314
2315 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2316   DCHECK(ToRegister(instr->context()).is(esi));
2317   DCHECK(ToRegister(instr->left()).is(edx));
2318   DCHECK(ToRegister(instr->right()).is(eax));
2319   DCHECK(ToRegister(instr->result()).is(eax));
2320
2321   Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
2322   CallCode(code, RelocInfo::CODE_TARGET, instr);
2323 }
2324
2325
2326 template<class InstrType>
2327 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2328   int left_block = instr->TrueDestination(chunk_);
2329   int right_block = instr->FalseDestination(chunk_);
2330
2331   int next_block = GetNextEmittedBlock();
2332
2333   if (right_block == left_block || cc == no_condition) {
2334     EmitGoto(left_block);
2335   } else if (left_block == next_block) {
2336     __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2337   } else if (right_block == next_block) {
2338     __ j(cc, chunk_->GetAssemblyLabel(left_block));
2339   } else {
2340     __ j(cc, chunk_->GetAssemblyLabel(left_block));
2341     __ jmp(chunk_->GetAssemblyLabel(right_block));
2342   }
2343 }
2344
2345
2346 template<class InstrType>
2347 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2348   int false_block = instr->FalseDestination(chunk_);
2349   if (cc == no_condition) {
2350     __ jmp(chunk_->GetAssemblyLabel(false_block));
2351   } else {
2352     __ j(cc, chunk_->GetAssemblyLabel(false_block));
2353   }
2354 }
2355
2356
2357 void LCodeGen::DoBranch(LBranch* instr) {
2358   Representation r = instr->hydrogen()->value()->representation();
2359   if (r.IsSmiOrInteger32()) {
2360     Register reg = ToRegister(instr->value());
2361     __ test(reg, Operand(reg));
2362     EmitBranch(instr, not_zero);
2363   } else if (r.IsDouble()) {
2364     X87Register reg = ToX87Register(instr->value());
2365     X87LoadForUsage(reg);
2366     __ fldz();
2367     __ FCmp();
2368     EmitBranch(instr, not_zero);
2369   } else {
2370     DCHECK(r.IsTagged());
2371     Register reg = ToRegister(instr->value());
2372     HType type = instr->hydrogen()->value()->type();
2373     if (type.IsBoolean()) {
2374       DCHECK(!info()->IsStub());
2375       __ cmp(reg, factory()->true_value());
2376       EmitBranch(instr, equal);
2377     } else if (type.IsSmi()) {
2378       DCHECK(!info()->IsStub());
2379       __ test(reg, Operand(reg));
2380       EmitBranch(instr, not_equal);
2381     } else if (type.IsJSArray()) {
2382       DCHECK(!info()->IsStub());
2383       EmitBranch(instr, no_condition);
2384     } else if (type.IsHeapNumber()) {
2385       UNREACHABLE();
2386     } else if (type.IsString()) {
2387       DCHECK(!info()->IsStub());
2388       __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2389       EmitBranch(instr, not_equal);
2390     } else {
2391       ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2392       if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2393
2394       if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2395         // undefined -> false.
2396         __ cmp(reg, factory()->undefined_value());
2397         __ j(equal, instr->FalseLabel(chunk_));
2398       }
2399       if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2400         // true -> true.
2401         __ cmp(reg, factory()->true_value());
2402         __ j(equal, instr->TrueLabel(chunk_));
2403         // false -> false.
2404         __ cmp(reg, factory()->false_value());
2405         __ j(equal, instr->FalseLabel(chunk_));
2406       }
2407       if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2408         // 'null' -> false.
2409         __ cmp(reg, factory()->null_value());
2410         __ j(equal, instr->FalseLabel(chunk_));
2411       }
2412
2413       if (expected.Contains(ToBooleanStub::SMI)) {
2414         // Smis: 0 -> false, all other -> true.
2415         __ test(reg, Operand(reg));
2416         __ j(equal, instr->FalseLabel(chunk_));
2417         __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2418       } else if (expected.NeedsMap()) {
2419         // If we need a map later and have a Smi -> deopt.
2420         __ test(reg, Immediate(kSmiTagMask));
2421         DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2422       }
2423
2424       Register map = no_reg;  // Keep the compiler happy.
2425       if (expected.NeedsMap()) {
2426         map = ToRegister(instr->temp());
2427         DCHECK(!map.is(reg));
2428         __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2429
2430         if (expected.CanBeUndetectable()) {
2431           // Undetectable -> false.
2432           __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2433                     1 << Map::kIsUndetectable);
2434           __ j(not_zero, instr->FalseLabel(chunk_));
2435         }
2436       }
2437
2438       if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2439         // spec object -> true.
2440         __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2441         __ j(above_equal, instr->TrueLabel(chunk_));
2442       }
2443
2444       if (expected.Contains(ToBooleanStub::STRING)) {
2445         // String value -> false iff empty.
2446         Label not_string;
2447         __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2448         __ j(above_equal, &not_string, Label::kNear);
2449         __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2450         __ j(not_zero, instr->TrueLabel(chunk_));
2451         __ jmp(instr->FalseLabel(chunk_));
2452         __ bind(&not_string);
2453       }
2454
2455       if (expected.Contains(ToBooleanStub::SYMBOL)) {
2456         // Symbol value -> true.
2457         __ CmpInstanceType(map, SYMBOL_TYPE);
2458         __ j(equal, instr->TrueLabel(chunk_));
2459       }
2460
2461       if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2462         // heap number -> false iff +0, -0, or NaN.
2463         Label not_heap_number;
2464         __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2465                factory()->heap_number_map());
2466         __ j(not_equal, &not_heap_number, Label::kNear);
2467         __ fldz();
2468         __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2469         __ FCmp();
2470         __ j(zero, instr->FalseLabel(chunk_));
2471         __ jmp(instr->TrueLabel(chunk_));
2472         __ bind(&not_heap_number);
2473       }
2474
2475       if (!expected.IsGeneric()) {
2476         // We've seen something for the first time -> deopt.
2477         // This can only happen if we are not generic already.
2478         DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2479       }
2480     }
2481   }
2482 }
2483
2484
2485 void LCodeGen::EmitGoto(int block) {
2486   if (!IsNextEmittedBlock(block)) {
2487     __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2488   }
2489 }
2490
2491
2492 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2493 }
2494
2495
2496 void LCodeGen::DoGoto(LGoto* instr) {
2497   EmitGoto(instr->block_id());
2498 }
2499
2500
2501 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2502   Condition cond = no_condition;
2503   switch (op) {
2504     case Token::EQ:
2505     case Token::EQ_STRICT:
2506       cond = equal;
2507       break;
2508     case Token::NE:
2509     case Token::NE_STRICT:
2510       cond = not_equal;
2511       break;
2512     case Token::LT:
2513       cond = is_unsigned ? below : less;
2514       break;
2515     case Token::GT:
2516       cond = is_unsigned ? above : greater;
2517       break;
2518     case Token::LTE:
2519       cond = is_unsigned ? below_equal : less_equal;
2520       break;
2521     case Token::GTE:
2522       cond = is_unsigned ? above_equal : greater_equal;
2523       break;
2524     case Token::IN:
2525     case Token::INSTANCEOF:
2526     default:
2527       UNREACHABLE();
2528   }
2529   return cond;
2530 }
2531
2532
2533 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2534   LOperand* left = instr->left();
2535   LOperand* right = instr->right();
2536   bool is_unsigned =
2537       instr->is_double() ||
2538       instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2539       instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2540   Condition cc = TokenToCondition(instr->op(), is_unsigned);
2541
2542   if (left->IsConstantOperand() && right->IsConstantOperand()) {
2543     // We can statically evaluate the comparison.
2544     double left_val = ToDouble(LConstantOperand::cast(left));
2545     double right_val = ToDouble(LConstantOperand::cast(right));
2546     int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2547         instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2548     EmitGoto(next_block);
2549   } else {
2550     if (instr->is_double()) {
2551       X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2552       __ FCmp();
2553       // Don't base result on EFLAGS when a NaN is involved. Instead
2554       // jump to the false block.
2555       __ j(parity_even, instr->FalseLabel(chunk_));
2556     } else {
2557       if (right->IsConstantOperand()) {
2558         __ cmp(ToOperand(left),
2559                ToImmediate(right, instr->hydrogen()->representation()));
2560       } else if (left->IsConstantOperand()) {
2561         __ cmp(ToOperand(right),
2562                ToImmediate(left, instr->hydrogen()->representation()));
2563         // We commuted the operands, so commute the condition.
2564         cc = CommuteCondition(cc);
2565       } else {
2566         __ cmp(ToRegister(left), ToOperand(right));
2567       }
2568     }
2569     EmitBranch(instr, cc);
2570   }
2571 }
2572
2573
2574 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2575   Register left = ToRegister(instr->left());
2576
2577   if (instr->right()->IsConstantOperand()) {
2578     Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2579     __ CmpObject(left, right);
2580   } else {
2581     Operand right = ToOperand(instr->right());
2582     __ cmp(left, right);
2583   }
2584   EmitBranch(instr, equal);
2585 }
2586
2587
2588 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2589   if (instr->hydrogen()->representation().IsTagged()) {
2590     Register input_reg = ToRegister(instr->object());
2591     __ cmp(input_reg, factory()->the_hole_value());
2592     EmitBranch(instr, equal);
2593     return;
2594   }
2595
2596   // Put the value to the top of stack
2597   X87Register src = ToX87Register(instr->object());
2598   X87LoadForUsage(src);
2599   __ fld(0);
2600   __ fld(0);
2601   __ FCmp();
2602   Label ok;
2603   __ j(parity_even, &ok, Label::kNear);
2604   __ fstp(0);
2605   EmitFalseBranch(instr, no_condition);
2606   __ bind(&ok);
2607
2608
2609   __ sub(esp, Immediate(kDoubleSize));
2610   __ fstp_d(MemOperand(esp, 0));
2611
2612   __ add(esp, Immediate(kDoubleSize));
2613   int offset = sizeof(kHoleNanUpper32);
2614   // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
2615   // so we check the upper with 0xffffffff for hole as a temporary fix.
2616   __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
2617   EmitBranch(instr, equal);
2618 }
2619
2620
2621 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2622   Representation rep = instr->hydrogen()->value()->representation();
2623   DCHECK(!rep.IsInteger32());
2624
2625   if (rep.IsDouble()) {
2626     X87Register input = ToX87Register(instr->value());
2627     X87LoadForUsage(input);
2628     __ FXamMinusZero();
2629     EmitBranch(instr, equal);
2630   } else {
2631     Register value = ToRegister(instr->value());
2632     Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2633     __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2634     __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2635            Immediate(0x1));
2636     EmitFalseBranch(instr, no_overflow);
2637     __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2638            Immediate(0x00000000));
2639     EmitBranch(instr, equal);
2640   }
2641 }
2642
2643
2644 Condition LCodeGen::EmitIsObject(Register input,
2645                                  Register temp1,
2646                                  Label* is_not_object,
2647                                  Label* is_object) {
2648   __ JumpIfSmi(input, is_not_object);
2649
2650   __ cmp(input, isolate()->factory()->null_value());
2651   __ j(equal, is_object);
2652
2653   __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2654   // Undetectable objects behave like undefined.
2655   __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2656             1 << Map::kIsUndetectable);
2657   __ j(not_zero, is_not_object);
2658
2659   __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2660   __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2661   __ j(below, is_not_object);
2662   __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2663   return below_equal;
2664 }
2665
2666
2667 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2668   Register reg = ToRegister(instr->value());
2669   Register temp = ToRegister(instr->temp());
2670
2671   Condition true_cond = EmitIsObject(
2672       reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2673
2674   EmitBranch(instr, true_cond);
2675 }
2676
2677
2678 Condition LCodeGen::EmitIsString(Register input,
2679                                  Register temp1,
2680                                  Label* is_not_string,
2681                                  SmiCheck check_needed = INLINE_SMI_CHECK) {
2682   if (check_needed == INLINE_SMI_CHECK) {
2683     __ JumpIfSmi(input, is_not_string);
2684   }
2685
2686   Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2687
2688   return cond;
2689 }
2690
2691
2692 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2693   Register reg = ToRegister(instr->value());
2694   Register temp = ToRegister(instr->temp());
2695
2696   SmiCheck check_needed =
2697       instr->hydrogen()->value()->type().IsHeapObject()
2698           ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2699
2700   Condition true_cond = EmitIsString(
2701       reg, temp, instr->FalseLabel(chunk_), check_needed);
2702
2703   EmitBranch(instr, true_cond);
2704 }
2705
2706
2707 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2708   Operand input = ToOperand(instr->value());
2709
2710   __ test(input, Immediate(kSmiTagMask));
2711   EmitBranch(instr, zero);
2712 }
2713
2714
2715 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2716   Register input = ToRegister(instr->value());
2717   Register temp = ToRegister(instr->temp());
2718
2719   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2720     STATIC_ASSERT(kSmiTag == 0);
2721     __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2722   }
2723   __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2724   __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2725             1 << Map::kIsUndetectable);
2726   EmitBranch(instr, not_zero);
2727 }
2728
2729
2730 static Condition ComputeCompareCondition(Token::Value op) {
2731   switch (op) {
2732     case Token::EQ_STRICT:
2733     case Token::EQ:
2734       return equal;
2735     case Token::LT:
2736       return less;
2737     case Token::GT:
2738       return greater;
2739     case Token::LTE:
2740       return less_equal;
2741     case Token::GTE:
2742       return greater_equal;
2743     default:
2744       UNREACHABLE();
2745       return no_condition;
2746   }
2747 }
2748
2749
2750 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2751   Token::Value op = instr->op();
2752
2753   Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2754   CallCode(ic, RelocInfo::CODE_TARGET, instr);
2755
2756   Condition condition = ComputeCompareCondition(op);
2757   __ test(eax, Operand(eax));
2758
2759   EmitBranch(instr, condition);
2760 }
2761
2762
2763 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2764   InstanceType from = instr->from();
2765   InstanceType to = instr->to();
2766   if (from == FIRST_TYPE) return to;
2767   DCHECK(from == to || to == LAST_TYPE);
2768   return from;
2769 }
2770
2771
2772 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2773   InstanceType from = instr->from();
2774   InstanceType to = instr->to();
2775   if (from == to) return equal;
2776   if (to == LAST_TYPE) return above_equal;
2777   if (from == FIRST_TYPE) return below_equal;
2778   UNREACHABLE();
2779   return equal;
2780 }
2781
2782
2783 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2784   Register input = ToRegister(instr->value());
2785   Register temp = ToRegister(instr->temp());
2786
2787   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2788     __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2789   }
2790
2791   __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2792   EmitBranch(instr, BranchCondition(instr->hydrogen()));
2793 }
2794
2795
2796 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2797   Register input = ToRegister(instr->value());
2798   Register result = ToRegister(instr->result());
2799
2800   __ AssertString(input);
2801
2802   __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2803   __ IndexFromHash(result, result);
2804 }
2805
2806
2807 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2808     LHasCachedArrayIndexAndBranch* instr) {
2809   Register input = ToRegister(instr->value());
2810
2811   __ test(FieldOperand(input, String::kHashFieldOffset),
2812           Immediate(String::kContainsCachedArrayIndexMask));
2813   EmitBranch(instr, equal);
2814 }
2815
2816
2817 // Branches to a label or falls through with the answer in the z flag.  Trashes
2818 // the temp registers, but not the input.
2819 void LCodeGen::EmitClassOfTest(Label* is_true,
2820                                Label* is_false,
2821                                Handle<String>class_name,
2822                                Register input,
2823                                Register temp,
2824                                Register temp2) {
2825   DCHECK(!input.is(temp));
2826   DCHECK(!input.is(temp2));
2827   DCHECK(!temp.is(temp2));
2828   __ JumpIfSmi(input, is_false);
2829
2830   if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2831     // Assuming the following assertions, we can use the same compares to test
2832     // for both being a function type and being in the object type range.
2833     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2834     STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2835                   FIRST_SPEC_OBJECT_TYPE + 1);
2836     STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2837                   LAST_SPEC_OBJECT_TYPE - 1);
2838     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2839     __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2840     __ j(below, is_false);
2841     __ j(equal, is_true);
2842     __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2843     __ j(equal, is_true);
2844   } else {
2845     // Faster code path to avoid two compares: subtract lower bound from the
2846     // actual type and do a signed compare with the width of the type range.
2847     __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2848     __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2849     __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2850     __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2851                                      FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2852     __ j(above, is_false);
2853   }
2854
2855   // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2856   // Check if the constructor in the map is a function.
2857   __ mov(temp, FieldOperand(temp, Map::kConstructorOffset));
2858   // Objects with a non-function constructor have class 'Object'.
2859   __ CmpObjectType(temp, JS_FUNCTION_TYPE, temp2);
2860   if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2861     __ j(not_equal, is_true);
2862   } else {
2863     __ j(not_equal, is_false);
2864   }
2865
2866   // temp now contains the constructor function. Grab the
2867   // instance class name from there.
2868   __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2869   __ mov(temp, FieldOperand(temp,
2870                             SharedFunctionInfo::kInstanceClassNameOffset));
2871   // The class name we are testing against is internalized since it's a literal.
2872   // The name in the constructor is internalized because of the way the context
2873   // is booted.  This routine isn't expected to work for random API-created
2874   // classes and it doesn't have to because you can't access it with natives
2875   // syntax.  Since both sides are internalized it is sufficient to use an
2876   // identity comparison.
2877   __ cmp(temp, class_name);
2878   // End with the answer in the z flag.
2879 }
2880
2881
2882 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2883   Register input = ToRegister(instr->value());
2884   Register temp = ToRegister(instr->temp());
2885   Register temp2 = ToRegister(instr->temp2());
2886
2887   Handle<String> class_name = instr->hydrogen()->class_name();
2888
2889   EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2890       class_name, input, temp, temp2);
2891
2892   EmitBranch(instr, equal);
2893 }
2894
2895
2896 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2897   Register reg = ToRegister(instr->value());
2898   __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2899   EmitBranch(instr, equal);
2900 }
2901
2902
2903 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2904   // Object and function are in fixed registers defined by the stub.
2905   DCHECK(ToRegister(instr->context()).is(esi));
2906   InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2907   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2908
2909   Label true_value, done;
2910   __ test(eax, Operand(eax));
2911   __ j(zero, &true_value, Label::kNear);
2912   __ mov(ToRegister(instr->result()), factory()->false_value());
2913   __ jmp(&done, Label::kNear);
2914   __ bind(&true_value);
2915   __ mov(ToRegister(instr->result()), factory()->true_value());
2916   __ bind(&done);
2917 }
2918
2919
2920 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2921   class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
2922    public:
2923     DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2924                                   LInstanceOfKnownGlobal* instr,
2925                                   const X87Stack& x87_stack)
2926         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2927     void Generate() OVERRIDE {
2928       codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2929     }
2930     LInstruction* instr() OVERRIDE { return instr_; }
2931     Label* map_check() { return &map_check_; }
2932    private:
2933     LInstanceOfKnownGlobal* instr_;
2934     Label map_check_;
2935   };
2936
2937   DeferredInstanceOfKnownGlobal* deferred;
2938   deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2939
2940   Label done, false_result;
2941   Register object = ToRegister(instr->value());
2942   Register temp = ToRegister(instr->temp());
2943
2944   // A Smi is not an instance of anything.
2945   __ JumpIfSmi(object, &false_result, Label::kNear);
2946
2947   // This is the inlined call site instanceof cache. The two occurences of the
2948   // hole value will be patched to the last map/result pair generated by the
2949   // instanceof stub.
2950   Label cache_miss;
2951   Register map = ToRegister(instr->temp());
2952   __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2953   __ bind(deferred->map_check());  // Label for calculating code patching.
2954   Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2955   __ cmp(map, Operand::ForCell(cache_cell));  // Patched to cached map.
2956   __ j(not_equal, &cache_miss, Label::kNear);
2957   __ mov(eax, factory()->the_hole_value());  // Patched to either true or false.
2958   __ jmp(&done, Label::kNear);
2959
2960   // The inlined call site cache did not match. Check for null and string
2961   // before calling the deferred code.
2962   __ bind(&cache_miss);
2963   // Null is not an instance of anything.
2964   __ cmp(object, factory()->null_value());
2965   __ j(equal, &false_result, Label::kNear);
2966
2967   // String values are not instances of anything.
2968   Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2969   __ j(is_string, &false_result, Label::kNear);
2970
2971   // Go to the deferred code.
2972   __ jmp(deferred->entry());
2973
2974   __ bind(&false_result);
2975   __ mov(ToRegister(instr->result()), factory()->false_value());
2976
2977   // Here result has either true or false. Deferred code also produces true or
2978   // false object.
2979   __ bind(deferred->exit());
2980   __ bind(&done);
2981 }
2982
2983
2984 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2985                                                Label* map_check) {
2986   PushSafepointRegistersScope scope(this);
2987
2988   InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2989   flags = static_cast<InstanceofStub::Flags>(
2990       flags | InstanceofStub::kArgsInRegisters);
2991   flags = static_cast<InstanceofStub::Flags>(
2992       flags | InstanceofStub::kCallSiteInlineCheck);
2993   flags = static_cast<InstanceofStub::Flags>(
2994       flags | InstanceofStub::kReturnTrueFalseObject);
2995   InstanceofStub stub(isolate(), flags);
2996
2997   // Get the temp register reserved by the instruction. This needs to be a
2998   // register which is pushed last by PushSafepointRegisters as top of the
2999   // stack is used to pass the offset to the location of the map check to
3000   // the stub.
3001   Register temp = ToRegister(instr->temp());
3002   DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
3003   __ LoadHeapObject(InstanceofStub::right(), instr->function());
3004   static const int kAdditionalDelta = 13;
3005   int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
3006   __ mov(temp, Immediate(delta));
3007   __ StoreToSafepointRegisterSlot(temp, temp);
3008   CallCodeGeneric(stub.GetCode(),
3009                   RelocInfo::CODE_TARGET,
3010                   instr,
3011                   RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
3012   // Get the deoptimization index of the LLazyBailout-environment that
3013   // corresponds to this instruction.
3014   LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3015   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3016
3017   // Put the result value into the eax slot and restore all registers.
3018   __ StoreToSafepointRegisterSlot(eax, eax);
3019 }
3020
3021
3022 void LCodeGen::DoCmpT(LCmpT* instr) {
3023   Token::Value op = instr->op();
3024
3025   Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
3026   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3027
3028   Condition condition = ComputeCompareCondition(op);
3029   Label true_value, done;
3030   __ test(eax, Operand(eax));
3031   __ j(condition, &true_value, Label::kNear);
3032   __ mov(ToRegister(instr->result()), factory()->false_value());
3033   __ jmp(&done, Label::kNear);
3034   __ bind(&true_value);
3035   __ mov(ToRegister(instr->result()), factory()->true_value());
3036   __ bind(&done);
3037 }
3038
3039
3040 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3041   int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3042
3043   if (instr->has_constant_parameter_count()) {
3044     int parameter_count = ToInteger32(instr->constant_parameter_count());
3045     if (dynamic_frame_alignment && FLAG_debug_code) {
3046       __ cmp(Operand(esp,
3047                      (parameter_count + extra_value_count) * kPointerSize),
3048              Immediate(kAlignmentZapValue));
3049       __ Assert(equal, kExpectedAlignmentMarker);
3050     }
3051     __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3052   } else {
3053     DCHECK(info()->IsStub());  // Functions would need to drop one more value.
3054     Register reg = ToRegister(instr->parameter_count());
3055     // The argument count parameter is a smi
3056     __ SmiUntag(reg);
3057     Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3058     if (dynamic_frame_alignment && FLAG_debug_code) {
3059       DCHECK(extra_value_count == 2);
3060       __ cmp(Operand(esp, reg, times_pointer_size,
3061                      extra_value_count * kPointerSize),
3062              Immediate(kAlignmentZapValue));
3063       __ Assert(equal, kExpectedAlignmentMarker);
3064     }
3065
3066     // emit code to restore stack based on instr->parameter_count()
3067     __ pop(return_addr_reg);  // save return address
3068     if (dynamic_frame_alignment) {
3069       __ inc(reg);  // 1 more for alignment
3070     }
3071     __ shl(reg, kPointerSizeLog2);
3072     __ add(esp, reg);
3073     __ jmp(return_addr_reg);
3074   }
3075 }
3076
3077
3078 void LCodeGen::DoReturn(LReturn* instr) {
3079   if (FLAG_trace && info()->IsOptimizing()) {
3080     // Preserve the return value on the stack and rely on the runtime call
3081     // to return the value in the same register.  We're leaving the code
3082     // managed by the register allocator and tearing down the frame, it's
3083     // safe to write to the context register.
3084     __ push(eax);
3085     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3086     __ CallRuntime(Runtime::kTraceExit, 1);
3087   }
3088   if (dynamic_frame_alignment_) {
3089     // Fetch the state of the dynamic frame alignment.
3090     __ mov(edx, Operand(ebp,
3091       JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3092   }
3093   int no_frame_start = -1;
3094   if (NeedsEagerFrame()) {
3095     __ mov(esp, ebp);
3096     __ pop(ebp);
3097     no_frame_start = masm_->pc_offset();
3098   }
3099   if (dynamic_frame_alignment_) {
3100     Label no_padding;
3101     __ cmp(edx, Immediate(kNoAlignmentPadding));
3102     __ j(equal, &no_padding, Label::kNear);
3103
3104     EmitReturn(instr, true);
3105     __ bind(&no_padding);
3106   }
3107
3108   EmitReturn(instr, false);
3109   if (no_frame_start != -1) {
3110     info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3111   }
3112 }
3113
3114
3115 void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) {
3116   Register result = ToRegister(instr->result());
3117   __ mov(result, Operand::ForCell(instr->hydrogen()->cell().handle()));
3118   if (instr->hydrogen()->RequiresHoleCheck()) {
3119     __ cmp(result, factory()->the_hole_value());
3120     DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3121   }
3122 }
3123
3124
3125 template <class T>
3126 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3127   DCHECK(FLAG_vector_ics);
3128   Register vector_register = ToRegister(instr->temp_vector());
3129   Register slot_register = VectorLoadICDescriptor::SlotRegister();
3130   DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
3131   DCHECK(slot_register.is(eax));
3132
3133   AllowDeferredHandleDereference vector_structure_check;
3134   Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3135   __ mov(vector_register, vector);
3136   // No need to allocate this register.
3137   FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3138   int index = vector->GetIndex(slot);
3139   __ mov(slot_register, Immediate(Smi::FromInt(index)));
3140 }
3141
3142
3143 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3144   DCHECK(ToRegister(instr->context()).is(esi));
3145   DCHECK(ToRegister(instr->global_object())
3146              .is(LoadDescriptor::ReceiverRegister()));
3147   DCHECK(ToRegister(instr->result()).is(eax));
3148
3149   __ mov(LoadDescriptor::NameRegister(), instr->name());
3150   if (FLAG_vector_ics) {
3151     EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3152   }
3153   ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
3154   Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode).code();
3155   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3156 }
3157
3158
3159 void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) {
3160   Register value = ToRegister(instr->value());
3161   Handle<PropertyCell> cell_handle = instr->hydrogen()->cell().handle();
3162
3163   // If the cell we are storing to contains the hole it could have
3164   // been deleted from the property dictionary. In that case, we need
3165   // to update the property details in the property dictionary to mark
3166   // it as no longer deleted. We deoptimize in that case.
3167   if (instr->hydrogen()->RequiresHoleCheck()) {
3168     __ cmp(Operand::ForCell(cell_handle), factory()->the_hole_value());
3169     DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3170   }
3171
3172   // Store the value.
3173   __ mov(Operand::ForCell(cell_handle), value);
3174   // Cells are always rescanned, so no write barrier here.
3175 }
3176
3177
3178 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3179   Register context = ToRegister(instr->context());
3180   Register result = ToRegister(instr->result());
3181   __ mov(result, ContextOperand(context, instr->slot_index()));
3182
3183   if (instr->hydrogen()->RequiresHoleCheck()) {
3184     __ cmp(result, factory()->the_hole_value());
3185     if (instr->hydrogen()->DeoptimizesOnHole()) {
3186       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3187     } else {
3188       Label is_not_hole;
3189       __ j(not_equal, &is_not_hole, Label::kNear);
3190       __ mov(result, factory()->undefined_value());
3191       __ bind(&is_not_hole);
3192     }
3193   }
3194 }
3195
3196
3197 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3198   Register context = ToRegister(instr->context());
3199   Register value = ToRegister(instr->value());
3200
3201   Label skip_assignment;
3202
3203   Operand target = ContextOperand(context, instr->slot_index());
3204   if (instr->hydrogen()->RequiresHoleCheck()) {
3205     __ cmp(target, factory()->the_hole_value());
3206     if (instr->hydrogen()->DeoptimizesOnHole()) {
3207       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3208     } else {
3209       __ j(not_equal, &skip_assignment, Label::kNear);
3210     }
3211   }
3212
3213   __ mov(target, value);
3214   if (instr->hydrogen()->NeedsWriteBarrier()) {
3215     SmiCheck check_needed =
3216         instr->hydrogen()->value()->type().IsHeapObject()
3217             ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3218     Register temp = ToRegister(instr->temp());
3219     int offset = Context::SlotOffset(instr->slot_index());
3220     __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3221                               EMIT_REMEMBERED_SET, check_needed);
3222   }
3223
3224   __ bind(&skip_assignment);
3225 }
3226
3227
3228 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3229   HObjectAccess access = instr->hydrogen()->access();
3230   int offset = access.offset();
3231
3232   if (access.IsExternalMemory()) {
3233     Register result = ToRegister(instr->result());
3234     MemOperand operand = instr->object()->IsConstantOperand()
3235         ? MemOperand::StaticVariable(ToExternalReference(
3236                 LConstantOperand::cast(instr->object())))
3237         : MemOperand(ToRegister(instr->object()), offset);
3238     __ Load(result, operand, access.representation());
3239     return;
3240   }
3241
3242   Register object = ToRegister(instr->object());
3243   if (instr->hydrogen()->representation().IsDouble()) {
3244     X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3245     return;
3246   }
3247
3248   Register result = ToRegister(instr->result());
3249   if (!access.IsInobject()) {
3250     __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3251     object = result;
3252   }
3253   __ Load(result, FieldOperand(object, offset), access.representation());
3254 }
3255
3256
3257 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3258   DCHECK(!operand->IsDoubleRegister());
3259   if (operand->IsConstantOperand()) {
3260     Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3261     AllowDeferredHandleDereference smi_check;
3262     if (object->IsSmi()) {
3263       __ Push(Handle<Smi>::cast(object));
3264     } else {
3265       __ PushHeapObject(Handle<HeapObject>::cast(object));
3266     }
3267   } else if (operand->IsRegister()) {
3268     __ push(ToRegister(operand));
3269   } else {
3270     __ push(ToOperand(operand));
3271   }
3272 }
3273
3274
3275 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3276   DCHECK(ToRegister(instr->context()).is(esi));
3277   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3278   DCHECK(ToRegister(instr->result()).is(eax));
3279
3280   __ mov(LoadDescriptor::NameRegister(), instr->name());
3281   if (FLAG_vector_ics) {
3282     EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3283   }
3284   Handle<Code> ic =
3285       CodeFactory::LoadICInOptimizedCode(isolate(), NOT_CONTEXTUAL).code();
3286   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3287 }
3288
3289
3290 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3291   Register function = ToRegister(instr->function());
3292   Register temp = ToRegister(instr->temp());
3293   Register result = ToRegister(instr->result());
3294
3295   // Get the prototype or initial map from the function.
3296   __ mov(result,
3297          FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3298
3299   // Check that the function has a prototype or an initial map.
3300   __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3301   DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3302
3303   // If the function does not have an initial map, we're done.
3304   Label done;
3305   __ CmpObjectType(result, MAP_TYPE, temp);
3306   __ j(not_equal, &done, Label::kNear);
3307
3308   // Get the prototype from the initial map.
3309   __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3310
3311   // All done.
3312   __ bind(&done);
3313 }
3314
3315
3316 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3317   Register result = ToRegister(instr->result());
3318   __ LoadRoot(result, instr->index());
3319 }
3320
3321
3322 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3323   Register arguments = ToRegister(instr->arguments());
3324   Register result = ToRegister(instr->result());
3325   if (instr->length()->IsConstantOperand() &&
3326       instr->index()->IsConstantOperand()) {
3327     int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3328     int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3329     int index = (const_length - const_index) + 1;
3330     __ mov(result, Operand(arguments, index * kPointerSize));
3331   } else {
3332     Register length = ToRegister(instr->length());
3333     Operand index = ToOperand(instr->index());
3334     // There are two words between the frame pointer and the last argument.
3335     // Subtracting from length accounts for one of them add one more.
3336     __ sub(length, index);
3337     __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3338   }
3339 }
3340
3341
3342 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3343   ElementsKind elements_kind = instr->elements_kind();
3344   LOperand* key = instr->key();
3345   if (!key->IsConstantOperand() &&
3346       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3347                                   elements_kind)) {
3348     __ SmiUntag(ToRegister(key));
3349   }
3350   Operand operand(BuildFastArrayOperand(
3351       instr->elements(),
3352       key,
3353       instr->hydrogen()->key()->representation(),
3354       elements_kind,
3355       instr->base_offset()));
3356   if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3357       elements_kind == FLOAT32_ELEMENTS) {
3358     X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3359   } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3360              elements_kind == FLOAT64_ELEMENTS) {
3361     X87Mov(ToX87Register(instr->result()), operand);
3362   } else {
3363     Register result(ToRegister(instr->result()));
3364     switch (elements_kind) {
3365       case EXTERNAL_INT8_ELEMENTS:
3366       case INT8_ELEMENTS:
3367         __ movsx_b(result, operand);
3368         break;
3369       case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3370       case EXTERNAL_UINT8_ELEMENTS:
3371       case UINT8_ELEMENTS:
3372       case UINT8_CLAMPED_ELEMENTS:
3373         __ movzx_b(result, operand);
3374         break;
3375       case EXTERNAL_INT16_ELEMENTS:
3376       case INT16_ELEMENTS:
3377         __ movsx_w(result, operand);
3378         break;
3379       case EXTERNAL_UINT16_ELEMENTS:
3380       case UINT16_ELEMENTS:
3381         __ movzx_w(result, operand);
3382         break;
3383       case EXTERNAL_INT32_ELEMENTS:
3384       case INT32_ELEMENTS:
3385         __ mov(result, operand);
3386         break;
3387       case EXTERNAL_UINT32_ELEMENTS:
3388       case UINT32_ELEMENTS:
3389         __ mov(result, operand);
3390         if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3391           __ test(result, Operand(result));
3392           DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3393         }
3394         break;
3395       case EXTERNAL_FLOAT32_ELEMENTS:
3396       case EXTERNAL_FLOAT64_ELEMENTS:
3397       case FLOAT32_ELEMENTS:
3398       case FLOAT64_ELEMENTS:
3399       case FAST_SMI_ELEMENTS:
3400       case FAST_ELEMENTS:
3401       case FAST_DOUBLE_ELEMENTS:
3402       case FAST_HOLEY_SMI_ELEMENTS:
3403       case FAST_HOLEY_ELEMENTS:
3404       case FAST_HOLEY_DOUBLE_ELEMENTS:
3405       case DICTIONARY_ELEMENTS:
3406       case SLOPPY_ARGUMENTS_ELEMENTS:
3407         UNREACHABLE();
3408         break;
3409     }
3410   }
3411 }
3412
3413
3414 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3415   if (instr->hydrogen()->RequiresHoleCheck()) {
3416     Operand hole_check_operand = BuildFastArrayOperand(
3417         instr->elements(), instr->key(),
3418         instr->hydrogen()->key()->representation(),
3419         FAST_DOUBLE_ELEMENTS,
3420         instr->base_offset() + sizeof(kHoleNanLower32));
3421     __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3422     DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3423   }
3424
3425   Operand double_load_operand = BuildFastArrayOperand(
3426       instr->elements(),
3427       instr->key(),
3428       instr->hydrogen()->key()->representation(),
3429       FAST_DOUBLE_ELEMENTS,
3430       instr->base_offset());
3431   X87Mov(ToX87Register(instr->result()), double_load_operand);
3432 }
3433
3434
3435 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3436   Register result = ToRegister(instr->result());
3437
3438   // Load the result.
3439   __ mov(result,
3440          BuildFastArrayOperand(instr->elements(), instr->key(),
3441                                instr->hydrogen()->key()->representation(),
3442                                FAST_ELEMENTS, instr->base_offset()));
3443
3444   // Check for the hole value.
3445   if (instr->hydrogen()->RequiresHoleCheck()) {
3446     if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3447       __ test(result, Immediate(kSmiTagMask));
3448       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3449     } else {
3450       __ cmp(result, factory()->the_hole_value());
3451       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3452     }
3453   }
3454 }
3455
3456
3457 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3458   if (instr->is_typed_elements()) {
3459     DoLoadKeyedExternalArray(instr);
3460   } else if (instr->hydrogen()->representation().IsDouble()) {
3461     DoLoadKeyedFixedDoubleArray(instr);
3462   } else {
3463     DoLoadKeyedFixedArray(instr);
3464   }
3465 }
3466
3467
3468 Operand LCodeGen::BuildFastArrayOperand(
3469     LOperand* elements_pointer,
3470     LOperand* key,
3471     Representation key_representation,
3472     ElementsKind elements_kind,
3473     uint32_t base_offset) {
3474   Register elements_pointer_reg = ToRegister(elements_pointer);
3475   int element_shift_size = ElementsKindToShiftSize(elements_kind);
3476   int shift_size = element_shift_size;
3477   if (key->IsConstantOperand()) {
3478     int constant_value = ToInteger32(LConstantOperand::cast(key));
3479     if (constant_value & 0xF0000000) {
3480       Abort(kArrayIndexConstantValueTooBig);
3481     }
3482     return Operand(elements_pointer_reg,
3483                    ((constant_value) << shift_size)
3484                        + base_offset);
3485   } else {
3486     // Take the tag bit into account while computing the shift size.
3487     if (key_representation.IsSmi() && (shift_size >= 1)) {
3488       shift_size -= kSmiTagSize;
3489     }
3490     ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3491     return Operand(elements_pointer_reg,
3492                    ToRegister(key),
3493                    scale_factor,
3494                    base_offset);
3495   }
3496 }
3497
3498
3499 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3500   DCHECK(ToRegister(instr->context()).is(esi));
3501   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3502   DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3503
3504   if (FLAG_vector_ics) {
3505     EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3506   }
3507
3508   Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(isolate()).code();
3509   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3510 }
3511
3512
3513 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3514   Register result = ToRegister(instr->result());
3515
3516   if (instr->hydrogen()->from_inlined()) {
3517     __ lea(result, Operand(esp, -2 * kPointerSize));
3518   } else {
3519     // Check for arguments adapter frame.
3520     Label done, adapted;
3521     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3522     __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3523     __ cmp(Operand(result),
3524            Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3525     __ j(equal, &adapted, Label::kNear);
3526
3527     // No arguments adaptor frame.
3528     __ mov(result, Operand(ebp));
3529     __ jmp(&done, Label::kNear);
3530
3531     // Arguments adaptor frame present.
3532     __ bind(&adapted);
3533     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3534
3535     // Result is the frame pointer for the frame if not adapted and for the real
3536     // frame below the adaptor frame if adapted.
3537     __ bind(&done);
3538   }
3539 }
3540
3541
3542 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3543   Operand elem = ToOperand(instr->elements());
3544   Register result = ToRegister(instr->result());
3545
3546   Label done;
3547
3548   // If no arguments adaptor frame the number of arguments is fixed.
3549   __ cmp(ebp, elem);
3550   __ mov(result, Immediate(scope()->num_parameters()));
3551   __ j(equal, &done, Label::kNear);
3552
3553   // Arguments adaptor frame present. Get argument length from there.
3554   __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3555   __ mov(result, Operand(result,
3556                          ArgumentsAdaptorFrameConstants::kLengthOffset));
3557   __ SmiUntag(result);
3558
3559   // Argument length is in result register.
3560   __ bind(&done);
3561 }
3562
3563
3564 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3565   Register receiver = ToRegister(instr->receiver());
3566   Register function = ToRegister(instr->function());
3567
3568   // If the receiver is null or undefined, we have to pass the global
3569   // object as a receiver to normal functions. Values have to be
3570   // passed unchanged to builtins and strict-mode functions.
3571   Label receiver_ok, global_object;
3572   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3573   Register scratch = ToRegister(instr->temp());
3574
3575   if (!instr->hydrogen()->known_function()) {
3576     // Do not transform the receiver to object for strict mode
3577     // functions.
3578     __ mov(scratch,
3579            FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3580     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3581               1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3582     __ j(not_equal, &receiver_ok, dist);
3583
3584     // Do not transform the receiver to object for builtins.
3585     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3586               1 << SharedFunctionInfo::kNativeBitWithinByte);
3587     __ j(not_equal, &receiver_ok, dist);
3588   }
3589
3590   // Normal function. Replace undefined or null with global receiver.
3591   __ cmp(receiver, factory()->null_value());
3592   __ j(equal, &global_object, Label::kNear);
3593   __ cmp(receiver, factory()->undefined_value());
3594   __ j(equal, &global_object, Label::kNear);
3595
3596   // The receiver should be a JS object.
3597   __ test(receiver, Immediate(kSmiTagMask));
3598   DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3599   __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3600   DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3601
3602   __ jmp(&receiver_ok, Label::kNear);
3603   __ bind(&global_object);
3604   __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3605   const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3606   __ mov(receiver, Operand(receiver, global_offset));
3607   const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3608   __ mov(receiver, FieldOperand(receiver, proxy_offset));
3609   __ bind(&receiver_ok);
3610 }
3611
3612
3613 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3614   Register receiver = ToRegister(instr->receiver());
3615   Register function = ToRegister(instr->function());
3616   Register length = ToRegister(instr->length());
3617   Register elements = ToRegister(instr->elements());
3618   DCHECK(receiver.is(eax));  // Used for parameter count.
3619   DCHECK(function.is(edi));  // Required by InvokeFunction.
3620   DCHECK(ToRegister(instr->result()).is(eax));
3621
3622   // Copy the arguments to this function possibly from the
3623   // adaptor frame below it.
3624   const uint32_t kArgumentsLimit = 1 * KB;
3625   __ cmp(length, kArgumentsLimit);
3626   DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3627
3628   __ push(receiver);
3629   __ mov(receiver, length);
3630
3631   // Loop through the arguments pushing them onto the execution
3632   // stack.
3633   Label invoke, loop;
3634   // length is a small non-negative integer, due to the test above.
3635   __ test(length, Operand(length));
3636   __ j(zero, &invoke, Label::kNear);
3637   __ bind(&loop);
3638   __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3639   __ dec(length);
3640   __ j(not_zero, &loop);
3641
3642   // Invoke the function.
3643   __ bind(&invoke);
3644   DCHECK(instr->HasPointerMap());
3645   LPointerMap* pointers = instr->pointer_map();
3646   SafepointGenerator safepoint_generator(
3647       this, pointers, Safepoint::kLazyDeopt);
3648   ParameterCount actual(eax);
3649   __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3650 }
3651
3652
3653 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3654   __ int3();
3655 }
3656
3657
3658 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3659   LOperand* argument = instr->value();
3660   EmitPushTaggedOperand(argument);
3661 }
3662
3663
3664 void LCodeGen::DoDrop(LDrop* instr) {
3665   __ Drop(instr->count());
3666 }
3667
3668
3669 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3670   Register result = ToRegister(instr->result());
3671   __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3672 }
3673
3674
3675 void LCodeGen::DoContext(LContext* instr) {
3676   Register result = ToRegister(instr->result());
3677   if (info()->IsOptimizing()) {
3678     __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3679   } else {
3680     // If there is no frame, the context must be in esi.
3681     DCHECK(result.is(esi));
3682   }
3683 }
3684
3685
3686 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3687   DCHECK(ToRegister(instr->context()).is(esi));
3688   __ push(esi);  // The context is the first argument.
3689   __ push(Immediate(instr->hydrogen()->pairs()));
3690   __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3691   CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3692 }
3693
3694
3695 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3696                                  int formal_parameter_count, int arity,
3697                                  LInstruction* instr) {
3698   bool dont_adapt_arguments =
3699       formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3700   bool can_invoke_directly =
3701       dont_adapt_arguments || formal_parameter_count == arity;
3702
3703   Register function_reg = edi;
3704
3705   if (can_invoke_directly) {
3706     // Change context.
3707     __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3708
3709     // Set eax to arguments count if adaption is not needed. Assumes that eax
3710     // is available to write to at this point.
3711     if (dont_adapt_arguments) {
3712       __ mov(eax, arity);
3713     }
3714
3715     // Invoke function directly.
3716     if (function.is_identical_to(info()->closure())) {
3717       __ CallSelf();
3718     } else {
3719       __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3720     }
3721     RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3722   } else {
3723     // We need to adapt arguments.
3724     LPointerMap* pointers = instr->pointer_map();
3725     SafepointGenerator generator(
3726         this, pointers, Safepoint::kLazyDeopt);
3727     ParameterCount count(arity);
3728     ParameterCount expected(formal_parameter_count);
3729     __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3730   }
3731 }
3732
3733
3734 void LCodeGen::DoTailCallThroughMegamorphicCache(
3735     LTailCallThroughMegamorphicCache* instr) {
3736   Register receiver = ToRegister(instr->receiver());
3737   Register name = ToRegister(instr->name());
3738   DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
3739   DCHECK(name.is(LoadDescriptor::NameRegister()));
3740   Register slot = FLAG_vector_ics ? ToRegister(instr->slot()) : no_reg;
3741   Register vector = FLAG_vector_ics ? ToRegister(instr->vector()) : no_reg;
3742
3743   Register scratch = ebx;
3744   Register extra = edi;
3745   DCHECK(!extra.is(slot) && !extra.is(vector));
3746   DCHECK(!scratch.is(receiver) && !scratch.is(name));
3747   DCHECK(!extra.is(receiver) && !extra.is(name));
3748
3749   // Important for the tail-call.
3750   bool must_teardown_frame = NeedsEagerFrame();
3751
3752   if (!instr->hydrogen()->is_just_miss()) {
3753     if (FLAG_vector_ics) {
3754       __ push(slot);
3755       __ push(vector);
3756     }
3757
3758     // The probe will tail call to a handler if found.
3759     // If --vector-ics is on, then it knows to pop the two args first.
3760     DCHECK(!instr->hydrogen()->is_keyed_load());
3761     isolate()->stub_cache()->GenerateProbe(
3762         masm(), Code::LOAD_IC, instr->hydrogen()->flags(), must_teardown_frame,
3763         receiver, name, scratch, extra);
3764
3765     if (FLAG_vector_ics) {
3766       __ pop(vector);
3767       __ pop(slot);
3768     }
3769   }
3770
3771   // Tail call to miss if we ended up here.
3772   if (must_teardown_frame) __ leave();
3773   if (instr->hydrogen()->is_keyed_load()) {
3774     KeyedLoadIC::GenerateMiss(masm());
3775   } else {
3776     LoadIC::GenerateMiss(masm());
3777   }
3778 }
3779
3780
3781 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3782   DCHECK(ToRegister(instr->result()).is(eax));
3783
3784   if (instr->hydrogen()->IsTailCall()) {
3785     if (NeedsEagerFrame()) __ leave();
3786
3787     if (instr->target()->IsConstantOperand()) {
3788       LConstantOperand* target = LConstantOperand::cast(instr->target());
3789       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3790       __ jmp(code, RelocInfo::CODE_TARGET);
3791     } else {
3792       DCHECK(instr->target()->IsRegister());
3793       Register target = ToRegister(instr->target());
3794       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3795       __ jmp(target);
3796     }
3797   } else {
3798     LPointerMap* pointers = instr->pointer_map();
3799     SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3800
3801     if (instr->target()->IsConstantOperand()) {
3802       LConstantOperand* target = LConstantOperand::cast(instr->target());
3803       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3804       generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3805       __ call(code, RelocInfo::CODE_TARGET);
3806     } else {
3807       DCHECK(instr->target()->IsRegister());
3808       Register target = ToRegister(instr->target());
3809       generator.BeforeCall(__ CallSize(Operand(target)));
3810       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3811       __ call(target);
3812     }
3813     generator.AfterCall();
3814   }
3815 }
3816
3817
3818 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3819   DCHECK(ToRegister(instr->function()).is(edi));
3820   DCHECK(ToRegister(instr->result()).is(eax));
3821
3822   if (instr->hydrogen()->pass_argument_count()) {
3823     __ mov(eax, instr->arity());
3824   }
3825
3826   // Change context.
3827   __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3828
3829   bool is_self_call = false;
3830   if (instr->hydrogen()->function()->IsConstant()) {
3831     HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3832     Handle<JSFunction> jsfun =
3833       Handle<JSFunction>::cast(fun_const->handle(isolate()));
3834     is_self_call = jsfun.is_identical_to(info()->closure());
3835   }
3836
3837   if (is_self_call) {
3838     __ CallSelf();
3839   } else {
3840     __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3841   }
3842
3843   RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3844 }
3845
3846
3847 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3848   Register input_reg = ToRegister(instr->value());
3849   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3850          factory()->heap_number_map());
3851   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3852
3853   Label slow, allocated, done;
3854   Register tmp = input_reg.is(eax) ? ecx : eax;
3855   Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3856
3857   // Preserve the value of all registers.
3858   PushSafepointRegistersScope scope(this);
3859
3860   __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3861   // Check the sign of the argument. If the argument is positive, just
3862   // return it. We do not need to patch the stack since |input| and
3863   // |result| are the same register and |input| will be restored
3864   // unchanged by popping safepoint registers.
3865   __ test(tmp, Immediate(HeapNumber::kSignMask));
3866   __ j(zero, &done, Label::kNear);
3867
3868   __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3869   __ jmp(&allocated, Label::kNear);
3870
3871   // Slow case: Call the runtime system to do the number allocation.
3872   __ bind(&slow);
3873   CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3874                           instr, instr->context());
3875   // Set the pointer to the new heap number in tmp.
3876   if (!tmp.is(eax)) __ mov(tmp, eax);
3877   // Restore input_reg after call to runtime.
3878   __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3879
3880   __ bind(&allocated);
3881   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3882   __ and_(tmp2, ~HeapNumber::kSignMask);
3883   __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3884   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3885   __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3886   __ StoreToSafepointRegisterSlot(input_reg, tmp);
3887
3888   __ bind(&done);
3889 }
3890
3891
3892 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3893   Register input_reg = ToRegister(instr->value());
3894   __ test(input_reg, Operand(input_reg));
3895   Label is_positive;
3896   __ j(not_sign, &is_positive, Label::kNear);
3897   __ neg(input_reg);  // Sets flags.
3898   DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3899   __ bind(&is_positive);
3900 }
3901
3902
3903 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3904   // Class for deferred case.
3905   class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
3906    public:
3907     DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3908                                     LMathAbs* instr,
3909                                     const X87Stack& x87_stack)
3910         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3911     void Generate() OVERRIDE {
3912       codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3913     }
3914     LInstruction* instr() OVERRIDE { return instr_; }
3915
3916    private:
3917     LMathAbs* instr_;
3918   };
3919
3920   DCHECK(instr->value()->Equals(instr->result()));
3921   Representation r = instr->hydrogen()->value()->representation();
3922
3923   if (r.IsDouble()) {
3924     X87Register value = ToX87Register(instr->value());
3925     X87Fxch(value);
3926     __ fabs();
3927   } else if (r.IsSmiOrInteger32()) {
3928     EmitIntegerMathAbs(instr);
3929   } else {  // Tagged case.
3930     DeferredMathAbsTaggedHeapNumber* deferred =
3931         new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3932     Register input_reg = ToRegister(instr->value());
3933     // Smi check.
3934     __ JumpIfNotSmi(input_reg, deferred->entry());
3935     EmitIntegerMathAbs(instr);
3936     __ bind(deferred->exit());
3937   }
3938 }
3939
3940
3941 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3942   Register output_reg = ToRegister(instr->result());
3943   X87Register input_reg = ToX87Register(instr->value());
3944   X87Fxch(input_reg);
3945
3946   Label not_minus_zero, done;
3947   // Deoptimize on unordered.
3948   __ fldz();
3949   __ fld(1);
3950   __ FCmp();
3951   DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3952   __ j(below, &not_minus_zero, Label::kNear);
3953
3954   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3955     // Check for negative zero.
3956     __ j(not_equal, &not_minus_zero, Label::kNear);
3957     // +- 0.0.
3958     __ fld(0);
3959     __ FXamSign();
3960     DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3961     __ Move(output_reg, Immediate(0));
3962     __ jmp(&done, Label::kFar);
3963   }
3964
3965   // Positive input.
3966   // rc=01B, round down.
3967   __ bind(&not_minus_zero);
3968   __ fnclex();
3969   __ X87SetRC(0x0400);
3970   __ sub(esp, Immediate(kPointerSize));
3971   __ fist_s(Operand(esp, 0));
3972   __ pop(output_reg);
3973   __ X87CheckIA();
3974   DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3975   __ fnclex();
3976   __ X87SetRC(0x0000);
3977   __ bind(&done);
3978 }
3979
3980
3981 void LCodeGen::DoMathRound(LMathRound* instr) {
3982   X87Register input_reg = ToX87Register(instr->value());
3983   Register result = ToRegister(instr->result());
3984   X87Fxch(input_reg);
3985   Label below_one_half, below_minus_one_half, done;
3986
3987   ExternalReference one_half = ExternalReference::address_of_one_half();
3988   ExternalReference minus_one_half =
3989       ExternalReference::address_of_minus_one_half();
3990
3991   __ fld_d(Operand::StaticVariable(one_half));
3992   __ fld(1);
3993   __ FCmp();
3994   __ j(carry, &below_one_half);
3995
3996   // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
3997   __ fld(0);
3998   __ fadd_d(Operand::StaticVariable(one_half));
3999   // rc=11B, round toward zero.
4000   __ X87SetRC(0x0c00);
4001   __ sub(esp, Immediate(kPointerSize));
4002   // Clear exception bits.
4003   __ fnclex();
4004   __ fistp_s(MemOperand(esp, 0));
4005   // Check overflow.
4006   __ X87CheckIA();
4007   __ pop(result);
4008   DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4009   __ fnclex();
4010   // Restore round mode.
4011   __ X87SetRC(0x0000);
4012   __ jmp(&done);
4013
4014   __ bind(&below_one_half);
4015   __ fld_d(Operand::StaticVariable(minus_one_half));
4016   __ fld(1);
4017   __ FCmp();
4018   __ j(carry, &below_minus_one_half);
4019   // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
4020   // we can ignore the difference between a result of -0 and +0.
4021   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4022     // If the sign is positive, we return +0.
4023     __ fld(0);
4024     __ FXamSign();
4025     DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4026   }
4027   __ Move(result, Immediate(0));
4028   __ jmp(&done);
4029
4030   __ bind(&below_minus_one_half);
4031   __ fld(0);
4032   __ fadd_d(Operand::StaticVariable(one_half));
4033   // rc=01B, round down.
4034   __ X87SetRC(0x0400);
4035   __ sub(esp, Immediate(kPointerSize));
4036   // Clear exception bits.
4037   __ fnclex();
4038   __ fistp_s(MemOperand(esp, 0));
4039   // Check overflow.
4040   __ X87CheckIA();
4041   __ pop(result);
4042   DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4043   __ fnclex();
4044   // Restore round mode.
4045   __ X87SetRC(0x0000);
4046
4047   __ bind(&done);
4048 }
4049
4050
4051 void LCodeGen::DoMathFround(LMathFround* instr) {
4052   X87Register input_reg = ToX87Register(instr->value());
4053   X87Fxch(input_reg);
4054   __ sub(esp, Immediate(kPointerSize));
4055   __ fstp_s(MemOperand(esp, 0));
4056   X87Fld(MemOperand(esp, 0), kX87FloatOperand);
4057   __ add(esp, Immediate(kPointerSize));
4058 }
4059
4060
4061 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4062   X87Register input = ToX87Register(instr->value());
4063   X87Register result_reg = ToX87Register(instr->result());
4064   Register temp_result = ToRegister(instr->temp1());
4065   Register temp = ToRegister(instr->temp2());
4066   Label slow, done, smi, finish;
4067   DCHECK(result_reg.is(input));
4068
4069   // Store input into Heap number and call runtime function kMathExpRT.
4070   if (FLAG_inline_new) {
4071     __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4072     __ jmp(&done, Label::kNear);
4073   }
4074
4075   // Slow case: Call the runtime system to do the number allocation.
4076   __ bind(&slow);
4077   {
4078     // TODO(3095996): Put a valid pointer value in the stack slot where the
4079     // result register is stored, as this register is in the pointer map, but
4080     // contains an integer value.
4081     __ Move(temp_result, Immediate(0));
4082
4083     // Preserve the value of all registers.
4084     PushSafepointRegistersScope scope(this);
4085
4086     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4087     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4088     RecordSafepointWithRegisters(
4089        instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4090     __ StoreToSafepointRegisterSlot(temp_result, eax);
4091   }
4092   __ bind(&done);
4093   X87LoadForUsage(input);
4094   __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4095
4096   {
4097     // Preserve the value of all registers.
4098     PushSafepointRegistersScope scope(this);
4099
4100     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4101     __ push(temp_result);
4102     __ CallRuntimeSaveDoubles(Runtime::kMathSqrtRT);
4103     RecordSafepointWithRegisters(instr->pointer_map(), 1,
4104                                  Safepoint::kNoLazyDeopt);
4105     __ StoreToSafepointRegisterSlot(temp_result, eax);
4106   }
4107   X87PrepareToWrite(result_reg);
4108   // return value of MathExpRT is Smi or Heap Number.
4109   __ JumpIfSmi(temp_result, &smi);
4110   // Heap number(double)
4111   __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4112   __ jmp(&finish);
4113   // SMI
4114   __ bind(&smi);
4115   __ SmiUntag(temp_result);
4116   __ push(temp_result);
4117   __ fild_s(MemOperand(esp, 0));
4118   __ pop(temp_result);
4119   __ bind(&finish);
4120   X87CommitWrite(result_reg);
4121 }
4122
4123
4124 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4125   X87Register input_reg = ToX87Register(instr->value());
4126   DCHECK(ToX87Register(instr->result()).is(input_reg));
4127   X87Fxch(input_reg);
4128   // Note that according to ECMA-262 15.8.2.13:
4129   // Math.pow(-Infinity, 0.5) == Infinity
4130   // Math.sqrt(-Infinity) == NaN
4131   Label done, sqrt;
4132   // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4133   __ fxam();
4134   __ push(eax);
4135   __ fnstsw_ax();
4136   __ and_(eax, Immediate(0x4700));
4137   __ cmp(eax, Immediate(0x0700));
4138   __ j(not_equal, &sqrt, Label::kNear);
4139   // If input is -Infinity, return Infinity.
4140   __ fchs();
4141   __ jmp(&done, Label::kNear);
4142
4143   // Square root.
4144   __ bind(&sqrt);
4145   __ fldz();
4146   __ faddp();  // Convert -0 to +0.
4147   __ fsqrt();
4148   __ bind(&done);
4149   __ pop(eax);
4150 }
4151
4152
4153 void LCodeGen::DoPower(LPower* instr) {
4154   Representation exponent_type = instr->hydrogen()->right()->representation();
4155   X87Register result = ToX87Register(instr->result());
4156   // Having marked this as a call, we can use any registers.
4157   X87Register base = ToX87Register(instr->left());
4158   ExternalReference one_half = ExternalReference::address_of_one_half();
4159
4160   if (exponent_type.IsSmi()) {
4161     Register exponent = ToRegister(instr->right());
4162     X87LoadForUsage(base);
4163     __ SmiUntag(exponent);
4164     __ push(exponent);
4165     __ fild_s(MemOperand(esp, 0));
4166     __ pop(exponent);
4167   } else if (exponent_type.IsTagged()) {
4168     Register exponent = ToRegister(instr->right());
4169     Register temp = exponent.is(ecx) ? eax : ecx;
4170     Label no_deopt, done;
4171     X87LoadForUsage(base);
4172     __ JumpIfSmi(exponent, &no_deopt);
4173     __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4174     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4175     // Heap number(double)
4176     __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4177     __ jmp(&done);
4178     // SMI
4179     __ bind(&no_deopt);
4180     __ SmiUntag(exponent);
4181     __ push(exponent);
4182     __ fild_s(MemOperand(esp, 0));
4183     __ pop(exponent);
4184     __ bind(&done);
4185   } else if (exponent_type.IsInteger32()) {
4186     Register exponent = ToRegister(instr->right());
4187     X87LoadForUsage(base);
4188     __ push(exponent);
4189     __ fild_s(MemOperand(esp, 0));
4190     __ pop(exponent);
4191   } else {
4192     DCHECK(exponent_type.IsDouble());
4193     X87Register exponent_double = ToX87Register(instr->right());
4194     X87LoadForUsage(base, exponent_double);
4195   }
4196
4197   // FP data stack {base, exponent(TOS)}.
4198   // Handle (exponent==+-0.5 && base == -0).
4199   Label not_plus_0;
4200   __ fld(0);
4201   __ fabs();
4202   X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4203   __ FCmp();
4204   __ j(parity_even, &not_plus_0, Label::kNear);  // NaN.
4205   __ j(not_equal, &not_plus_0, Label::kNear);
4206   __ fldz();
4207   // FP data stack {base, exponent(TOS), zero}.
4208   __ faddp(2);
4209   __ bind(&not_plus_0);
4210
4211   {
4212     __ PrepareCallCFunction(4, eax);
4213     __ fstp_d(MemOperand(esp, kDoubleSize));  // Exponent value.
4214     __ fstp_d(MemOperand(esp, 0));            // Base value.
4215     X87PrepareToWrite(result);
4216     __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4217                      4);
4218     // Return value is in st(0) on ia32.
4219     X87CommitWrite(result);
4220   }
4221 }
4222
4223
4224 void LCodeGen::DoMathLog(LMathLog* instr) {
4225   DCHECK(instr->value()->Equals(instr->result()));
4226   X87Register input_reg = ToX87Register(instr->value());
4227   X87Fxch(input_reg);
4228
4229   Label positive, done, zero, nan_result;
4230   __ fldz();
4231   __ fld(1);
4232   __ FCmp();
4233   __ j(below, &nan_result, Label::kNear);
4234   __ j(equal, &zero, Label::kNear);
4235   // Positive input.
4236   // {input, ln2}.
4237   __ fldln2();
4238   // {ln2, input}.
4239   __ fxch();
4240   // {result}.
4241   __ fyl2x();
4242   __ jmp(&done, Label::kNear);
4243
4244   __ bind(&nan_result);
4245   X87PrepareToWrite(input_reg);
4246   __ push(Immediate(0xffffffff));
4247   __ push(Immediate(0x7fffffff));
4248   __ fld_d(MemOperand(esp, 0));
4249   __ lea(esp, Operand(esp, kDoubleSize));
4250   X87CommitWrite(input_reg);
4251   __ jmp(&done, Label::kNear);
4252
4253   __ bind(&zero);
4254   ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4255   X87PrepareToWrite(input_reg);
4256   __ fld_d(Operand::StaticVariable(ninf));
4257   X87CommitWrite(input_reg);
4258
4259   __ bind(&done);
4260 }
4261
4262
4263 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4264   Register input = ToRegister(instr->value());
4265   Register result = ToRegister(instr->result());
4266   Label not_zero_input;
4267   __ bsr(result, input);
4268
4269   __ j(not_zero, &not_zero_input);
4270   __ Move(result, Immediate(63));  // 63^31 == 32
4271
4272   __ bind(&not_zero_input);
4273   __ xor_(result, Immediate(31));  // for x in [0..31], 31^x == 31-x.
4274 }
4275
4276
4277 void LCodeGen::DoMathExp(LMathExp* instr) {
4278   X87Register input = ToX87Register(instr->value());
4279   X87Register result_reg = ToX87Register(instr->result());
4280   Register temp_result = ToRegister(instr->temp1());
4281   Register temp = ToRegister(instr->temp2());
4282   Label slow, done, smi, finish;
4283   DCHECK(result_reg.is(input));
4284
4285   // Store input into Heap number and call runtime function kMathExpRT.
4286   if (FLAG_inline_new) {
4287     __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4288     __ jmp(&done, Label::kNear);
4289   }
4290
4291   // Slow case: Call the runtime system to do the number allocation.
4292   __ bind(&slow);
4293   {
4294     // TODO(3095996): Put a valid pointer value in the stack slot where the
4295     // result register is stored, as this register is in the pointer map, but
4296     // contains an integer value.
4297     __ Move(temp_result, Immediate(0));
4298
4299     // Preserve the value of all registers.
4300     PushSafepointRegistersScope scope(this);
4301
4302     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4303     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4304     RecordSafepointWithRegisters(instr->pointer_map(), 0,
4305                                  Safepoint::kNoLazyDeopt);
4306     __ StoreToSafepointRegisterSlot(temp_result, eax);
4307   }
4308   __ bind(&done);
4309   X87LoadForUsage(input);
4310   __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4311
4312   {
4313     // Preserve the value of all registers.
4314     PushSafepointRegistersScope scope(this);
4315
4316     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4317     __ push(temp_result);
4318     __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4319     RecordSafepointWithRegisters(instr->pointer_map(), 1,
4320                                  Safepoint::kNoLazyDeopt);
4321     __ StoreToSafepointRegisterSlot(temp_result, eax);
4322   }
4323   X87PrepareToWrite(result_reg);
4324   // return value of MathExpRT is Smi or Heap Number.
4325   __ JumpIfSmi(temp_result, &smi);
4326   // Heap number(double)
4327   __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4328   __ jmp(&finish);
4329   // SMI
4330   __ bind(&smi);
4331   __ SmiUntag(temp_result);
4332   __ push(temp_result);
4333   __ fild_s(MemOperand(esp, 0));
4334   __ pop(temp_result);
4335   __ bind(&finish);
4336   X87CommitWrite(result_reg);
4337 }
4338
4339
4340 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4341   DCHECK(ToRegister(instr->context()).is(esi));
4342   DCHECK(ToRegister(instr->function()).is(edi));
4343   DCHECK(instr->HasPointerMap());
4344
4345   Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4346   if (known_function.is_null()) {
4347     LPointerMap* pointers = instr->pointer_map();
4348     SafepointGenerator generator(
4349         this, pointers, Safepoint::kLazyDeopt);
4350     ParameterCount count(instr->arity());
4351     __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4352   } else {
4353     CallKnownFunction(known_function,
4354                       instr->hydrogen()->formal_parameter_count(),
4355                       instr->arity(), instr);
4356   }
4357 }
4358
4359
4360 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4361   DCHECK(ToRegister(instr->context()).is(esi));
4362   DCHECK(ToRegister(instr->function()).is(edi));
4363   DCHECK(ToRegister(instr->result()).is(eax));
4364
4365   int arity = instr->arity();
4366   CallFunctionFlags flags = instr->hydrogen()->function_flags();
4367   if (instr->hydrogen()->HasVectorAndSlot()) {
4368     Register slot_register = ToRegister(instr->temp_slot());
4369     Register vector_register = ToRegister(instr->temp_vector());
4370     DCHECK(slot_register.is(edx));
4371     DCHECK(vector_register.is(ebx));
4372
4373     AllowDeferredHandleDereference vector_structure_check;
4374     Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
4375     int index = vector->GetIndex(instr->hydrogen()->slot());
4376
4377     __ mov(vector_register, vector);
4378     __ mov(slot_register, Immediate(Smi::FromInt(index)));
4379
4380     CallICState::CallType call_type =
4381         (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
4382
4383     Handle<Code> ic =
4384         CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
4385     CallCode(ic, RelocInfo::CODE_TARGET, instr);
4386   } else {
4387     CallFunctionStub stub(isolate(), arity, flags);
4388     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4389   }
4390 }
4391
4392
4393 void LCodeGen::DoCallNew(LCallNew* instr) {
4394   DCHECK(ToRegister(instr->context()).is(esi));
4395   DCHECK(ToRegister(instr->constructor()).is(edi));
4396   DCHECK(ToRegister(instr->result()).is(eax));
4397
4398   // No cell in ebx for construct type feedback in optimized code
4399   __ mov(ebx, isolate()->factory()->undefined_value());
4400   CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4401   __ Move(eax, Immediate(instr->arity()));
4402   CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4403 }
4404
4405
4406 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4407   DCHECK(ToRegister(instr->context()).is(esi));
4408   DCHECK(ToRegister(instr->constructor()).is(edi));
4409   DCHECK(ToRegister(instr->result()).is(eax));
4410
4411   __ Move(eax, Immediate(instr->arity()));
4412   __ mov(ebx, isolate()->factory()->undefined_value());
4413   ElementsKind kind = instr->hydrogen()->elements_kind();
4414   AllocationSiteOverrideMode override_mode =
4415       (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4416           ? DISABLE_ALLOCATION_SITES
4417           : DONT_OVERRIDE;
4418
4419   if (instr->arity() == 0) {
4420     ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4421     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4422   } else if (instr->arity() == 1) {
4423     Label done;
4424     if (IsFastPackedElementsKind(kind)) {
4425       Label packed_case;
4426       // We might need a change here
4427       // look at the first argument
4428       __ mov(ecx, Operand(esp, 0));
4429       __ test(ecx, ecx);
4430       __ j(zero, &packed_case, Label::kNear);
4431
4432       ElementsKind holey_kind = GetHoleyElementsKind(kind);
4433       ArraySingleArgumentConstructorStub stub(isolate(),
4434                                               holey_kind,
4435                                               override_mode);
4436       CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4437       __ jmp(&done, Label::kNear);
4438       __ bind(&packed_case);
4439     }
4440
4441     ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4442     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4443     __ bind(&done);
4444   } else {
4445     ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4446     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4447   }
4448 }
4449
4450
4451 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4452   DCHECK(ToRegister(instr->context()).is(esi));
4453   CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4454 }
4455
4456
4457 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4458   Register function = ToRegister(instr->function());
4459   Register code_object = ToRegister(instr->code_object());
4460   __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4461   __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4462 }
4463
4464
4465 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4466   Register result = ToRegister(instr->result());
4467   Register base = ToRegister(instr->base_object());
4468   if (instr->offset()->IsConstantOperand()) {
4469     LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4470     __ lea(result, Operand(base, ToInteger32(offset)));
4471   } else {
4472     Register offset = ToRegister(instr->offset());
4473     __ lea(result, Operand(base, offset, times_1, 0));
4474   }
4475 }
4476
4477
4478 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4479   Representation representation = instr->hydrogen()->field_representation();
4480
4481   HObjectAccess access = instr->hydrogen()->access();
4482   int offset = access.offset();
4483
4484   if (access.IsExternalMemory()) {
4485     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4486     MemOperand operand = instr->object()->IsConstantOperand()
4487         ? MemOperand::StaticVariable(
4488             ToExternalReference(LConstantOperand::cast(instr->object())))
4489         : MemOperand(ToRegister(instr->object()), offset);
4490     if (instr->value()->IsConstantOperand()) {
4491       LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4492       __ mov(operand, Immediate(ToInteger32(operand_value)));
4493     } else {
4494       Register value = ToRegister(instr->value());
4495       __ Store(value, operand, representation);
4496     }
4497     return;
4498   }
4499
4500   Register object = ToRegister(instr->object());
4501   __ AssertNotSmi(object);
4502   DCHECK(!representation.IsSmi() ||
4503          !instr->value()->IsConstantOperand() ||
4504          IsSmi(LConstantOperand::cast(instr->value())));
4505   if (representation.IsDouble()) {
4506     DCHECK(access.IsInobject());
4507     DCHECK(!instr->hydrogen()->has_transition());
4508     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4509     X87Register value = ToX87Register(instr->value());
4510     X87Mov(FieldOperand(object, offset), value);
4511     return;
4512   }
4513
4514   if (instr->hydrogen()->has_transition()) {
4515     Handle<Map> transition = instr->hydrogen()->transition_map();
4516     AddDeprecationDependency(transition);
4517     __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4518     if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4519       Register temp = ToRegister(instr->temp());
4520       Register temp_map = ToRegister(instr->temp_map());
4521       __ mov(temp_map, transition);
4522       __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4523       // Update the write barrier for the map field.
4524       __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4525     }
4526   }
4527
4528   // Do the store.
4529   Register write_register = object;
4530   if (!access.IsInobject()) {
4531     write_register = ToRegister(instr->temp());
4532     __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4533   }
4534
4535   MemOperand operand = FieldOperand(write_register, offset);
4536   if (instr->value()->IsConstantOperand()) {
4537     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4538     if (operand_value->IsRegister()) {
4539       Register value = ToRegister(operand_value);
4540       __ Store(value, operand, representation);
4541     } else if (representation.IsInteger32()) {
4542       Immediate immediate = ToImmediate(operand_value, representation);
4543       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4544       __ mov(operand, immediate);
4545     } else {
4546       Handle<Object> handle_value = ToHandle(operand_value);
4547       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4548       __ mov(operand, handle_value);
4549     }
4550   } else {
4551     Register value = ToRegister(instr->value());
4552     __ Store(value, operand, representation);
4553   }
4554
4555   if (instr->hydrogen()->NeedsWriteBarrier()) {
4556     Register value = ToRegister(instr->value());
4557     Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4558     // Update the write barrier for the object for in-object properties.
4559     __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4560                         EMIT_REMEMBERED_SET,
4561                         instr->hydrogen()->SmiCheckForWriteBarrier(),
4562                         instr->hydrogen()->PointersToHereCheckForValue());
4563   }
4564 }
4565
4566
4567 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4568   DCHECK(ToRegister(instr->context()).is(esi));
4569   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4570   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4571
4572   __ mov(StoreDescriptor::NameRegister(), instr->name());
4573   Handle<Code> ic = StoreIC::initialize_stub(isolate(), instr->language_mode());
4574   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4575 }
4576
4577
4578 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4579   Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4580   if (instr->index()->IsConstantOperand()) {
4581     __ cmp(ToOperand(instr->length()),
4582            ToImmediate(LConstantOperand::cast(instr->index()),
4583                        instr->hydrogen()->length()->representation()));
4584     cc = CommuteCondition(cc);
4585   } else if (instr->length()->IsConstantOperand()) {
4586     __ cmp(ToOperand(instr->index()),
4587            ToImmediate(LConstantOperand::cast(instr->length()),
4588                        instr->hydrogen()->index()->representation()));
4589   } else {
4590     __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4591   }
4592   if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4593     Label done;
4594     __ j(NegateCondition(cc), &done, Label::kNear);
4595     __ int3();
4596     __ bind(&done);
4597   } else {
4598     DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4599   }
4600 }
4601
4602
4603 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4604   ElementsKind elements_kind = instr->elements_kind();
4605   LOperand* key = instr->key();
4606   if (!key->IsConstantOperand() &&
4607       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4608                                   elements_kind)) {
4609     __ SmiUntag(ToRegister(key));
4610   }
4611   Operand operand(BuildFastArrayOperand(
4612       instr->elements(),
4613       key,
4614       instr->hydrogen()->key()->representation(),
4615       elements_kind,
4616       instr->base_offset()));
4617   if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4618       elements_kind == FLOAT32_ELEMENTS) {
4619     X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4620   } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4621              elements_kind == FLOAT64_ELEMENTS) {
4622     uint64_t int_val = kHoleNanInt64;
4623     int32_t lower = static_cast<int32_t>(int_val);
4624     int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4625     Operand operand2 = BuildFastArrayOperand(
4626         instr->elements(), instr->key(),
4627         instr->hydrogen()->key()->representation(), elements_kind,
4628         instr->base_offset() + kPointerSize);
4629
4630     Label no_special_nan_handling, done;
4631     X87Register value = ToX87Register(instr->value());
4632     X87Fxch(value);
4633     __ lea(esp, Operand(esp, -kDoubleSize));
4634     __ fst_d(MemOperand(esp, 0));
4635     __ lea(esp, Operand(esp, kDoubleSize));
4636     int offset = sizeof(kHoleNanUpper32);
4637     // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4638     // so we check the upper with 0xffffffff for hole as a temporary fix.
4639     __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4640     __ j(not_equal, &no_special_nan_handling, Label::kNear);
4641     __ mov(operand, Immediate(lower));
4642     __ mov(operand2, Immediate(upper));
4643     __ jmp(&done, Label::kNear);
4644
4645     __ bind(&no_special_nan_handling);
4646     __ fst_d(operand);
4647     __ bind(&done);
4648   } else {
4649     Register value = ToRegister(instr->value());
4650     switch (elements_kind) {
4651       case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4652       case EXTERNAL_UINT8_ELEMENTS:
4653       case EXTERNAL_INT8_ELEMENTS:
4654       case UINT8_ELEMENTS:
4655       case INT8_ELEMENTS:
4656       case UINT8_CLAMPED_ELEMENTS:
4657         __ mov_b(operand, value);
4658         break;
4659       case EXTERNAL_INT16_ELEMENTS:
4660       case EXTERNAL_UINT16_ELEMENTS:
4661       case UINT16_ELEMENTS:
4662       case INT16_ELEMENTS:
4663         __ mov_w(operand, value);
4664         break;
4665       case EXTERNAL_INT32_ELEMENTS:
4666       case EXTERNAL_UINT32_ELEMENTS:
4667       case UINT32_ELEMENTS:
4668       case INT32_ELEMENTS:
4669         __ mov(operand, value);
4670         break;
4671       case EXTERNAL_FLOAT32_ELEMENTS:
4672       case EXTERNAL_FLOAT64_ELEMENTS:
4673       case FLOAT32_ELEMENTS:
4674       case FLOAT64_ELEMENTS:
4675       case FAST_SMI_ELEMENTS:
4676       case FAST_ELEMENTS:
4677       case FAST_DOUBLE_ELEMENTS:
4678       case FAST_HOLEY_SMI_ELEMENTS:
4679       case FAST_HOLEY_ELEMENTS:
4680       case FAST_HOLEY_DOUBLE_ELEMENTS:
4681       case DICTIONARY_ELEMENTS:
4682       case SLOPPY_ARGUMENTS_ELEMENTS:
4683         UNREACHABLE();
4684         break;
4685     }
4686   }
4687 }
4688
4689
4690 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4691   Operand double_store_operand = BuildFastArrayOperand(
4692       instr->elements(),
4693       instr->key(),
4694       instr->hydrogen()->key()->representation(),
4695       FAST_DOUBLE_ELEMENTS,
4696       instr->base_offset());
4697
4698   uint64_t int_val = kHoleNanInt64;
4699   int32_t lower = static_cast<int32_t>(int_val);
4700   int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4701   Operand double_store_operand2 = BuildFastArrayOperand(
4702       instr->elements(), instr->key(),
4703       instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
4704       instr->base_offset() + kPointerSize);
4705
4706   if (instr->hydrogen()->IsConstantHoleStore()) {
4707     // This means we should store the (double) hole. No floating point
4708     // registers required.
4709     __ mov(double_store_operand, Immediate(lower));
4710     __ mov(double_store_operand2, Immediate(upper));
4711   } else {
4712     Label no_special_nan_handling, done;
4713     X87Register value = ToX87Register(instr->value());
4714     X87Fxch(value);
4715
4716     if (instr->NeedsCanonicalization()) {
4717       __ fld(0);
4718       __ fld(0);
4719       __ FCmp();
4720       __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4721       // All NaNs are Canonicalized to 0x7fffffffffffffff
4722       __ mov(double_store_operand, Immediate(0xffffffff));
4723       __ mov(double_store_operand2, Immediate(0x7fffffff));
4724       __ jmp(&done, Label::kNear);
4725     } else {
4726       __ lea(esp, Operand(esp, -kDoubleSize));
4727       __ fst_d(MemOperand(esp, 0));
4728       __ lea(esp, Operand(esp, kDoubleSize));
4729       int offset = sizeof(kHoleNanUpper32);
4730       // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4731       // so we check the upper with 0xffffffff for hole as a temporary fix.
4732       __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4733       __ j(not_equal, &no_special_nan_handling, Label::kNear);
4734       __ mov(double_store_operand, Immediate(lower));
4735       __ mov(double_store_operand2, Immediate(upper));
4736       __ jmp(&done, Label::kNear);
4737     }
4738     __ bind(&no_special_nan_handling);
4739     __ fst_d(double_store_operand);
4740     __ bind(&done);
4741   }
4742 }
4743
4744
4745 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4746   Register elements = ToRegister(instr->elements());
4747   Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4748
4749   Operand operand = BuildFastArrayOperand(
4750       instr->elements(),
4751       instr->key(),
4752       instr->hydrogen()->key()->representation(),
4753       FAST_ELEMENTS,
4754       instr->base_offset());
4755   if (instr->value()->IsRegister()) {
4756     __ mov(operand, ToRegister(instr->value()));
4757   } else {
4758     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4759     if (IsSmi(operand_value)) {
4760       Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4761       __ mov(operand, immediate);
4762     } else {
4763       DCHECK(!IsInteger32(operand_value));
4764       Handle<Object> handle_value = ToHandle(operand_value);
4765       __ mov(operand, handle_value);
4766     }
4767   }
4768
4769   if (instr->hydrogen()->NeedsWriteBarrier()) {
4770     DCHECK(instr->value()->IsRegister());
4771     Register value = ToRegister(instr->value());
4772     DCHECK(!instr->key()->IsConstantOperand());
4773     SmiCheck check_needed =
4774         instr->hydrogen()->value()->type().IsHeapObject()
4775           ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4776     // Compute address of modified element and store it into key register.
4777     __ lea(key, operand);
4778     __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4779                    check_needed,
4780                    instr->hydrogen()->PointersToHereCheckForValue());
4781   }
4782 }
4783
4784
4785 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4786   // By cases...external, fast-double, fast
4787   if (instr->is_typed_elements()) {
4788     DoStoreKeyedExternalArray(instr);
4789   } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4790     DoStoreKeyedFixedDoubleArray(instr);
4791   } else {
4792     DoStoreKeyedFixedArray(instr);
4793   }
4794 }
4795
4796
4797 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4798   DCHECK(ToRegister(instr->context()).is(esi));
4799   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4800   DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4801   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4802
4803   Handle<Code> ic =
4804       CodeFactory::KeyedStoreIC(isolate(), instr->language_mode()).code();
4805   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4806 }
4807
4808
4809 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4810   Register object = ToRegister(instr->object());
4811   Register temp = ToRegister(instr->temp());
4812   Label no_memento_found;
4813   __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4814   DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4815   __ bind(&no_memento_found);
4816 }
4817
4818
4819 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4820   Register object_reg = ToRegister(instr->object());
4821
4822   Handle<Map> from_map = instr->original_map();
4823   Handle<Map> to_map = instr->transitioned_map();
4824   ElementsKind from_kind = instr->from_kind();
4825   ElementsKind to_kind = instr->to_kind();
4826
4827   Label not_applicable;
4828   bool is_simple_map_transition =
4829       IsSimpleMapChangeTransition(from_kind, to_kind);
4830   Label::Distance branch_distance =
4831       is_simple_map_transition ? Label::kNear : Label::kFar;
4832   __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4833   __ j(not_equal, &not_applicable, branch_distance);
4834   if (is_simple_map_transition) {
4835     Register new_map_reg = ToRegister(instr->new_map_temp());
4836     __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4837            Immediate(to_map));
4838     // Write barrier.
4839     DCHECK_NOT_NULL(instr->temp());
4840     __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4841                          ToRegister(instr->temp()), kDontSaveFPRegs);
4842   } else {
4843     DCHECK(ToRegister(instr->context()).is(esi));
4844     DCHECK(object_reg.is(eax));
4845     PushSafepointRegistersScope scope(this);
4846     __ mov(ebx, to_map);
4847     bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4848     TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4849     __ CallStub(&stub);
4850     RecordSafepointWithLazyDeopt(instr,
4851         RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4852   }
4853   __ bind(&not_applicable);
4854 }
4855
4856
4857 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4858   class DeferredStringCharCodeAt FINAL : public LDeferredCode {
4859    public:
4860     DeferredStringCharCodeAt(LCodeGen* codegen,
4861                              LStringCharCodeAt* instr,
4862                              const X87Stack& x87_stack)
4863         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4864     void Generate() OVERRIDE { codegen()->DoDeferredStringCharCodeAt(instr_); }
4865     LInstruction* instr() OVERRIDE { return instr_; }
4866
4867    private:
4868     LStringCharCodeAt* instr_;
4869   };
4870
4871   DeferredStringCharCodeAt* deferred =
4872       new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4873
4874   StringCharLoadGenerator::Generate(masm(),
4875                                     factory(),
4876                                     ToRegister(instr->string()),
4877                                     ToRegister(instr->index()),
4878                                     ToRegister(instr->result()),
4879                                     deferred->entry());
4880   __ bind(deferred->exit());
4881 }
4882
4883
4884 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4885   Register string = ToRegister(instr->string());
4886   Register result = ToRegister(instr->result());
4887
4888   // TODO(3095996): Get rid of this. For now, we need to make the
4889   // result register contain a valid pointer because it is already
4890   // contained in the register pointer map.
4891   __ Move(result, Immediate(0));
4892
4893   PushSafepointRegistersScope scope(this);
4894   __ push(string);
4895   // Push the index as a smi. This is safe because of the checks in
4896   // DoStringCharCodeAt above.
4897   STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4898   if (instr->index()->IsConstantOperand()) {
4899     Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4900                                       Representation::Smi());
4901     __ push(immediate);
4902   } else {
4903     Register index = ToRegister(instr->index());
4904     __ SmiTag(index);
4905     __ push(index);
4906   }
4907   CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4908                           instr, instr->context());
4909   __ AssertSmi(eax);
4910   __ SmiUntag(eax);
4911   __ StoreToSafepointRegisterSlot(result, eax);
4912 }
4913
4914
4915 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4916   class DeferredStringCharFromCode FINAL : public LDeferredCode {
4917    public:
4918     DeferredStringCharFromCode(LCodeGen* codegen,
4919                                LStringCharFromCode* instr,
4920                                const X87Stack& x87_stack)
4921         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4922     void Generate() OVERRIDE {
4923       codegen()->DoDeferredStringCharFromCode(instr_);
4924     }
4925     LInstruction* instr() OVERRIDE { return instr_; }
4926
4927    private:
4928     LStringCharFromCode* instr_;
4929   };
4930
4931   DeferredStringCharFromCode* deferred =
4932       new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
4933
4934   DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4935   Register char_code = ToRegister(instr->char_code());
4936   Register result = ToRegister(instr->result());
4937   DCHECK(!char_code.is(result));
4938
4939   __ cmp(char_code, String::kMaxOneByteCharCode);
4940   __ j(above, deferred->entry());
4941   __ Move(result, Immediate(factory()->single_character_string_cache()));
4942   __ mov(result, FieldOperand(result,
4943                               char_code, times_pointer_size,
4944                               FixedArray::kHeaderSize));
4945   __ cmp(result, factory()->undefined_value());
4946   __ j(equal, deferred->entry());
4947   __ bind(deferred->exit());
4948 }
4949
4950
4951 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4952   Register char_code = ToRegister(instr->char_code());
4953   Register result = ToRegister(instr->result());
4954
4955   // TODO(3095996): Get rid of this. For now, we need to make the
4956   // result register contain a valid pointer because it is already
4957   // contained in the register pointer map.
4958   __ Move(result, Immediate(0));
4959
4960   PushSafepointRegistersScope scope(this);
4961   __ SmiTag(char_code);
4962   __ push(char_code);
4963   CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4964   __ StoreToSafepointRegisterSlot(result, eax);
4965 }
4966
4967
4968 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4969   DCHECK(ToRegister(instr->context()).is(esi));
4970   DCHECK(ToRegister(instr->left()).is(edx));
4971   DCHECK(ToRegister(instr->right()).is(eax));
4972   StringAddStub stub(isolate(),
4973                      instr->hydrogen()->flags(),
4974                      instr->hydrogen()->pretenure_flag());
4975   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4976 }
4977
4978
4979 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4980   LOperand* input = instr->value();
4981   LOperand* output = instr->result();
4982   DCHECK(input->IsRegister() || input->IsStackSlot());
4983   DCHECK(output->IsDoubleRegister());
4984   if (input->IsRegister()) {
4985     Register input_reg = ToRegister(input);
4986     __ push(input_reg);
4987     X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
4988     __ pop(input_reg);
4989   } else {
4990     X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
4991   }
4992 }
4993
4994
4995 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4996   LOperand* input = instr->value();
4997   LOperand* output = instr->result();
4998   X87Register res = ToX87Register(output);
4999   X87PrepareToWrite(res);
5000   __ LoadUint32NoSSE2(ToRegister(input));
5001   X87CommitWrite(res);
5002 }
5003
5004
5005 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
5006   class DeferredNumberTagI FINAL : public LDeferredCode {
5007    public:
5008     DeferredNumberTagI(LCodeGen* codegen,
5009                        LNumberTagI* instr,
5010                        const X87Stack& x87_stack)
5011         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5012     void Generate() OVERRIDE {
5013       codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5014                                        SIGNED_INT32);
5015     }
5016     LInstruction* instr() OVERRIDE { return instr_; }
5017
5018    private:
5019     LNumberTagI* instr_;
5020   };
5021
5022   LOperand* input = instr->value();
5023   DCHECK(input->IsRegister() && input->Equals(instr->result()));
5024   Register reg = ToRegister(input);
5025
5026   DeferredNumberTagI* deferred =
5027       new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
5028   __ SmiTag(reg);
5029   __ j(overflow, deferred->entry());
5030   __ bind(deferred->exit());
5031 }
5032
5033
5034 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5035   class DeferredNumberTagU FINAL : public LDeferredCode {
5036    public:
5037     DeferredNumberTagU(LCodeGen* codegen,
5038                        LNumberTagU* instr,
5039                        const X87Stack& x87_stack)
5040         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5041     void Generate() OVERRIDE {
5042       codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5043                                        UNSIGNED_INT32);
5044     }
5045     LInstruction* instr() OVERRIDE { return instr_; }
5046
5047    private:
5048     LNumberTagU* instr_;
5049   };
5050
5051   LOperand* input = instr->value();
5052   DCHECK(input->IsRegister() && input->Equals(instr->result()));
5053   Register reg = ToRegister(input);
5054
5055   DeferredNumberTagU* deferred =
5056       new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
5057   __ cmp(reg, Immediate(Smi::kMaxValue));
5058   __ j(above, deferred->entry());
5059   __ SmiTag(reg);
5060   __ bind(deferred->exit());
5061 }
5062
5063
5064 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
5065                                      LOperand* value,
5066                                      LOperand* temp,
5067                                      IntegerSignedness signedness) {
5068   Label done, slow;
5069   Register reg = ToRegister(value);
5070   Register tmp = ToRegister(temp);
5071
5072   if (signedness == SIGNED_INT32) {
5073     // There was overflow, so bits 30 and 31 of the original integer
5074     // disagree. Try to allocate a heap number in new space and store
5075     // the value in there. If that fails, call the runtime system.
5076     __ SmiUntag(reg);
5077     __ xor_(reg, 0x80000000);
5078     __ push(reg);
5079     __ fild_s(Operand(esp, 0));
5080     __ pop(reg);
5081   } else {
5082     // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5083     // int manually.
5084     __ push(Immediate(0));
5085     __ push(reg);
5086     __ fild_d(Operand(esp, 0));
5087     __ pop(reg);
5088     __ pop(reg);
5089   }
5090
5091   if (FLAG_inline_new) {
5092     __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5093     __ jmp(&done, Label::kNear);
5094   }
5095
5096   // Slow case: Call the runtime system to do the number allocation.
5097   __ bind(&slow);
5098   {
5099     // TODO(3095996): Put a valid pointer value in the stack slot where the
5100     // result register is stored, as this register is in the pointer map, but
5101     // contains an integer value.
5102     __ Move(reg, Immediate(0));
5103
5104     // Preserve the value of all registers.
5105     PushSafepointRegistersScope scope(this);
5106
5107     // NumberTagI and NumberTagD use the context from the frame, rather than
5108     // the environment's HContext or HInlinedContext value.
5109     // They only call Runtime::kAllocateHeapNumber.
5110     // The corresponding HChange instructions are added in a phase that does
5111     // not have easy access to the local context.
5112     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5113     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5114     RecordSafepointWithRegisters(
5115         instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5116     __ StoreToSafepointRegisterSlot(reg, eax);
5117   }
5118
5119   __ bind(&done);
5120   __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5121 }
5122
5123
5124 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5125   class DeferredNumberTagD FINAL : public LDeferredCode {
5126    public:
5127     DeferredNumberTagD(LCodeGen* codegen,
5128                        LNumberTagD* instr,
5129                        const X87Stack& x87_stack)
5130         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5131     void Generate() OVERRIDE { codegen()->DoDeferredNumberTagD(instr_); }
5132     LInstruction* instr() OVERRIDE { return instr_; }
5133
5134    private:
5135     LNumberTagD* instr_;
5136   };
5137
5138   Register reg = ToRegister(instr->result());
5139
5140   // Put the value to the top of stack
5141   X87Register src = ToX87Register(instr->value());
5142   // Don't use X87LoadForUsage here, which is only used by Instruction which
5143   // clobbers fp registers.
5144   x87_stack_.Fxch(src);
5145
5146   DeferredNumberTagD* deferred =
5147       new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5148   if (FLAG_inline_new) {
5149     Register tmp = ToRegister(instr->temp());
5150     __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5151   } else {
5152     __ jmp(deferred->entry());
5153   }
5154   __ bind(deferred->exit());
5155   __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5156 }
5157
5158
5159 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5160   // TODO(3095996): Get rid of this. For now, we need to make the
5161   // result register contain a valid pointer because it is already
5162   // contained in the register pointer map.
5163   Register reg = ToRegister(instr->result());
5164   __ Move(reg, Immediate(0));
5165
5166   PushSafepointRegistersScope scope(this);
5167   // NumberTagI and NumberTagD use the context from the frame, rather than
5168   // the environment's HContext or HInlinedContext value.
5169   // They only call Runtime::kAllocateHeapNumber.
5170   // The corresponding HChange instructions are added in a phase that does
5171   // not have easy access to the local context.
5172   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5173   __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5174   RecordSafepointWithRegisters(
5175       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5176   __ StoreToSafepointRegisterSlot(reg, eax);
5177 }
5178
5179
5180 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5181   HChange* hchange = instr->hydrogen();
5182   Register input = ToRegister(instr->value());
5183   if (hchange->CheckFlag(HValue::kCanOverflow) &&
5184       hchange->value()->CheckFlag(HValue::kUint32)) {
5185     __ test(input, Immediate(0xc0000000));
5186     DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
5187   }
5188   __ SmiTag(input);
5189   if (hchange->CheckFlag(HValue::kCanOverflow) &&
5190       !hchange->value()->CheckFlag(HValue::kUint32)) {
5191     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5192   }
5193 }
5194
5195
5196 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5197   LOperand* input = instr->value();
5198   Register result = ToRegister(input);
5199   DCHECK(input->IsRegister() && input->Equals(instr->result()));
5200   if (instr->needs_check()) {
5201     __ test(result, Immediate(kSmiTagMask));
5202     DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5203   } else {
5204     __ AssertSmi(result);
5205   }
5206   __ SmiUntag(result);
5207 }
5208
5209
5210 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5211                                       Register temp_reg, X87Register res_reg,
5212                                       NumberUntagDMode mode) {
5213   bool can_convert_undefined_to_nan =
5214       instr->hydrogen()->can_convert_undefined_to_nan();
5215   bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5216
5217   Label load_smi, done;
5218
5219   X87PrepareToWrite(res_reg);
5220   if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5221     // Smi check.
5222     __ JumpIfSmi(input_reg, &load_smi);
5223
5224     // Heap number map check.
5225     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5226            factory()->heap_number_map());
5227     if (!can_convert_undefined_to_nan) {
5228       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5229     } else {
5230       Label heap_number, convert;
5231       __ j(equal, &heap_number);
5232
5233       // Convert undefined (or hole) to NaN.
5234       __ cmp(input_reg, factory()->undefined_value());
5235       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5236
5237       __ bind(&convert);
5238       __ push(Immediate(0xffffffff));
5239       __ push(Immediate(0x7fffffff));
5240       __ fld_d(MemOperand(esp, 0));
5241       __ lea(esp, Operand(esp, kDoubleSize));
5242       __ jmp(&done, Label::kNear);
5243
5244       __ bind(&heap_number);
5245     }
5246     // Heap number to x87 conversion.
5247     __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5248     if (deoptimize_on_minus_zero) {
5249       __ fldz();
5250       __ FCmp();
5251       __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5252       __ j(not_zero, &done, Label::kNear);
5253
5254       // Use general purpose registers to check if we have -0.0
5255       __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5256       __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5257       __ j(zero, &done, Label::kNear);
5258
5259       // Pop FPU stack before deoptimizing.
5260       __ fstp(0);
5261       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5262     }
5263     __ jmp(&done, Label::kNear);
5264   } else {
5265     DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5266   }
5267
5268   __ bind(&load_smi);
5269   // Clobbering a temp is faster than re-tagging the
5270   // input register since we avoid dependencies.
5271   __ mov(temp_reg, input_reg);
5272   __ SmiUntag(temp_reg);  // Untag smi before converting to float.
5273   __ push(temp_reg);
5274   __ fild_s(Operand(esp, 0));
5275   __ add(esp, Immediate(kPointerSize));
5276   __ bind(&done);
5277   X87CommitWrite(res_reg);
5278 }
5279
5280
5281 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5282   Register input_reg = ToRegister(instr->value());
5283
5284   // The input was optimistically untagged; revert it.
5285   STATIC_ASSERT(kSmiTagSize == 1);
5286   __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5287
5288   if (instr->truncating()) {
5289     Label no_heap_number, check_bools, check_false;
5290
5291     // Heap number map check.
5292     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5293            factory()->heap_number_map());
5294     __ j(not_equal, &no_heap_number, Label::kNear);
5295     __ TruncateHeapNumberToI(input_reg, input_reg);
5296     __ jmp(done);
5297
5298     __ bind(&no_heap_number);
5299     // Check for Oddballs. Undefined/False is converted to zero and True to one
5300     // for truncating conversions.
5301     __ cmp(input_reg, factory()->undefined_value());
5302     __ j(not_equal, &check_bools, Label::kNear);
5303     __ Move(input_reg, Immediate(0));
5304     __ jmp(done);
5305
5306     __ bind(&check_bools);
5307     __ cmp(input_reg, factory()->true_value());
5308     __ j(not_equal, &check_false, Label::kNear);
5309     __ Move(input_reg, Immediate(1));
5310     __ jmp(done);
5311
5312     __ bind(&check_false);
5313     __ cmp(input_reg, factory()->false_value());
5314     DeoptimizeIf(not_equal, instr,
5315                  Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5316     __ Move(input_reg, Immediate(0));
5317   } else {
5318     // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5319     // should first try a fast conversion and then bailout to this slow case.
5320     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5321            isolate()->factory()->heap_number_map());
5322     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5323
5324     __ sub(esp, Immediate(kPointerSize));
5325     __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5326
5327     if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5328       Label no_precision_lost, not_nan, zero_check;
5329       __ fld(0);
5330
5331       __ fist_s(MemOperand(esp, 0));
5332       __ fild_s(MemOperand(esp, 0));
5333       __ FCmp();
5334       __ pop(input_reg);
5335
5336       __ j(equal, &no_precision_lost, Label::kNear);
5337       __ fstp(0);
5338       DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5339       __ bind(&no_precision_lost);
5340
5341       __ j(parity_odd, &not_nan);
5342       __ fstp(0);
5343       DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5344       __ bind(&not_nan);
5345
5346       __ test(input_reg, Operand(input_reg));
5347       __ j(zero, &zero_check, Label::kNear);
5348       __ fstp(0);
5349       __ jmp(done);
5350
5351       __ bind(&zero_check);
5352       // To check for minus zero, we load the value again as float, and check
5353       // if that is still 0.
5354       __ sub(esp, Immediate(kPointerSize));
5355       __ fstp_s(Operand(esp, 0));
5356       __ pop(input_reg);
5357       __ test(input_reg, Operand(input_reg));
5358       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5359     } else {
5360       __ fist_s(MemOperand(esp, 0));
5361       __ fild_s(MemOperand(esp, 0));
5362       __ FCmp();
5363       __ pop(input_reg);
5364       DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
5365       DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5366     }
5367   }
5368 }
5369
5370
5371 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5372   class DeferredTaggedToI FINAL : public LDeferredCode {
5373    public:
5374     DeferredTaggedToI(LCodeGen* codegen,
5375                       LTaggedToI* instr,
5376                       const X87Stack& x87_stack)
5377         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5378     void Generate() OVERRIDE { codegen()->DoDeferredTaggedToI(instr_, done()); }
5379     LInstruction* instr() OVERRIDE { return instr_; }
5380
5381    private:
5382     LTaggedToI* instr_;
5383   };
5384
5385   LOperand* input = instr->value();
5386   DCHECK(input->IsRegister());
5387   Register input_reg = ToRegister(input);
5388   DCHECK(input_reg.is(ToRegister(instr->result())));
5389
5390   if (instr->hydrogen()->value()->representation().IsSmi()) {
5391     __ SmiUntag(input_reg);
5392   } else {
5393     DeferredTaggedToI* deferred =
5394         new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5395     // Optimistically untag the input.
5396     // If the input is a HeapObject, SmiUntag will set the carry flag.
5397     STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5398     __ SmiUntag(input_reg);
5399     // Branch to deferred code if the input was tagged.
5400     // The deferred code will take care of restoring the tag.
5401     __ j(carry, deferred->entry());
5402     __ bind(deferred->exit());
5403   }
5404 }
5405
5406
5407 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5408   LOperand* input = instr->value();
5409   DCHECK(input->IsRegister());
5410   LOperand* temp = instr->temp();
5411   DCHECK(temp->IsRegister());
5412   LOperand* result = instr->result();
5413   DCHECK(result->IsDoubleRegister());
5414
5415   Register input_reg = ToRegister(input);
5416   Register temp_reg = ToRegister(temp);
5417
5418   HValue* value = instr->hydrogen()->value();
5419   NumberUntagDMode mode = value->representation().IsSmi()
5420       ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5421
5422   EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5423                          mode);
5424 }
5425
5426
5427 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5428   LOperand* input = instr->value();
5429   DCHECK(input->IsDoubleRegister());
5430   LOperand* result = instr->result();
5431   DCHECK(result->IsRegister());
5432   Register result_reg = ToRegister(result);
5433
5434   if (instr->truncating()) {
5435     X87Register input_reg = ToX87Register(input);
5436     X87Fxch(input_reg);
5437     __ TruncateX87TOSToI(result_reg);
5438   } else {
5439     Label lost_precision, is_nan, minus_zero, done;
5440     X87Register input_reg = ToX87Register(input);
5441     X87Fxch(input_reg);
5442     __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5443                  &lost_precision, &is_nan, &minus_zero);
5444     __ jmp(&done);
5445     __ bind(&lost_precision);
5446     DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5447     __ bind(&is_nan);
5448     DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5449     __ bind(&minus_zero);
5450     DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5451     __ bind(&done);
5452   }
5453 }
5454
5455
5456 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5457   LOperand* input = instr->value();
5458   DCHECK(input->IsDoubleRegister());
5459   LOperand* result = instr->result();
5460   DCHECK(result->IsRegister());
5461   Register result_reg = ToRegister(result);
5462
5463   Label lost_precision, is_nan, minus_zero, done;
5464   X87Register input_reg = ToX87Register(input);
5465   X87Fxch(input_reg);
5466   __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5467                &lost_precision, &is_nan, &minus_zero);
5468   __ jmp(&done);
5469   __ bind(&lost_precision);
5470   DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5471   __ bind(&is_nan);
5472   DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5473   __ bind(&minus_zero);
5474   DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5475   __ bind(&done);
5476   __ SmiTag(result_reg);
5477   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5478 }
5479
5480
5481 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5482   LOperand* input = instr->value();
5483   __ test(ToOperand(input), Immediate(kSmiTagMask));
5484   DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5485 }
5486
5487
5488 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5489   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5490     LOperand* input = instr->value();
5491     __ test(ToOperand(input), Immediate(kSmiTagMask));
5492     DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5493   }
5494 }
5495
5496
5497 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5498   Register input = ToRegister(instr->value());
5499   Register temp = ToRegister(instr->temp());
5500
5501   __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5502
5503   if (instr->hydrogen()->is_interval_check()) {
5504     InstanceType first;
5505     InstanceType last;
5506     instr->hydrogen()->GetCheckInterval(&first, &last);
5507
5508     __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5509             static_cast<int8_t>(first));
5510
5511     // If there is only one type in the interval check for equality.
5512     if (first == last) {
5513       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5514     } else {
5515       DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5516       // Omit check for the last type.
5517       if (last != LAST_TYPE) {
5518         __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5519                 static_cast<int8_t>(last));
5520         DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5521       }
5522     }
5523   } else {
5524     uint8_t mask;
5525     uint8_t tag;
5526     instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5527
5528     if (base::bits::IsPowerOfTwo32(mask)) {
5529       DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5530       __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5531       DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5532                    Deoptimizer::kWrongInstanceType);
5533     } else {
5534       __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5535       __ and_(temp, mask);
5536       __ cmp(temp, tag);
5537       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5538     }
5539   }
5540 }
5541
5542
5543 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5544   Handle<HeapObject> object = instr->hydrogen()->object().handle();
5545   if (instr->hydrogen()->object_in_new_space()) {
5546     Register reg = ToRegister(instr->value());
5547     Handle<Cell> cell = isolate()->factory()->NewCell(object);
5548     __ cmp(reg, Operand::ForCell(cell));
5549   } else {
5550     Operand operand = ToOperand(instr->value());
5551     __ cmp(operand, object);
5552   }
5553   DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5554 }
5555
5556
5557 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5558   {
5559     PushSafepointRegistersScope scope(this);
5560     __ push(object);
5561     __ xor_(esi, esi);
5562     __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5563     RecordSafepointWithRegisters(
5564         instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5565
5566     __ test(eax, Immediate(kSmiTagMask));
5567   }
5568   DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5569 }
5570
5571
5572 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5573   class DeferredCheckMaps FINAL : public LDeferredCode {
5574    public:
5575     DeferredCheckMaps(LCodeGen* codegen,
5576                       LCheckMaps* instr,
5577                       Register object,
5578                       const X87Stack& x87_stack)
5579         : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5580       SetExit(check_maps());
5581     }
5582     void Generate() OVERRIDE {
5583       codegen()->DoDeferredInstanceMigration(instr_, object_);
5584     }
5585     Label* check_maps() { return &check_maps_; }
5586     LInstruction* instr() OVERRIDE { return instr_; }
5587
5588    private:
5589     LCheckMaps* instr_;
5590     Label check_maps_;
5591     Register object_;
5592   };
5593
5594   if (instr->hydrogen()->IsStabilityCheck()) {
5595     const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5596     for (int i = 0; i < maps->size(); ++i) {
5597       AddStabilityDependency(maps->at(i).handle());
5598     }
5599     return;
5600   }
5601
5602   LOperand* input = instr->value();
5603   DCHECK(input->IsRegister());
5604   Register reg = ToRegister(input);
5605
5606   DeferredCheckMaps* deferred = NULL;
5607   if (instr->hydrogen()->HasMigrationTarget()) {
5608     deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5609     __ bind(deferred->check_maps());
5610   }
5611
5612   const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5613   Label success;
5614   for (int i = 0; i < maps->size() - 1; i++) {
5615     Handle<Map> map = maps->at(i).handle();
5616     __ CompareMap(reg, map);
5617     __ j(equal, &success, Label::kNear);
5618   }
5619
5620   Handle<Map> map = maps->at(maps->size() - 1).handle();
5621   __ CompareMap(reg, map);
5622   if (instr->hydrogen()->HasMigrationTarget()) {
5623     __ j(not_equal, deferred->entry());
5624   } else {
5625     DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5626   }
5627
5628   __ bind(&success);
5629 }
5630
5631
5632 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5633   X87Register value_reg = ToX87Register(instr->unclamped());
5634   Register result_reg = ToRegister(instr->result());
5635   X87Fxch(value_reg);
5636   __ ClampTOSToUint8(result_reg);
5637 }
5638
5639
5640 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5641   DCHECK(instr->unclamped()->Equals(instr->result()));
5642   Register value_reg = ToRegister(instr->result());
5643   __ ClampUint8(value_reg);
5644 }
5645
5646
5647 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5648   Register input_reg = ToRegister(instr->unclamped());
5649   Register result_reg = ToRegister(instr->result());
5650   Register scratch = ToRegister(instr->scratch());
5651   Register scratch2 = ToRegister(instr->scratch2());
5652   Register scratch3 = ToRegister(instr->scratch3());
5653   Label is_smi, done, heap_number, valid_exponent,
5654       largest_value, zero_result, maybe_nan_or_infinity;
5655
5656   __ JumpIfSmi(input_reg, &is_smi);
5657
5658   // Check for heap number
5659   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5660          factory()->heap_number_map());
5661   __ j(equal, &heap_number, Label::kNear);
5662
5663   // Check for undefined. Undefined is converted to zero for clamping
5664   // conversions.
5665   __ cmp(input_reg, factory()->undefined_value());
5666   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5667   __ jmp(&zero_result, Label::kNear);
5668
5669   // Heap number
5670   __ bind(&heap_number);
5671
5672   // Surprisingly, all of the hand-crafted bit-manipulations below are much
5673   // faster than the x86 FPU built-in instruction, especially since "banker's
5674   // rounding" would be additionally very expensive
5675
5676   // Get exponent word.
5677   __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5678   __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5679
5680   // Test for negative values --> clamp to zero
5681   __ test(scratch, scratch);
5682   __ j(negative, &zero_result, Label::kNear);
5683
5684   // Get exponent alone in scratch2.
5685   __ mov(scratch2, scratch);
5686   __ and_(scratch2, HeapNumber::kExponentMask);
5687   __ shr(scratch2, HeapNumber::kExponentShift);
5688   __ j(zero, &zero_result, Label::kNear);
5689   __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5690   __ j(negative, &zero_result, Label::kNear);
5691
5692   const uint32_t non_int8_exponent = 7;
5693   __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5694   // If the exponent is too big, check for special values.
5695   __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5696
5697   __ bind(&valid_exponent);
5698   // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5699   // < 7. The shift bias is the number of bits to shift the mantissa such that
5700   // with an exponent of 7 such the that top-most one is in bit 30, allowing
5701   // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5702   // 1).
5703   int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5704   __ lea(result_reg, MemOperand(scratch2, shift_bias));
5705   // Here result_reg (ecx) is the shift, scratch is the exponent word.  Get the
5706   // top bits of the mantissa.
5707   __ and_(scratch, HeapNumber::kMantissaMask);
5708   // Put back the implicit 1 of the mantissa
5709   __ or_(scratch, 1 << HeapNumber::kExponentShift);
5710   // Shift up to round
5711   __ shl_cl(scratch);
5712   // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5713   // use the bit in the "ones" place and add it to the "halves" place, which has
5714   // the effect of rounding to even.
5715   __ mov(scratch2, scratch);
5716   const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5717   const uint32_t one_bit_shift = one_half_bit_shift + 1;
5718   __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5719   __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5720   Label no_round;
5721   __ j(less, &no_round, Label::kNear);
5722   Label round_up;
5723   __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5724   __ j(greater, &round_up, Label::kNear);
5725   __ test(scratch3, scratch3);
5726   __ j(not_zero, &round_up, Label::kNear);
5727   __ mov(scratch2, scratch);
5728   __ and_(scratch2, Immediate(1 << one_bit_shift));
5729   __ shr(scratch2, 1);
5730   __ bind(&round_up);
5731   __ add(scratch, scratch2);
5732   __ j(overflow, &largest_value, Label::kNear);
5733   __ bind(&no_round);
5734   __ shr(scratch, 23);
5735   __ mov(result_reg, scratch);
5736   __ jmp(&done, Label::kNear);
5737
5738   __ bind(&maybe_nan_or_infinity);
5739   // Check for NaN/Infinity, all other values map to 255
5740   __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5741   __ j(not_equal, &largest_value, Label::kNear);
5742
5743   // Check for NaN, which differs from Infinity in that at least one mantissa
5744   // bit is set.
5745   __ and_(scratch, HeapNumber::kMantissaMask);
5746   __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5747   __ j(not_zero, &zero_result, Label::kNear);  // M!=0 --> NaN
5748   // Infinity -> Fall through to map to 255.
5749
5750   __ bind(&largest_value);
5751   __ mov(result_reg, Immediate(255));
5752   __ jmp(&done, Label::kNear);
5753
5754   __ bind(&zero_result);
5755   __ xor_(result_reg, result_reg);
5756   __ jmp(&done, Label::kNear);
5757
5758   // smi
5759   __ bind(&is_smi);
5760   if (!input_reg.is(result_reg)) {
5761     __ mov(result_reg, input_reg);
5762   }
5763   __ SmiUntag(result_reg);
5764   __ ClampUint8(result_reg);
5765   __ bind(&done);
5766 }
5767
5768
5769 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5770   X87Register value_reg = ToX87Register(instr->value());
5771   Register result_reg = ToRegister(instr->result());
5772   X87Fxch(value_reg);
5773   __ sub(esp, Immediate(kDoubleSize));
5774   __ fst_d(Operand(esp, 0));
5775   if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5776     __ mov(result_reg, Operand(esp, kPointerSize));
5777   } else {
5778     __ mov(result_reg, Operand(esp, 0));
5779   }
5780   __ add(esp, Immediate(kDoubleSize));
5781 }
5782
5783
5784 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5785   Register hi_reg = ToRegister(instr->hi());
5786   Register lo_reg = ToRegister(instr->lo());
5787   X87Register result_reg = ToX87Register(instr->result());
5788   // Follow below pattern to write a x87 fp register.
5789   X87PrepareToWrite(result_reg);
5790   __ sub(esp, Immediate(kDoubleSize));
5791   __ mov(Operand(esp, 0), lo_reg);
5792   __ mov(Operand(esp, kPointerSize), hi_reg);
5793   __ fld_d(Operand(esp, 0));
5794   __ add(esp, Immediate(kDoubleSize));
5795   X87CommitWrite(result_reg);
5796 }
5797
5798
5799 void LCodeGen::DoAllocate(LAllocate* instr) {
5800   class DeferredAllocate FINAL : public LDeferredCode {
5801    public:
5802     DeferredAllocate(LCodeGen* codegen,
5803                      LAllocate* instr,
5804                      const X87Stack& x87_stack)
5805         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5806     void Generate() OVERRIDE { codegen()->DoDeferredAllocate(instr_); }
5807     LInstruction* instr() OVERRIDE { return instr_; }
5808
5809    private:
5810     LAllocate* instr_;
5811   };
5812
5813   DeferredAllocate* deferred =
5814       new(zone()) DeferredAllocate(this, instr, x87_stack_);
5815
5816   Register result = ToRegister(instr->result());
5817   Register temp = ToRegister(instr->temp());
5818
5819   // Allocate memory for the object.
5820   AllocationFlags flags = TAG_OBJECT;
5821   if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5822     flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5823   }
5824   if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5825     DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5826     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5827     flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5828   } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5829     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5830     flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5831   }
5832
5833   if (instr->size()->IsConstantOperand()) {
5834     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5835     if (size <= Page::kMaxRegularHeapObjectSize) {
5836       __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5837     } else {
5838       __ jmp(deferred->entry());
5839     }
5840   } else {
5841     Register size = ToRegister(instr->size());
5842     __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5843   }
5844
5845   __ bind(deferred->exit());
5846
5847   if (instr->hydrogen()->MustPrefillWithFiller()) {
5848     if (instr->size()->IsConstantOperand()) {
5849       int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5850       __ mov(temp, (size / kPointerSize) - 1);
5851     } else {
5852       temp = ToRegister(instr->size());
5853       __ shr(temp, kPointerSizeLog2);
5854       __ dec(temp);
5855     }
5856     Label loop;
5857     __ bind(&loop);
5858     __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5859         isolate()->factory()->one_pointer_filler_map());
5860     __ dec(temp);
5861     __ j(not_zero, &loop);
5862   }
5863 }
5864
5865
5866 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5867   Register result = ToRegister(instr->result());
5868
5869   // TODO(3095996): Get rid of this. For now, we need to make the
5870   // result register contain a valid pointer because it is already
5871   // contained in the register pointer map.
5872   __ Move(result, Immediate(Smi::FromInt(0)));
5873
5874   PushSafepointRegistersScope scope(this);
5875   if (instr->size()->IsRegister()) {
5876     Register size = ToRegister(instr->size());
5877     DCHECK(!size.is(result));
5878     __ SmiTag(ToRegister(instr->size()));
5879     __ push(size);
5880   } else {
5881     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5882     if (size >= 0 && size <= Smi::kMaxValue) {
5883       __ push(Immediate(Smi::FromInt(size)));
5884     } else {
5885       // We should never get here at runtime => abort
5886       __ int3();
5887       return;
5888     }
5889   }
5890
5891   int flags = AllocateDoubleAlignFlag::encode(
5892       instr->hydrogen()->MustAllocateDoubleAligned());
5893   if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5894     DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5895     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5896     flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5897   } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5898     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5899     flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5900   } else {
5901     flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5902   }
5903   __ push(Immediate(Smi::FromInt(flags)));
5904
5905   CallRuntimeFromDeferred(
5906       Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5907   __ StoreToSafepointRegisterSlot(result, eax);
5908 }
5909
5910
5911 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5912   DCHECK(ToRegister(instr->value()).is(eax));
5913   __ push(eax);
5914   CallRuntime(Runtime::kToFastProperties, 1, instr);
5915 }
5916
5917
5918 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5919   DCHECK(ToRegister(instr->context()).is(esi));
5920   Label materialized;
5921   // Registers will be used as follows:
5922   // ecx = literals array.
5923   // ebx = regexp literal.
5924   // eax = regexp literal clone.
5925   // esi = context.
5926   int literal_offset =
5927       FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5928   __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5929   __ mov(ebx, FieldOperand(ecx, literal_offset));
5930   __ cmp(ebx, factory()->undefined_value());
5931   __ j(not_equal, &materialized, Label::kNear);
5932
5933   // Create regexp literal using runtime function
5934   // Result will be in eax.
5935   __ push(ecx);
5936   __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5937   __ push(Immediate(instr->hydrogen()->pattern()));
5938   __ push(Immediate(instr->hydrogen()->flags()));
5939   CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5940   __ mov(ebx, eax);
5941
5942   __ bind(&materialized);
5943   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5944   Label allocated, runtime_allocate;
5945   __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5946   __ jmp(&allocated, Label::kNear);
5947
5948   __ bind(&runtime_allocate);
5949   __ push(ebx);
5950   __ push(Immediate(Smi::FromInt(size)));
5951   CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5952   __ pop(ebx);
5953
5954   __ bind(&allocated);
5955   // Copy the content into the newly allocated memory.
5956   // (Unroll copy loop once for better throughput).
5957   for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5958     __ mov(edx, FieldOperand(ebx, i));
5959     __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5960     __ mov(FieldOperand(eax, i), edx);
5961     __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5962   }
5963   if ((size % (2 * kPointerSize)) != 0) {
5964     __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5965     __ mov(FieldOperand(eax, size - kPointerSize), edx);
5966   }
5967 }
5968
5969
5970 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5971   DCHECK(ToRegister(instr->context()).is(esi));
5972   // Use the fast case closure allocation code that allocates in new
5973   // space for nested functions that don't need literals cloning.
5974   bool pretenure = instr->hydrogen()->pretenure();
5975   if (!pretenure && instr->hydrogen()->has_no_literals()) {
5976     FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5977                             instr->hydrogen()->kind());
5978     __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5979     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5980   } else {
5981     __ push(esi);
5982     __ push(Immediate(instr->hydrogen()->shared_info()));
5983     __ push(Immediate(pretenure ? factory()->true_value()
5984                                 : factory()->false_value()));
5985     CallRuntime(Runtime::kNewClosure, 3, instr);
5986   }
5987 }
5988
5989
5990 void LCodeGen::DoTypeof(LTypeof* instr) {
5991   DCHECK(ToRegister(instr->context()).is(esi));
5992   LOperand* input = instr->value();
5993   EmitPushTaggedOperand(input);
5994   CallRuntime(Runtime::kTypeof, 1, instr);
5995 }
5996
5997
5998 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5999   Register input = ToRegister(instr->value());
6000   Condition final_branch_condition = EmitTypeofIs(instr, input);
6001   if (final_branch_condition != no_condition) {
6002     EmitBranch(instr, final_branch_condition);
6003   }
6004 }
6005
6006
6007 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
6008   Label* true_label = instr->TrueLabel(chunk_);
6009   Label* false_label = instr->FalseLabel(chunk_);
6010   Handle<String> type_name = instr->type_literal();
6011   int left_block = instr->TrueDestination(chunk_);
6012   int right_block = instr->FalseDestination(chunk_);
6013   int next_block = GetNextEmittedBlock();
6014
6015   Label::Distance true_distance = left_block == next_block ? Label::kNear
6016                                                            : Label::kFar;
6017   Label::Distance false_distance = right_block == next_block ? Label::kNear
6018                                                              : Label::kFar;
6019   Condition final_branch_condition = no_condition;
6020   if (String::Equals(type_name, factory()->number_string())) {
6021     __ JumpIfSmi(input, true_label, true_distance);
6022     __ cmp(FieldOperand(input, HeapObject::kMapOffset),
6023            factory()->heap_number_map());
6024     final_branch_condition = equal;
6025
6026   } else if (String::Equals(type_name, factory()->string_string())) {
6027     __ JumpIfSmi(input, false_label, false_distance);
6028     __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
6029     __ j(above_equal, false_label, false_distance);
6030     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6031               1 << Map::kIsUndetectable);
6032     final_branch_condition = zero;
6033
6034   } else if (String::Equals(type_name, factory()->symbol_string())) {
6035     __ JumpIfSmi(input, false_label, false_distance);
6036     __ CmpObjectType(input, SYMBOL_TYPE, input);
6037     final_branch_condition = equal;
6038
6039   } else if (String::Equals(type_name, factory()->boolean_string())) {
6040     __ cmp(input, factory()->true_value());
6041     __ j(equal, true_label, true_distance);
6042     __ cmp(input, factory()->false_value());
6043     final_branch_condition = equal;
6044
6045   } else if (String::Equals(type_name, factory()->undefined_string())) {
6046     __ cmp(input, factory()->undefined_value());
6047     __ j(equal, true_label, true_distance);
6048     __ JumpIfSmi(input, false_label, false_distance);
6049     // Check for undetectable objects => true.
6050     __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
6051     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6052               1 << Map::kIsUndetectable);
6053     final_branch_condition = not_zero;
6054
6055   } else if (String::Equals(type_name, factory()->function_string())) {
6056     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
6057     __ JumpIfSmi(input, false_label, false_distance);
6058     __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
6059     __ j(equal, true_label, true_distance);
6060     __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
6061     final_branch_condition = equal;
6062
6063   } else if (String::Equals(type_name, factory()->object_string())) {
6064     __ JumpIfSmi(input, false_label, false_distance);
6065     __ cmp(input, factory()->null_value());
6066     __ j(equal, true_label, true_distance);
6067     __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
6068     __ j(below, false_label, false_distance);
6069     __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6070     __ j(above, false_label, false_distance);
6071     // Check for undetectable objects => false.
6072     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6073               1 << Map::kIsUndetectable);
6074     final_branch_condition = zero;
6075
6076   } else {
6077     __ jmp(false_label, false_distance);
6078   }
6079   return final_branch_condition;
6080 }
6081
6082
6083 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6084   Register temp = ToRegister(instr->temp());
6085
6086   EmitIsConstructCall(temp);
6087   EmitBranch(instr, equal);
6088 }
6089
6090
6091 void LCodeGen::EmitIsConstructCall(Register temp) {
6092   // Get the frame pointer for the calling frame.
6093   __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6094
6095   // Skip the arguments adaptor frame if it exists.
6096   Label check_frame_marker;
6097   __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6098          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6099   __ j(not_equal, &check_frame_marker, Label::kNear);
6100   __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6101
6102   // Check the marker in the calling frame.
6103   __ bind(&check_frame_marker);
6104   __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6105          Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6106 }
6107
6108
6109 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6110   if (!info()->IsStub()) {
6111     // Ensure that we have enough space after the previous lazy-bailout
6112     // instruction for patching the code here.
6113     int current_pc = masm()->pc_offset();
6114     if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6115       int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6116       __ Nop(padding_size);
6117     }
6118   }
6119   last_lazy_deopt_pc_ = masm()->pc_offset();
6120 }
6121
6122
6123 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6124   last_lazy_deopt_pc_ = masm()->pc_offset();
6125   DCHECK(instr->HasEnvironment());
6126   LEnvironment* env = instr->environment();
6127   RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6128   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6129 }
6130
6131
6132 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6133   Deoptimizer::BailoutType type = instr->hydrogen()->type();
6134   // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6135   // needed return address), even though the implementation of LAZY and EAGER is
6136   // now identical. When LAZY is eventually completely folded into EAGER, remove
6137   // the special case below.
6138   if (info()->IsStub() && type == Deoptimizer::EAGER) {
6139     type = Deoptimizer::LAZY;
6140   }
6141   DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6142 }
6143
6144
6145 void LCodeGen::DoDummy(LDummy* instr) {
6146   // Nothing to see here, move on!
6147 }
6148
6149
6150 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6151   // Nothing to see here, move on!
6152 }
6153
6154
6155 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6156   PushSafepointRegistersScope scope(this);
6157   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6158   __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6159   RecordSafepointWithLazyDeopt(
6160       instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6161   DCHECK(instr->HasEnvironment());
6162   LEnvironment* env = instr->environment();
6163   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6164 }
6165
6166
6167 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6168   class DeferredStackCheck FINAL : public LDeferredCode {
6169    public:
6170     DeferredStackCheck(LCodeGen* codegen,
6171                        LStackCheck* instr,
6172                        const X87Stack& x87_stack)
6173         : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6174     void Generate() OVERRIDE { codegen()->DoDeferredStackCheck(instr_); }
6175     LInstruction* instr() OVERRIDE { return instr_; }
6176
6177    private:
6178     LStackCheck* instr_;
6179   };
6180
6181   DCHECK(instr->HasEnvironment());
6182   LEnvironment* env = instr->environment();
6183   // There is no LLazyBailout instruction for stack-checks. We have to
6184   // prepare for lazy deoptimization explicitly here.
6185   if (instr->hydrogen()->is_function_entry()) {
6186     // Perform stack overflow check.
6187     Label done;
6188     ExternalReference stack_limit =
6189         ExternalReference::address_of_stack_limit(isolate());
6190     __ cmp(esp, Operand::StaticVariable(stack_limit));
6191     __ j(above_equal, &done, Label::kNear);
6192
6193     DCHECK(instr->context()->IsRegister());
6194     DCHECK(ToRegister(instr->context()).is(esi));
6195     CallCode(isolate()->builtins()->StackCheck(),
6196              RelocInfo::CODE_TARGET,
6197              instr);
6198     __ bind(&done);
6199   } else {
6200     DCHECK(instr->hydrogen()->is_backwards_branch());
6201     // Perform stack overflow check if this goto needs it before jumping.
6202     DeferredStackCheck* deferred_stack_check =
6203         new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6204     ExternalReference stack_limit =
6205         ExternalReference::address_of_stack_limit(isolate());
6206     __ cmp(esp, Operand::StaticVariable(stack_limit));
6207     __ j(below, deferred_stack_check->entry());
6208     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6209     __ bind(instr->done_label());
6210     deferred_stack_check->SetExit(instr->done_label());
6211     RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6212     // Don't record a deoptimization index for the safepoint here.
6213     // This will be done explicitly when emitting call and the safepoint in
6214     // the deferred code.
6215   }
6216 }
6217
6218
6219 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6220   // This is a pseudo-instruction that ensures that the environment here is
6221   // properly registered for deoptimization and records the assembler's PC
6222   // offset.
6223   LEnvironment* environment = instr->environment();
6224
6225   // If the environment were already registered, we would have no way of
6226   // backpatching it with the spill slot operands.
6227   DCHECK(!environment->HasBeenRegistered());
6228   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6229
6230   GenerateOsrPrologue();
6231 }
6232
6233
6234 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6235   DCHECK(ToRegister(instr->context()).is(esi));
6236   __ cmp(eax, isolate()->factory()->undefined_value());
6237   DeoptimizeIf(equal, instr, Deoptimizer::kUndefined);
6238
6239   __ cmp(eax, isolate()->factory()->null_value());
6240   DeoptimizeIf(equal, instr, Deoptimizer::kNull);
6241
6242   __ test(eax, Immediate(kSmiTagMask));
6243   DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
6244
6245   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6246   __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6247   DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
6248
6249   Label use_cache, call_runtime;
6250   __ CheckEnumCache(&call_runtime);
6251
6252   __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6253   __ jmp(&use_cache, Label::kNear);
6254
6255   // Get the set of properties to enumerate.
6256   __ bind(&call_runtime);
6257   __ push(eax);
6258   CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6259
6260   __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6261          isolate()->factory()->meta_map());
6262   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6263   __ bind(&use_cache);
6264 }
6265
6266
6267 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6268   Register map = ToRegister(instr->map());
6269   Register result = ToRegister(instr->result());
6270   Label load_cache, done;
6271   __ EnumLength(result, map);
6272   __ cmp(result, Immediate(Smi::FromInt(0)));
6273   __ j(not_equal, &load_cache, Label::kNear);
6274   __ mov(result, isolate()->factory()->empty_fixed_array());
6275   __ jmp(&done, Label::kNear);
6276
6277   __ bind(&load_cache);
6278   __ LoadInstanceDescriptors(map, result);
6279   __ mov(result,
6280          FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6281   __ mov(result,
6282          FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6283   __ bind(&done);
6284   __ test(result, result);
6285   DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
6286 }
6287
6288
6289 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6290   Register object = ToRegister(instr->value());
6291   __ cmp(ToRegister(instr->map()),
6292          FieldOperand(object, HeapObject::kMapOffset));
6293   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6294 }
6295
6296
6297 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6298                                            Register object,
6299                                            Register index) {
6300   PushSafepointRegistersScope scope(this);
6301   __ push(object);
6302   __ push(index);
6303   __ xor_(esi, esi);
6304   __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6305   RecordSafepointWithRegisters(
6306       instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6307   __ StoreToSafepointRegisterSlot(object, eax);
6308 }
6309
6310
6311 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6312   class DeferredLoadMutableDouble FINAL : public LDeferredCode {
6313    public:
6314     DeferredLoadMutableDouble(LCodeGen* codegen,
6315                               LLoadFieldByIndex* instr,
6316                               Register object,
6317                               Register index,
6318                               const X87Stack& x87_stack)
6319         : LDeferredCode(codegen, x87_stack),
6320           instr_(instr),
6321           object_(object),
6322           index_(index) {
6323     }
6324     void Generate() OVERRIDE {
6325       codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6326     }
6327     LInstruction* instr() OVERRIDE { return instr_; }
6328
6329    private:
6330     LLoadFieldByIndex* instr_;
6331     Register object_;
6332     Register index_;
6333   };
6334
6335   Register object = ToRegister(instr->object());
6336   Register index = ToRegister(instr->index());
6337
6338   DeferredLoadMutableDouble* deferred;
6339   deferred = new(zone()) DeferredLoadMutableDouble(
6340       this, instr, object, index, x87_stack_);
6341
6342   Label out_of_object, done;
6343   __ test(index, Immediate(Smi::FromInt(1)));
6344   __ j(not_zero, deferred->entry());
6345
6346   __ sar(index, 1);
6347
6348   __ cmp(index, Immediate(0));
6349   __ j(less, &out_of_object, Label::kNear);
6350   __ mov(object, FieldOperand(object,
6351                               index,
6352                               times_half_pointer_size,
6353                               JSObject::kHeaderSize));
6354   __ jmp(&done, Label::kNear);
6355
6356   __ bind(&out_of_object);
6357   __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6358   __ neg(index);
6359   // Index is now equal to out of object property index plus 1.
6360   __ mov(object, FieldOperand(object,
6361                               index,
6362                               times_half_pointer_size,
6363                               FixedArray::kHeaderSize - kPointerSize));
6364   __ bind(deferred->exit());
6365   __ bind(&done);
6366 }
6367
6368
6369 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6370   Register context = ToRegister(instr->context());
6371   __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6372 }
6373
6374
6375 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6376   Handle<ScopeInfo> scope_info = instr->scope_info();
6377   __ Push(scope_info);
6378   __ push(ToRegister(instr->function()));
6379   CallRuntime(Runtime::kPushBlockContext, 2, instr);
6380   RecordSafepoint(Safepoint::kNoLazyDeopt);
6381 }
6382
6383
6384 #undef __
6385
6386 } }  // namespace v8::internal
6387
6388 #endif  // V8_TARGET_ARCH_X87