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