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