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