Reland of "Remove ExternalArray, derived types, and element kinds"
[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 == FLOAT32_ELEMENTS) {
3072     XMMRegister result(ToDoubleRegister(instr->result()));
3073     __ movss(result, operand);
3074     __ cvtss2sd(result, result);
3075   } else if (elements_kind == FLOAT64_ELEMENTS) {
3076     __ movsd(ToDoubleRegister(instr->result()), operand);
3077   } else {
3078     Register result(ToRegister(instr->result()));
3079     switch (elements_kind) {
3080       case INT8_ELEMENTS:
3081         __ movsx_b(result, operand);
3082         break;
3083       case UINT8_ELEMENTS:
3084       case UINT8_CLAMPED_ELEMENTS:
3085         __ movzx_b(result, operand);
3086         break;
3087       case INT16_ELEMENTS:
3088         __ movsx_w(result, operand);
3089         break;
3090       case UINT16_ELEMENTS:
3091         __ movzx_w(result, operand);
3092         break;
3093       case INT32_ELEMENTS:
3094         __ mov(result, operand);
3095         break;
3096       case UINT32_ELEMENTS:
3097         __ mov(result, operand);
3098         if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3099           __ test(result, Operand(result));
3100           DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3101         }
3102         break;
3103       case FLOAT32_ELEMENTS:
3104       case FLOAT64_ELEMENTS:
3105       case FAST_SMI_ELEMENTS:
3106       case FAST_ELEMENTS:
3107       case FAST_DOUBLE_ELEMENTS:
3108       case FAST_HOLEY_SMI_ELEMENTS:
3109       case FAST_HOLEY_ELEMENTS:
3110       case FAST_HOLEY_DOUBLE_ELEMENTS:
3111       case DICTIONARY_ELEMENTS:
3112       case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3113       case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3114         UNREACHABLE();
3115         break;
3116     }
3117   }
3118 }
3119
3120
3121 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3122   if (instr->hydrogen()->RequiresHoleCheck()) {
3123     Operand hole_check_operand = BuildFastArrayOperand(
3124         instr->elements(), instr->key(),
3125         instr->hydrogen()->key()->representation(),
3126         FAST_DOUBLE_ELEMENTS,
3127         instr->base_offset() + sizeof(kHoleNanLower32));
3128     __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3129     DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3130   }
3131
3132   Operand double_load_operand = BuildFastArrayOperand(
3133       instr->elements(),
3134       instr->key(),
3135       instr->hydrogen()->key()->representation(),
3136       FAST_DOUBLE_ELEMENTS,
3137       instr->base_offset());
3138   XMMRegister result = ToDoubleRegister(instr->result());
3139   __ movsd(result, double_load_operand);
3140 }
3141
3142
3143 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3144   Register result = ToRegister(instr->result());
3145
3146   // Load the result.
3147   __ mov(result,
3148          BuildFastArrayOperand(instr->elements(), instr->key(),
3149                                instr->hydrogen()->key()->representation(),
3150                                FAST_ELEMENTS, instr->base_offset()));
3151
3152   // Check for the hole value.
3153   if (instr->hydrogen()->RequiresHoleCheck()) {
3154     if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3155       __ test(result, Immediate(kSmiTagMask));
3156       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3157     } else {
3158       __ cmp(result, factory()->the_hole_value());
3159       DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3160     }
3161   } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3162     DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3163     Label done;
3164     __ cmp(result, factory()->the_hole_value());
3165     __ j(not_equal, &done);
3166     if (info()->IsStub()) {
3167       // A stub can safely convert the hole to undefined only if the array
3168       // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3169       // it needs to bail out.
3170       __ mov(result, isolate()->factory()->array_protector());
3171       __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3172              Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3173       DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3174     }
3175     __ mov(result, isolate()->factory()->undefined_value());
3176     __ bind(&done);
3177   }
3178 }
3179
3180
3181 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3182   if (instr->is_fixed_typed_array()) {
3183     DoLoadKeyedExternalArray(instr);
3184   } else if (instr->hydrogen()->representation().IsDouble()) {
3185     DoLoadKeyedFixedDoubleArray(instr);
3186   } else {
3187     DoLoadKeyedFixedArray(instr);
3188   }
3189 }
3190
3191
3192 Operand LCodeGen::BuildFastArrayOperand(
3193     LOperand* elements_pointer,
3194     LOperand* key,
3195     Representation key_representation,
3196     ElementsKind elements_kind,
3197     uint32_t base_offset) {
3198   Register elements_pointer_reg = ToRegister(elements_pointer);
3199   int element_shift_size = ElementsKindToShiftSize(elements_kind);
3200   int shift_size = element_shift_size;
3201   if (key->IsConstantOperand()) {
3202     int constant_value = ToInteger32(LConstantOperand::cast(key));
3203     if (constant_value & 0xF0000000) {
3204       Abort(kArrayIndexConstantValueTooBig);
3205     }
3206     return Operand(elements_pointer_reg,
3207                    ((constant_value) << shift_size)
3208                        + base_offset);
3209   } else {
3210     // Take the tag bit into account while computing the shift size.
3211     if (key_representation.IsSmi() && (shift_size >= 1)) {
3212       shift_size -= kSmiTagSize;
3213     }
3214     ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3215     return Operand(elements_pointer_reg,
3216                    ToRegister(key),
3217                    scale_factor,
3218                    base_offset);
3219   }
3220 }
3221
3222
3223 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3224   DCHECK(ToRegister(instr->context()).is(esi));
3225   DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3226   DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3227
3228   if (instr->hydrogen()->HasVectorAndSlot()) {
3229     EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3230   }
3231
3232   Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3233                         isolate(), instr->hydrogen()->language_mode(),
3234                         instr->hydrogen()->initialization_state()).code();
3235   CallCode(ic, RelocInfo::CODE_TARGET, instr);
3236 }
3237
3238
3239 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3240   Register result = ToRegister(instr->result());
3241
3242   if (instr->hydrogen()->from_inlined()) {
3243     __ lea(result, Operand(esp, -2 * kPointerSize));
3244   } else {
3245     // Check for arguments adapter frame.
3246     Label done, adapted;
3247     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3248     __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3249     __ cmp(Operand(result),
3250            Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3251     __ j(equal, &adapted, Label::kNear);
3252
3253     // No arguments adaptor frame.
3254     __ mov(result, Operand(ebp));
3255     __ jmp(&done, Label::kNear);
3256
3257     // Arguments adaptor frame present.
3258     __ bind(&adapted);
3259     __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3260
3261     // Result is the frame pointer for the frame if not adapted and for the real
3262     // frame below the adaptor frame if adapted.
3263     __ bind(&done);
3264   }
3265 }
3266
3267
3268 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3269   Operand elem = ToOperand(instr->elements());
3270   Register result = ToRegister(instr->result());
3271
3272   Label done;
3273
3274   // If no arguments adaptor frame the number of arguments is fixed.
3275   __ cmp(ebp, elem);
3276   __ mov(result, Immediate(scope()->num_parameters()));
3277   __ j(equal, &done, Label::kNear);
3278
3279   // Arguments adaptor frame present. Get argument length from there.
3280   __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3281   __ mov(result, Operand(result,
3282                          ArgumentsAdaptorFrameConstants::kLengthOffset));
3283   __ SmiUntag(result);
3284
3285   // Argument length is in result register.
3286   __ bind(&done);
3287 }
3288
3289
3290 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3291   Register receiver = ToRegister(instr->receiver());
3292   Register function = ToRegister(instr->function());
3293
3294   // If the receiver is null or undefined, we have to pass the global
3295   // object as a receiver to normal functions. Values have to be
3296   // passed unchanged to builtins and strict-mode functions.
3297   Label receiver_ok, global_object;
3298   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3299   Register scratch = ToRegister(instr->temp());
3300
3301   if (!instr->hydrogen()->known_function()) {
3302     // Do not transform the receiver to object for strict mode
3303     // functions.
3304     __ mov(scratch,
3305            FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3306     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3307               1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3308     __ j(not_equal, &receiver_ok, dist);
3309
3310     // Do not transform the receiver to object for builtins.
3311     __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3312               1 << SharedFunctionInfo::kNativeBitWithinByte);
3313     __ j(not_equal, &receiver_ok, dist);
3314   }
3315
3316   // Normal function. Replace undefined or null with global receiver.
3317   __ cmp(receiver, factory()->null_value());
3318   __ j(equal, &global_object, Label::kNear);
3319   __ cmp(receiver, factory()->undefined_value());
3320   __ j(equal, &global_object, Label::kNear);
3321
3322   // The receiver should be a JS object.
3323   __ test(receiver, Immediate(kSmiTagMask));
3324   DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3325   __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3326   DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3327
3328   __ jmp(&receiver_ok, Label::kNear);
3329   __ bind(&global_object);
3330   __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3331   const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3332   __ mov(receiver, Operand(receiver, global_offset));
3333   const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3334   __ mov(receiver, FieldOperand(receiver, proxy_offset));
3335   __ bind(&receiver_ok);
3336 }
3337
3338
3339 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3340   Register receiver = ToRegister(instr->receiver());
3341   Register function = ToRegister(instr->function());
3342   Register length = ToRegister(instr->length());
3343   Register elements = ToRegister(instr->elements());
3344   DCHECK(receiver.is(eax));  // Used for parameter count.
3345   DCHECK(function.is(edi));  // Required by InvokeFunction.
3346   DCHECK(ToRegister(instr->result()).is(eax));
3347
3348   // Copy the arguments to this function possibly from the
3349   // adaptor frame below it.
3350   const uint32_t kArgumentsLimit = 1 * KB;
3351   __ cmp(length, kArgumentsLimit);
3352   DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3353
3354   __ push(receiver);
3355   __ mov(receiver, length);
3356
3357   // Loop through the arguments pushing them onto the execution
3358   // stack.
3359   Label invoke, loop;
3360   // length is a small non-negative integer, due to the test above.
3361   __ test(length, Operand(length));
3362   __ j(zero, &invoke, Label::kNear);
3363   __ bind(&loop);
3364   __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3365   __ dec(length);
3366   __ j(not_zero, &loop);
3367
3368   // Invoke the function.
3369   __ bind(&invoke);
3370   DCHECK(instr->HasPointerMap());
3371   LPointerMap* pointers = instr->pointer_map();
3372   SafepointGenerator safepoint_generator(
3373       this, pointers, Safepoint::kLazyDeopt);
3374   ParameterCount actual(eax);
3375   __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3376 }
3377
3378
3379 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3380   __ int3();
3381 }
3382
3383
3384 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3385   LOperand* argument = instr->value();
3386   EmitPushTaggedOperand(argument);
3387 }
3388
3389
3390 void LCodeGen::DoDrop(LDrop* instr) {
3391   __ Drop(instr->count());
3392 }
3393
3394
3395 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3396   Register result = ToRegister(instr->result());
3397   __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3398 }
3399
3400
3401 void LCodeGen::DoContext(LContext* instr) {
3402   Register result = ToRegister(instr->result());
3403   if (info()->IsOptimizing()) {
3404     __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3405   } else {
3406     // If there is no frame, the context must be in esi.
3407     DCHECK(result.is(esi));
3408   }
3409 }
3410
3411
3412 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3413   DCHECK(ToRegister(instr->context()).is(esi));
3414   __ push(esi);  // The context is the first argument.
3415   __ push(Immediate(instr->hydrogen()->pairs()));
3416   __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3417   CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3418 }
3419
3420
3421 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3422                                  int formal_parameter_count, int arity,
3423                                  LInstruction* instr) {
3424   bool dont_adapt_arguments =
3425       formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3426   bool can_invoke_directly =
3427       dont_adapt_arguments || formal_parameter_count == arity;
3428
3429   Register function_reg = edi;
3430
3431   if (can_invoke_directly) {
3432     // Change context.
3433     __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3434
3435     // Set eax to arguments count if adaption is not needed. Assumes that eax
3436     // is available to write to at this point.
3437     if (dont_adapt_arguments) {
3438       __ mov(eax, arity);
3439     }
3440
3441     // Invoke function directly.
3442     if (function.is_identical_to(info()->closure())) {
3443       __ CallSelf();
3444     } else {
3445       __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3446     }
3447     RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3448   } else {
3449     // We need to adapt arguments.
3450     LPointerMap* pointers = instr->pointer_map();
3451     SafepointGenerator generator(
3452         this, pointers, Safepoint::kLazyDeopt);
3453     ParameterCount count(arity);
3454     ParameterCount expected(formal_parameter_count);
3455     __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3456   }
3457 }
3458
3459
3460 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3461   DCHECK(ToRegister(instr->result()).is(eax));
3462
3463   if (instr->hydrogen()->IsTailCall()) {
3464     if (NeedsEagerFrame()) __ leave();
3465
3466     if (instr->target()->IsConstantOperand()) {
3467       LConstantOperand* target = LConstantOperand::cast(instr->target());
3468       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3469       __ jmp(code, RelocInfo::CODE_TARGET);
3470     } else {
3471       DCHECK(instr->target()->IsRegister());
3472       Register target = ToRegister(instr->target());
3473       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3474       __ jmp(target);
3475     }
3476   } else {
3477     LPointerMap* pointers = instr->pointer_map();
3478     SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3479
3480     if (instr->target()->IsConstantOperand()) {
3481       LConstantOperand* target = LConstantOperand::cast(instr->target());
3482       Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3483       generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3484       __ call(code, RelocInfo::CODE_TARGET);
3485     } else {
3486       DCHECK(instr->target()->IsRegister());
3487       Register target = ToRegister(instr->target());
3488       generator.BeforeCall(__ CallSize(Operand(target)));
3489       __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3490       __ call(target);
3491     }
3492     generator.AfterCall();
3493   }
3494 }
3495
3496
3497 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3498   DCHECK(ToRegister(instr->function()).is(edi));
3499   DCHECK(ToRegister(instr->result()).is(eax));
3500
3501   if (instr->hydrogen()->pass_argument_count()) {
3502     __ mov(eax, instr->arity());
3503   }
3504
3505   // Change context.
3506   __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3507
3508   bool is_self_call = false;
3509   if (instr->hydrogen()->function()->IsConstant()) {
3510     HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3511     Handle<JSFunction> jsfun =
3512       Handle<JSFunction>::cast(fun_const->handle(isolate()));
3513     is_self_call = jsfun.is_identical_to(info()->closure());
3514   }
3515
3516   if (is_self_call) {
3517     __ CallSelf();
3518   } else {
3519     __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3520   }
3521
3522   RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3523 }
3524
3525
3526 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3527   Register input_reg = ToRegister(instr->value());
3528   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3529          factory()->heap_number_map());
3530   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3531
3532   Label slow, allocated, done;
3533   Register tmp = input_reg.is(eax) ? ecx : eax;
3534   Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3535
3536   // Preserve the value of all registers.
3537   PushSafepointRegistersScope scope(this);
3538
3539   __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3540   // Check the sign of the argument. If the argument is positive, just
3541   // return it. We do not need to patch the stack since |input| and
3542   // |result| are the same register and |input| will be restored
3543   // unchanged by popping safepoint registers.
3544   __ test(tmp, Immediate(HeapNumber::kSignMask));
3545   __ j(zero, &done, Label::kNear);
3546
3547   __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3548   __ jmp(&allocated, Label::kNear);
3549
3550   // Slow case: Call the runtime system to do the number allocation.
3551   __ bind(&slow);
3552   CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3553                           instr, instr->context());
3554   // Set the pointer to the new heap number in tmp.
3555   if (!tmp.is(eax)) __ mov(tmp, eax);
3556   // Restore input_reg after call to runtime.
3557   __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3558
3559   __ bind(&allocated);
3560   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3561   __ and_(tmp2, ~HeapNumber::kSignMask);
3562   __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3563   __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3564   __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3565   __ StoreToSafepointRegisterSlot(input_reg, tmp);
3566
3567   __ bind(&done);
3568 }
3569
3570
3571 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3572   Register input_reg = ToRegister(instr->value());
3573   __ test(input_reg, Operand(input_reg));
3574   Label is_positive;
3575   __ j(not_sign, &is_positive, Label::kNear);
3576   __ neg(input_reg);  // Sets flags.
3577   DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3578   __ bind(&is_positive);
3579 }
3580
3581
3582 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3583   // Class for deferred case.
3584   class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3585    public:
3586     DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3587                                     LMathAbs* instr)
3588         : LDeferredCode(codegen), instr_(instr) { }
3589     void Generate() override {
3590       codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3591     }
3592     LInstruction* instr() override { return instr_; }
3593
3594    private:
3595     LMathAbs* instr_;
3596   };
3597
3598   DCHECK(instr->value()->Equals(instr->result()));
3599   Representation r = instr->hydrogen()->value()->representation();
3600
3601   if (r.IsDouble()) {
3602     XMMRegister scratch = double_scratch0();
3603     XMMRegister input_reg = ToDoubleRegister(instr->value());
3604     __ xorps(scratch, scratch);
3605     __ subsd(scratch, input_reg);
3606     __ andps(input_reg, scratch);
3607   } else if (r.IsSmiOrInteger32()) {
3608     EmitIntegerMathAbs(instr);
3609   } else {  // Tagged case.
3610     DeferredMathAbsTaggedHeapNumber* deferred =
3611         new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3612     Register input_reg = ToRegister(instr->value());
3613     // Smi check.
3614     __ JumpIfNotSmi(input_reg, deferred->entry());
3615     EmitIntegerMathAbs(instr);
3616     __ bind(deferred->exit());
3617   }
3618 }
3619
3620
3621 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3622   XMMRegister xmm_scratch = double_scratch0();
3623   Register output_reg = ToRegister(instr->result());
3624   XMMRegister input_reg = ToDoubleRegister(instr->value());
3625
3626   if (CpuFeatures::IsSupported(SSE4_1)) {
3627     CpuFeatureScope scope(masm(), SSE4_1);
3628     if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3629       // Deoptimize on negative zero.
3630       Label non_zero;
3631       __ xorps(xmm_scratch, xmm_scratch);  // Zero the register.
3632       __ ucomisd(input_reg, xmm_scratch);
3633       __ j(not_equal, &non_zero, Label::kNear);
3634       __ movmskpd(output_reg, input_reg);
3635       __ test(output_reg, Immediate(1));
3636       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3637       __ bind(&non_zero);
3638     }
3639     __ roundsd(xmm_scratch, input_reg, kRoundDown);
3640     __ cvttsd2si(output_reg, Operand(xmm_scratch));
3641     // Overflow is signalled with minint.
3642     __ cmp(output_reg, 0x1);
3643     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3644   } else {
3645     Label negative_sign, done;
3646     // Deoptimize on unordered.
3647     __ xorps(xmm_scratch, xmm_scratch);  // Zero the register.
3648     __ ucomisd(input_reg, xmm_scratch);
3649     DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3650     __ j(below, &negative_sign, Label::kNear);
3651
3652     if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3653       // Check for negative zero.
3654       Label positive_sign;
3655       __ j(above, &positive_sign, Label::kNear);
3656       __ movmskpd(output_reg, input_reg);
3657       __ test(output_reg, Immediate(1));
3658       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3659       __ Move(output_reg, Immediate(0));
3660       __ jmp(&done, Label::kNear);
3661       __ bind(&positive_sign);
3662     }
3663
3664     // Use truncating instruction (OK because input is positive).
3665     __ cvttsd2si(output_reg, Operand(input_reg));
3666     // Overflow is signalled with minint.
3667     __ cmp(output_reg, 0x1);
3668     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3669     __ jmp(&done, Label::kNear);
3670
3671     // Non-zero negative reaches here.
3672     __ bind(&negative_sign);
3673     // Truncate, then compare and compensate.
3674     __ cvttsd2si(output_reg, Operand(input_reg));
3675     __ Cvtsi2sd(xmm_scratch, output_reg);
3676     __ ucomisd(input_reg, xmm_scratch);
3677     __ j(equal, &done, Label::kNear);
3678     __ sub(output_reg, Immediate(1));
3679     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3680
3681     __ bind(&done);
3682   }
3683 }
3684
3685
3686 void LCodeGen::DoMathRound(LMathRound* instr) {
3687   Register output_reg = ToRegister(instr->result());
3688   XMMRegister input_reg = ToDoubleRegister(instr->value());
3689   XMMRegister xmm_scratch = double_scratch0();
3690   XMMRegister input_temp = ToDoubleRegister(instr->temp());
3691   ExternalReference one_half = ExternalReference::address_of_one_half();
3692   ExternalReference minus_one_half =
3693       ExternalReference::address_of_minus_one_half();
3694
3695   Label done, round_to_zero, below_one_half, do_not_compensate;
3696   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3697
3698   __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3699   __ ucomisd(xmm_scratch, input_reg);
3700   __ j(above, &below_one_half, Label::kNear);
3701
3702   // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3703   __ addsd(xmm_scratch, input_reg);
3704   __ cvttsd2si(output_reg, Operand(xmm_scratch));
3705   // Overflow is signalled with minint.
3706   __ cmp(output_reg, 0x1);
3707   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3708   __ jmp(&done, dist);
3709
3710   __ bind(&below_one_half);
3711   __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3712   __ ucomisd(xmm_scratch, input_reg);
3713   __ j(below_equal, &round_to_zero, Label::kNear);
3714
3715   // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3716   // compare and compensate.
3717   __ movaps(input_temp, input_reg);  // Do not alter input_reg.
3718   __ subsd(input_temp, xmm_scratch);
3719   __ cvttsd2si(output_reg, Operand(input_temp));
3720   // Catch minint due to overflow, and to prevent overflow when compensating.
3721   __ cmp(output_reg, 0x1);
3722   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3723
3724   __ Cvtsi2sd(xmm_scratch, output_reg);
3725   __ ucomisd(xmm_scratch, input_temp);
3726   __ j(equal, &done, dist);
3727   __ sub(output_reg, Immediate(1));
3728   // No overflow because we already ruled out minint.
3729   __ jmp(&done, dist);
3730
3731   __ bind(&round_to_zero);
3732   // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3733   // we can ignore the difference between a result of -0 and +0.
3734   if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3735     // If the sign is positive, we return +0.
3736     __ movmskpd(output_reg, input_reg);
3737     __ test(output_reg, Immediate(1));
3738     DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3739   }
3740   __ Move(output_reg, Immediate(0));
3741   __ bind(&done);
3742 }
3743
3744
3745 void LCodeGen::DoMathFround(LMathFround* instr) {
3746   XMMRegister input_reg = ToDoubleRegister(instr->value());
3747   XMMRegister output_reg = ToDoubleRegister(instr->result());
3748   __ cvtsd2ss(output_reg, input_reg);
3749   __ cvtss2sd(output_reg, output_reg);
3750 }
3751
3752
3753 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3754   Operand input = ToOperand(instr->value());
3755   XMMRegister output = ToDoubleRegister(instr->result());
3756   __ sqrtsd(output, input);
3757 }
3758
3759
3760 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3761   XMMRegister xmm_scratch = double_scratch0();
3762   XMMRegister input_reg = ToDoubleRegister(instr->value());
3763   Register scratch = ToRegister(instr->temp());
3764   DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3765
3766   // Note that according to ECMA-262 15.8.2.13:
3767   // Math.pow(-Infinity, 0.5) == Infinity
3768   // Math.sqrt(-Infinity) == NaN
3769   Label done, sqrt;
3770   // Check base for -Infinity.  According to IEEE-754, single-precision
3771   // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3772   __ mov(scratch, 0xFF800000);
3773   __ movd(xmm_scratch, scratch);
3774   __ cvtss2sd(xmm_scratch, xmm_scratch);
3775   __ ucomisd(input_reg, xmm_scratch);
3776   // Comparing -Infinity with NaN results in "unordered", which sets the
3777   // zero flag as if both were equal.  However, it also sets the carry flag.
3778   __ j(not_equal, &sqrt, Label::kNear);
3779   __ j(carry, &sqrt, Label::kNear);
3780   // If input is -Infinity, return Infinity.
3781   __ xorps(input_reg, input_reg);
3782   __ subsd(input_reg, xmm_scratch);
3783   __ jmp(&done, Label::kNear);
3784
3785   // Square root.
3786   __ bind(&sqrt);
3787   __ xorps(xmm_scratch, xmm_scratch);
3788   __ addsd(input_reg, xmm_scratch);  // Convert -0 to +0.
3789   __ sqrtsd(input_reg, input_reg);
3790   __ bind(&done);
3791 }
3792
3793
3794 void LCodeGen::DoPower(LPower* instr) {
3795   Representation exponent_type = instr->hydrogen()->right()->representation();
3796   // Having marked this as a call, we can use any registers.
3797   // Just make sure that the input/output registers are the expected ones.
3798   Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3799   DCHECK(!instr->right()->IsDoubleRegister() ||
3800          ToDoubleRegister(instr->right()).is(xmm1));
3801   DCHECK(!instr->right()->IsRegister() ||
3802          ToRegister(instr->right()).is(tagged_exponent));
3803   DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3804   DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3805
3806   if (exponent_type.IsSmi()) {
3807     MathPowStub stub(isolate(), MathPowStub::TAGGED);
3808     __ CallStub(&stub);
3809   } else if (exponent_type.IsTagged()) {
3810     Label no_deopt;
3811     __ JumpIfSmi(tagged_exponent, &no_deopt);
3812     DCHECK(!ecx.is(tagged_exponent));
3813     __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3814     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3815     __ bind(&no_deopt);
3816     MathPowStub stub(isolate(), MathPowStub::TAGGED);
3817     __ CallStub(&stub);
3818   } else if (exponent_type.IsInteger32()) {
3819     MathPowStub stub(isolate(), MathPowStub::INTEGER);
3820     __ CallStub(&stub);
3821   } else {
3822     DCHECK(exponent_type.IsDouble());
3823     MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3824     __ CallStub(&stub);
3825   }
3826 }
3827
3828
3829 void LCodeGen::DoMathLog(LMathLog* instr) {
3830   DCHECK(instr->value()->Equals(instr->result()));
3831   XMMRegister input_reg = ToDoubleRegister(instr->value());
3832   XMMRegister xmm_scratch = double_scratch0();
3833   Label positive, done, zero;
3834   __ xorps(xmm_scratch, xmm_scratch);
3835   __ ucomisd(input_reg, xmm_scratch);
3836   __ j(above, &positive, Label::kNear);
3837   __ j(not_carry, &zero, Label::kNear);
3838   __ pcmpeqd(input_reg, input_reg);
3839   __ jmp(&done, Label::kNear);
3840   __ bind(&zero);
3841   ExternalReference ninf =
3842       ExternalReference::address_of_negative_infinity();
3843   __ movsd(input_reg, Operand::StaticVariable(ninf));
3844   __ jmp(&done, Label::kNear);
3845   __ bind(&positive);
3846   __ fldln2();
3847   __ sub(Operand(esp), Immediate(kDoubleSize));
3848   __ movsd(Operand(esp, 0), input_reg);
3849   __ fld_d(Operand(esp, 0));
3850   __ fyl2x();
3851   __ fstp_d(Operand(esp, 0));
3852   __ movsd(input_reg, Operand(esp, 0));
3853   __ add(Operand(esp), Immediate(kDoubleSize));
3854   __ bind(&done);
3855 }
3856
3857
3858 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3859   Register input = ToRegister(instr->value());
3860   Register result = ToRegister(instr->result());
3861
3862   __ Lzcnt(result, input);
3863 }
3864
3865
3866 void LCodeGen::DoMathExp(LMathExp* instr) {
3867   XMMRegister input = ToDoubleRegister(instr->value());
3868   XMMRegister result = ToDoubleRegister(instr->result());
3869   XMMRegister temp0 = double_scratch0();
3870   Register temp1 = ToRegister(instr->temp1());
3871   Register temp2 = ToRegister(instr->temp2());
3872
3873   MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3874 }
3875
3876
3877 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3878   DCHECK(ToRegister(instr->context()).is(esi));
3879   DCHECK(ToRegister(instr->function()).is(edi));
3880   DCHECK(instr->HasPointerMap());
3881
3882   Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3883   if (known_function.is_null()) {
3884     LPointerMap* pointers = instr->pointer_map();
3885     SafepointGenerator generator(
3886         this, pointers, Safepoint::kLazyDeopt);
3887     ParameterCount count(instr->arity());
3888     __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3889   } else {
3890     CallKnownFunction(known_function,
3891                       instr->hydrogen()->formal_parameter_count(),
3892                       instr->arity(), instr);
3893   }
3894 }
3895
3896
3897 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3898   DCHECK(ToRegister(instr->context()).is(esi));
3899   DCHECK(ToRegister(instr->function()).is(edi));
3900   DCHECK(ToRegister(instr->result()).is(eax));
3901
3902   int arity = instr->arity();
3903   CallFunctionFlags flags = instr->hydrogen()->function_flags();
3904   if (instr->hydrogen()->HasVectorAndSlot()) {
3905     Register slot_register = ToRegister(instr->temp_slot());
3906     Register vector_register = ToRegister(instr->temp_vector());
3907     DCHECK(slot_register.is(edx));
3908     DCHECK(vector_register.is(ebx));
3909
3910     AllowDeferredHandleDereference vector_structure_check;
3911     Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3912     int index = vector->GetIndex(instr->hydrogen()->slot());
3913
3914     __ mov(vector_register, vector);
3915     __ mov(slot_register, Immediate(Smi::FromInt(index)));
3916
3917     CallICState::CallType call_type =
3918         (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3919
3920     Handle<Code> ic =
3921         CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3922     CallCode(ic, RelocInfo::CODE_TARGET, instr);
3923   } else {
3924     CallFunctionStub stub(isolate(), arity, flags);
3925     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3926   }
3927 }
3928
3929
3930 void LCodeGen::DoCallNew(LCallNew* instr) {
3931   DCHECK(ToRegister(instr->context()).is(esi));
3932   DCHECK(ToRegister(instr->constructor()).is(edi));
3933   DCHECK(ToRegister(instr->result()).is(eax));
3934
3935   // No cell in ebx for construct type feedback in optimized code
3936   __ mov(ebx, isolate()->factory()->undefined_value());
3937   CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3938   __ Move(eax, Immediate(instr->arity()));
3939   CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3940 }
3941
3942
3943 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3944   DCHECK(ToRegister(instr->context()).is(esi));
3945   DCHECK(ToRegister(instr->constructor()).is(edi));
3946   DCHECK(ToRegister(instr->result()).is(eax));
3947
3948   __ Move(eax, Immediate(instr->arity()));
3949   if (instr->arity() == 1) {
3950     // We only need the allocation site for the case we have a length argument.
3951     // The case may bail out to the runtime, which will determine the correct
3952     // elements kind with the site.
3953     __ mov(ebx, instr->hydrogen()->site());
3954   } else {
3955     __ mov(ebx, isolate()->factory()->undefined_value());
3956   }
3957
3958   ElementsKind kind = instr->hydrogen()->elements_kind();
3959   AllocationSiteOverrideMode override_mode =
3960       (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3961           ? DISABLE_ALLOCATION_SITES
3962           : DONT_OVERRIDE;
3963
3964   if (instr->arity() == 0) {
3965     ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3966     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3967   } else if (instr->arity() == 1) {
3968     Label done;
3969     if (IsFastPackedElementsKind(kind)) {
3970       Label packed_case;
3971       // We might need a change here
3972       // look at the first argument
3973       __ mov(ecx, Operand(esp, 0));
3974       __ test(ecx, ecx);
3975       __ j(zero, &packed_case, Label::kNear);
3976
3977       ElementsKind holey_kind = GetHoleyElementsKind(kind);
3978       ArraySingleArgumentConstructorStub stub(isolate(),
3979                                               holey_kind,
3980                                               override_mode);
3981       CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3982       __ jmp(&done, Label::kNear);
3983       __ bind(&packed_case);
3984     }
3985
3986     ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
3987     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3988     __ bind(&done);
3989   } else {
3990     ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
3991     CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3992   }
3993 }
3994
3995
3996 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3997   DCHECK(ToRegister(instr->context()).is(esi));
3998   CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
3999 }
4000
4001
4002 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4003   Register function = ToRegister(instr->function());
4004   Register code_object = ToRegister(instr->code_object());
4005   __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4006   __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4007 }
4008
4009
4010 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4011   Register result = ToRegister(instr->result());
4012   Register base = ToRegister(instr->base_object());
4013   if (instr->offset()->IsConstantOperand()) {
4014     LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4015     __ lea(result, Operand(base, ToInteger32(offset)));
4016   } else {
4017     Register offset = ToRegister(instr->offset());
4018     __ lea(result, Operand(base, offset, times_1, 0));
4019   }
4020 }
4021
4022
4023 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4024   Representation representation = instr->hydrogen()->field_representation();
4025
4026   HObjectAccess access = instr->hydrogen()->access();
4027   int offset = access.offset();
4028
4029   if (access.IsExternalMemory()) {
4030     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4031     MemOperand operand = instr->object()->IsConstantOperand()
4032         ? MemOperand::StaticVariable(
4033             ToExternalReference(LConstantOperand::cast(instr->object())))
4034         : MemOperand(ToRegister(instr->object()), offset);
4035     if (instr->value()->IsConstantOperand()) {
4036       LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4037       __ mov(operand, Immediate(ToInteger32(operand_value)));
4038     } else {
4039       Register value = ToRegister(instr->value());
4040       __ Store(value, operand, representation);
4041     }
4042     return;
4043   }
4044
4045   Register object = ToRegister(instr->object());
4046   __ AssertNotSmi(object);
4047
4048   DCHECK(!representation.IsSmi() ||
4049          !instr->value()->IsConstantOperand() ||
4050          IsSmi(LConstantOperand::cast(instr->value())));
4051   if (representation.IsDouble()) {
4052     DCHECK(access.IsInobject());
4053     DCHECK(!instr->hydrogen()->has_transition());
4054     DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4055     XMMRegister value = ToDoubleRegister(instr->value());
4056     __ movsd(FieldOperand(object, offset), value);
4057     return;
4058   }
4059
4060   if (instr->hydrogen()->has_transition()) {
4061     Handle<Map> transition = instr->hydrogen()->transition_map();
4062     AddDeprecationDependency(transition);
4063     __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4064     if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4065       Register temp = ToRegister(instr->temp());
4066       Register temp_map = ToRegister(instr->temp_map());
4067       // Update the write barrier for the map field.
4068       __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4069     }
4070   }
4071
4072   // Do the store.
4073   Register write_register = object;
4074   if (!access.IsInobject()) {
4075     write_register = ToRegister(instr->temp());
4076     __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4077   }
4078
4079   MemOperand operand = FieldOperand(write_register, offset);
4080   if (instr->value()->IsConstantOperand()) {
4081     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4082     if (operand_value->IsRegister()) {
4083       Register value = ToRegister(operand_value);
4084       __ Store(value, operand, representation);
4085     } else if (representation.IsInteger32() || representation.IsExternal()) {
4086       Immediate immediate = ToImmediate(operand_value, representation);
4087       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4088       __ mov(operand, immediate);
4089     } else {
4090       Handle<Object> handle_value = ToHandle(operand_value);
4091       DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4092       __ mov(operand, handle_value);
4093     }
4094   } else {
4095     Register value = ToRegister(instr->value());
4096     __ Store(value, operand, representation);
4097   }
4098
4099   if (instr->hydrogen()->NeedsWriteBarrier()) {
4100     Register value = ToRegister(instr->value());
4101     Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4102     // Update the write barrier for the object for in-object properties.
4103     __ RecordWriteField(write_register,
4104                         offset,
4105                         value,
4106                         temp,
4107                         kSaveFPRegs,
4108                         EMIT_REMEMBERED_SET,
4109                         instr->hydrogen()->SmiCheckForWriteBarrier(),
4110                         instr->hydrogen()->PointersToHereCheckForValue());
4111   }
4112 }
4113
4114
4115 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4116   DCHECK(ToRegister(instr->context()).is(esi));
4117   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4118   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4119
4120   if (instr->hydrogen()->HasVectorAndSlot()) {
4121     EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
4122   }
4123
4124   __ mov(StoreDescriptor::NameRegister(), instr->name());
4125   Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
4126                         isolate(), instr->language_mode(),
4127                         instr->hydrogen()->initialization_state()).code();
4128   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4129 }
4130
4131
4132 void LCodeGen::DoStoreGlobalViaContext(LStoreGlobalViaContext* instr) {
4133   DCHECK(ToRegister(instr->context()).is(esi));
4134   DCHECK(ToRegister(instr->value())
4135              .is(StoreGlobalViaContextDescriptor::ValueRegister()));
4136
4137   int const slot = instr->slot_index();
4138   int const depth = instr->depth();
4139   if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
4140     __ mov(StoreGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
4141     Handle<Code> stub = CodeFactory::StoreGlobalViaContext(
4142                             isolate(), depth, instr->language_mode())
4143                             .code();
4144     CallCode(stub, RelocInfo::CODE_TARGET, instr);
4145   } else {
4146     __ Push(Smi::FromInt(slot));
4147     __ Push(StoreGlobalViaContextDescriptor::ValueRegister());
4148     __ CallRuntime(is_strict(instr->language_mode())
4149                        ? Runtime::kStoreGlobalViaContext_Strict
4150                        : Runtime::kStoreGlobalViaContext_Sloppy,
4151                    2);
4152   }
4153 }
4154
4155
4156 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4157   Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4158   if (instr->index()->IsConstantOperand()) {
4159     __ cmp(ToOperand(instr->length()),
4160            ToImmediate(LConstantOperand::cast(instr->index()),
4161                        instr->hydrogen()->length()->representation()));
4162     cc = CommuteCondition(cc);
4163   } else if (instr->length()->IsConstantOperand()) {
4164     __ cmp(ToOperand(instr->index()),
4165            ToImmediate(LConstantOperand::cast(instr->length()),
4166                        instr->hydrogen()->index()->representation()));
4167   } else {
4168     __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4169   }
4170   if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4171     Label done;
4172     __ j(NegateCondition(cc), &done, Label::kNear);
4173     __ int3();
4174     __ bind(&done);
4175   } else {
4176     DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4177   }
4178 }
4179
4180
4181 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4182   ElementsKind elements_kind = instr->elements_kind();
4183   LOperand* key = instr->key();
4184   if (!key->IsConstantOperand() &&
4185       ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4186                                   elements_kind)) {
4187     __ SmiUntag(ToRegister(key));
4188   }
4189   Operand operand(BuildFastArrayOperand(
4190       instr->elements(),
4191       key,
4192       instr->hydrogen()->key()->representation(),
4193       elements_kind,
4194       instr->base_offset()));
4195   if (elements_kind == FLOAT32_ELEMENTS) {
4196     XMMRegister xmm_scratch = double_scratch0();
4197     __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4198     __ movss(operand, xmm_scratch);
4199   } else if (elements_kind == FLOAT64_ELEMENTS) {
4200     __ movsd(operand, ToDoubleRegister(instr->value()));
4201   } else {
4202     Register value = ToRegister(instr->value());
4203     switch (elements_kind) {
4204       case UINT8_ELEMENTS:
4205       case INT8_ELEMENTS:
4206       case UINT8_CLAMPED_ELEMENTS:
4207         __ mov_b(operand, value);
4208         break;
4209       case UINT16_ELEMENTS:
4210       case INT16_ELEMENTS:
4211         __ mov_w(operand, value);
4212         break;
4213       case UINT32_ELEMENTS:
4214       case INT32_ELEMENTS:
4215         __ mov(operand, value);
4216         break;
4217       case FLOAT32_ELEMENTS:
4218       case FLOAT64_ELEMENTS:
4219       case FAST_SMI_ELEMENTS:
4220       case FAST_ELEMENTS:
4221       case FAST_DOUBLE_ELEMENTS:
4222       case FAST_HOLEY_SMI_ELEMENTS:
4223       case FAST_HOLEY_ELEMENTS:
4224       case FAST_HOLEY_DOUBLE_ELEMENTS:
4225       case DICTIONARY_ELEMENTS:
4226       case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4227       case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
4228         UNREACHABLE();
4229         break;
4230     }
4231   }
4232 }
4233
4234
4235 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4236   Operand double_store_operand = BuildFastArrayOperand(
4237       instr->elements(),
4238       instr->key(),
4239       instr->hydrogen()->key()->representation(),
4240       FAST_DOUBLE_ELEMENTS,
4241       instr->base_offset());
4242
4243   XMMRegister value = ToDoubleRegister(instr->value());
4244
4245   if (instr->NeedsCanonicalization()) {
4246     XMMRegister xmm_scratch = double_scratch0();
4247     // Turn potential sNaN value into qNaN.
4248     __ xorps(xmm_scratch, xmm_scratch);
4249     __ subsd(value, xmm_scratch);
4250   }
4251
4252   __ movsd(double_store_operand, value);
4253 }
4254
4255
4256 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4257   Register elements = ToRegister(instr->elements());
4258   Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4259
4260   Operand operand = BuildFastArrayOperand(
4261       instr->elements(),
4262       instr->key(),
4263       instr->hydrogen()->key()->representation(),
4264       FAST_ELEMENTS,
4265       instr->base_offset());
4266   if (instr->value()->IsRegister()) {
4267     __ mov(operand, ToRegister(instr->value()));
4268   } else {
4269     LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4270     if (IsSmi(operand_value)) {
4271       Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4272       __ mov(operand, immediate);
4273     } else {
4274       DCHECK(!IsInteger32(operand_value));
4275       Handle<Object> handle_value = ToHandle(operand_value);
4276       __ mov(operand, handle_value);
4277     }
4278   }
4279
4280   if (instr->hydrogen()->NeedsWriteBarrier()) {
4281     DCHECK(instr->value()->IsRegister());
4282     Register value = ToRegister(instr->value());
4283     DCHECK(!instr->key()->IsConstantOperand());
4284     SmiCheck check_needed =
4285         instr->hydrogen()->value()->type().IsHeapObject()
4286           ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4287     // Compute address of modified element and store it into key register.
4288     __ lea(key, operand);
4289     __ RecordWrite(elements,
4290                    key,
4291                    value,
4292                    kSaveFPRegs,
4293                    EMIT_REMEMBERED_SET,
4294                    check_needed,
4295                    instr->hydrogen()->PointersToHereCheckForValue());
4296   }
4297 }
4298
4299
4300 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4301   // By cases...external, fast-double, fast
4302   if (instr->is_fixed_typed_array()) {
4303     DoStoreKeyedExternalArray(instr);
4304   } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4305     DoStoreKeyedFixedDoubleArray(instr);
4306   } else {
4307     DoStoreKeyedFixedArray(instr);
4308   }
4309 }
4310
4311
4312 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4313   DCHECK(ToRegister(instr->context()).is(esi));
4314   DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4315   DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4316   DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4317
4318   if (instr->hydrogen()->HasVectorAndSlot()) {
4319     EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4320   }
4321
4322   Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4323                         isolate(), instr->language_mode(),
4324                         instr->hydrogen()->initialization_state()).code();
4325   CallCode(ic, RelocInfo::CODE_TARGET, instr);
4326 }
4327
4328
4329 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4330   Register object = ToRegister(instr->object());
4331   Register temp = ToRegister(instr->temp());
4332   Label no_memento_found;
4333   __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4334   DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4335   __ bind(&no_memento_found);
4336 }
4337
4338
4339 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4340   class DeferredMaybeGrowElements final : public LDeferredCode {
4341    public:
4342     DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4343         : LDeferredCode(codegen), instr_(instr) {}
4344     void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4345     LInstruction* instr() override { return instr_; }
4346
4347    private:
4348     LMaybeGrowElements* instr_;
4349   };
4350
4351   Register result = eax;
4352   DeferredMaybeGrowElements* deferred =
4353       new (zone()) DeferredMaybeGrowElements(this, instr);
4354   LOperand* key = instr->key();
4355   LOperand* current_capacity = instr->current_capacity();
4356
4357   DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4358   DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4359   DCHECK(key->IsConstantOperand() || key->IsRegister());
4360   DCHECK(current_capacity->IsConstantOperand() ||
4361          current_capacity->IsRegister());
4362
4363   if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4364     int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4365     int32_t constant_capacity =
4366         ToInteger32(LConstantOperand::cast(current_capacity));
4367     if (constant_key >= constant_capacity) {
4368       // Deferred case.
4369       __ jmp(deferred->entry());
4370     }
4371   } else if (key->IsConstantOperand()) {
4372     int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4373     __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4374     __ j(less_equal, deferred->entry());
4375   } else if (current_capacity->IsConstantOperand()) {
4376     int32_t constant_capacity =
4377         ToInteger32(LConstantOperand::cast(current_capacity));
4378     __ cmp(ToRegister(key), Immediate(constant_capacity));
4379     __ j(greater_equal, deferred->entry());
4380   } else {
4381     __ cmp(ToRegister(key), ToRegister(current_capacity));
4382     __ j(greater_equal, deferred->entry());
4383   }
4384
4385   __ mov(result, ToOperand(instr->elements()));
4386   __ bind(deferred->exit());
4387 }
4388
4389
4390 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4391   // TODO(3095996): Get rid of this. For now, we need to make the
4392   // result register contain a valid pointer because it is already
4393   // contained in the register pointer map.
4394   Register result = eax;
4395   __ Move(result, Immediate(0));
4396
4397   // We have to call a stub.
4398   {
4399     PushSafepointRegistersScope scope(this);
4400     if (instr->object()->IsRegister()) {
4401       __ Move(result, ToRegister(instr->object()));
4402     } else {
4403       __ mov(result, ToOperand(instr->object()));
4404     }
4405
4406     LOperand* key = instr->key();
4407     if (key->IsConstantOperand()) {
4408       __ mov(ebx, ToImmediate(key, Representation::Smi()));
4409     } else {
4410       __ Move(ebx, ToRegister(key));
4411       __ SmiTag(ebx);
4412     }
4413
4414     GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4415                                instr->hydrogen()->kind());
4416     __ CallStub(&stub);
4417     RecordSafepointWithLazyDeopt(
4418         instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4419     __ StoreToSafepointRegisterSlot(result, result);
4420   }
4421
4422   // Deopt on smi, which means the elements array changed to dictionary mode.
4423   __ test(result, Immediate(kSmiTagMask));
4424   DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4425 }
4426
4427
4428 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4429   Register object_reg = ToRegister(instr->object());
4430
4431   Handle<Map> from_map = instr->original_map();
4432   Handle<Map> to_map = instr->transitioned_map();
4433   ElementsKind from_kind = instr->from_kind();
4434   ElementsKind to_kind = instr->to_kind();
4435
4436   Label not_applicable;
4437   bool is_simple_map_transition =
4438       IsSimpleMapChangeTransition(from_kind, to_kind);
4439   Label::Distance branch_distance =
4440       is_simple_map_transition ? Label::kNear : Label::kFar;
4441   __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4442   __ j(not_equal, &not_applicable, branch_distance);
4443   if (is_simple_map_transition) {
4444     Register new_map_reg = ToRegister(instr->new_map_temp());
4445     __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4446            Immediate(to_map));
4447     // Write barrier.
4448     DCHECK_NOT_NULL(instr->temp());
4449     __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4450                          ToRegister(instr->temp()),
4451                          kDontSaveFPRegs);
4452   } else {
4453     DCHECK(ToRegister(instr->context()).is(esi));
4454     DCHECK(object_reg.is(eax));
4455     PushSafepointRegistersScope scope(this);
4456     __ mov(ebx, to_map);
4457     bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4458     TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4459     __ CallStub(&stub);
4460     RecordSafepointWithLazyDeopt(instr,
4461         RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4462   }
4463   __ bind(&not_applicable);
4464 }
4465
4466
4467 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4468   class DeferredStringCharCodeAt final : public LDeferredCode {
4469    public:
4470     DeferredStringCharCodeAt(LCodeGen* codegen,
4471                              LStringCharCodeAt* instr)
4472         : LDeferredCode(codegen), instr_(instr) { }
4473     void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4474     LInstruction* instr() override { return instr_; }
4475
4476    private:
4477     LStringCharCodeAt* instr_;
4478   };
4479
4480   DeferredStringCharCodeAt* deferred =
4481       new(zone()) DeferredStringCharCodeAt(this, instr);
4482
4483   StringCharLoadGenerator::Generate(masm(),
4484                                     factory(),
4485                                     ToRegister(instr->string()),
4486                                     ToRegister(instr->index()),
4487                                     ToRegister(instr->result()),
4488                                     deferred->entry());
4489   __ bind(deferred->exit());
4490 }
4491
4492
4493 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4494   Register string = ToRegister(instr->string());
4495   Register result = ToRegister(instr->result());
4496
4497   // TODO(3095996): Get rid of this. For now, we need to make the
4498   // result register contain a valid pointer because it is already
4499   // contained in the register pointer map.
4500   __ Move(result, Immediate(0));
4501
4502   PushSafepointRegistersScope scope(this);
4503   __ push(string);
4504   // Push the index as a smi. This is safe because of the checks in
4505   // DoStringCharCodeAt above.
4506   STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4507   if (instr->index()->IsConstantOperand()) {
4508     Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4509                                       Representation::Smi());
4510     __ push(immediate);
4511   } else {
4512     Register index = ToRegister(instr->index());
4513     __ SmiTag(index);
4514     __ push(index);
4515   }
4516   CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4517                           instr, instr->context());
4518   __ AssertSmi(eax);
4519   __ SmiUntag(eax);
4520   __ StoreToSafepointRegisterSlot(result, eax);
4521 }
4522
4523
4524 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4525   class DeferredStringCharFromCode final : public LDeferredCode {
4526    public:
4527     DeferredStringCharFromCode(LCodeGen* codegen,
4528                                LStringCharFromCode* instr)
4529         : LDeferredCode(codegen), instr_(instr) { }
4530     void Generate() override {
4531       codegen()->DoDeferredStringCharFromCode(instr_);
4532     }
4533     LInstruction* instr() override { return instr_; }
4534
4535    private:
4536     LStringCharFromCode* instr_;
4537   };
4538
4539   DeferredStringCharFromCode* deferred =
4540       new(zone()) DeferredStringCharFromCode(this, instr);
4541
4542   DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4543   Register char_code = ToRegister(instr->char_code());
4544   Register result = ToRegister(instr->result());
4545   DCHECK(!char_code.is(result));
4546
4547   __ cmp(char_code, String::kMaxOneByteCharCode);
4548   __ j(above, deferred->entry());
4549   __ Move(result, Immediate(factory()->single_character_string_cache()));
4550   __ mov(result, FieldOperand(result,
4551                               char_code, times_pointer_size,
4552                               FixedArray::kHeaderSize));
4553   __ cmp(result, factory()->undefined_value());
4554   __ j(equal, deferred->entry());
4555   __ bind(deferred->exit());
4556 }
4557
4558
4559 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4560   Register char_code = ToRegister(instr->char_code());
4561   Register result = ToRegister(instr->result());
4562
4563   // TODO(3095996): Get rid of this. For now, we need to make the
4564   // result register contain a valid pointer because it is already
4565   // contained in the register pointer map.
4566   __ Move(result, Immediate(0));
4567
4568   PushSafepointRegistersScope scope(this);
4569   __ SmiTag(char_code);
4570   __ push(char_code);
4571   CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4572   __ StoreToSafepointRegisterSlot(result, eax);
4573 }
4574
4575
4576 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4577   DCHECK(ToRegister(instr->context()).is(esi));
4578   DCHECK(ToRegister(instr->left()).is(edx));
4579   DCHECK(ToRegister(instr->right()).is(eax));
4580   StringAddStub stub(isolate(),
4581                      instr->hydrogen()->flags(),
4582                      instr->hydrogen()->pretenure_flag());
4583   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4584 }
4585
4586
4587 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4588   LOperand* input = instr->value();
4589   LOperand* output = instr->result();
4590   DCHECK(input->IsRegister() || input->IsStackSlot());
4591   DCHECK(output->IsDoubleRegister());
4592   __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4593 }
4594
4595
4596 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4597   LOperand* input = instr->value();
4598   LOperand* output = instr->result();
4599   __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4600 }
4601
4602
4603 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4604   class DeferredNumberTagI final : public LDeferredCode {
4605    public:
4606     DeferredNumberTagI(LCodeGen* codegen,
4607                        LNumberTagI* instr)
4608         : LDeferredCode(codegen), instr_(instr) { }
4609     void Generate() override {
4610       codegen()->DoDeferredNumberTagIU(
4611           instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4612     }
4613     LInstruction* instr() override { return instr_; }
4614
4615    private:
4616     LNumberTagI* instr_;
4617   };
4618
4619   LOperand* input = instr->value();
4620   DCHECK(input->IsRegister() && input->Equals(instr->result()));
4621   Register reg = ToRegister(input);
4622
4623   DeferredNumberTagI* deferred =
4624       new(zone()) DeferredNumberTagI(this, instr);
4625   __ SmiTag(reg);
4626   __ j(overflow, deferred->entry());
4627   __ bind(deferred->exit());
4628 }
4629
4630
4631 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4632   class DeferredNumberTagU final : public LDeferredCode {
4633    public:
4634     DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4635         : LDeferredCode(codegen), instr_(instr) { }
4636     void Generate() override {
4637       codegen()->DoDeferredNumberTagIU(
4638           instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4639     }
4640     LInstruction* instr() override { return instr_; }
4641
4642    private:
4643     LNumberTagU* instr_;
4644   };
4645
4646   LOperand* input = instr->value();
4647   DCHECK(input->IsRegister() && input->Equals(instr->result()));
4648   Register reg = ToRegister(input);
4649
4650   DeferredNumberTagU* deferred =
4651       new(zone()) DeferredNumberTagU(this, instr);
4652   __ cmp(reg, Immediate(Smi::kMaxValue));
4653   __ j(above, deferred->entry());
4654   __ SmiTag(reg);
4655   __ bind(deferred->exit());
4656 }
4657
4658
4659 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4660                                      LOperand* value,
4661                                      LOperand* temp,
4662                                      IntegerSignedness signedness) {
4663   Label done, slow;
4664   Register reg = ToRegister(value);
4665   Register tmp = ToRegister(temp);
4666   XMMRegister xmm_scratch = double_scratch0();
4667
4668   if (signedness == SIGNED_INT32) {
4669     // There was overflow, so bits 30 and 31 of the original integer
4670     // disagree. Try to allocate a heap number in new space and store
4671     // the value in there. If that fails, call the runtime system.
4672     __ SmiUntag(reg);
4673     __ xor_(reg, 0x80000000);
4674     __ Cvtsi2sd(xmm_scratch, Operand(reg));
4675   } else {
4676     __ LoadUint32(xmm_scratch, reg);
4677   }
4678
4679   if (FLAG_inline_new) {
4680     __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4681     __ jmp(&done, Label::kNear);
4682   }
4683
4684   // Slow case: Call the runtime system to do the number allocation.
4685   __ bind(&slow);
4686   {
4687     // TODO(3095996): Put a valid pointer value in the stack slot where the
4688     // result register is stored, as this register is in the pointer map, but
4689     // contains an integer value.
4690     __ Move(reg, Immediate(0));
4691
4692     // Preserve the value of all registers.
4693     PushSafepointRegistersScope scope(this);
4694
4695     // NumberTagI and NumberTagD use the context from the frame, rather than
4696     // the environment's HContext or HInlinedContext value.
4697     // They only call Runtime::kAllocateHeapNumber.
4698     // The corresponding HChange instructions are added in a phase that does
4699     // not have easy access to the local context.
4700     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4701     __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4702     RecordSafepointWithRegisters(
4703         instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4704     __ StoreToSafepointRegisterSlot(reg, eax);
4705   }
4706
4707   // Done. Put the value in xmm_scratch into the value of the allocated heap
4708   // number.
4709   __ bind(&done);
4710   __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4711 }
4712
4713
4714 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4715   class DeferredNumberTagD final : public LDeferredCode {
4716    public:
4717     DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4718         : LDeferredCode(codegen), instr_(instr) { }
4719     void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4720     LInstruction* instr() override { return instr_; }
4721
4722    private:
4723     LNumberTagD* instr_;
4724   };
4725
4726   Register reg = ToRegister(instr->result());
4727
4728   DeferredNumberTagD* deferred =
4729       new(zone()) DeferredNumberTagD(this, instr);
4730   if (FLAG_inline_new) {
4731     Register tmp = ToRegister(instr->temp());
4732     __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4733   } else {
4734     __ jmp(deferred->entry());
4735   }
4736   __ bind(deferred->exit());
4737   XMMRegister input_reg = ToDoubleRegister(instr->value());
4738   __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4739 }
4740
4741
4742 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4743   // TODO(3095996): Get rid of this. For now, we need to make the
4744   // result register contain a valid pointer because it is already
4745   // contained in the register pointer map.
4746   Register reg = ToRegister(instr->result());
4747   __ Move(reg, Immediate(0));
4748
4749   PushSafepointRegistersScope scope(this);
4750   // NumberTagI and NumberTagD use the context from the frame, rather than
4751   // the environment's HContext or HInlinedContext value.
4752   // They only call Runtime::kAllocateHeapNumber.
4753   // The corresponding HChange instructions are added in a phase that does
4754   // not have easy access to the local context.
4755   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4756   __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4757   RecordSafepointWithRegisters(
4758       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4759   __ StoreToSafepointRegisterSlot(reg, eax);
4760 }
4761
4762
4763 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4764   HChange* hchange = instr->hydrogen();
4765   Register input = ToRegister(instr->value());
4766   if (hchange->CheckFlag(HValue::kCanOverflow) &&
4767       hchange->value()->CheckFlag(HValue::kUint32)) {
4768     __ test(input, Immediate(0xc0000000));
4769     DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4770   }
4771   __ SmiTag(input);
4772   if (hchange->CheckFlag(HValue::kCanOverflow) &&
4773       !hchange->value()->CheckFlag(HValue::kUint32)) {
4774     DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4775   }
4776 }
4777
4778
4779 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4780   LOperand* input = instr->value();
4781   Register result = ToRegister(input);
4782   DCHECK(input->IsRegister() && input->Equals(instr->result()));
4783   if (instr->needs_check()) {
4784     __ test(result, Immediate(kSmiTagMask));
4785     DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4786   } else {
4787     __ AssertSmi(result);
4788   }
4789   __ SmiUntag(result);
4790 }
4791
4792
4793 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4794                                 Register temp_reg, XMMRegister result_reg,
4795                                 NumberUntagDMode mode) {
4796   bool can_convert_undefined_to_nan =
4797       instr->hydrogen()->can_convert_undefined_to_nan();
4798   bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4799
4800   Label convert, load_smi, done;
4801
4802   if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4803     // Smi check.
4804     __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4805
4806     // Heap number map check.
4807     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4808            factory()->heap_number_map());
4809     if (can_convert_undefined_to_nan) {
4810       __ j(not_equal, &convert, Label::kNear);
4811     } else {
4812       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4813     }
4814
4815     // Heap number to XMM conversion.
4816     __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4817
4818     if (deoptimize_on_minus_zero) {
4819       XMMRegister xmm_scratch = double_scratch0();
4820       __ xorps(xmm_scratch, xmm_scratch);
4821       __ ucomisd(result_reg, xmm_scratch);
4822       __ j(not_zero, &done, Label::kNear);
4823       __ movmskpd(temp_reg, result_reg);
4824       __ test_b(temp_reg, 1);
4825       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4826     }
4827     __ jmp(&done, Label::kNear);
4828
4829     if (can_convert_undefined_to_nan) {
4830       __ bind(&convert);
4831
4832       // Convert undefined to NaN.
4833       __ cmp(input_reg, factory()->undefined_value());
4834       DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4835
4836       __ pcmpeqd(result_reg, result_reg);
4837       __ jmp(&done, Label::kNear);
4838     }
4839   } else {
4840     DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4841   }
4842
4843   __ bind(&load_smi);
4844   // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4845   // input register since we avoid dependencies.
4846   __ mov(temp_reg, input_reg);
4847   __ SmiUntag(temp_reg);  // Untag smi before converting to float.
4848   __ Cvtsi2sd(result_reg, Operand(temp_reg));
4849   __ bind(&done);
4850 }
4851
4852
4853 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4854   Register input_reg = ToRegister(instr->value());
4855
4856   // The input was optimistically untagged; revert it.
4857   STATIC_ASSERT(kSmiTagSize == 1);
4858   __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4859
4860   if (instr->truncating()) {
4861     Label no_heap_number, check_bools, check_false;
4862
4863     // Heap number map check.
4864     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4865            factory()->heap_number_map());
4866     __ j(not_equal, &no_heap_number, Label::kNear);
4867     __ TruncateHeapNumberToI(input_reg, input_reg);
4868     __ jmp(done);
4869
4870     __ bind(&no_heap_number);
4871     // Check for Oddballs. Undefined/False is converted to zero and True to one
4872     // for truncating conversions.
4873     __ cmp(input_reg, factory()->undefined_value());
4874     __ j(not_equal, &check_bools, Label::kNear);
4875     __ Move(input_reg, Immediate(0));
4876     __ jmp(done);
4877
4878     __ bind(&check_bools);
4879     __ cmp(input_reg, factory()->true_value());
4880     __ j(not_equal, &check_false, Label::kNear);
4881     __ Move(input_reg, Immediate(1));
4882     __ jmp(done);
4883
4884     __ bind(&check_false);
4885     __ cmp(input_reg, factory()->false_value());
4886     DeoptimizeIf(not_equal, instr,
4887                  Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4888     __ Move(input_reg, Immediate(0));
4889   } else {
4890     XMMRegister scratch = ToDoubleRegister(instr->temp());
4891     DCHECK(!scratch.is(xmm0));
4892     __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4893            isolate()->factory()->heap_number_map());
4894     DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4895     __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4896     __ cvttsd2si(input_reg, Operand(xmm0));
4897     __ Cvtsi2sd(scratch, Operand(input_reg));
4898     __ ucomisd(xmm0, scratch);
4899     DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4900     DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4901     if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4902       __ test(input_reg, Operand(input_reg));
4903       __ j(not_zero, done);
4904       __ movmskpd(input_reg, xmm0);
4905       __ and_(input_reg, 1);
4906       DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4907     }
4908   }
4909 }
4910
4911
4912 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4913   class DeferredTaggedToI final : public LDeferredCode {
4914    public:
4915     DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4916         : LDeferredCode(codegen), instr_(instr) { }
4917     void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4918     LInstruction* instr() override { return instr_; }
4919
4920    private:
4921     LTaggedToI* instr_;
4922   };
4923
4924   LOperand* input = instr->value();
4925   DCHECK(input->IsRegister());
4926   Register input_reg = ToRegister(input);
4927   DCHECK(input_reg.is(ToRegister(instr->result())));
4928
4929   if (instr->hydrogen()->value()->representation().IsSmi()) {
4930     __ SmiUntag(input_reg);
4931   } else {
4932     DeferredTaggedToI* deferred =
4933         new(zone()) DeferredTaggedToI(this, instr);
4934     // Optimistically untag the input.
4935     // If the input is a HeapObject, SmiUntag will set the carry flag.
4936     STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4937     __ SmiUntag(input_reg);
4938     // Branch to deferred code if the input was tagged.
4939     // The deferred code will take care of restoring the tag.
4940     __ j(carry, deferred->entry());
4941     __ bind(deferred->exit());
4942   }
4943 }
4944
4945
4946 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4947   LOperand* input = instr->value();
4948   DCHECK(input->IsRegister());
4949   LOperand* temp = instr->temp();
4950   DCHECK(temp->IsRegister());
4951   LOperand* result = instr->result();
4952   DCHECK(result->IsDoubleRegister());
4953
4954   Register input_reg = ToRegister(input);
4955   Register temp_reg = ToRegister(temp);
4956
4957   HValue* value = instr->hydrogen()->value();
4958   NumberUntagDMode mode = value->representation().IsSmi()
4959       ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4960
4961   XMMRegister result_reg = ToDoubleRegister(result);
4962   EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4963 }
4964
4965
4966 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4967   LOperand* input = instr->value();
4968   DCHECK(input->IsDoubleRegister());
4969   LOperand* result = instr->result();
4970   DCHECK(result->IsRegister());
4971   Register result_reg = ToRegister(result);
4972
4973   if (instr->truncating()) {
4974     XMMRegister input_reg = ToDoubleRegister(input);
4975     __ TruncateDoubleToI(result_reg, input_reg);
4976   } else {
4977     Label lost_precision, is_nan, minus_zero, done;
4978     XMMRegister input_reg = ToDoubleRegister(input);
4979     XMMRegister xmm_scratch = double_scratch0();
4980     Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4981     __ DoubleToI(result_reg, input_reg, xmm_scratch,
4982                  instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4983                  &is_nan, &minus_zero, dist);
4984     __ jmp(&done, dist);
4985     __ bind(&lost_precision);
4986     DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4987     __ bind(&is_nan);
4988     DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4989     __ bind(&minus_zero);
4990     DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4991     __ bind(&done);
4992   }
4993 }
4994
4995
4996 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4997   LOperand* input = instr->value();
4998   DCHECK(input->IsDoubleRegister());
4999   LOperand* result = instr->result();
5000   DCHECK(result->IsRegister());
5001   Register result_reg = ToRegister(result);
5002
5003   Label lost_precision, is_nan, minus_zero, done;
5004   XMMRegister input_reg = ToDoubleRegister(input);
5005   XMMRegister xmm_scratch = double_scratch0();
5006   Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
5007   __ DoubleToI(result_reg, input_reg, xmm_scratch,
5008                instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
5009                &minus_zero, dist);
5010   __ jmp(&done, dist);
5011   __ bind(&lost_precision);
5012   DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5013   __ bind(&is_nan);
5014   DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5015   __ bind(&minus_zero);
5016   DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5017   __ bind(&done);
5018   __ SmiTag(result_reg);
5019   DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5020 }
5021
5022
5023 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5024   LOperand* input = instr->value();
5025   __ test(ToOperand(input), Immediate(kSmiTagMask));
5026   DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5027 }
5028
5029
5030 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5031   if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5032     LOperand* input = instr->value();
5033     __ test(ToOperand(input), Immediate(kSmiTagMask));
5034     DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5035   }
5036 }
5037
5038
5039 void LCodeGen::DoCheckArrayBufferNotNeutered(
5040     LCheckArrayBufferNotNeutered* instr) {
5041   Register view = ToRegister(instr->view());
5042   Register scratch = ToRegister(instr->scratch());
5043
5044   __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5045   __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5046             1 << JSArrayBuffer::WasNeutered::kShift);
5047   DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5048 }
5049
5050
5051 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5052   Register input = ToRegister(instr->value());
5053   Register temp = ToRegister(instr->temp());
5054
5055   __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5056
5057   if (instr->hydrogen()->is_interval_check()) {
5058     InstanceType first;
5059     InstanceType last;
5060     instr->hydrogen()->GetCheckInterval(&first, &last);
5061
5062     __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5063             static_cast<int8_t>(first));
5064
5065     // If there is only one type in the interval check for equality.
5066     if (first == last) {
5067       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5068     } else {
5069       DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5070       // Omit check for the last type.
5071       if (last != LAST_TYPE) {
5072         __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5073                 static_cast<int8_t>(last));
5074         DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5075       }
5076     }
5077   } else {
5078     uint8_t mask;
5079     uint8_t tag;
5080     instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5081
5082     if (base::bits::IsPowerOfTwo32(mask)) {
5083       DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5084       __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5085       DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5086                    Deoptimizer::kWrongInstanceType);
5087     } else {
5088       __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5089       __ and_(temp, mask);
5090       __ cmp(temp, tag);
5091       DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5092     }
5093   }
5094 }
5095
5096
5097 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5098   Handle<HeapObject> object = instr->hydrogen()->object().handle();
5099   if (instr->hydrogen()->object_in_new_space()) {
5100     Register reg = ToRegister(instr->value());
5101     Handle<Cell> cell = isolate()->factory()->NewCell(object);
5102     __ cmp(reg, Operand::ForCell(cell));
5103   } else {
5104     Operand operand = ToOperand(instr->value());
5105     __ cmp(operand, object);
5106   }
5107   DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5108 }
5109
5110
5111 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5112   {
5113     PushSafepointRegistersScope scope(this);
5114     __ push(object);
5115     __ xor_(esi, esi);
5116     __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5117     RecordSafepointWithRegisters(
5118         instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5119
5120     __ test(eax, Immediate(kSmiTagMask));
5121   }
5122   DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5123 }
5124
5125
5126 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5127   class DeferredCheckMaps final : public LDeferredCode {
5128    public:
5129     DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr,  Register object)
5130         : LDeferredCode(codegen), instr_(instr), object_(object) {
5131       SetExit(check_maps());
5132     }
5133     void Generate() override {
5134       codegen()->DoDeferredInstanceMigration(instr_, object_);
5135     }
5136     Label* check_maps() { return &check_maps_; }
5137     LInstruction* instr() override { return instr_; }
5138
5139    private:
5140     LCheckMaps* instr_;
5141     Label check_maps_;
5142     Register object_;
5143   };
5144
5145   if (instr->hydrogen()->IsStabilityCheck()) {
5146     const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5147     for (int i = 0; i < maps->size(); ++i) {
5148       AddStabilityDependency(maps->at(i).handle());
5149     }
5150     return;
5151   }
5152
5153   LOperand* input = instr->value();
5154   DCHECK(input->IsRegister());
5155   Register reg = ToRegister(input);
5156
5157   DeferredCheckMaps* deferred = NULL;
5158   if (instr->hydrogen()->HasMigrationTarget()) {
5159     deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5160     __ bind(deferred->check_maps());
5161   }
5162
5163   const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5164   Label success;
5165   for (int i = 0; i < maps->size() - 1; i++) {
5166     Handle<Map> map = maps->at(i).handle();
5167     __ CompareMap(reg, map);
5168     __ j(equal, &success, Label::kNear);
5169   }
5170
5171   Handle<Map> map = maps->at(maps->size() - 1).handle();
5172   __ CompareMap(reg, map);
5173   if (instr->hydrogen()->HasMigrationTarget()) {
5174     __ j(not_equal, deferred->entry());
5175   } else {
5176     DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5177   }
5178
5179   __ bind(&success);
5180 }
5181
5182
5183 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5184   XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5185   XMMRegister xmm_scratch = double_scratch0();
5186   Register result_reg = ToRegister(instr->result());
5187   __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5188 }
5189
5190
5191 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5192   DCHECK(instr->unclamped()->Equals(instr->result()));
5193   Register value_reg = ToRegister(instr->result());
5194   __ ClampUint8(value_reg);
5195 }
5196
5197
5198 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5199   DCHECK(instr->unclamped()->Equals(instr->result()));
5200   Register input_reg = ToRegister(instr->unclamped());
5201   XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5202   XMMRegister xmm_scratch = double_scratch0();
5203   Label is_smi, done, heap_number;
5204
5205   __ JumpIfSmi(input_reg, &is_smi);
5206
5207   // Check for heap number
5208   __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5209          factory()->heap_number_map());
5210   __ j(equal, &heap_number, Label::kNear);
5211
5212   // Check for undefined. Undefined is converted to zero for clamping
5213   // conversions.
5214   __ cmp(input_reg, factory()->undefined_value());
5215   DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5216   __ mov(input_reg, 0);
5217   __ jmp(&done, Label::kNear);
5218
5219   // Heap number
5220   __ bind(&heap_number);
5221   __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5222   __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5223   __ jmp(&done, Label::kNear);
5224
5225   // smi
5226   __ bind(&is_smi);
5227   __ SmiUntag(input_reg);
5228   __ ClampUint8(input_reg);
5229   __ bind(&done);
5230 }
5231
5232
5233 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5234   XMMRegister value_reg = ToDoubleRegister(instr->value());
5235   Register result_reg = ToRegister(instr->result());
5236   if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5237     if (CpuFeatures::IsSupported(SSE4_1)) {
5238       CpuFeatureScope scope2(masm(), SSE4_1);
5239       __ pextrd(result_reg, value_reg, 1);
5240     } else {
5241       XMMRegister xmm_scratch = double_scratch0();
5242       __ pshufd(xmm_scratch, value_reg, 1);
5243       __ movd(result_reg, xmm_scratch);
5244     }
5245   } else {
5246     __ movd(result_reg, value_reg);
5247   }
5248 }
5249
5250
5251 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5252   Register hi_reg = ToRegister(instr->hi());
5253   Register lo_reg = ToRegister(instr->lo());
5254   XMMRegister result_reg = ToDoubleRegister(instr->result());
5255
5256   if (CpuFeatures::IsSupported(SSE4_1)) {
5257     CpuFeatureScope scope2(masm(), SSE4_1);
5258     __ movd(result_reg, lo_reg);
5259     __ pinsrd(result_reg, hi_reg, 1);
5260   } else {
5261     XMMRegister xmm_scratch = double_scratch0();
5262     __ movd(result_reg, hi_reg);
5263     __ psllq(result_reg, 32);
5264     __ movd(xmm_scratch, lo_reg);
5265     __ orps(result_reg, xmm_scratch);
5266   }
5267 }
5268
5269
5270 void LCodeGen::DoAllocate(LAllocate* instr) {
5271   class DeferredAllocate final : public LDeferredCode {
5272    public:
5273     DeferredAllocate(LCodeGen* codegen,  LAllocate* instr)
5274         : LDeferredCode(codegen), instr_(instr) { }
5275     void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5276     LInstruction* instr() override { return instr_; }
5277
5278    private:
5279     LAllocate* instr_;
5280   };
5281
5282   DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5283
5284   Register result = ToRegister(instr->result());
5285   Register temp = ToRegister(instr->temp());
5286
5287   // Allocate memory for the object.
5288   AllocationFlags flags = TAG_OBJECT;
5289   if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5290     flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5291   }
5292   if (instr->hydrogen()->IsOldSpaceAllocation()) {
5293     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5294     flags = static_cast<AllocationFlags>(flags | PRETENURE);
5295   }
5296
5297   if (instr->size()->IsConstantOperand()) {
5298     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5299     if (size <= Page::kMaxRegularHeapObjectSize) {
5300       __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5301     } else {
5302       __ jmp(deferred->entry());
5303     }
5304   } else {
5305     Register size = ToRegister(instr->size());
5306     __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5307   }
5308
5309   __ bind(deferred->exit());
5310
5311   if (instr->hydrogen()->MustPrefillWithFiller()) {
5312     if (instr->size()->IsConstantOperand()) {
5313       int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5314       __ mov(temp, (size / kPointerSize) - 1);
5315     } else {
5316       temp = ToRegister(instr->size());
5317       __ shr(temp, kPointerSizeLog2);
5318       __ dec(temp);
5319     }
5320     Label loop;
5321     __ bind(&loop);
5322     __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5323         isolate()->factory()->one_pointer_filler_map());
5324     __ dec(temp);
5325     __ j(not_zero, &loop);
5326   }
5327 }
5328
5329
5330 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5331   Register result = ToRegister(instr->result());
5332
5333   // TODO(3095996): Get rid of this. For now, we need to make the
5334   // result register contain a valid pointer because it is already
5335   // contained in the register pointer map.
5336   __ Move(result, Immediate(Smi::FromInt(0)));
5337
5338   PushSafepointRegistersScope scope(this);
5339   if (instr->size()->IsRegister()) {
5340     Register size = ToRegister(instr->size());
5341     DCHECK(!size.is(result));
5342     __ SmiTag(ToRegister(instr->size()));
5343     __ push(size);
5344   } else {
5345     int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5346     if (size >= 0 && size <= Smi::kMaxValue) {
5347       __ push(Immediate(Smi::FromInt(size)));
5348     } else {
5349       // We should never get here at runtime => abort
5350       __ int3();
5351       return;
5352     }
5353   }
5354
5355   int flags = AllocateDoubleAlignFlag::encode(
5356       instr->hydrogen()->MustAllocateDoubleAligned());
5357   if (instr->hydrogen()->IsOldSpaceAllocation()) {
5358     DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5359     flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5360   } else {
5361     flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5362   }
5363   __ push(Immediate(Smi::FromInt(flags)));
5364
5365   CallRuntimeFromDeferred(
5366       Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5367   __ StoreToSafepointRegisterSlot(result, eax);
5368 }
5369
5370
5371 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5372   DCHECK(ToRegister(instr->value()).is(eax));
5373   __ push(eax);
5374   CallRuntime(Runtime::kToFastProperties, 1, instr);
5375 }
5376
5377
5378 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5379   DCHECK(ToRegister(instr->context()).is(esi));
5380   Label materialized;
5381   // Registers will be used as follows:
5382   // ecx = literals array.
5383   // ebx = regexp literal.
5384   // eax = regexp literal clone.
5385   // esi = context.
5386   int literal_offset =
5387       FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5388   __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5389   __ mov(ebx, FieldOperand(ecx, literal_offset));
5390   __ cmp(ebx, factory()->undefined_value());
5391   __ j(not_equal, &materialized, Label::kNear);
5392
5393   // Create regexp literal using runtime function
5394   // Result will be in eax.
5395   __ push(ecx);
5396   __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5397   __ push(Immediate(instr->hydrogen()->pattern()));
5398   __ push(Immediate(instr->hydrogen()->flags()));
5399   CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5400   __ mov(ebx, eax);
5401
5402   __ bind(&materialized);
5403   int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5404   Label allocated, runtime_allocate;
5405   __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5406   __ jmp(&allocated, Label::kNear);
5407
5408   __ bind(&runtime_allocate);
5409   __ push(ebx);
5410   __ push(Immediate(Smi::FromInt(size)));
5411   CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5412   __ pop(ebx);
5413
5414   __ bind(&allocated);
5415   // Copy the content into the newly allocated memory.
5416   // (Unroll copy loop once for better throughput).
5417   for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5418     __ mov(edx, FieldOperand(ebx, i));
5419     __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5420     __ mov(FieldOperand(eax, i), edx);
5421     __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5422   }
5423   if ((size % (2 * kPointerSize)) != 0) {
5424     __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5425     __ mov(FieldOperand(eax, size - kPointerSize), edx);
5426   }
5427 }
5428
5429
5430 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5431   DCHECK(ToRegister(instr->context()).is(esi));
5432   // Use the fast case closure allocation code that allocates in new
5433   // space for nested functions that don't need literals cloning.
5434   bool pretenure = instr->hydrogen()->pretenure();
5435   if (!pretenure && instr->hydrogen()->has_no_literals()) {
5436     FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5437                             instr->hydrogen()->kind());
5438     __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5439     CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5440   } else {
5441     __ push(esi);
5442     __ push(Immediate(instr->hydrogen()->shared_info()));
5443     __ push(Immediate(pretenure ? factory()->true_value()
5444                                 : factory()->false_value()));
5445     CallRuntime(Runtime::kNewClosure, 3, instr);
5446   }
5447 }
5448
5449
5450 void LCodeGen::DoTypeof(LTypeof* instr) {
5451   DCHECK(ToRegister(instr->context()).is(esi));
5452   DCHECK(ToRegister(instr->value()).is(ebx));
5453   Label end, do_call;
5454   Register value_register = ToRegister(instr->value());
5455   __ JumpIfNotSmi(value_register, &do_call);
5456   __ mov(eax, Immediate(isolate()->factory()->number_string()));
5457   __ jmp(&end);
5458   __ bind(&do_call);
5459   TypeofStub stub(isolate());
5460   CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5461   __ bind(&end);
5462 }
5463
5464
5465 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5466   Register input = ToRegister(instr->value());
5467   Condition final_branch_condition = EmitTypeofIs(instr, input);
5468   if (final_branch_condition != no_condition) {
5469     EmitBranch(instr, final_branch_condition);
5470   }
5471 }
5472
5473
5474 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5475   Label* true_label = instr->TrueLabel(chunk_);
5476   Label* false_label = instr->FalseLabel(chunk_);
5477   Handle<String> type_name = instr->type_literal();
5478   int left_block = instr->TrueDestination(chunk_);
5479   int right_block = instr->FalseDestination(chunk_);
5480   int next_block = GetNextEmittedBlock();
5481
5482   Label::Distance true_distance = left_block == next_block ? Label::kNear
5483                                                            : Label::kFar;
5484   Label::Distance false_distance = right_block == next_block ? Label::kNear
5485                                                              : Label::kFar;
5486   Condition final_branch_condition = no_condition;
5487   if (String::Equals(type_name, factory()->number_string())) {
5488     __ JumpIfSmi(input, true_label, true_distance);
5489     __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5490            factory()->heap_number_map());
5491     final_branch_condition = equal;
5492
5493   } else if (String::Equals(type_name, factory()->string_string())) {
5494     __ JumpIfSmi(input, false_label, false_distance);
5495     __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5496     __ j(above_equal, false_label, false_distance);
5497     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5498               1 << Map::kIsUndetectable);
5499     final_branch_condition = zero;
5500
5501   } else if (String::Equals(type_name, factory()->symbol_string())) {
5502     __ JumpIfSmi(input, false_label, false_distance);
5503     __ CmpObjectType(input, SYMBOL_TYPE, input);
5504     final_branch_condition = equal;
5505
5506   } else if (String::Equals(type_name, factory()->boolean_string())) {
5507     __ cmp(input, factory()->true_value());
5508     __ j(equal, true_label, true_distance);
5509     __ cmp(input, factory()->false_value());
5510     final_branch_condition = equal;
5511
5512   } else if (String::Equals(type_name, factory()->undefined_string())) {
5513     __ cmp(input, factory()->undefined_value());
5514     __ j(equal, true_label, true_distance);
5515     __ JumpIfSmi(input, false_label, false_distance);
5516     // Check for undetectable objects => true.
5517     __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5518     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5519               1 << Map::kIsUndetectable);
5520     final_branch_condition = not_zero;
5521
5522   } else if (String::Equals(type_name, factory()->function_string())) {
5523     STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5524     __ JumpIfSmi(input, false_label, false_distance);
5525     __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5526     __ j(equal, true_label, true_distance);
5527     __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5528     final_branch_condition = equal;
5529
5530   } else if (String::Equals(type_name, factory()->object_string())) {
5531     __ JumpIfSmi(input, false_label, false_distance);
5532     __ cmp(input, factory()->null_value());
5533     __ j(equal, true_label, true_distance);
5534     __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5535     __ j(below, false_label, false_distance);
5536     __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5537     __ j(above, false_label, false_distance);
5538     // Check for undetectable objects => false.
5539     __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5540               1 << Map::kIsUndetectable);
5541     final_branch_condition = zero;
5542
5543   } else if (String::Equals(type_name, factory()->float32x4_string())) {
5544     __ JumpIfSmi(input, false_label, false_distance);
5545     __ CmpObjectType(input, FLOAT32X4_TYPE, input);
5546     final_branch_condition = equal;
5547
5548   } else {
5549     __ jmp(false_label, false_distance);
5550   }
5551   return final_branch_condition;
5552 }
5553
5554
5555 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5556   Register temp = ToRegister(instr->temp());
5557
5558   EmitIsConstructCall(temp);
5559   EmitBranch(instr, equal);
5560 }
5561
5562
5563 void LCodeGen::EmitIsConstructCall(Register temp) {
5564   // Get the frame pointer for the calling frame.
5565   __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5566
5567   // Skip the arguments adaptor frame if it exists.
5568   Label check_frame_marker;
5569   __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5570          Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5571   __ j(not_equal, &check_frame_marker, Label::kNear);
5572   __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5573
5574   // Check the marker in the calling frame.
5575   __ bind(&check_frame_marker);
5576   __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5577          Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5578 }
5579
5580
5581 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5582   if (!info()->IsStub()) {
5583     // Ensure that we have enough space after the previous lazy-bailout
5584     // instruction for patching the code here.
5585     int current_pc = masm()->pc_offset();
5586     if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5587       int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5588       __ Nop(padding_size);
5589     }
5590   }
5591   last_lazy_deopt_pc_ = masm()->pc_offset();
5592 }
5593
5594
5595 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5596   last_lazy_deopt_pc_ = masm()->pc_offset();
5597   DCHECK(instr->HasEnvironment());
5598   LEnvironment* env = instr->environment();
5599   RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5600   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5601 }
5602
5603
5604 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5605   Deoptimizer::BailoutType type = instr->hydrogen()->type();
5606   // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5607   // needed return address), even though the implementation of LAZY and EAGER is
5608   // now identical. When LAZY is eventually completely folded into EAGER, remove
5609   // the special case below.
5610   if (info()->IsStub() && type == Deoptimizer::EAGER) {
5611     type = Deoptimizer::LAZY;
5612   }
5613   DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5614 }
5615
5616
5617 void LCodeGen::DoDummy(LDummy* instr) {
5618   // Nothing to see here, move on!
5619 }
5620
5621
5622 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5623   // Nothing to see here, move on!
5624 }
5625
5626
5627 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5628   PushSafepointRegistersScope scope(this);
5629   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5630   __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5631   RecordSafepointWithLazyDeopt(
5632       instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5633   DCHECK(instr->HasEnvironment());
5634   LEnvironment* env = instr->environment();
5635   safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5636 }
5637
5638
5639 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5640   class DeferredStackCheck final : public LDeferredCode {
5641    public:
5642     DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5643         : LDeferredCode(codegen), instr_(instr) { }
5644     void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5645     LInstruction* instr() override { return instr_; }
5646
5647    private:
5648     LStackCheck* instr_;
5649   };
5650
5651   DCHECK(instr->HasEnvironment());
5652   LEnvironment* env = instr->environment();
5653   // There is no LLazyBailout instruction for stack-checks. We have to
5654   // prepare for lazy deoptimization explicitly here.
5655   if (instr->hydrogen()->is_function_entry()) {
5656     // Perform stack overflow check.
5657     Label done;
5658     ExternalReference stack_limit =
5659         ExternalReference::address_of_stack_limit(isolate());
5660     __ cmp(esp, Operand::StaticVariable(stack_limit));
5661     __ j(above_equal, &done, Label::kNear);
5662
5663     DCHECK(instr->context()->IsRegister());
5664     DCHECK(ToRegister(instr->context()).is(esi));
5665     CallCode(isolate()->builtins()->StackCheck(),
5666              RelocInfo::CODE_TARGET,
5667              instr);
5668     __ bind(&done);
5669   } else {
5670     DCHECK(instr->hydrogen()->is_backwards_branch());
5671     // Perform stack overflow check if this goto needs it before jumping.
5672     DeferredStackCheck* deferred_stack_check =
5673         new(zone()) DeferredStackCheck(this, instr);
5674     ExternalReference stack_limit =
5675         ExternalReference::address_of_stack_limit(isolate());
5676     __ cmp(esp, Operand::StaticVariable(stack_limit));
5677     __ j(below, deferred_stack_check->entry());
5678     EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5679     __ bind(instr->done_label());
5680     deferred_stack_check->SetExit(instr->done_label());
5681     RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5682     // Don't record a deoptimization index for the safepoint here.
5683     // This will be done explicitly when emitting call and the safepoint in
5684     // the deferred code.
5685   }
5686 }
5687
5688
5689 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5690   // This is a pseudo-instruction that ensures that the environment here is
5691   // properly registered for deoptimization and records the assembler's PC
5692   // offset.
5693   LEnvironment* environment = instr->environment();
5694
5695   // If the environment were already registered, we would have no way of
5696   // backpatching it with the spill slot operands.
5697   DCHECK(!environment->HasBeenRegistered());
5698   RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5699
5700   GenerateOsrPrologue();
5701 }
5702
5703
5704 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5705   DCHECK(ToRegister(instr->context()).is(esi));
5706   __ test(eax, Immediate(kSmiTagMask));
5707   DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5708
5709   STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5710   __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5711   DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5712
5713   Label use_cache, call_runtime;
5714   __ CheckEnumCache(&call_runtime);
5715
5716   __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5717   __ jmp(&use_cache, Label::kNear);
5718
5719   // Get the set of properties to enumerate.
5720   __ bind(&call_runtime);
5721   __ push(eax);
5722   CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5723
5724   __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5725          isolate()->factory()->meta_map());
5726   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5727   __ bind(&use_cache);
5728 }
5729
5730
5731 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5732   Register map = ToRegister(instr->map());
5733   Register result = ToRegister(instr->result());
5734   Label load_cache, done;
5735   __ EnumLength(result, map);
5736   __ cmp(result, Immediate(Smi::FromInt(0)));
5737   __ j(not_equal, &load_cache, Label::kNear);
5738   __ mov(result, isolate()->factory()->empty_fixed_array());
5739   __ jmp(&done, Label::kNear);
5740
5741   __ bind(&load_cache);
5742   __ LoadInstanceDescriptors(map, result);
5743   __ mov(result,
5744          FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5745   __ mov(result,
5746          FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5747   __ bind(&done);
5748   __ test(result, result);
5749   DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5750 }
5751
5752
5753 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5754   Register object = ToRegister(instr->value());
5755   __ cmp(ToRegister(instr->map()),
5756          FieldOperand(object, HeapObject::kMapOffset));
5757   DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5758 }
5759
5760
5761 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5762                                            Register object,
5763                                            Register index) {
5764   PushSafepointRegistersScope scope(this);
5765   __ push(object);
5766   __ push(index);
5767   __ xor_(esi, esi);
5768   __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5769   RecordSafepointWithRegisters(
5770       instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5771   __ StoreToSafepointRegisterSlot(object, eax);
5772 }
5773
5774
5775 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5776   class DeferredLoadMutableDouble final : public LDeferredCode {
5777    public:
5778     DeferredLoadMutableDouble(LCodeGen* codegen,
5779                               LLoadFieldByIndex* instr,
5780                               Register object,
5781                               Register index)
5782         : LDeferredCode(codegen),
5783           instr_(instr),
5784           object_(object),
5785           index_(index) {
5786     }
5787     void Generate() override {
5788       codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5789     }
5790     LInstruction* instr() override { return instr_; }
5791
5792    private:
5793     LLoadFieldByIndex* instr_;
5794     Register object_;
5795     Register index_;
5796   };
5797
5798   Register object = ToRegister(instr->object());
5799   Register index = ToRegister(instr->index());
5800
5801   DeferredLoadMutableDouble* deferred;
5802   deferred = new(zone()) DeferredLoadMutableDouble(
5803       this, instr, object, index);
5804
5805   Label out_of_object, done;
5806   __ test(index, Immediate(Smi::FromInt(1)));
5807   __ j(not_zero, deferred->entry());
5808
5809   __ sar(index, 1);
5810
5811   __ cmp(index, Immediate(0));
5812   __ j(less, &out_of_object, Label::kNear);
5813   __ mov(object, FieldOperand(object,
5814                               index,
5815                               times_half_pointer_size,
5816                               JSObject::kHeaderSize));
5817   __ jmp(&done, Label::kNear);
5818
5819   __ bind(&out_of_object);
5820   __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5821   __ neg(index);
5822   // Index is now equal to out of object property index plus 1.
5823   __ mov(object, FieldOperand(object,
5824                               index,
5825                               times_half_pointer_size,
5826                               FixedArray::kHeaderSize - kPointerSize));
5827   __ bind(deferred->exit());
5828   __ bind(&done);
5829 }
5830
5831
5832 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5833   Register context = ToRegister(instr->context());
5834   __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5835 }
5836
5837
5838 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5839   Handle<ScopeInfo> scope_info = instr->scope_info();
5840   __ Push(scope_info);
5841   __ push(ToRegister(instr->function()));
5842   CallRuntime(Runtime::kPushBlockContext, 2, instr);
5843   RecordSafepoint(Safepoint::kNoLazyDeopt);
5844 }
5845
5846
5847 #undef __
5848
5849 }  // namespace internal
5850 }  // namespace v8
5851
5852 #endif  // V8_TARGET_ARCH_IA32