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