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