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