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