deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / arm / macro-assembler-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 <limits.h>  // For LONG_MIN, LONG_MAX.
6
7 #include "src/v8.h"
8
9 #if V8_TARGET_ARCH_ARM
10
11 #include "src/base/bits.h"
12 #include "src/base/division-by-constant.h"
13 #include "src/bootstrapper.h"
14 #include "src/codegen.h"
15 #include "src/cpu-profiler.h"
16 #include "src/debug.h"
17 #include "src/isolate-inl.h"
18 #include "src/runtime/runtime.h"
19
20 namespace v8 {
21 namespace internal {
22
23 MacroAssembler::MacroAssembler(Isolate* arg_isolate, void* buffer, int size)
24     : Assembler(arg_isolate, buffer, size),
25       generating_stub_(false),
26       has_frame_(false) {
27   if (isolate() != NULL) {
28     code_object_ = Handle<Object>(isolate()->heap()->undefined_value(),
29                                   isolate());
30   }
31 }
32
33
34 void MacroAssembler::Jump(Register target, Condition cond) {
35   bx(target, cond);
36 }
37
38
39 void MacroAssembler::Jump(intptr_t target, RelocInfo::Mode rmode,
40                           Condition cond) {
41   DCHECK(RelocInfo::IsCodeTarget(rmode));
42   mov(pc, Operand(target, rmode), LeaveCC, cond);
43 }
44
45
46 void MacroAssembler::Jump(Address target, RelocInfo::Mode rmode,
47                           Condition cond) {
48   DCHECK(!RelocInfo::IsCodeTarget(rmode));
49   Jump(reinterpret_cast<intptr_t>(target), rmode, cond);
50 }
51
52
53 void MacroAssembler::Jump(Handle<Code> code, RelocInfo::Mode rmode,
54                           Condition cond) {
55   DCHECK(RelocInfo::IsCodeTarget(rmode));
56   // 'code' is always generated ARM code, never THUMB code
57   AllowDeferredHandleDereference embedding_raw_address;
58   Jump(reinterpret_cast<intptr_t>(code.location()), rmode, cond);
59 }
60
61
62 int MacroAssembler::CallSize(Register target, Condition cond) {
63   return kInstrSize;
64 }
65
66
67 void MacroAssembler::Call(Register target, Condition cond) {
68   // Block constant pool for the call instruction sequence.
69   BlockConstPoolScope block_const_pool(this);
70   Label start;
71   bind(&start);
72   blx(target, cond);
73   DCHECK_EQ(CallSize(target, cond), SizeOfCodeGeneratedSince(&start));
74 }
75
76
77 int MacroAssembler::CallSize(
78     Address target, RelocInfo::Mode rmode, Condition cond) {
79   Instr mov_instr = cond | MOV | LeaveCC;
80   Operand mov_operand = Operand(reinterpret_cast<intptr_t>(target), rmode);
81   return kInstrSize +
82          mov_operand.instructions_required(this, mov_instr) * kInstrSize;
83 }
84
85
86 int MacroAssembler::CallStubSize(
87     CodeStub* stub, TypeFeedbackId ast_id, Condition cond) {
88   return CallSize(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id, cond);
89 }
90
91
92 int MacroAssembler::CallSizeNotPredictableCodeSize(Isolate* isolate,
93                                                    Address target,
94                                                    RelocInfo::Mode rmode,
95                                                    Condition cond) {
96   Instr mov_instr = cond | MOV | LeaveCC;
97   Operand mov_operand = Operand(reinterpret_cast<intptr_t>(target), rmode);
98   return kInstrSize +
99          mov_operand.instructions_required(NULL, mov_instr) * kInstrSize;
100 }
101
102
103 void MacroAssembler::Call(Address target,
104                           RelocInfo::Mode rmode,
105                           Condition cond,
106                           TargetAddressStorageMode mode) {
107   // Block constant pool for the call instruction sequence.
108   BlockConstPoolScope block_const_pool(this);
109   Label start;
110   bind(&start);
111
112   bool old_predictable_code_size = predictable_code_size();
113   if (mode == NEVER_INLINE_TARGET_ADDRESS) {
114     set_predictable_code_size(true);
115   }
116
117 #ifdef DEBUG
118   // Check the expected size before generating code to ensure we assume the same
119   // constant pool availability (e.g., whether constant pool is full or not).
120   int expected_size = CallSize(target, rmode, cond);
121 #endif
122
123   // Call sequence on V7 or later may be :
124   //  movw  ip, #... @ call address low 16
125   //  movt  ip, #... @ call address high 16
126   //  blx   ip
127   //                      @ return address
128   // Or for pre-V7 or values that may be back-patched
129   // to avoid ICache flushes:
130   //  ldr   ip, [pc, #...] @ call address
131   //  blx   ip
132   //                      @ return address
133
134   // Statement positions are expected to be recorded when the target
135   // address is loaded. The mov method will automatically record
136   // positions when pc is the target, since this is not the case here
137   // we have to do it explicitly.
138   positions_recorder()->WriteRecordedPositions();
139
140   mov(ip, Operand(reinterpret_cast<int32_t>(target), rmode));
141   blx(ip, cond);
142
143   DCHECK_EQ(expected_size, SizeOfCodeGeneratedSince(&start));
144   if (mode == NEVER_INLINE_TARGET_ADDRESS) {
145     set_predictable_code_size(old_predictable_code_size);
146   }
147 }
148
149
150 int MacroAssembler::CallSize(Handle<Code> code,
151                              RelocInfo::Mode rmode,
152                              TypeFeedbackId ast_id,
153                              Condition cond) {
154   AllowDeferredHandleDereference using_raw_address;
155   return CallSize(reinterpret_cast<Address>(code.location()), rmode, cond);
156 }
157
158
159 void MacroAssembler::Call(Handle<Code> code,
160                           RelocInfo::Mode rmode,
161                           TypeFeedbackId ast_id,
162                           Condition cond,
163                           TargetAddressStorageMode mode) {
164   Label start;
165   bind(&start);
166   DCHECK(RelocInfo::IsCodeTarget(rmode));
167   if (rmode == RelocInfo::CODE_TARGET && !ast_id.IsNone()) {
168     SetRecordedAstId(ast_id);
169     rmode = RelocInfo::CODE_TARGET_WITH_ID;
170   }
171   // 'code' is always generated ARM code, never THUMB code
172   AllowDeferredHandleDereference embedding_raw_address;
173   Call(reinterpret_cast<Address>(code.location()), rmode, cond, mode);
174 }
175
176
177 void MacroAssembler::Ret(Condition cond) {
178   bx(lr, cond);
179 }
180
181
182 void MacroAssembler::Drop(int count, Condition cond) {
183   if (count > 0) {
184     add(sp, sp, Operand(count * kPointerSize), LeaveCC, cond);
185   }
186 }
187
188
189 void MacroAssembler::Ret(int drop, Condition cond) {
190   Drop(drop, cond);
191   Ret(cond);
192 }
193
194
195 void MacroAssembler::Swap(Register reg1,
196                           Register reg2,
197                           Register scratch,
198                           Condition cond) {
199   if (scratch.is(no_reg)) {
200     eor(reg1, reg1, Operand(reg2), LeaveCC, cond);
201     eor(reg2, reg2, Operand(reg1), LeaveCC, cond);
202     eor(reg1, reg1, Operand(reg2), LeaveCC, cond);
203   } else {
204     mov(scratch, reg1, LeaveCC, cond);
205     mov(reg1, reg2, LeaveCC, cond);
206     mov(reg2, scratch, LeaveCC, cond);
207   }
208 }
209
210
211 void MacroAssembler::Call(Label* target) {
212   bl(target);
213 }
214
215
216 void MacroAssembler::Push(Handle<Object> handle) {
217   mov(ip, Operand(handle));
218   push(ip);
219 }
220
221
222 void MacroAssembler::Move(Register dst, Handle<Object> value) {
223   AllowDeferredHandleDereference smi_check;
224   if (value->IsSmi()) {
225     mov(dst, Operand(value));
226   } else {
227     DCHECK(value->IsHeapObject());
228     if (isolate()->heap()->InNewSpace(*value)) {
229       Handle<Cell> cell = isolate()->factory()->NewCell(value);
230       mov(dst, Operand(cell));
231       ldr(dst, FieldMemOperand(dst, Cell::kValueOffset));
232     } else {
233       mov(dst, Operand(value));
234     }
235   }
236 }
237
238
239 void MacroAssembler::Move(Register dst, Register src, Condition cond) {
240   if (!dst.is(src)) {
241     mov(dst, src, LeaveCC, cond);
242   }
243 }
244
245
246 void MacroAssembler::Move(DwVfpRegister dst, DwVfpRegister src) {
247   if (!dst.is(src)) {
248     vmov(dst, src);
249   }
250 }
251
252
253 void MacroAssembler::Mls(Register dst, Register src1, Register src2,
254                          Register srcA, Condition cond) {
255   if (CpuFeatures::IsSupported(MLS)) {
256     CpuFeatureScope scope(this, MLS);
257     mls(dst, src1, src2, srcA, cond);
258   } else {
259     DCHECK(!srcA.is(ip));
260     mul(ip, src1, src2, LeaveCC, cond);
261     sub(dst, srcA, ip, LeaveCC, cond);
262   }
263 }
264
265
266 void MacroAssembler::And(Register dst, Register src1, const Operand& src2,
267                          Condition cond) {
268   if (!src2.is_reg() &&
269       !src2.must_output_reloc_info(this) &&
270       src2.immediate() == 0) {
271     mov(dst, Operand::Zero(), LeaveCC, cond);
272   } else if (!(src2.instructions_required(this) == 1) &&
273              !src2.must_output_reloc_info(this) &&
274              CpuFeatures::IsSupported(ARMv7) &&
275              base::bits::IsPowerOfTwo32(src2.immediate() + 1)) {
276     ubfx(dst, src1, 0,
277         WhichPowerOf2(static_cast<uint32_t>(src2.immediate()) + 1), cond);
278   } else {
279     and_(dst, src1, src2, LeaveCC, cond);
280   }
281 }
282
283
284 void MacroAssembler::Ubfx(Register dst, Register src1, int lsb, int width,
285                           Condition cond) {
286   DCHECK(lsb < 32);
287   if (!CpuFeatures::IsSupported(ARMv7) || predictable_code_size()) {
288     int mask = (1 << (width + lsb)) - 1 - ((1 << lsb) - 1);
289     and_(dst, src1, Operand(mask), LeaveCC, cond);
290     if (lsb != 0) {
291       mov(dst, Operand(dst, LSR, lsb), LeaveCC, cond);
292     }
293   } else {
294     ubfx(dst, src1, lsb, width, cond);
295   }
296 }
297
298
299 void MacroAssembler::Sbfx(Register dst, Register src1, int lsb, int width,
300                           Condition cond) {
301   DCHECK(lsb < 32);
302   if (!CpuFeatures::IsSupported(ARMv7) || predictable_code_size()) {
303     int mask = (1 << (width + lsb)) - 1 - ((1 << lsb) - 1);
304     and_(dst, src1, Operand(mask), LeaveCC, cond);
305     int shift_up = 32 - lsb - width;
306     int shift_down = lsb + shift_up;
307     if (shift_up != 0) {
308       mov(dst, Operand(dst, LSL, shift_up), LeaveCC, cond);
309     }
310     if (shift_down != 0) {
311       mov(dst, Operand(dst, ASR, shift_down), LeaveCC, cond);
312     }
313   } else {
314     sbfx(dst, src1, lsb, width, cond);
315   }
316 }
317
318
319 void MacroAssembler::Bfi(Register dst,
320                          Register src,
321                          Register scratch,
322                          int lsb,
323                          int width,
324                          Condition cond) {
325   DCHECK(0 <= lsb && lsb < 32);
326   DCHECK(0 <= width && width < 32);
327   DCHECK(lsb + width < 32);
328   DCHECK(!scratch.is(dst));
329   if (width == 0) return;
330   if (!CpuFeatures::IsSupported(ARMv7) || predictable_code_size()) {
331     int mask = (1 << (width + lsb)) - 1 - ((1 << lsb) - 1);
332     bic(dst, dst, Operand(mask));
333     and_(scratch, src, Operand((1 << width) - 1));
334     mov(scratch, Operand(scratch, LSL, lsb));
335     orr(dst, dst, scratch);
336   } else {
337     bfi(dst, src, lsb, width, cond);
338   }
339 }
340
341
342 void MacroAssembler::Bfc(Register dst, Register src, int lsb, int width,
343                          Condition cond) {
344   DCHECK(lsb < 32);
345   if (!CpuFeatures::IsSupported(ARMv7) || predictable_code_size()) {
346     int mask = (1 << (width + lsb)) - 1 - ((1 << lsb) - 1);
347     bic(dst, src, Operand(mask));
348   } else {
349     Move(dst, src, cond);
350     bfc(dst, lsb, width, cond);
351   }
352 }
353
354
355 void MacroAssembler::Usat(Register dst, int satpos, const Operand& src,
356                           Condition cond) {
357   if (!CpuFeatures::IsSupported(ARMv7) || predictable_code_size()) {
358     DCHECK(!dst.is(pc) && !src.rm().is(pc));
359     DCHECK((satpos >= 0) && (satpos <= 31));
360
361     // These asserts are required to ensure compatibility with the ARMv7
362     // implementation.
363     DCHECK((src.shift_op() == ASR) || (src.shift_op() == LSL));
364     DCHECK(src.rs().is(no_reg));
365
366     Label done;
367     int satval = (1 << satpos) - 1;
368
369     if (cond != al) {
370       b(NegateCondition(cond), &done);  // Skip saturate if !condition.
371     }
372     if (!(src.is_reg() && dst.is(src.rm()))) {
373       mov(dst, src);
374     }
375     tst(dst, Operand(~satval));
376     b(eq, &done);
377     mov(dst, Operand::Zero(), LeaveCC, mi);  // 0 if negative.
378     mov(dst, Operand(satval), LeaveCC, pl);  // satval if positive.
379     bind(&done);
380   } else {
381     usat(dst, satpos, src, cond);
382   }
383 }
384
385
386 void MacroAssembler::Load(Register dst,
387                           const MemOperand& src,
388                           Representation r) {
389   DCHECK(!r.IsDouble());
390   if (r.IsInteger8()) {
391     ldrsb(dst, src);
392   } else if (r.IsUInteger8()) {
393     ldrb(dst, src);
394   } else if (r.IsInteger16()) {
395     ldrsh(dst, src);
396   } else if (r.IsUInteger16()) {
397     ldrh(dst, src);
398   } else {
399     ldr(dst, src);
400   }
401 }
402
403
404 void MacroAssembler::Store(Register src,
405                            const MemOperand& dst,
406                            Representation r) {
407   DCHECK(!r.IsDouble());
408   if (r.IsInteger8() || r.IsUInteger8()) {
409     strb(src, dst);
410   } else if (r.IsInteger16() || r.IsUInteger16()) {
411     strh(src, dst);
412   } else {
413     if (r.IsHeapObject()) {
414       AssertNotSmi(src);
415     } else if (r.IsSmi()) {
416       AssertSmi(src);
417     }
418     str(src, dst);
419   }
420 }
421
422
423 void MacroAssembler::LoadRoot(Register destination,
424                               Heap::RootListIndex index,
425                               Condition cond) {
426   if (CpuFeatures::IsSupported(MOVW_MOVT_IMMEDIATE_LOADS) &&
427       isolate()->heap()->RootCanBeTreatedAsConstant(index) &&
428       !predictable_code_size()) {
429     // The CPU supports fast immediate values, and this root will never
430     // change. We will load it as a relocatable immediate value.
431     Handle<Object> root(&isolate()->heap()->roots_array_start()[index]);
432     mov(destination, Operand(root), LeaveCC, cond);
433     return;
434   }
435   ldr(destination, MemOperand(kRootRegister, index << kPointerSizeLog2), cond);
436 }
437
438
439 void MacroAssembler::StoreRoot(Register source,
440                                Heap::RootListIndex index,
441                                Condition cond) {
442   DCHECK(Heap::RootCanBeWrittenAfterInitialization(index));
443   str(source, MemOperand(kRootRegister, index << kPointerSizeLog2), cond);
444 }
445
446
447 void MacroAssembler::InNewSpace(Register object,
448                                 Register scratch,
449                                 Condition cond,
450                                 Label* branch) {
451   DCHECK(cond == eq || cond == ne);
452   and_(scratch, object, Operand(ExternalReference::new_space_mask(isolate())));
453   cmp(scratch, Operand(ExternalReference::new_space_start(isolate())));
454   b(cond, branch);
455 }
456
457
458 void MacroAssembler::RecordWriteField(
459     Register object,
460     int offset,
461     Register value,
462     Register dst,
463     LinkRegisterStatus lr_status,
464     SaveFPRegsMode save_fp,
465     RememberedSetAction remembered_set_action,
466     SmiCheck smi_check,
467     PointersToHereCheck pointers_to_here_check_for_value) {
468   // First, check if a write barrier is even needed. The tests below
469   // catch stores of Smis.
470   Label done;
471
472   // Skip barrier if writing a smi.
473   if (smi_check == INLINE_SMI_CHECK) {
474     JumpIfSmi(value, &done);
475   }
476
477   // Although the object register is tagged, the offset is relative to the start
478   // of the object, so so offset must be a multiple of kPointerSize.
479   DCHECK(IsAligned(offset, kPointerSize));
480
481   add(dst, object, Operand(offset - kHeapObjectTag));
482   if (emit_debug_code()) {
483     Label ok;
484     tst(dst, Operand((1 << kPointerSizeLog2) - 1));
485     b(eq, &ok);
486     stop("Unaligned cell in write barrier");
487     bind(&ok);
488   }
489
490   RecordWrite(object,
491               dst,
492               value,
493               lr_status,
494               save_fp,
495               remembered_set_action,
496               OMIT_SMI_CHECK,
497               pointers_to_here_check_for_value);
498
499   bind(&done);
500
501   // Clobber clobbered input registers when running with the debug-code flag
502   // turned on to provoke errors.
503   if (emit_debug_code()) {
504     mov(value, Operand(bit_cast<int32_t>(kZapValue + 4)));
505     mov(dst, Operand(bit_cast<int32_t>(kZapValue + 8)));
506   }
507 }
508
509
510 // Will clobber 4 registers: object, map, dst, ip.  The
511 // register 'object' contains a heap object pointer.
512 void MacroAssembler::RecordWriteForMap(Register object,
513                                        Register map,
514                                        Register dst,
515                                        LinkRegisterStatus lr_status,
516                                        SaveFPRegsMode fp_mode) {
517   if (emit_debug_code()) {
518     ldr(dst, FieldMemOperand(map, HeapObject::kMapOffset));
519     cmp(dst, Operand(isolate()->factory()->meta_map()));
520     Check(eq, kWrongAddressOrValuePassedToRecordWrite);
521   }
522
523   if (!FLAG_incremental_marking) {
524     return;
525   }
526
527   if (emit_debug_code()) {
528     ldr(ip, FieldMemOperand(object, HeapObject::kMapOffset));
529     cmp(ip, map);
530     Check(eq, kWrongAddressOrValuePassedToRecordWrite);
531   }
532
533   Label done;
534
535   // A single check of the map's pages interesting flag suffices, since it is
536   // only set during incremental collection, and then it's also guaranteed that
537   // the from object's page's interesting flag is also set.  This optimization
538   // relies on the fact that maps can never be in new space.
539   CheckPageFlag(map,
540                 map,  // Used as scratch.
541                 MemoryChunk::kPointersToHereAreInterestingMask,
542                 eq,
543                 &done);
544
545   add(dst, object, Operand(HeapObject::kMapOffset - kHeapObjectTag));
546   if (emit_debug_code()) {
547     Label ok;
548     tst(dst, Operand((1 << kPointerSizeLog2) - 1));
549     b(eq, &ok);
550     stop("Unaligned cell in write barrier");
551     bind(&ok);
552   }
553
554   // Record the actual write.
555   if (lr_status == kLRHasNotBeenSaved) {
556     push(lr);
557   }
558   RecordWriteStub stub(isolate(), object, map, dst, OMIT_REMEMBERED_SET,
559                        fp_mode);
560   CallStub(&stub);
561   if (lr_status == kLRHasNotBeenSaved) {
562     pop(lr);
563   }
564
565   bind(&done);
566
567   // Count number of write barriers in generated code.
568   isolate()->counters()->write_barriers_static()->Increment();
569   IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, ip, dst);
570
571   // Clobber clobbered registers when running with the debug-code flag
572   // turned on to provoke errors.
573   if (emit_debug_code()) {
574     mov(dst, Operand(bit_cast<int32_t>(kZapValue + 12)));
575     mov(map, Operand(bit_cast<int32_t>(kZapValue + 16)));
576   }
577 }
578
579
580 // Will clobber 4 registers: object, address, scratch, ip.  The
581 // register 'object' contains a heap object pointer.  The heap object
582 // tag is shifted away.
583 void MacroAssembler::RecordWrite(
584     Register object,
585     Register address,
586     Register value,
587     LinkRegisterStatus lr_status,
588     SaveFPRegsMode fp_mode,
589     RememberedSetAction remembered_set_action,
590     SmiCheck smi_check,
591     PointersToHereCheck pointers_to_here_check_for_value) {
592   DCHECK(!object.is(value));
593   if (emit_debug_code()) {
594     ldr(ip, MemOperand(address));
595     cmp(ip, value);
596     Check(eq, kWrongAddressOrValuePassedToRecordWrite);
597   }
598
599   if (remembered_set_action == OMIT_REMEMBERED_SET &&
600       !FLAG_incremental_marking) {
601     return;
602   }
603
604   // First, check if a write barrier is even needed. The tests below
605   // catch stores of smis and stores into the young generation.
606   Label done;
607
608   if (smi_check == INLINE_SMI_CHECK) {
609     JumpIfSmi(value, &done);
610   }
611
612   if (pointers_to_here_check_for_value != kPointersToHereAreAlwaysInteresting) {
613     CheckPageFlag(value,
614                   value,  // Used as scratch.
615                   MemoryChunk::kPointersToHereAreInterestingMask,
616                   eq,
617                   &done);
618   }
619   CheckPageFlag(object,
620                 value,  // Used as scratch.
621                 MemoryChunk::kPointersFromHereAreInterestingMask,
622                 eq,
623                 &done);
624
625   // Record the actual write.
626   if (lr_status == kLRHasNotBeenSaved) {
627     push(lr);
628   }
629   RecordWriteStub stub(isolate(), object, value, address, remembered_set_action,
630                        fp_mode);
631   CallStub(&stub);
632   if (lr_status == kLRHasNotBeenSaved) {
633     pop(lr);
634   }
635
636   bind(&done);
637
638   // Count number of write barriers in generated code.
639   isolate()->counters()->write_barriers_static()->Increment();
640   IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, ip,
641                    value);
642
643   // Clobber clobbered registers when running with the debug-code flag
644   // turned on to provoke errors.
645   if (emit_debug_code()) {
646     mov(address, Operand(bit_cast<int32_t>(kZapValue + 12)));
647     mov(value, Operand(bit_cast<int32_t>(kZapValue + 16)));
648   }
649 }
650
651
652 void MacroAssembler::RememberedSetHelper(Register object,  // For debug tests.
653                                          Register address,
654                                          Register scratch,
655                                          SaveFPRegsMode fp_mode,
656                                          RememberedSetFinalAction and_then) {
657   Label done;
658   if (emit_debug_code()) {
659     Label ok;
660     JumpIfNotInNewSpace(object, scratch, &ok);
661     stop("Remembered set pointer is in new space");
662     bind(&ok);
663   }
664   // Load store buffer top.
665   ExternalReference store_buffer =
666       ExternalReference::store_buffer_top(isolate());
667   mov(ip, Operand(store_buffer));
668   ldr(scratch, MemOperand(ip));
669   // Store pointer to buffer and increment buffer top.
670   str(address, MemOperand(scratch, kPointerSize, PostIndex));
671   // Write back new top of buffer.
672   str(scratch, MemOperand(ip));
673   // Call stub on end of buffer.
674   // Check for end of buffer.
675   tst(scratch, Operand(StoreBuffer::kStoreBufferOverflowBit));
676   if (and_then == kFallThroughAtEnd) {
677     b(eq, &done);
678   } else {
679     DCHECK(and_then == kReturnAtEnd);
680     Ret(eq);
681   }
682   push(lr);
683   StoreBufferOverflowStub store_buffer_overflow(isolate(), fp_mode);
684   CallStub(&store_buffer_overflow);
685   pop(lr);
686   bind(&done);
687   if (and_then == kReturnAtEnd) {
688     Ret();
689   }
690 }
691
692
693 void MacroAssembler::PushFixedFrame(Register marker_reg) {
694   DCHECK(!marker_reg.is_valid() || marker_reg.code() < cp.code());
695   stm(db_w, sp, (marker_reg.is_valid() ? marker_reg.bit() : 0) |
696                 cp.bit() |
697                 (FLAG_enable_ool_constant_pool ? pp.bit() : 0) |
698                 fp.bit() |
699                 lr.bit());
700 }
701
702
703 void MacroAssembler::PopFixedFrame(Register marker_reg) {
704   DCHECK(!marker_reg.is_valid() || marker_reg.code() < cp.code());
705   ldm(ia_w, sp, (marker_reg.is_valid() ? marker_reg.bit() : 0) |
706                 cp.bit() |
707                 (FLAG_enable_ool_constant_pool ? pp.bit() : 0) |
708                 fp.bit() |
709                 lr.bit());
710 }
711
712
713 // Push and pop all registers that can hold pointers.
714 void MacroAssembler::PushSafepointRegisters() {
715   // Safepoints expect a block of contiguous register values starting with r0:
716   DCHECK(((1 << kNumSafepointSavedRegisters) - 1) == kSafepointSavedRegisters);
717   // Safepoints expect a block of kNumSafepointRegisters values on the
718   // stack, so adjust the stack for unsaved registers.
719   const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
720   DCHECK(num_unsaved >= 0);
721   sub(sp, sp, Operand(num_unsaved * kPointerSize));
722   stm(db_w, sp, kSafepointSavedRegisters);
723 }
724
725
726 void MacroAssembler::PopSafepointRegisters() {
727   const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
728   ldm(ia_w, sp, kSafepointSavedRegisters);
729   add(sp, sp, Operand(num_unsaved * kPointerSize));
730 }
731
732
733 void MacroAssembler::StoreToSafepointRegisterSlot(Register src, Register dst) {
734   str(src, SafepointRegisterSlot(dst));
735 }
736
737
738 void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
739   ldr(dst, SafepointRegisterSlot(src));
740 }
741
742
743 int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
744   // The registers are pushed starting with the highest encoding,
745   // which means that lowest encodings are closest to the stack pointer.
746   DCHECK(reg_code >= 0 && reg_code < kNumSafepointRegisters);
747   return reg_code;
748 }
749
750
751 MemOperand MacroAssembler::SafepointRegisterSlot(Register reg) {
752   return MemOperand(sp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
753 }
754
755
756 MemOperand MacroAssembler::SafepointRegistersAndDoublesSlot(Register reg) {
757   // Number of d-regs not known at snapshot time.
758   DCHECK(!serializer_enabled());
759   // General purpose registers are pushed last on the stack.
760   int doubles_size = DwVfpRegister::NumAllocatableRegisters() * kDoubleSize;
761   int register_offset = SafepointRegisterStackIndex(reg.code()) * kPointerSize;
762   return MemOperand(sp, doubles_size + register_offset);
763 }
764
765
766 void MacroAssembler::Ldrd(Register dst1, Register dst2,
767                           const MemOperand& src, Condition cond) {
768   DCHECK(src.rm().is(no_reg));
769   DCHECK(!dst1.is(lr));  // r14.
770
771   // V8 does not use this addressing mode, so the fallback code
772   // below doesn't support it yet.
773   DCHECK((src.am() != PreIndex) && (src.am() != NegPreIndex));
774
775   // Generate two ldr instructions if ldrd is not available.
776   if (CpuFeatures::IsSupported(ARMv7) && !predictable_code_size() &&
777       (dst1.code() % 2 == 0) && (dst1.code() + 1 == dst2.code())) {
778     CpuFeatureScope scope(this, ARMv7);
779     ldrd(dst1, dst2, src, cond);
780   } else {
781     if ((src.am() == Offset) || (src.am() == NegOffset)) {
782       MemOperand src2(src);
783       src2.set_offset(src2.offset() + 4);
784       if (dst1.is(src.rn())) {
785         ldr(dst2, src2, cond);
786         ldr(dst1, src, cond);
787       } else {
788         ldr(dst1, src, cond);
789         ldr(dst2, src2, cond);
790       }
791     } else {  // PostIndex or NegPostIndex.
792       DCHECK((src.am() == PostIndex) || (src.am() == NegPostIndex));
793       if (dst1.is(src.rn())) {
794         ldr(dst2, MemOperand(src.rn(), 4, Offset), cond);
795         ldr(dst1, src, cond);
796       } else {
797         MemOperand src2(src);
798         src2.set_offset(src2.offset() - 4);
799         ldr(dst1, MemOperand(src.rn(), 4, PostIndex), cond);
800         ldr(dst2, src2, cond);
801       }
802     }
803   }
804 }
805
806
807 void MacroAssembler::Strd(Register src1, Register src2,
808                           const MemOperand& dst, Condition cond) {
809   DCHECK(dst.rm().is(no_reg));
810   DCHECK(!src1.is(lr));  // r14.
811
812   // V8 does not use this addressing mode, so the fallback code
813   // below doesn't support it yet.
814   DCHECK((dst.am() != PreIndex) && (dst.am() != NegPreIndex));
815
816   // Generate two str instructions if strd is not available.
817   if (CpuFeatures::IsSupported(ARMv7) && !predictable_code_size() &&
818       (src1.code() % 2 == 0) && (src1.code() + 1 == src2.code())) {
819     CpuFeatureScope scope(this, ARMv7);
820     strd(src1, src2, dst, cond);
821   } else {
822     MemOperand dst2(dst);
823     if ((dst.am() == Offset) || (dst.am() == NegOffset)) {
824       dst2.set_offset(dst2.offset() + 4);
825       str(src1, dst, cond);
826       str(src2, dst2, cond);
827     } else {  // PostIndex or NegPostIndex.
828       DCHECK((dst.am() == PostIndex) || (dst.am() == NegPostIndex));
829       dst2.set_offset(dst2.offset() - 4);
830       str(src1, MemOperand(dst.rn(), 4, PostIndex), cond);
831       str(src2, dst2, cond);
832     }
833   }
834 }
835
836
837 void MacroAssembler::VFPEnsureFPSCRState(Register scratch) {
838   // If needed, restore wanted bits of FPSCR.
839   Label fpscr_done;
840   vmrs(scratch);
841   if (emit_debug_code()) {
842     Label rounding_mode_correct;
843     tst(scratch, Operand(kVFPRoundingModeMask));
844     b(eq, &rounding_mode_correct);
845     // Don't call Assert here, since Runtime_Abort could re-enter here.
846     stop("Default rounding mode not set");
847     bind(&rounding_mode_correct);
848   }
849   tst(scratch, Operand(kVFPDefaultNaNModeControlBit));
850   b(ne, &fpscr_done);
851   orr(scratch, scratch, Operand(kVFPDefaultNaNModeControlBit));
852   vmsr(scratch);
853   bind(&fpscr_done);
854 }
855
856
857 void MacroAssembler::VFPCanonicalizeNaN(const DwVfpRegister dst,
858                                         const DwVfpRegister src,
859                                         const Condition cond) {
860   vsub(dst, src, kDoubleRegZero, cond);
861 }
862
863
864 void MacroAssembler::VFPCompareAndSetFlags(const DwVfpRegister src1,
865                                            const DwVfpRegister src2,
866                                            const Condition cond) {
867   // Compare and move FPSCR flags to the normal condition flags.
868   VFPCompareAndLoadFlags(src1, src2, pc, cond);
869 }
870
871 void MacroAssembler::VFPCompareAndSetFlags(const DwVfpRegister src1,
872                                            const double src2,
873                                            const Condition cond) {
874   // Compare and move FPSCR flags to the normal condition flags.
875   VFPCompareAndLoadFlags(src1, src2, pc, cond);
876 }
877
878
879 void MacroAssembler::VFPCompareAndLoadFlags(const DwVfpRegister src1,
880                                             const DwVfpRegister src2,
881                                             const Register fpscr_flags,
882                                             const Condition cond) {
883   // Compare and load FPSCR.
884   vcmp(src1, src2, cond);
885   vmrs(fpscr_flags, cond);
886 }
887
888 void MacroAssembler::VFPCompareAndLoadFlags(const DwVfpRegister src1,
889                                             const double src2,
890                                             const Register fpscr_flags,
891                                             const Condition cond) {
892   // Compare and load FPSCR.
893   vcmp(src1, src2, cond);
894   vmrs(fpscr_flags, cond);
895 }
896
897 void MacroAssembler::Vmov(const DwVfpRegister dst,
898                           const double imm,
899                           const Register scratch) {
900   static const DoubleRepresentation minus_zero(-0.0);
901   static const DoubleRepresentation zero(0.0);
902   DoubleRepresentation value_rep(imm);
903   // Handle special values first.
904   if (value_rep == zero) {
905     vmov(dst, kDoubleRegZero);
906   } else if (value_rep == minus_zero) {
907     vneg(dst, kDoubleRegZero);
908   } else {
909     vmov(dst, imm, scratch);
910   }
911 }
912
913
914 void MacroAssembler::VmovHigh(Register dst, DwVfpRegister src) {
915   if (src.code() < 16) {
916     const LowDwVfpRegister loc = LowDwVfpRegister::from_code(src.code());
917     vmov(dst, loc.high());
918   } else {
919     vmov(dst, VmovIndexHi, src);
920   }
921 }
922
923
924 void MacroAssembler::VmovHigh(DwVfpRegister dst, Register src) {
925   if (dst.code() < 16) {
926     const LowDwVfpRegister loc = LowDwVfpRegister::from_code(dst.code());
927     vmov(loc.high(), src);
928   } else {
929     vmov(dst, VmovIndexHi, src);
930   }
931 }
932
933
934 void MacroAssembler::VmovLow(Register dst, DwVfpRegister src) {
935   if (src.code() < 16) {
936     const LowDwVfpRegister loc = LowDwVfpRegister::from_code(src.code());
937     vmov(dst, loc.low());
938   } else {
939     vmov(dst, VmovIndexLo, src);
940   }
941 }
942
943
944 void MacroAssembler::VmovLow(DwVfpRegister dst, Register src) {
945   if (dst.code() < 16) {
946     const LowDwVfpRegister loc = LowDwVfpRegister::from_code(dst.code());
947     vmov(loc.low(), src);
948   } else {
949     vmov(dst, VmovIndexLo, src);
950   }
951 }
952
953
954 void MacroAssembler::LoadConstantPoolPointerRegister() {
955   if (FLAG_enable_ool_constant_pool) {
956     int constant_pool_offset = Code::kConstantPoolOffset - Code::kHeaderSize -
957         pc_offset() - Instruction::kPCReadOffset;
958     DCHECK(ImmediateFitsAddrMode2Instruction(constant_pool_offset));
959     ldr(pp, MemOperand(pc, constant_pool_offset));
960   }
961 }
962
963
964 void MacroAssembler::StubPrologue() {
965   PushFixedFrame();
966   Push(Smi::FromInt(StackFrame::STUB));
967   // Adjust FP to point to saved FP.
968   add(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
969   if (FLAG_enable_ool_constant_pool) {
970     LoadConstantPoolPointerRegister();
971     set_ool_constant_pool_available(true);
972   }
973 }
974
975
976 void MacroAssembler::Prologue(bool code_pre_aging) {
977   { PredictableCodeSizeScope predictible_code_size_scope(
978         this, kNoCodeAgeSequenceLength);
979     // The following three instructions must remain together and unmodified
980     // for code aging to work properly.
981     if (code_pre_aging) {
982       // Pre-age the code.
983       Code* stub = Code::GetPreAgedCodeAgeStub(isolate());
984       add(r0, pc, Operand(-8));
985       ldr(pc, MemOperand(pc, -4));
986       emit_code_stub_address(stub);
987     } else {
988       PushFixedFrame(r1);
989       nop(ip.code());
990       // Adjust FP to point to saved FP.
991       add(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
992     }
993   }
994   if (FLAG_enable_ool_constant_pool) {
995     LoadConstantPoolPointerRegister();
996     set_ool_constant_pool_available(true);
997   }
998 }
999
1000
1001 void MacroAssembler::EnterFrame(StackFrame::Type type,
1002                                 bool load_constant_pool_pointer_reg) {
1003   // r0-r3: preserved
1004   PushFixedFrame();
1005   if (FLAG_enable_ool_constant_pool && load_constant_pool_pointer_reg) {
1006     LoadConstantPoolPointerRegister();
1007   }
1008   mov(ip, Operand(Smi::FromInt(type)));
1009   push(ip);
1010   mov(ip, Operand(CodeObject()));
1011   push(ip);
1012   // Adjust FP to point to saved FP.
1013   add(fp, sp,
1014       Operand(StandardFrameConstants::kFixedFrameSizeFromFp + kPointerSize));
1015 }
1016
1017
1018 int MacroAssembler::LeaveFrame(StackFrame::Type type) {
1019   // r0: preserved
1020   // r1: preserved
1021   // r2: preserved
1022
1023   // Drop the execution stack down to the frame pointer and restore
1024   // the caller frame pointer, return address and constant pool pointer
1025   // (if FLAG_enable_ool_constant_pool).
1026   int frame_ends;
1027   if (FLAG_enable_ool_constant_pool) {
1028     add(sp, fp, Operand(StandardFrameConstants::kConstantPoolOffset));
1029     frame_ends = pc_offset();
1030     ldm(ia_w, sp, pp.bit() | fp.bit() | lr.bit());
1031   } else {
1032     mov(sp, fp);
1033     frame_ends = pc_offset();
1034     ldm(ia_w, sp, fp.bit() | lr.bit());
1035   }
1036   return frame_ends;
1037 }
1038
1039
1040 void MacroAssembler::EnterExitFrame(bool save_doubles, int stack_space) {
1041   // Set up the frame structure on the stack.
1042   DCHECK_EQ(2 * kPointerSize, ExitFrameConstants::kCallerSPDisplacement);
1043   DCHECK_EQ(1 * kPointerSize, ExitFrameConstants::kCallerPCOffset);
1044   DCHECK_EQ(0 * kPointerSize, ExitFrameConstants::kCallerFPOffset);
1045   Push(lr, fp);
1046   mov(fp, Operand(sp));  // Set up new frame pointer.
1047   // Reserve room for saved entry sp and code object.
1048   sub(sp, sp, Operand(ExitFrameConstants::kFrameSize));
1049   if (emit_debug_code()) {
1050     mov(ip, Operand::Zero());
1051     str(ip, MemOperand(fp, ExitFrameConstants::kSPOffset));
1052   }
1053   if (FLAG_enable_ool_constant_pool) {
1054     str(pp, MemOperand(fp, ExitFrameConstants::kConstantPoolOffset));
1055   }
1056   mov(ip, Operand(CodeObject()));
1057   str(ip, MemOperand(fp, ExitFrameConstants::kCodeOffset));
1058
1059   // Save the frame pointer and the context in top.
1060   mov(ip, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
1061   str(fp, MemOperand(ip));
1062   mov(ip, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
1063   str(cp, MemOperand(ip));
1064
1065   // Optionally save all double registers.
1066   if (save_doubles) {
1067     SaveFPRegs(sp, ip);
1068     // Note that d0 will be accessible at
1069     //   fp - ExitFrameConstants::kFrameSize -
1070     //   DwVfpRegister::kMaxNumRegisters * kDoubleSize,
1071     // since the sp slot, code slot and constant pool slot (if
1072     // FLAG_enable_ool_constant_pool) were pushed after the fp.
1073   }
1074
1075   // Reserve place for the return address and stack space and align the frame
1076   // preparing for calling the runtime function.
1077   const int frame_alignment = MacroAssembler::ActivationFrameAlignment();
1078   sub(sp, sp, Operand((stack_space + 1) * kPointerSize));
1079   if (frame_alignment > 0) {
1080     DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
1081     and_(sp, sp, Operand(-frame_alignment));
1082   }
1083
1084   // Set the exit frame sp value to point just before the return address
1085   // location.
1086   add(ip, sp, Operand(kPointerSize));
1087   str(ip, MemOperand(fp, ExitFrameConstants::kSPOffset));
1088 }
1089
1090
1091 void MacroAssembler::InitializeNewString(Register string,
1092                                          Register length,
1093                                          Heap::RootListIndex map_index,
1094                                          Register scratch1,
1095                                          Register scratch2) {
1096   SmiTag(scratch1, length);
1097   LoadRoot(scratch2, map_index);
1098   str(scratch1, FieldMemOperand(string, String::kLengthOffset));
1099   mov(scratch1, Operand(String::kEmptyHashField));
1100   str(scratch2, FieldMemOperand(string, HeapObject::kMapOffset));
1101   str(scratch1, FieldMemOperand(string, String::kHashFieldOffset));
1102 }
1103
1104
1105 int MacroAssembler::ActivationFrameAlignment() {
1106 #if V8_HOST_ARCH_ARM
1107   // Running on the real platform. Use the alignment as mandated by the local
1108   // environment.
1109   // Note: This will break if we ever start generating snapshots on one ARM
1110   // platform for another ARM platform with a different alignment.
1111   return base::OS::ActivationFrameAlignment();
1112 #else  // V8_HOST_ARCH_ARM
1113   // If we are using the simulator then we should always align to the expected
1114   // alignment. As the simulator is used to generate snapshots we do not know
1115   // if the target platform will need alignment, so this is controlled from a
1116   // flag.
1117   return FLAG_sim_stack_alignment;
1118 #endif  // V8_HOST_ARCH_ARM
1119 }
1120
1121
1122 void MacroAssembler::LeaveExitFrame(bool save_doubles, Register argument_count,
1123                                     bool restore_context,
1124                                     bool argument_count_is_length) {
1125   ConstantPoolUnavailableScope constant_pool_unavailable(this);
1126
1127   // Optionally restore all double registers.
1128   if (save_doubles) {
1129     // Calculate the stack location of the saved doubles and restore them.
1130     const int offset = ExitFrameConstants::kFrameSize;
1131     sub(r3, fp,
1132         Operand(offset + DwVfpRegister::kMaxNumRegisters * kDoubleSize));
1133     RestoreFPRegs(r3, ip);
1134   }
1135
1136   // Clear top frame.
1137   mov(r3, Operand::Zero());
1138   mov(ip, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
1139   str(r3, MemOperand(ip));
1140
1141   // Restore current context from top and clear it in debug mode.
1142   if (restore_context) {
1143     mov(ip, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
1144     ldr(cp, MemOperand(ip));
1145   }
1146 #ifdef DEBUG
1147   mov(ip, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
1148   str(r3, MemOperand(ip));
1149 #endif
1150
1151   // Tear down the exit frame, pop the arguments, and return.
1152   if (FLAG_enable_ool_constant_pool) {
1153     ldr(pp, MemOperand(fp, ExitFrameConstants::kConstantPoolOffset));
1154   }
1155   mov(sp, Operand(fp));
1156   ldm(ia_w, sp, fp.bit() | lr.bit());
1157   if (argument_count.is_valid()) {
1158     if (argument_count_is_length) {
1159       add(sp, sp, argument_count);
1160     } else {
1161       add(sp, sp, Operand(argument_count, LSL, kPointerSizeLog2));
1162     }
1163   }
1164 }
1165
1166
1167 void MacroAssembler::MovFromFloatResult(const DwVfpRegister dst) {
1168   if (use_eabi_hardfloat()) {
1169     Move(dst, d0);
1170   } else {
1171     vmov(dst, r0, r1);
1172   }
1173 }
1174
1175
1176 // On ARM this is just a synonym to make the purpose clear.
1177 void MacroAssembler::MovFromFloatParameter(DwVfpRegister dst) {
1178   MovFromFloatResult(dst);
1179 }
1180
1181
1182 void MacroAssembler::InvokePrologue(const ParameterCount& expected,
1183                                     const ParameterCount& actual,
1184                                     Handle<Code> code_constant,
1185                                     Register code_reg,
1186                                     Label* done,
1187                                     bool* definitely_mismatches,
1188                                     InvokeFlag flag,
1189                                     const CallWrapper& call_wrapper) {
1190   bool definitely_matches = false;
1191   *definitely_mismatches = false;
1192   Label regular_invoke;
1193
1194   // Check whether the expected and actual arguments count match. If not,
1195   // setup registers according to contract with ArgumentsAdaptorTrampoline:
1196   //  r0: actual arguments count
1197   //  r1: function (passed through to callee)
1198   //  r2: expected arguments count
1199
1200   // The code below is made a lot easier because the calling code already sets
1201   // up actual and expected registers according to the contract if values are
1202   // passed in registers.
1203   DCHECK(actual.is_immediate() || actual.reg().is(r0));
1204   DCHECK(expected.is_immediate() || expected.reg().is(r2));
1205   DCHECK((!code_constant.is_null() && code_reg.is(no_reg)) || code_reg.is(r3));
1206
1207   if (expected.is_immediate()) {
1208     DCHECK(actual.is_immediate());
1209     if (expected.immediate() == actual.immediate()) {
1210       definitely_matches = true;
1211     } else {
1212       mov(r0, Operand(actual.immediate()));
1213       const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
1214       if (expected.immediate() == sentinel) {
1215         // Don't worry about adapting arguments for builtins that
1216         // don't want that done. Skip adaption code by making it look
1217         // like we have a match between expected and actual number of
1218         // arguments.
1219         definitely_matches = true;
1220       } else {
1221         *definitely_mismatches = true;
1222         mov(r2, Operand(expected.immediate()));
1223       }
1224     }
1225   } else {
1226     if (actual.is_immediate()) {
1227       cmp(expected.reg(), Operand(actual.immediate()));
1228       b(eq, &regular_invoke);
1229       mov(r0, Operand(actual.immediate()));
1230     } else {
1231       cmp(expected.reg(), Operand(actual.reg()));
1232       b(eq, &regular_invoke);
1233     }
1234   }
1235
1236   if (!definitely_matches) {
1237     if (!code_constant.is_null()) {
1238       mov(r3, Operand(code_constant));
1239       add(r3, r3, Operand(Code::kHeaderSize - kHeapObjectTag));
1240     }
1241
1242     Handle<Code> adaptor =
1243         isolate()->builtins()->ArgumentsAdaptorTrampoline();
1244     if (flag == CALL_FUNCTION) {
1245       call_wrapper.BeforeCall(CallSize(adaptor));
1246       Call(adaptor);
1247       call_wrapper.AfterCall();
1248       if (!*definitely_mismatches) {
1249         b(done);
1250       }
1251     } else {
1252       Jump(adaptor, RelocInfo::CODE_TARGET);
1253     }
1254     bind(&regular_invoke);
1255   }
1256 }
1257
1258
1259 void MacroAssembler::InvokeCode(Register code,
1260                                 const ParameterCount& expected,
1261                                 const ParameterCount& actual,
1262                                 InvokeFlag flag,
1263                                 const CallWrapper& call_wrapper) {
1264   // You can't call a function without a valid frame.
1265   DCHECK(flag == JUMP_FUNCTION || has_frame());
1266
1267   Label done;
1268   bool definitely_mismatches = false;
1269   InvokePrologue(expected, actual, Handle<Code>::null(), code,
1270                  &done, &definitely_mismatches, flag,
1271                  call_wrapper);
1272   if (!definitely_mismatches) {
1273     if (flag == CALL_FUNCTION) {
1274       call_wrapper.BeforeCall(CallSize(code));
1275       Call(code);
1276       call_wrapper.AfterCall();
1277     } else {
1278       DCHECK(flag == JUMP_FUNCTION);
1279       Jump(code);
1280     }
1281
1282     // Continue here if InvokePrologue does handle the invocation due to
1283     // mismatched parameter counts.
1284     bind(&done);
1285   }
1286 }
1287
1288
1289 void MacroAssembler::InvokeFunction(Register fun,
1290                                     const ParameterCount& actual,
1291                                     InvokeFlag flag,
1292                                     const CallWrapper& call_wrapper) {
1293   // You can't call a function without a valid frame.
1294   DCHECK(flag == JUMP_FUNCTION || has_frame());
1295
1296   // Contract with called JS functions requires that function is passed in r1.
1297   DCHECK(fun.is(r1));
1298
1299   Register expected_reg = r2;
1300   Register code_reg = r3;
1301
1302   ldr(code_reg, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
1303   ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset));
1304   ldr(expected_reg,
1305       FieldMemOperand(code_reg,
1306                       SharedFunctionInfo::kFormalParameterCountOffset));
1307   SmiUntag(expected_reg);
1308   ldr(code_reg,
1309       FieldMemOperand(r1, JSFunction::kCodeEntryOffset));
1310
1311   ParameterCount expected(expected_reg);
1312   InvokeCode(code_reg, expected, actual, flag, call_wrapper);
1313 }
1314
1315
1316 void MacroAssembler::InvokeFunction(Register function,
1317                                     const ParameterCount& expected,
1318                                     const ParameterCount& actual,
1319                                     InvokeFlag flag,
1320                                     const CallWrapper& call_wrapper) {
1321   // You can't call a function without a valid frame.
1322   DCHECK(flag == JUMP_FUNCTION || has_frame());
1323
1324   // Contract with called JS functions requires that function is passed in r1.
1325   DCHECK(function.is(r1));
1326
1327   // Get the function and setup the context.
1328   ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset));
1329
1330   // We call indirectly through the code field in the function to
1331   // allow recompilation to take effect without changing any of the
1332   // call sites.
1333   ldr(r3, FieldMemOperand(r1, JSFunction::kCodeEntryOffset));
1334   InvokeCode(r3, expected, actual, flag, call_wrapper);
1335 }
1336
1337
1338 void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
1339                                     const ParameterCount& expected,
1340                                     const ParameterCount& actual,
1341                                     InvokeFlag flag,
1342                                     const CallWrapper& call_wrapper) {
1343   Move(r1, function);
1344   InvokeFunction(r1, expected, actual, flag, call_wrapper);
1345 }
1346
1347
1348 void MacroAssembler::IsObjectJSObjectType(Register heap_object,
1349                                           Register map,
1350                                           Register scratch,
1351                                           Label* fail) {
1352   ldr(map, FieldMemOperand(heap_object, HeapObject::kMapOffset));
1353   IsInstanceJSObjectType(map, scratch, fail);
1354 }
1355
1356
1357 void MacroAssembler::IsInstanceJSObjectType(Register map,
1358                                             Register scratch,
1359                                             Label* fail) {
1360   ldrb(scratch, FieldMemOperand(map, Map::kInstanceTypeOffset));
1361   cmp(scratch, Operand(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
1362   b(lt, fail);
1363   cmp(scratch, Operand(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
1364   b(gt, fail);
1365 }
1366
1367
1368 void MacroAssembler::IsObjectJSStringType(Register object,
1369                                           Register scratch,
1370                                           Label* fail) {
1371   DCHECK(kNotStringTag != 0);
1372
1373   ldr(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
1374   ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
1375   tst(scratch, Operand(kIsNotStringMask));
1376   b(ne, fail);
1377 }
1378
1379
1380 void MacroAssembler::IsObjectNameType(Register object,
1381                                       Register scratch,
1382                                       Label* fail) {
1383   ldr(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
1384   ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
1385   cmp(scratch, Operand(LAST_NAME_TYPE));
1386   b(hi, fail);
1387 }
1388
1389
1390 void MacroAssembler::DebugBreak() {
1391   mov(r0, Operand::Zero());
1392   mov(r1, Operand(ExternalReference(Runtime::kDebugBreak, isolate())));
1393   CEntryStub ces(isolate(), 1);
1394   DCHECK(AllowThisStubCall(&ces));
1395   Call(ces.GetCode(), RelocInfo::DEBUG_BREAK);
1396 }
1397
1398
1399 void MacroAssembler::PushStackHandler() {
1400   // Adjust this code if not the case.
1401   STATIC_ASSERT(StackHandlerConstants::kSize == 1 * kPointerSize);
1402   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
1403
1404   // Link the current handler as the next handler.
1405   mov(r6, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
1406   ldr(r5, MemOperand(r6));
1407   push(r5);
1408
1409   // Set this new handler as the current one.
1410   str(sp, MemOperand(r6));
1411 }
1412
1413
1414 void MacroAssembler::PopStackHandler() {
1415   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
1416   pop(r1);
1417   mov(ip, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
1418   add(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
1419   str(r1, MemOperand(ip));
1420 }
1421
1422
1423 void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
1424                                             Register scratch,
1425                                             Label* miss) {
1426   Label same_contexts;
1427
1428   DCHECK(!holder_reg.is(scratch));
1429   DCHECK(!holder_reg.is(ip));
1430   DCHECK(!scratch.is(ip));
1431
1432   // Load current lexical context from the stack frame.
1433   ldr(scratch, MemOperand(fp, StandardFrameConstants::kContextOffset));
1434   // In debug mode, make sure the lexical context is set.
1435 #ifdef DEBUG
1436   cmp(scratch, Operand::Zero());
1437   Check(ne, kWeShouldNotHaveAnEmptyLexicalContext);
1438 #endif
1439
1440   // Load the native context of the current context.
1441   int offset =
1442       Context::kHeaderSize + Context::GLOBAL_OBJECT_INDEX * kPointerSize;
1443   ldr(scratch, FieldMemOperand(scratch, offset));
1444   ldr(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
1445
1446   // Check the context is a native context.
1447   if (emit_debug_code()) {
1448     // Cannot use ip as a temporary in this verification code. Due to the fact
1449     // that ip is clobbered as part of cmp with an object Operand.
1450     push(holder_reg);  // Temporarily save holder on the stack.
1451     // Read the first word and compare to the native_context_map.
1452     ldr(holder_reg, FieldMemOperand(scratch, HeapObject::kMapOffset));
1453     LoadRoot(ip, Heap::kNativeContextMapRootIndex);
1454     cmp(holder_reg, ip);
1455     Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext);
1456     pop(holder_reg);  // Restore holder.
1457   }
1458
1459   // Check if both contexts are the same.
1460   ldr(ip, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
1461   cmp(scratch, Operand(ip));
1462   b(eq, &same_contexts);
1463
1464   // Check the context is a native context.
1465   if (emit_debug_code()) {
1466     // Cannot use ip as a temporary in this verification code. Due to the fact
1467     // that ip is clobbered as part of cmp with an object Operand.
1468     push(holder_reg);  // Temporarily save holder on the stack.
1469     mov(holder_reg, ip);  // Move ip to its holding place.
1470     LoadRoot(ip, Heap::kNullValueRootIndex);
1471     cmp(holder_reg, ip);
1472     Check(ne, kJSGlobalProxyContextShouldNotBeNull);
1473
1474     ldr(holder_reg, FieldMemOperand(holder_reg, HeapObject::kMapOffset));
1475     LoadRoot(ip, Heap::kNativeContextMapRootIndex);
1476     cmp(holder_reg, ip);
1477     Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext);
1478     // Restore ip is not needed. ip is reloaded below.
1479     pop(holder_reg);  // Restore holder.
1480     // Restore ip to holder's context.
1481     ldr(ip, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
1482   }
1483
1484   // Check that the security token in the calling global object is
1485   // compatible with the security token in the receiving global
1486   // object.
1487   int token_offset = Context::kHeaderSize +
1488                      Context::SECURITY_TOKEN_INDEX * kPointerSize;
1489
1490   ldr(scratch, FieldMemOperand(scratch, token_offset));
1491   ldr(ip, FieldMemOperand(ip, token_offset));
1492   cmp(scratch, Operand(ip));
1493   b(ne, miss);
1494
1495   bind(&same_contexts);
1496 }
1497
1498
1499 // Compute the hash code from the untagged key.  This must be kept in sync with
1500 // ComputeIntegerHash in utils.h and KeyedLoadGenericStub in
1501 // code-stub-hydrogen.cc
1502 void MacroAssembler::GetNumberHash(Register t0, Register scratch) {
1503   // First of all we assign the hash seed to scratch.
1504   LoadRoot(scratch, Heap::kHashSeedRootIndex);
1505   SmiUntag(scratch);
1506
1507   // Xor original key with a seed.
1508   eor(t0, t0, Operand(scratch));
1509
1510   // Compute the hash code from the untagged key.  This must be kept in sync
1511   // with ComputeIntegerHash in utils.h.
1512   //
1513   // hash = ~hash + (hash << 15);
1514   mvn(scratch, Operand(t0));
1515   add(t0, scratch, Operand(t0, LSL, 15));
1516   // hash = hash ^ (hash >> 12);
1517   eor(t0, t0, Operand(t0, LSR, 12));
1518   // hash = hash + (hash << 2);
1519   add(t0, t0, Operand(t0, LSL, 2));
1520   // hash = hash ^ (hash >> 4);
1521   eor(t0, t0, Operand(t0, LSR, 4));
1522   // hash = hash * 2057;
1523   mov(scratch, Operand(t0, LSL, 11));
1524   add(t0, t0, Operand(t0, LSL, 3));
1525   add(t0, t0, scratch);
1526   // hash = hash ^ (hash >> 16);
1527   eor(t0, t0, Operand(t0, LSR, 16));
1528 }
1529
1530
1531 void MacroAssembler::LoadFromNumberDictionary(Label* miss,
1532                                               Register elements,
1533                                               Register key,
1534                                               Register result,
1535                                               Register t0,
1536                                               Register t1,
1537                                               Register t2) {
1538   // Register use:
1539   //
1540   // elements - holds the slow-case elements of the receiver on entry.
1541   //            Unchanged unless 'result' is the same register.
1542   //
1543   // key      - holds the smi key on entry.
1544   //            Unchanged unless 'result' is the same register.
1545   //
1546   // result   - holds the result on exit if the load succeeded.
1547   //            Allowed to be the same as 'key' or 'result'.
1548   //            Unchanged on bailout so 'key' or 'result' can be used
1549   //            in further computation.
1550   //
1551   // Scratch registers:
1552   //
1553   // t0 - holds the untagged key on entry and holds the hash once computed.
1554   //
1555   // t1 - used to hold the capacity mask of the dictionary
1556   //
1557   // t2 - used for the index into the dictionary.
1558   Label done;
1559
1560   GetNumberHash(t0, t1);
1561
1562   // Compute the capacity mask.
1563   ldr(t1, FieldMemOperand(elements, SeededNumberDictionary::kCapacityOffset));
1564   SmiUntag(t1);
1565   sub(t1, t1, Operand(1));
1566
1567   // Generate an unrolled loop that performs a few probes before giving up.
1568   for (int i = 0; i < kNumberDictionaryProbes; i++) {
1569     // Use t2 for index calculations and keep the hash intact in t0.
1570     mov(t2, t0);
1571     // Compute the masked index: (hash + i + i * i) & mask.
1572     if (i > 0) {
1573       add(t2, t2, Operand(SeededNumberDictionary::GetProbeOffset(i)));
1574     }
1575     and_(t2, t2, Operand(t1));
1576
1577     // Scale the index by multiplying by the element size.
1578     DCHECK(SeededNumberDictionary::kEntrySize == 3);
1579     add(t2, t2, Operand(t2, LSL, 1));  // t2 = t2 * 3
1580
1581     // Check if the key is identical to the name.
1582     add(t2, elements, Operand(t2, LSL, kPointerSizeLog2));
1583     ldr(ip, FieldMemOperand(t2, SeededNumberDictionary::kElementsStartOffset));
1584     cmp(key, Operand(ip));
1585     if (i != kNumberDictionaryProbes - 1) {
1586       b(eq, &done);
1587     } else {
1588       b(ne, miss);
1589     }
1590   }
1591
1592   bind(&done);
1593   // Check that the value is a field property.
1594   // t2: elements + (index * kPointerSize)
1595   const int kDetailsOffset =
1596       SeededNumberDictionary::kElementsStartOffset + 2 * kPointerSize;
1597   ldr(t1, FieldMemOperand(t2, kDetailsOffset));
1598   DCHECK_EQ(DATA, 0);
1599   tst(t1, Operand(Smi::FromInt(PropertyDetails::TypeField::kMask)));
1600   b(ne, miss);
1601
1602   // Get the value at the masked, scaled index and return.
1603   const int kValueOffset =
1604       SeededNumberDictionary::kElementsStartOffset + kPointerSize;
1605   ldr(result, FieldMemOperand(t2, kValueOffset));
1606 }
1607
1608
1609 void MacroAssembler::Allocate(int object_size,
1610                               Register result,
1611                               Register scratch1,
1612                               Register scratch2,
1613                               Label* gc_required,
1614                               AllocationFlags flags) {
1615   DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
1616   if (!FLAG_inline_new) {
1617     if (emit_debug_code()) {
1618       // Trash the registers to simulate an allocation failure.
1619       mov(result, Operand(0x7091));
1620       mov(scratch1, Operand(0x7191));
1621       mov(scratch2, Operand(0x7291));
1622     }
1623     jmp(gc_required);
1624     return;
1625   }
1626
1627   DCHECK(!result.is(scratch1));
1628   DCHECK(!result.is(scratch2));
1629   DCHECK(!scratch1.is(scratch2));
1630   DCHECK(!scratch1.is(ip));
1631   DCHECK(!scratch2.is(ip));
1632
1633   // Make object size into bytes.
1634   if ((flags & SIZE_IN_WORDS) != 0) {
1635     object_size *= kPointerSize;
1636   }
1637   DCHECK_EQ(0, object_size & kObjectAlignmentMask);
1638
1639   // Check relative positions of allocation top and limit addresses.
1640   // The values must be adjacent in memory to allow the use of LDM.
1641   // Also, assert that the registers are numbered such that the values
1642   // are loaded in the correct order.
1643   ExternalReference allocation_top =
1644       AllocationUtils::GetAllocationTopReference(isolate(), flags);
1645   ExternalReference allocation_limit =
1646       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
1647
1648   intptr_t top   =
1649       reinterpret_cast<intptr_t>(allocation_top.address());
1650   intptr_t limit =
1651       reinterpret_cast<intptr_t>(allocation_limit.address());
1652   DCHECK((limit - top) == kPointerSize);
1653   DCHECK(result.code() < ip.code());
1654
1655   // Set up allocation top address register.
1656   Register topaddr = scratch1;
1657   mov(topaddr, Operand(allocation_top));
1658
1659   // This code stores a temporary value in ip. This is OK, as the code below
1660   // does not need ip for implicit literal generation.
1661   if ((flags & RESULT_CONTAINS_TOP) == 0) {
1662     // Load allocation top into result and allocation limit into ip.
1663     ldm(ia, topaddr, result.bit() | ip.bit());
1664   } else {
1665     if (emit_debug_code()) {
1666       // Assert that result actually contains top on entry. ip is used
1667       // immediately below so this use of ip does not cause difference with
1668       // respect to register content between debug and release mode.
1669       ldr(ip, MemOperand(topaddr));
1670       cmp(result, ip);
1671       Check(eq, kUnexpectedAllocationTop);
1672     }
1673     // Load allocation limit into ip. Result already contains allocation top.
1674     ldr(ip, MemOperand(topaddr, limit - top));
1675   }
1676
1677   if ((flags & DOUBLE_ALIGNMENT) != 0) {
1678     // Align the next allocation. Storing the filler map without checking top is
1679     // safe in new-space because the limit of the heap is aligned there.
1680     DCHECK((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
1681     STATIC_ASSERT(kPointerAlignment * 2 == kDoubleAlignment);
1682     and_(scratch2, result, Operand(kDoubleAlignmentMask), SetCC);
1683     Label aligned;
1684     b(eq, &aligned);
1685     if ((flags & PRETENURE_OLD_DATA_SPACE) != 0) {
1686       cmp(result, Operand(ip));
1687       b(hs, gc_required);
1688     }
1689     mov(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
1690     str(scratch2, MemOperand(result, kDoubleSize / 2, PostIndex));
1691     bind(&aligned);
1692   }
1693
1694   // Calculate new top and bail out if new space is exhausted. Use result
1695   // to calculate the new top. We must preserve the ip register at this
1696   // point, so we cannot just use add().
1697   DCHECK(object_size > 0);
1698   Register source = result;
1699   Condition cond = al;
1700   int shift = 0;
1701   while (object_size != 0) {
1702     if (((object_size >> shift) & 0x03) == 0) {
1703       shift += 2;
1704     } else {
1705       int bits = object_size & (0xff << shift);
1706       object_size -= bits;
1707       shift += 8;
1708       Operand bits_operand(bits);
1709       DCHECK(bits_operand.instructions_required(this) == 1);
1710       add(scratch2, source, bits_operand, SetCC, cond);
1711       source = scratch2;
1712       cond = cc;
1713     }
1714   }
1715   b(cs, gc_required);
1716   cmp(scratch2, Operand(ip));
1717   b(hi, gc_required);
1718   str(scratch2, MemOperand(topaddr));
1719
1720   // Tag object if requested.
1721   if ((flags & TAG_OBJECT) != 0) {
1722     add(result, result, Operand(kHeapObjectTag));
1723   }
1724 }
1725
1726
1727 void MacroAssembler::Allocate(Register object_size,
1728                               Register result,
1729                               Register scratch1,
1730                               Register scratch2,
1731                               Label* gc_required,
1732                               AllocationFlags flags) {
1733   if (!FLAG_inline_new) {
1734     if (emit_debug_code()) {
1735       // Trash the registers to simulate an allocation failure.
1736       mov(result, Operand(0x7091));
1737       mov(scratch1, Operand(0x7191));
1738       mov(scratch2, Operand(0x7291));
1739     }
1740     jmp(gc_required);
1741     return;
1742   }
1743
1744   // Assert that the register arguments are different and that none of
1745   // them are ip. ip is used explicitly in the code generated below.
1746   DCHECK(!result.is(scratch1));
1747   DCHECK(!result.is(scratch2));
1748   DCHECK(!scratch1.is(scratch2));
1749   DCHECK(!object_size.is(ip));
1750   DCHECK(!result.is(ip));
1751   DCHECK(!scratch1.is(ip));
1752   DCHECK(!scratch2.is(ip));
1753
1754   // Check relative positions of allocation top and limit addresses.
1755   // The values must be adjacent in memory to allow the use of LDM.
1756   // Also, assert that the registers are numbered such that the values
1757   // are loaded in the correct order.
1758   ExternalReference allocation_top =
1759       AllocationUtils::GetAllocationTopReference(isolate(), flags);
1760   ExternalReference allocation_limit =
1761       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
1762   intptr_t top =
1763       reinterpret_cast<intptr_t>(allocation_top.address());
1764   intptr_t limit =
1765       reinterpret_cast<intptr_t>(allocation_limit.address());
1766   DCHECK((limit - top) == kPointerSize);
1767   DCHECK(result.code() < ip.code());
1768
1769   // Set up allocation top address.
1770   Register topaddr = scratch1;
1771   mov(topaddr, Operand(allocation_top));
1772
1773   // This code stores a temporary value in ip. This is OK, as the code below
1774   // does not need ip for implicit literal generation.
1775   if ((flags & RESULT_CONTAINS_TOP) == 0) {
1776     // Load allocation top into result and allocation limit into ip.
1777     ldm(ia, topaddr, result.bit() | ip.bit());
1778   } else {
1779     if (emit_debug_code()) {
1780       // Assert that result actually contains top on entry. ip is used
1781       // immediately below so this use of ip does not cause difference with
1782       // respect to register content between debug and release mode.
1783       ldr(ip, MemOperand(topaddr));
1784       cmp(result, ip);
1785       Check(eq, kUnexpectedAllocationTop);
1786     }
1787     // Load allocation limit into ip. Result already contains allocation top.
1788     ldr(ip, MemOperand(topaddr, limit - top));
1789   }
1790
1791   if ((flags & DOUBLE_ALIGNMENT) != 0) {
1792     // Align the next allocation. Storing the filler map without checking top is
1793     // safe in new-space because the limit of the heap is aligned there.
1794     DCHECK((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
1795     DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
1796     and_(scratch2, result, Operand(kDoubleAlignmentMask), SetCC);
1797     Label aligned;
1798     b(eq, &aligned);
1799     if ((flags & PRETENURE_OLD_DATA_SPACE) != 0) {
1800       cmp(result, Operand(ip));
1801       b(hs, gc_required);
1802     }
1803     mov(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
1804     str(scratch2, MemOperand(result, kDoubleSize / 2, PostIndex));
1805     bind(&aligned);
1806   }
1807
1808   // Calculate new top and bail out if new space is exhausted. Use result
1809   // to calculate the new top. Object size may be in words so a shift is
1810   // required to get the number of bytes.
1811   if ((flags & SIZE_IN_WORDS) != 0) {
1812     add(scratch2, result, Operand(object_size, LSL, kPointerSizeLog2), SetCC);
1813   } else {
1814     add(scratch2, result, Operand(object_size), SetCC);
1815   }
1816   b(cs, gc_required);
1817   cmp(scratch2, Operand(ip));
1818   b(hi, gc_required);
1819
1820   // Update allocation top. result temporarily holds the new top.
1821   if (emit_debug_code()) {
1822     tst(scratch2, Operand(kObjectAlignmentMask));
1823     Check(eq, kUnalignedAllocationInNewSpace);
1824   }
1825   str(scratch2, MemOperand(topaddr));
1826
1827   // Tag object if requested.
1828   if ((flags & TAG_OBJECT) != 0) {
1829     add(result, result, Operand(kHeapObjectTag));
1830   }
1831 }
1832
1833
1834 void MacroAssembler::UndoAllocationInNewSpace(Register object,
1835                                               Register scratch) {
1836   ExternalReference new_space_allocation_top =
1837       ExternalReference::new_space_allocation_top_address(isolate());
1838
1839   // Make sure the object has no tag before resetting top.
1840   and_(object, object, Operand(~kHeapObjectTagMask));
1841 #ifdef DEBUG
1842   // Check that the object un-allocated is below the current top.
1843   mov(scratch, Operand(new_space_allocation_top));
1844   ldr(scratch, MemOperand(scratch));
1845   cmp(object, scratch);
1846   Check(lt, kUndoAllocationOfNonAllocatedMemory);
1847 #endif
1848   // Write the address of the object to un-allocate as the current top.
1849   mov(scratch, Operand(new_space_allocation_top));
1850   str(object, MemOperand(scratch));
1851 }
1852
1853
1854 void MacroAssembler::AllocateTwoByteString(Register result,
1855                                            Register length,
1856                                            Register scratch1,
1857                                            Register scratch2,
1858                                            Register scratch3,
1859                                            Label* gc_required) {
1860   // Calculate the number of bytes needed for the characters in the string while
1861   // observing object alignment.
1862   DCHECK((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
1863   mov(scratch1, Operand(length, LSL, 1));  // Length in bytes, not chars.
1864   add(scratch1, scratch1,
1865       Operand(kObjectAlignmentMask + SeqTwoByteString::kHeaderSize));
1866   and_(scratch1, scratch1, Operand(~kObjectAlignmentMask));
1867
1868   // Allocate two-byte string in new space.
1869   Allocate(scratch1,
1870            result,
1871            scratch2,
1872            scratch3,
1873            gc_required,
1874            TAG_OBJECT);
1875
1876   // Set the map, length and hash field.
1877   InitializeNewString(result,
1878                       length,
1879                       Heap::kStringMapRootIndex,
1880                       scratch1,
1881                       scratch2);
1882 }
1883
1884
1885 void MacroAssembler::AllocateOneByteString(Register result, Register length,
1886                                            Register scratch1, Register scratch2,
1887                                            Register scratch3,
1888                                            Label* gc_required) {
1889   // Calculate the number of bytes needed for the characters in the string while
1890   // observing object alignment.
1891   DCHECK((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
1892   DCHECK(kCharSize == 1);
1893   add(scratch1, length,
1894       Operand(kObjectAlignmentMask + SeqOneByteString::kHeaderSize));
1895   and_(scratch1, scratch1, Operand(~kObjectAlignmentMask));
1896
1897   // Allocate one-byte string in new space.
1898   Allocate(scratch1,
1899            result,
1900            scratch2,
1901            scratch3,
1902            gc_required,
1903            TAG_OBJECT);
1904
1905   // Set the map, length and hash field.
1906   InitializeNewString(result, length, Heap::kOneByteStringMapRootIndex,
1907                       scratch1, scratch2);
1908 }
1909
1910
1911 void MacroAssembler::AllocateTwoByteConsString(Register result,
1912                                                Register length,
1913                                                Register scratch1,
1914                                                Register scratch2,
1915                                                Label* gc_required) {
1916   Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
1917            TAG_OBJECT);
1918
1919   InitializeNewString(result,
1920                       length,
1921                       Heap::kConsStringMapRootIndex,
1922                       scratch1,
1923                       scratch2);
1924 }
1925
1926
1927 void MacroAssembler::AllocateOneByteConsString(Register result, Register length,
1928                                                Register scratch1,
1929                                                Register scratch2,
1930                                                Label* gc_required) {
1931   Allocate(ConsString::kSize,
1932            result,
1933            scratch1,
1934            scratch2,
1935            gc_required,
1936            TAG_OBJECT);
1937
1938   InitializeNewString(result, length, Heap::kConsOneByteStringMapRootIndex,
1939                       scratch1, scratch2);
1940 }
1941
1942
1943 void MacroAssembler::AllocateTwoByteSlicedString(Register result,
1944                                                  Register length,
1945                                                  Register scratch1,
1946                                                  Register scratch2,
1947                                                  Label* gc_required) {
1948   Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
1949            TAG_OBJECT);
1950
1951   InitializeNewString(result,
1952                       length,
1953                       Heap::kSlicedStringMapRootIndex,
1954                       scratch1,
1955                       scratch2);
1956 }
1957
1958
1959 void MacroAssembler::AllocateOneByteSlicedString(Register result,
1960                                                  Register length,
1961                                                  Register scratch1,
1962                                                  Register scratch2,
1963                                                  Label* gc_required) {
1964   Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
1965            TAG_OBJECT);
1966
1967   InitializeNewString(result, length, Heap::kSlicedOneByteStringMapRootIndex,
1968                       scratch1, scratch2);
1969 }
1970
1971
1972 void MacroAssembler::CompareObjectType(Register object,
1973                                        Register map,
1974                                        Register type_reg,
1975                                        InstanceType type) {
1976   const Register temp = type_reg.is(no_reg) ? ip : type_reg;
1977
1978   ldr(map, FieldMemOperand(object, HeapObject::kMapOffset));
1979   CompareInstanceType(map, temp, type);
1980 }
1981
1982
1983 void MacroAssembler::CheckObjectTypeRange(Register object,
1984                                           Register map,
1985                                           InstanceType min_type,
1986                                           InstanceType max_type,
1987                                           Label* false_label) {
1988   STATIC_ASSERT(Map::kInstanceTypeOffset < 4096);
1989   STATIC_ASSERT(LAST_TYPE < 256);
1990   ldr(map, FieldMemOperand(object, HeapObject::kMapOffset));
1991   ldrb(ip, FieldMemOperand(map, Map::kInstanceTypeOffset));
1992   sub(ip, ip, Operand(min_type));
1993   cmp(ip, Operand(max_type - min_type));
1994   b(hi, false_label);
1995 }
1996
1997
1998 void MacroAssembler::CompareInstanceType(Register map,
1999                                          Register type_reg,
2000                                          InstanceType type) {
2001   // Registers map and type_reg can be ip. These two lines assert
2002   // that ip can be used with the two instructions (the constants
2003   // will never need ip).
2004   STATIC_ASSERT(Map::kInstanceTypeOffset < 4096);
2005   STATIC_ASSERT(LAST_TYPE < 256);
2006   ldrb(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
2007   cmp(type_reg, Operand(type));
2008 }
2009
2010
2011 void MacroAssembler::CompareRoot(Register obj,
2012                                  Heap::RootListIndex index) {
2013   DCHECK(!obj.is(ip));
2014   LoadRoot(ip, index);
2015   cmp(obj, ip);
2016 }
2017
2018
2019 void MacroAssembler::CheckFastElements(Register map,
2020                                        Register scratch,
2021                                        Label* fail) {
2022   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
2023   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
2024   STATIC_ASSERT(FAST_ELEMENTS == 2);
2025   STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
2026   ldrb(scratch, FieldMemOperand(map, Map::kBitField2Offset));
2027   cmp(scratch, Operand(Map::kMaximumBitField2FastHoleyElementValue));
2028   b(hi, fail);
2029 }
2030
2031
2032 void MacroAssembler::CheckFastObjectElements(Register map,
2033                                              Register scratch,
2034                                              Label* fail) {
2035   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
2036   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
2037   STATIC_ASSERT(FAST_ELEMENTS == 2);
2038   STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
2039   ldrb(scratch, FieldMemOperand(map, Map::kBitField2Offset));
2040   cmp(scratch, Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
2041   b(ls, fail);
2042   cmp(scratch, Operand(Map::kMaximumBitField2FastHoleyElementValue));
2043   b(hi, fail);
2044 }
2045
2046
2047 void MacroAssembler::CheckFastSmiElements(Register map,
2048                                           Register scratch,
2049                                           Label* fail) {
2050   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
2051   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
2052   ldrb(scratch, FieldMemOperand(map, Map::kBitField2Offset));
2053   cmp(scratch, Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
2054   b(hi, fail);
2055 }
2056
2057
2058 void MacroAssembler::StoreNumberToDoubleElements(
2059                                       Register value_reg,
2060                                       Register key_reg,
2061                                       Register elements_reg,
2062                                       Register scratch1,
2063                                       LowDwVfpRegister double_scratch,
2064                                       Label* fail,
2065                                       int elements_offset) {
2066   Label smi_value, store;
2067
2068   // Handle smi values specially.
2069   JumpIfSmi(value_reg, &smi_value);
2070
2071   // Ensure that the object is a heap number
2072   CheckMap(value_reg,
2073            scratch1,
2074            isolate()->factory()->heap_number_map(),
2075            fail,
2076            DONT_DO_SMI_CHECK);
2077
2078   vldr(double_scratch, FieldMemOperand(value_reg, HeapNumber::kValueOffset));
2079   // Force a canonical NaN.
2080   if (emit_debug_code()) {
2081     vmrs(ip);
2082     tst(ip, Operand(kVFPDefaultNaNModeControlBit));
2083     Assert(ne, kDefaultNaNModeNotSet);
2084   }
2085   VFPCanonicalizeNaN(double_scratch);
2086   b(&store);
2087
2088   bind(&smi_value);
2089   SmiToDouble(double_scratch, value_reg);
2090
2091   bind(&store);
2092   add(scratch1, elements_reg, Operand::DoubleOffsetFromSmiKey(key_reg));
2093   vstr(double_scratch,
2094        FieldMemOperand(scratch1,
2095                        FixedDoubleArray::kHeaderSize - elements_offset));
2096 }
2097
2098
2099 void MacroAssembler::CompareMap(Register obj,
2100                                 Register scratch,
2101                                 Handle<Map> map,
2102                                 Label* early_success) {
2103   ldr(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
2104   CompareMap(scratch, map, early_success);
2105 }
2106
2107
2108 void MacroAssembler::CompareMap(Register obj_map,
2109                                 Handle<Map> map,
2110                                 Label* early_success) {
2111   cmp(obj_map, Operand(map));
2112 }
2113
2114
2115 void MacroAssembler::CheckMap(Register obj,
2116                               Register scratch,
2117                               Handle<Map> map,
2118                               Label* fail,
2119                               SmiCheckType smi_check_type) {
2120   if (smi_check_type == DO_SMI_CHECK) {
2121     JumpIfSmi(obj, fail);
2122   }
2123
2124   Label success;
2125   CompareMap(obj, scratch, map, &success);
2126   b(ne, fail);
2127   bind(&success);
2128 }
2129
2130
2131 void MacroAssembler::CheckMap(Register obj,
2132                               Register scratch,
2133                               Heap::RootListIndex index,
2134                               Label* fail,
2135                               SmiCheckType smi_check_type) {
2136   if (smi_check_type == DO_SMI_CHECK) {
2137     JumpIfSmi(obj, fail);
2138   }
2139   ldr(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
2140   LoadRoot(ip, index);
2141   cmp(scratch, ip);
2142   b(ne, fail);
2143 }
2144
2145
2146 void MacroAssembler::DispatchWeakMap(Register obj, Register scratch1,
2147                                      Register scratch2, Handle<WeakCell> cell,
2148                                      Handle<Code> success,
2149                                      SmiCheckType smi_check_type) {
2150   Label fail;
2151   if (smi_check_type == DO_SMI_CHECK) {
2152     JumpIfSmi(obj, &fail);
2153   }
2154   ldr(scratch1, FieldMemOperand(obj, HeapObject::kMapOffset));
2155   CmpWeakValue(scratch1, cell, scratch2);
2156   Jump(success, RelocInfo::CODE_TARGET, eq);
2157   bind(&fail);
2158 }
2159
2160
2161 void MacroAssembler::CmpWeakValue(Register value, Handle<WeakCell> cell,
2162                                   Register scratch) {
2163   mov(scratch, Operand(cell));
2164   ldr(scratch, FieldMemOperand(scratch, WeakCell::kValueOffset));
2165   cmp(value, scratch);
2166 }
2167
2168
2169 void MacroAssembler::GetWeakValue(Register value, Handle<WeakCell> cell) {
2170   mov(value, Operand(cell));
2171   ldr(value, FieldMemOperand(value, WeakCell::kValueOffset));
2172 }
2173
2174
2175 void MacroAssembler::LoadWeakValue(Register value, Handle<WeakCell> cell,
2176                                    Label* miss) {
2177   GetWeakValue(value, cell);
2178   JumpIfSmi(value, miss);
2179 }
2180
2181
2182 void MacroAssembler::GetMapConstructor(Register result, Register map,
2183                                        Register temp, Register temp2) {
2184   Label done, loop;
2185   ldr(result, FieldMemOperand(map, Map::kConstructorOrBackPointerOffset));
2186   bind(&loop);
2187   JumpIfSmi(result, &done);
2188   CompareObjectType(result, temp, temp2, MAP_TYPE);
2189   b(ne, &done);
2190   ldr(result, FieldMemOperand(result, Map::kConstructorOrBackPointerOffset));
2191   b(&loop);
2192   bind(&done);
2193 }
2194
2195
2196 void MacroAssembler::TryGetFunctionPrototype(Register function,
2197                                              Register result,
2198                                              Register scratch,
2199                                              Label* miss,
2200                                              bool miss_on_bound_function) {
2201   Label non_instance;
2202   if (miss_on_bound_function) {
2203     // Check that the receiver isn't a smi.
2204     JumpIfSmi(function, miss);
2205
2206     // Check that the function really is a function.  Load map into result reg.
2207     CompareObjectType(function, result, scratch, JS_FUNCTION_TYPE);
2208     b(ne, miss);
2209
2210     ldr(scratch,
2211         FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset));
2212     ldr(scratch,
2213         FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset));
2214     tst(scratch,
2215         Operand(Smi::FromInt(1 << SharedFunctionInfo::kBoundFunction)));
2216     b(ne, miss);
2217
2218     // Make sure that the function has an instance prototype.
2219     ldrb(scratch, FieldMemOperand(result, Map::kBitFieldOffset));
2220     tst(scratch, Operand(1 << Map::kHasNonInstancePrototype));
2221     b(ne, &non_instance);
2222   }
2223
2224   // Get the prototype or initial map from the function.
2225   ldr(result,
2226       FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2227
2228   // If the prototype or initial map is the hole, don't return it and
2229   // simply miss the cache instead. This will allow us to allocate a
2230   // prototype object on-demand in the runtime system.
2231   LoadRoot(ip, Heap::kTheHoleValueRootIndex);
2232   cmp(result, ip);
2233   b(eq, miss);
2234
2235   // If the function does not have an initial map, we're done.
2236   Label done;
2237   CompareObjectType(result, scratch, scratch, MAP_TYPE);
2238   b(ne, &done);
2239
2240   // Get the prototype from the initial map.
2241   ldr(result, FieldMemOperand(result, Map::kPrototypeOffset));
2242
2243   if (miss_on_bound_function) {
2244     jmp(&done);
2245
2246     // Non-instance prototype: Fetch prototype from constructor field
2247     // in initial map.
2248     bind(&non_instance);
2249     GetMapConstructor(result, result, scratch, ip);
2250   }
2251
2252   // All done.
2253   bind(&done);
2254 }
2255
2256
2257 void MacroAssembler::CallStub(CodeStub* stub,
2258                               TypeFeedbackId ast_id,
2259                               Condition cond) {
2260   DCHECK(AllowThisStubCall(stub));  // Stub calls are not allowed in some stubs.
2261   Call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id, cond);
2262 }
2263
2264
2265 void MacroAssembler::TailCallStub(CodeStub* stub, Condition cond) {
2266   Jump(stub->GetCode(), RelocInfo::CODE_TARGET, cond);
2267 }
2268
2269
2270 bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
2271   return has_frame_ || !stub->SometimesSetsUpAFrame();
2272 }
2273
2274
2275 void MacroAssembler::IndexFromHash(Register hash, Register index) {
2276   // If the hash field contains an array index pick it out. The assert checks
2277   // that the constants for the maximum number of digits for an array index
2278   // cached in the hash field and the number of bits reserved for it does not
2279   // conflict.
2280   DCHECK(TenToThe(String::kMaxCachedArrayIndexLength) <
2281          (1 << String::kArrayIndexValueBits));
2282   DecodeFieldToSmi<String::ArrayIndexValueBits>(index, hash);
2283 }
2284
2285
2286 void MacroAssembler::SmiToDouble(LowDwVfpRegister value, Register smi) {
2287   if (CpuFeatures::IsSupported(VFP3)) {
2288     vmov(value.low(), smi);
2289     vcvt_f64_s32(value, 1);
2290   } else {
2291     SmiUntag(ip, smi);
2292     vmov(value.low(), ip);
2293     vcvt_f64_s32(value, value.low());
2294   }
2295 }
2296
2297
2298 void MacroAssembler::TestDoubleIsInt32(DwVfpRegister double_input,
2299                                        LowDwVfpRegister double_scratch) {
2300   DCHECK(!double_input.is(double_scratch));
2301   vcvt_s32_f64(double_scratch.low(), double_input);
2302   vcvt_f64_s32(double_scratch, double_scratch.low());
2303   VFPCompareAndSetFlags(double_input, double_scratch);
2304 }
2305
2306
2307 void MacroAssembler::TryDoubleToInt32Exact(Register result,
2308                                            DwVfpRegister double_input,
2309                                            LowDwVfpRegister double_scratch) {
2310   DCHECK(!double_input.is(double_scratch));
2311   vcvt_s32_f64(double_scratch.low(), double_input);
2312   vmov(result, double_scratch.low());
2313   vcvt_f64_s32(double_scratch, double_scratch.low());
2314   VFPCompareAndSetFlags(double_input, double_scratch);
2315 }
2316
2317
2318 void MacroAssembler::TryInt32Floor(Register result,
2319                                    DwVfpRegister double_input,
2320                                    Register input_high,
2321                                    LowDwVfpRegister double_scratch,
2322                                    Label* done,
2323                                    Label* exact) {
2324   DCHECK(!result.is(input_high));
2325   DCHECK(!double_input.is(double_scratch));
2326   Label negative, exception;
2327
2328   VmovHigh(input_high, double_input);
2329
2330   // Test for NaN and infinities.
2331   Sbfx(result, input_high,
2332        HeapNumber::kExponentShift, HeapNumber::kExponentBits);
2333   cmp(result, Operand(-1));
2334   b(eq, &exception);
2335   // Test for values that can be exactly represented as a
2336   // signed 32-bit integer.
2337   TryDoubleToInt32Exact(result, double_input, double_scratch);
2338   // If exact, return (result already fetched).
2339   b(eq, exact);
2340   cmp(input_high, Operand::Zero());
2341   b(mi, &negative);
2342
2343   // Input is in ]+0, +inf[.
2344   // If result equals 0x7fffffff input was out of range or
2345   // in ]0x7fffffff, 0x80000000[. We ignore this last case which
2346   // could fits into an int32, that means we always think input was
2347   // out of range and always go to exception.
2348   // If result < 0x7fffffff, go to done, result fetched.
2349   cmn(result, Operand(1));
2350   b(mi, &exception);
2351   b(done);
2352
2353   // Input is in ]-inf, -0[.
2354   // If x is a non integer negative number,
2355   // floor(x) <=> round_to_zero(x) - 1.
2356   bind(&negative);
2357   sub(result, result, Operand(1), SetCC);
2358   // If result is still negative, go to done, result fetched.
2359   // Else, we had an overflow and we fall through exception.
2360   b(mi, done);
2361   bind(&exception);
2362 }
2363
2364 void MacroAssembler::TryInlineTruncateDoubleToI(Register result,
2365                                                 DwVfpRegister double_input,
2366                                                 Label* done) {
2367   LowDwVfpRegister double_scratch = kScratchDoubleReg;
2368   vcvt_s32_f64(double_scratch.low(), double_input);
2369   vmov(result, double_scratch.low());
2370
2371   // If result is not saturated (0x7fffffff or 0x80000000), we are done.
2372   sub(ip, result, Operand(1));
2373   cmp(ip, Operand(0x7ffffffe));
2374   b(lt, done);
2375 }
2376
2377
2378 void MacroAssembler::TruncateDoubleToI(Register result,
2379                                        DwVfpRegister double_input) {
2380   Label done;
2381
2382   TryInlineTruncateDoubleToI(result, double_input, &done);
2383
2384   // If we fell through then inline version didn't succeed - call stub instead.
2385   push(lr);
2386   sub(sp, sp, Operand(kDoubleSize));  // Put input on stack.
2387   vstr(double_input, MemOperand(sp, 0));
2388
2389   DoubleToIStub stub(isolate(), sp, result, 0, true, true);
2390   CallStub(&stub);
2391
2392   add(sp, sp, Operand(kDoubleSize));
2393   pop(lr);
2394
2395   bind(&done);
2396 }
2397
2398
2399 void MacroAssembler::TruncateHeapNumberToI(Register result,
2400                                            Register object) {
2401   Label done;
2402   LowDwVfpRegister double_scratch = kScratchDoubleReg;
2403   DCHECK(!result.is(object));
2404
2405   vldr(double_scratch,
2406        MemOperand(object, HeapNumber::kValueOffset - kHeapObjectTag));
2407   TryInlineTruncateDoubleToI(result, double_scratch, &done);
2408
2409   // If we fell through then inline version didn't succeed - call stub instead.
2410   push(lr);
2411   DoubleToIStub stub(isolate(),
2412                      object,
2413                      result,
2414                      HeapNumber::kValueOffset - kHeapObjectTag,
2415                      true,
2416                      true);
2417   CallStub(&stub);
2418   pop(lr);
2419
2420   bind(&done);
2421 }
2422
2423
2424 void MacroAssembler::TruncateNumberToI(Register object,
2425                                        Register result,
2426                                        Register heap_number_map,
2427                                        Register scratch1,
2428                                        Label* not_number) {
2429   Label done;
2430   DCHECK(!result.is(object));
2431
2432   UntagAndJumpIfSmi(result, object, &done);
2433   JumpIfNotHeapNumber(object, heap_number_map, scratch1, not_number);
2434   TruncateHeapNumberToI(result, object);
2435
2436   bind(&done);
2437 }
2438
2439
2440 void MacroAssembler::GetLeastBitsFromSmi(Register dst,
2441                                          Register src,
2442                                          int num_least_bits) {
2443   if (CpuFeatures::IsSupported(ARMv7) && !predictable_code_size()) {
2444     ubfx(dst, src, kSmiTagSize, num_least_bits);
2445   } else {
2446     SmiUntag(dst, src);
2447     and_(dst, dst, Operand((1 << num_least_bits) - 1));
2448   }
2449 }
2450
2451
2452 void MacroAssembler::GetLeastBitsFromInt32(Register dst,
2453                                            Register src,
2454                                            int num_least_bits) {
2455   and_(dst, src, Operand((1 << num_least_bits) - 1));
2456 }
2457
2458
2459 void MacroAssembler::CallRuntime(const Runtime::Function* f,
2460                                  int num_arguments,
2461                                  SaveFPRegsMode save_doubles) {
2462   // All parameters are on the stack.  r0 has the return value after call.
2463
2464   // If the expected number of arguments of the runtime function is
2465   // constant, we check that the actual number of arguments match the
2466   // expectation.
2467   CHECK(f->nargs < 0 || f->nargs == num_arguments);
2468
2469   // TODO(1236192): Most runtime routines don't need the number of
2470   // arguments passed in because it is constant. At some point we
2471   // should remove this need and make the runtime routine entry code
2472   // smarter.
2473   mov(r0, Operand(num_arguments));
2474   mov(r1, Operand(ExternalReference(f, isolate())));
2475   CEntryStub stub(isolate(), 1, save_doubles);
2476   CallStub(&stub);
2477 }
2478
2479
2480 void MacroAssembler::CallExternalReference(const ExternalReference& ext,
2481                                            int num_arguments) {
2482   mov(r0, Operand(num_arguments));
2483   mov(r1, Operand(ext));
2484
2485   CEntryStub stub(isolate(), 1);
2486   CallStub(&stub);
2487 }
2488
2489
2490 void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
2491                                                int num_arguments,
2492                                                int result_size) {
2493   // TODO(1236192): Most runtime routines don't need the number of
2494   // arguments passed in because it is constant. At some point we
2495   // should remove this need and make the runtime routine entry code
2496   // smarter.
2497   mov(r0, Operand(num_arguments));
2498   JumpToExternalReference(ext);
2499 }
2500
2501
2502 void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
2503                                      int num_arguments,
2504                                      int result_size) {
2505   TailCallExternalReference(ExternalReference(fid, isolate()),
2506                             num_arguments,
2507                             result_size);
2508 }
2509
2510
2511 void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin) {
2512 #if defined(__thumb__)
2513   // Thumb mode builtin.
2514   DCHECK((reinterpret_cast<intptr_t>(builtin.address()) & 1) == 1);
2515 #endif
2516   mov(r1, Operand(builtin));
2517   CEntryStub stub(isolate(), 1);
2518   Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
2519 }
2520
2521
2522 void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
2523                                    InvokeFlag flag,
2524                                    const CallWrapper& call_wrapper) {
2525   // You can't call a builtin without a valid frame.
2526   DCHECK(flag == JUMP_FUNCTION || has_frame());
2527
2528   GetBuiltinEntry(r2, id);
2529   if (flag == CALL_FUNCTION) {
2530     call_wrapper.BeforeCall(CallSize(r2));
2531     Call(r2);
2532     call_wrapper.AfterCall();
2533   } else {
2534     DCHECK(flag == JUMP_FUNCTION);
2535     Jump(r2);
2536   }
2537 }
2538
2539
2540 void MacroAssembler::GetBuiltinFunction(Register target,
2541                                         Builtins::JavaScript id) {
2542   // Load the builtins object into target register.
2543   ldr(target,
2544       MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2545   ldr(target, FieldMemOperand(target, GlobalObject::kBuiltinsOffset));
2546   // Load the JavaScript builtin function from the builtins object.
2547   ldr(target, FieldMemOperand(target,
2548                           JSBuiltinsObject::OffsetOfFunctionWithId(id)));
2549 }
2550
2551
2552 void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
2553   DCHECK(!target.is(r1));
2554   GetBuiltinFunction(r1, id);
2555   // Load the code entry point from the builtins object.
2556   ldr(target, FieldMemOperand(r1, JSFunction::kCodeEntryOffset));
2557 }
2558
2559
2560 void MacroAssembler::SetCounter(StatsCounter* counter, int value,
2561                                 Register scratch1, Register scratch2) {
2562   if (FLAG_native_code_counters && counter->Enabled()) {
2563     mov(scratch1, Operand(value));
2564     mov(scratch2, Operand(ExternalReference(counter)));
2565     str(scratch1, MemOperand(scratch2));
2566   }
2567 }
2568
2569
2570 void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
2571                                       Register scratch1, Register scratch2) {
2572   DCHECK(value > 0);
2573   if (FLAG_native_code_counters && counter->Enabled()) {
2574     mov(scratch2, Operand(ExternalReference(counter)));
2575     ldr(scratch1, MemOperand(scratch2));
2576     add(scratch1, scratch1, Operand(value));
2577     str(scratch1, MemOperand(scratch2));
2578   }
2579 }
2580
2581
2582 void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
2583                                       Register scratch1, Register scratch2) {
2584   DCHECK(value > 0);
2585   if (FLAG_native_code_counters && counter->Enabled()) {
2586     mov(scratch2, Operand(ExternalReference(counter)));
2587     ldr(scratch1, MemOperand(scratch2));
2588     sub(scratch1, scratch1, Operand(value));
2589     str(scratch1, MemOperand(scratch2));
2590   }
2591 }
2592
2593
2594 void MacroAssembler::Assert(Condition cond, BailoutReason reason) {
2595   if (emit_debug_code())
2596     Check(cond, reason);
2597 }
2598
2599
2600 void MacroAssembler::AssertFastElements(Register elements) {
2601   if (emit_debug_code()) {
2602     DCHECK(!elements.is(ip));
2603     Label ok;
2604     push(elements);
2605     ldr(elements, FieldMemOperand(elements, HeapObject::kMapOffset));
2606     LoadRoot(ip, Heap::kFixedArrayMapRootIndex);
2607     cmp(elements, ip);
2608     b(eq, &ok);
2609     LoadRoot(ip, Heap::kFixedDoubleArrayMapRootIndex);
2610     cmp(elements, ip);
2611     b(eq, &ok);
2612     LoadRoot(ip, Heap::kFixedCOWArrayMapRootIndex);
2613     cmp(elements, ip);
2614     b(eq, &ok);
2615     Abort(kJSObjectWithFastElementsMapHasSlowElements);
2616     bind(&ok);
2617     pop(elements);
2618   }
2619 }
2620
2621
2622 void MacroAssembler::Check(Condition cond, BailoutReason reason) {
2623   Label L;
2624   b(cond, &L);
2625   Abort(reason);
2626   // will not return here
2627   bind(&L);
2628 }
2629
2630
2631 void MacroAssembler::Abort(BailoutReason reason) {
2632   Label abort_start;
2633   bind(&abort_start);
2634 #ifdef DEBUG
2635   const char* msg = GetBailoutReason(reason);
2636   if (msg != NULL) {
2637     RecordComment("Abort message: ");
2638     RecordComment(msg);
2639   }
2640
2641   if (FLAG_trap_on_abort) {
2642     stop(msg);
2643     return;
2644   }
2645 #endif
2646
2647   mov(r0, Operand(Smi::FromInt(reason)));
2648   push(r0);
2649
2650   // Disable stub call restrictions to always allow calls to abort.
2651   if (!has_frame_) {
2652     // We don't actually want to generate a pile of code for this, so just
2653     // claim there is a stack frame, without generating one.
2654     FrameScope scope(this, StackFrame::NONE);
2655     CallRuntime(Runtime::kAbort, 1);
2656   } else {
2657     CallRuntime(Runtime::kAbort, 1);
2658   }
2659   // will not return here
2660   if (is_const_pool_blocked()) {
2661     // If the calling code cares about the exact number of
2662     // instructions generated, we insert padding here to keep the size
2663     // of the Abort macro constant.
2664     static const int kExpectedAbortInstructions = 7;
2665     int abort_instructions = InstructionsGeneratedSince(&abort_start);
2666     DCHECK(abort_instructions <= kExpectedAbortInstructions);
2667     while (abort_instructions++ < kExpectedAbortInstructions) {
2668       nop();
2669     }
2670   }
2671 }
2672
2673
2674 void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
2675   if (context_chain_length > 0) {
2676     // Move up the chain of contexts to the context containing the slot.
2677     ldr(dst, MemOperand(cp, Context::SlotOffset(Context::PREVIOUS_INDEX)));
2678     for (int i = 1; i < context_chain_length; i++) {
2679       ldr(dst, MemOperand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
2680     }
2681   } else {
2682     // Slot is in the current function context.  Move it into the
2683     // destination register in case we store into it (the write barrier
2684     // cannot be allowed to destroy the context in esi).
2685     mov(dst, cp);
2686   }
2687 }
2688
2689
2690 void MacroAssembler::LoadTransitionedArrayMapConditional(
2691     ElementsKind expected_kind,
2692     ElementsKind transitioned_kind,
2693     Register map_in_out,
2694     Register scratch,
2695     Label* no_map_match) {
2696   // Load the global or builtins object from the current context.
2697   ldr(scratch,
2698       MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2699   ldr(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
2700
2701   // Check that the function's map is the same as the expected cached map.
2702   ldr(scratch,
2703       MemOperand(scratch,
2704                  Context::SlotOffset(Context::JS_ARRAY_MAPS_INDEX)));
2705   size_t offset = expected_kind * kPointerSize +
2706       FixedArrayBase::kHeaderSize;
2707   ldr(ip, FieldMemOperand(scratch, offset));
2708   cmp(map_in_out, ip);
2709   b(ne, no_map_match);
2710
2711   // Use the transitioned cached map.
2712   offset = transitioned_kind * kPointerSize +
2713       FixedArrayBase::kHeaderSize;
2714   ldr(map_in_out, FieldMemOperand(scratch, offset));
2715 }
2716
2717
2718 void MacroAssembler::LoadGlobalFunction(int index, Register function) {
2719   // Load the global or builtins object from the current context.
2720   ldr(function,
2721       MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2722   // Load the native context from the global or builtins object.
2723   ldr(function, FieldMemOperand(function,
2724                                 GlobalObject::kNativeContextOffset));
2725   // Load the function from the native context.
2726   ldr(function, MemOperand(function, Context::SlotOffset(index)));
2727 }
2728
2729
2730 void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
2731                                                   Register map,
2732                                                   Register scratch) {
2733   // Load the initial map. The global functions all have initial maps.
2734   ldr(map, FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2735   if (emit_debug_code()) {
2736     Label ok, fail;
2737     CheckMap(map, scratch, Heap::kMetaMapRootIndex, &fail, DO_SMI_CHECK);
2738     b(&ok);
2739     bind(&fail);
2740     Abort(kGlobalFunctionsMustHaveInitialMap);
2741     bind(&ok);
2742   }
2743 }
2744
2745
2746 void MacroAssembler::JumpIfNotPowerOfTwoOrZero(
2747     Register reg,
2748     Register scratch,
2749     Label* not_power_of_two_or_zero) {
2750   sub(scratch, reg, Operand(1), SetCC);
2751   b(mi, not_power_of_two_or_zero);
2752   tst(scratch, reg);
2753   b(ne, not_power_of_two_or_zero);
2754 }
2755
2756
2757 void MacroAssembler::JumpIfNotPowerOfTwoOrZeroAndNeg(
2758     Register reg,
2759     Register scratch,
2760     Label* zero_and_neg,
2761     Label* not_power_of_two) {
2762   sub(scratch, reg, Operand(1), SetCC);
2763   b(mi, zero_and_neg);
2764   tst(scratch, reg);
2765   b(ne, not_power_of_two);
2766 }
2767
2768
2769 void MacroAssembler::JumpIfNotBothSmi(Register reg1,
2770                                       Register reg2,
2771                                       Label* on_not_both_smi) {
2772   STATIC_ASSERT(kSmiTag == 0);
2773   tst(reg1, Operand(kSmiTagMask));
2774   tst(reg2, Operand(kSmiTagMask), eq);
2775   b(ne, on_not_both_smi);
2776 }
2777
2778
2779 void MacroAssembler::UntagAndJumpIfSmi(
2780     Register dst, Register src, Label* smi_case) {
2781   STATIC_ASSERT(kSmiTag == 0);
2782   SmiUntag(dst, src, SetCC);
2783   b(cc, smi_case);  // Shifter carry is not set for a smi.
2784 }
2785
2786
2787 void MacroAssembler::UntagAndJumpIfNotSmi(
2788     Register dst, Register src, Label* non_smi_case) {
2789   STATIC_ASSERT(kSmiTag == 0);
2790   SmiUntag(dst, src, SetCC);
2791   b(cs, non_smi_case);  // Shifter carry is set for a non-smi.
2792 }
2793
2794
2795 void MacroAssembler::JumpIfEitherSmi(Register reg1,
2796                                      Register reg2,
2797                                      Label* on_either_smi) {
2798   STATIC_ASSERT(kSmiTag == 0);
2799   tst(reg1, Operand(kSmiTagMask));
2800   tst(reg2, Operand(kSmiTagMask), ne);
2801   b(eq, on_either_smi);
2802 }
2803
2804
2805 void MacroAssembler::AssertNotSmi(Register object) {
2806   if (emit_debug_code()) {
2807     STATIC_ASSERT(kSmiTag == 0);
2808     tst(object, Operand(kSmiTagMask));
2809     Check(ne, kOperandIsASmi);
2810   }
2811 }
2812
2813
2814 void MacroAssembler::AssertSmi(Register object) {
2815   if (emit_debug_code()) {
2816     STATIC_ASSERT(kSmiTag == 0);
2817     tst(object, Operand(kSmiTagMask));
2818     Check(eq, kOperandIsNotSmi);
2819   }
2820 }
2821
2822
2823 void MacroAssembler::AssertString(Register object) {
2824   if (emit_debug_code()) {
2825     STATIC_ASSERT(kSmiTag == 0);
2826     tst(object, Operand(kSmiTagMask));
2827     Check(ne, kOperandIsASmiAndNotAString);
2828     push(object);
2829     ldr(object, FieldMemOperand(object, HeapObject::kMapOffset));
2830     CompareInstanceType(object, object, FIRST_NONSTRING_TYPE);
2831     pop(object);
2832     Check(lo, kOperandIsNotAString);
2833   }
2834 }
2835
2836
2837 void MacroAssembler::AssertName(Register object) {
2838   if (emit_debug_code()) {
2839     STATIC_ASSERT(kSmiTag == 0);
2840     tst(object, Operand(kSmiTagMask));
2841     Check(ne, kOperandIsASmiAndNotAName);
2842     push(object);
2843     ldr(object, FieldMemOperand(object, HeapObject::kMapOffset));
2844     CompareInstanceType(object, object, LAST_NAME_TYPE);
2845     pop(object);
2846     Check(le, kOperandIsNotAName);
2847   }
2848 }
2849
2850
2851 void MacroAssembler::AssertUndefinedOrAllocationSite(Register object,
2852                                                      Register scratch) {
2853   if (emit_debug_code()) {
2854     Label done_checking;
2855     AssertNotSmi(object);
2856     CompareRoot(object, Heap::kUndefinedValueRootIndex);
2857     b(eq, &done_checking);
2858     ldr(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
2859     CompareRoot(scratch, Heap::kAllocationSiteMapRootIndex);
2860     Assert(eq, kExpectedUndefinedOrCell);
2861     bind(&done_checking);
2862   }
2863 }
2864
2865
2866 void MacroAssembler::AssertIsRoot(Register reg, Heap::RootListIndex index) {
2867   if (emit_debug_code()) {
2868     CompareRoot(reg, index);
2869     Check(eq, kHeapNumberMapRegisterClobbered);
2870   }
2871 }
2872
2873
2874 void MacroAssembler::JumpIfNotHeapNumber(Register object,
2875                                          Register heap_number_map,
2876                                          Register scratch,
2877                                          Label* on_not_heap_number) {
2878   ldr(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
2879   AssertIsRoot(heap_number_map, Heap::kHeapNumberMapRootIndex);
2880   cmp(scratch, heap_number_map);
2881   b(ne, on_not_heap_number);
2882 }
2883
2884
2885 void MacroAssembler::LookupNumberStringCache(Register object,
2886                                              Register result,
2887                                              Register scratch1,
2888                                              Register scratch2,
2889                                              Register scratch3,
2890                                              Label* not_found) {
2891   // Use of registers. Register result is used as a temporary.
2892   Register number_string_cache = result;
2893   Register mask = scratch3;
2894
2895   // Load the number string cache.
2896   LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
2897
2898   // Make the hash mask from the length of the number string cache. It
2899   // contains two elements (number and string) for each cache entry.
2900   ldr(mask, FieldMemOperand(number_string_cache, FixedArray::kLengthOffset));
2901   // Divide length by two (length is a smi).
2902   mov(mask, Operand(mask, ASR, kSmiTagSize + 1));
2903   sub(mask, mask, Operand(1));  // Make mask.
2904
2905   // Calculate the entry in the number string cache. The hash value in the
2906   // number string cache for smis is just the smi value, and the hash for
2907   // doubles is the xor of the upper and lower words. See
2908   // Heap::GetNumberStringCache.
2909   Label is_smi;
2910   Label load_result_from_cache;
2911   JumpIfSmi(object, &is_smi);
2912   CheckMap(object,
2913            scratch1,
2914            Heap::kHeapNumberMapRootIndex,
2915            not_found,
2916            DONT_DO_SMI_CHECK);
2917
2918   STATIC_ASSERT(8 == kDoubleSize);
2919   add(scratch1,
2920       object,
2921       Operand(HeapNumber::kValueOffset - kHeapObjectTag));
2922   ldm(ia, scratch1, scratch1.bit() | scratch2.bit());
2923   eor(scratch1, scratch1, Operand(scratch2));
2924   and_(scratch1, scratch1, Operand(mask));
2925
2926   // Calculate address of entry in string cache: each entry consists
2927   // of two pointer sized fields.
2928   add(scratch1,
2929       number_string_cache,
2930       Operand(scratch1, LSL, kPointerSizeLog2 + 1));
2931
2932   Register probe = mask;
2933   ldr(probe, FieldMemOperand(scratch1, FixedArray::kHeaderSize));
2934   JumpIfSmi(probe, not_found);
2935   sub(scratch2, object, Operand(kHeapObjectTag));
2936   vldr(d0, scratch2, HeapNumber::kValueOffset);
2937   sub(probe, probe, Operand(kHeapObjectTag));
2938   vldr(d1, probe, HeapNumber::kValueOffset);
2939   VFPCompareAndSetFlags(d0, d1);
2940   b(ne, not_found);  // The cache did not contain this value.
2941   b(&load_result_from_cache);
2942
2943   bind(&is_smi);
2944   Register scratch = scratch1;
2945   and_(scratch, mask, Operand(object, ASR, 1));
2946   // Calculate address of entry in string cache: each entry consists
2947   // of two pointer sized fields.
2948   add(scratch,
2949       number_string_cache,
2950       Operand(scratch, LSL, kPointerSizeLog2 + 1));
2951
2952   // Check if the entry is the smi we are looking for.
2953   ldr(probe, FieldMemOperand(scratch, FixedArray::kHeaderSize));
2954   cmp(object, probe);
2955   b(ne, not_found);
2956
2957   // Get the result from the cache.
2958   bind(&load_result_from_cache);
2959   ldr(result, FieldMemOperand(scratch, FixedArray::kHeaderSize + kPointerSize));
2960   IncrementCounter(isolate()->counters()->number_to_string_native(),
2961                    1,
2962                    scratch1,
2963                    scratch2);
2964 }
2965
2966
2967 void MacroAssembler::JumpIfNonSmisNotBothSequentialOneByteStrings(
2968     Register first, Register second, Register scratch1, Register scratch2,
2969     Label* failure) {
2970   // Test that both first and second are sequential one-byte strings.
2971   // Assume that they are non-smis.
2972   ldr(scratch1, FieldMemOperand(first, HeapObject::kMapOffset));
2973   ldr(scratch2, FieldMemOperand(second, HeapObject::kMapOffset));
2974   ldrb(scratch1, FieldMemOperand(scratch1, Map::kInstanceTypeOffset));
2975   ldrb(scratch2, FieldMemOperand(scratch2, Map::kInstanceTypeOffset));
2976
2977   JumpIfBothInstanceTypesAreNotSequentialOneByte(scratch1, scratch2, scratch1,
2978                                                  scratch2, failure);
2979 }
2980
2981 void MacroAssembler::JumpIfNotBothSequentialOneByteStrings(Register first,
2982                                                            Register second,
2983                                                            Register scratch1,
2984                                                            Register scratch2,
2985                                                            Label* failure) {
2986   // Check that neither is a smi.
2987   and_(scratch1, first, Operand(second));
2988   JumpIfSmi(scratch1, failure);
2989   JumpIfNonSmisNotBothSequentialOneByteStrings(first, second, scratch1,
2990                                                scratch2, failure);
2991 }
2992
2993
2994 void MacroAssembler::JumpIfNotUniqueNameInstanceType(Register reg,
2995                                                      Label* not_unique_name) {
2996   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
2997   Label succeed;
2998   tst(reg, Operand(kIsNotStringMask | kIsNotInternalizedMask));
2999   b(eq, &succeed);
3000   cmp(reg, Operand(SYMBOL_TYPE));
3001   b(ne, not_unique_name);
3002
3003   bind(&succeed);
3004 }
3005
3006
3007 // Allocates a heap number or jumps to the need_gc label if the young space
3008 // is full and a scavenge is needed.
3009 void MacroAssembler::AllocateHeapNumber(Register result,
3010                                         Register scratch1,
3011                                         Register scratch2,
3012                                         Register heap_number_map,
3013                                         Label* gc_required,
3014                                         TaggingMode tagging_mode,
3015                                         MutableMode mode) {
3016   // Allocate an object in the heap for the heap number and tag it as a heap
3017   // object.
3018   Allocate(HeapNumber::kSize, result, scratch1, scratch2, gc_required,
3019            tagging_mode == TAG_RESULT ? TAG_OBJECT : NO_ALLOCATION_FLAGS);
3020
3021   Heap::RootListIndex map_index = mode == MUTABLE
3022       ? Heap::kMutableHeapNumberMapRootIndex
3023       : Heap::kHeapNumberMapRootIndex;
3024   AssertIsRoot(heap_number_map, map_index);
3025
3026   // Store heap number map in the allocated object.
3027   if (tagging_mode == TAG_RESULT) {
3028     str(heap_number_map, FieldMemOperand(result, HeapObject::kMapOffset));
3029   } else {
3030     str(heap_number_map, MemOperand(result, HeapObject::kMapOffset));
3031   }
3032 }
3033
3034
3035 void MacroAssembler::AllocateHeapNumberWithValue(Register result,
3036                                                  DwVfpRegister value,
3037                                                  Register scratch1,
3038                                                  Register scratch2,
3039                                                  Register heap_number_map,
3040                                                  Label* gc_required) {
3041   AllocateHeapNumber(result, scratch1, scratch2, heap_number_map, gc_required);
3042   sub(scratch1, result, Operand(kHeapObjectTag));
3043   vstr(value, scratch1, HeapNumber::kValueOffset);
3044 }
3045
3046
3047 // Copies a fixed number of fields of heap objects from src to dst.
3048 void MacroAssembler::CopyFields(Register dst,
3049                                 Register src,
3050                                 LowDwVfpRegister double_scratch,
3051                                 int field_count) {
3052   int double_count = field_count / (DwVfpRegister::kSizeInBytes / kPointerSize);
3053   for (int i = 0; i < double_count; i++) {
3054     vldr(double_scratch, FieldMemOperand(src, i * DwVfpRegister::kSizeInBytes));
3055     vstr(double_scratch, FieldMemOperand(dst, i * DwVfpRegister::kSizeInBytes));
3056   }
3057
3058   STATIC_ASSERT(SwVfpRegister::kSizeInBytes == kPointerSize);
3059   STATIC_ASSERT(2 * SwVfpRegister::kSizeInBytes == DwVfpRegister::kSizeInBytes);
3060
3061   int remain = field_count % (DwVfpRegister::kSizeInBytes / kPointerSize);
3062   if (remain != 0) {
3063     vldr(double_scratch.low(),
3064          FieldMemOperand(src, (field_count - 1) * kPointerSize));
3065     vstr(double_scratch.low(),
3066          FieldMemOperand(dst, (field_count - 1) * kPointerSize));
3067   }
3068 }
3069
3070
3071 void MacroAssembler::CopyBytes(Register src,
3072                                Register dst,
3073                                Register length,
3074                                Register scratch) {
3075   Label align_loop_1, word_loop, byte_loop, byte_loop_1, done;
3076
3077   // Align src before copying in word size chunks.
3078   cmp(length, Operand(kPointerSize));
3079   b(le, &byte_loop);
3080
3081   bind(&align_loop_1);
3082   tst(src, Operand(kPointerSize - 1));
3083   b(eq, &word_loop);
3084   ldrb(scratch, MemOperand(src, 1, PostIndex));
3085   strb(scratch, MemOperand(dst, 1, PostIndex));
3086   sub(length, length, Operand(1), SetCC);
3087   b(&align_loop_1);
3088   // Copy bytes in word size chunks.
3089   bind(&word_loop);
3090   if (emit_debug_code()) {
3091     tst(src, Operand(kPointerSize - 1));
3092     Assert(eq, kExpectingAlignmentForCopyBytes);
3093   }
3094   cmp(length, Operand(kPointerSize));
3095   b(lt, &byte_loop);
3096   ldr(scratch, MemOperand(src, kPointerSize, PostIndex));
3097   if (CpuFeatures::IsSupported(UNALIGNED_ACCESSES)) {
3098     str(scratch, MemOperand(dst, kPointerSize, PostIndex));
3099   } else {
3100     strb(scratch, MemOperand(dst, 1, PostIndex));
3101     mov(scratch, Operand(scratch, LSR, 8));
3102     strb(scratch, MemOperand(dst, 1, PostIndex));
3103     mov(scratch, Operand(scratch, LSR, 8));
3104     strb(scratch, MemOperand(dst, 1, PostIndex));
3105     mov(scratch, Operand(scratch, LSR, 8));
3106     strb(scratch, MemOperand(dst, 1, PostIndex));
3107   }
3108   sub(length, length, Operand(kPointerSize));
3109   b(&word_loop);
3110
3111   // Copy the last bytes if any left.
3112   bind(&byte_loop);
3113   cmp(length, Operand::Zero());
3114   b(eq, &done);
3115   bind(&byte_loop_1);
3116   ldrb(scratch, MemOperand(src, 1, PostIndex));
3117   strb(scratch, MemOperand(dst, 1, PostIndex));
3118   sub(length, length, Operand(1), SetCC);
3119   b(ne, &byte_loop_1);
3120   bind(&done);
3121 }
3122
3123
3124 void MacroAssembler::InitializeFieldsWithFiller(Register start_offset,
3125                                                 Register end_offset,
3126                                                 Register filler) {
3127   Label loop, entry;
3128   b(&entry);
3129   bind(&loop);
3130   str(filler, MemOperand(start_offset, kPointerSize, PostIndex));
3131   bind(&entry);
3132   cmp(start_offset, end_offset);
3133   b(lt, &loop);
3134 }
3135
3136
3137 void MacroAssembler::CheckFor32DRegs(Register scratch) {
3138   mov(scratch, Operand(ExternalReference::cpu_features()));
3139   ldr(scratch, MemOperand(scratch));
3140   tst(scratch, Operand(1u << VFP32DREGS));
3141 }
3142
3143
3144 void MacroAssembler::SaveFPRegs(Register location, Register scratch) {
3145   CheckFor32DRegs(scratch);
3146   vstm(db_w, location, d16, d31, ne);
3147   sub(location, location, Operand(16 * kDoubleSize), LeaveCC, eq);
3148   vstm(db_w, location, d0, d15);
3149 }
3150
3151
3152 void MacroAssembler::RestoreFPRegs(Register location, Register scratch) {
3153   CheckFor32DRegs(scratch);
3154   vldm(ia_w, location, d0, d15);
3155   vldm(ia_w, location, d16, d31, ne);
3156   add(location, location, Operand(16 * kDoubleSize), LeaveCC, eq);
3157 }
3158
3159
3160 void MacroAssembler::JumpIfBothInstanceTypesAreNotSequentialOneByte(
3161     Register first, Register second, Register scratch1, Register scratch2,
3162     Label* failure) {
3163   const int kFlatOneByteStringMask =
3164       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
3165   const int kFlatOneByteStringTag =
3166       kStringTag | kOneByteStringTag | kSeqStringTag;
3167   and_(scratch1, first, Operand(kFlatOneByteStringMask));
3168   and_(scratch2, second, Operand(kFlatOneByteStringMask));
3169   cmp(scratch1, Operand(kFlatOneByteStringTag));
3170   // Ignore second test if first test failed.
3171   cmp(scratch2, Operand(kFlatOneByteStringTag), eq);
3172   b(ne, failure);
3173 }
3174
3175
3176 void MacroAssembler::JumpIfInstanceTypeIsNotSequentialOneByte(Register type,
3177                                                               Register scratch,
3178                                                               Label* failure) {
3179   const int kFlatOneByteStringMask =
3180       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
3181   const int kFlatOneByteStringTag =
3182       kStringTag | kOneByteStringTag | kSeqStringTag;
3183   and_(scratch, type, Operand(kFlatOneByteStringMask));
3184   cmp(scratch, Operand(kFlatOneByteStringTag));
3185   b(ne, failure);
3186 }
3187
3188 static const int kRegisterPassedArguments = 4;
3189
3190
3191 int MacroAssembler::CalculateStackPassedWords(int num_reg_arguments,
3192                                               int num_double_arguments) {
3193   int stack_passed_words = 0;
3194   if (use_eabi_hardfloat()) {
3195     // In the hard floating point calling convention, we can use
3196     // all double registers to pass doubles.
3197     if (num_double_arguments > DoubleRegister::NumRegisters()) {
3198       stack_passed_words +=
3199           2 * (num_double_arguments - DoubleRegister::NumRegisters());
3200     }
3201   } else {
3202     // In the soft floating point calling convention, every double
3203     // argument is passed using two registers.
3204     num_reg_arguments += 2 * num_double_arguments;
3205   }
3206   // Up to four simple arguments are passed in registers r0..r3.
3207   if (num_reg_arguments > kRegisterPassedArguments) {
3208     stack_passed_words += num_reg_arguments - kRegisterPassedArguments;
3209   }
3210   return stack_passed_words;
3211 }
3212
3213
3214 void MacroAssembler::EmitSeqStringSetCharCheck(Register string,
3215                                                Register index,
3216                                                Register value,
3217                                                uint32_t encoding_mask) {
3218   Label is_object;
3219   SmiTst(string);
3220   Check(ne, kNonObject);
3221
3222   ldr(ip, FieldMemOperand(string, HeapObject::kMapOffset));
3223   ldrb(ip, FieldMemOperand(ip, Map::kInstanceTypeOffset));
3224
3225   and_(ip, ip, Operand(kStringRepresentationMask | kStringEncodingMask));
3226   cmp(ip, Operand(encoding_mask));
3227   Check(eq, kUnexpectedStringType);
3228
3229   // The index is assumed to be untagged coming in, tag it to compare with the
3230   // string length without using a temp register, it is restored at the end of
3231   // this function.
3232   Label index_tag_ok, index_tag_bad;
3233   TrySmiTag(index, index, &index_tag_bad);
3234   b(&index_tag_ok);
3235   bind(&index_tag_bad);
3236   Abort(kIndexIsTooLarge);
3237   bind(&index_tag_ok);
3238
3239   ldr(ip, FieldMemOperand(string, String::kLengthOffset));
3240   cmp(index, ip);
3241   Check(lt, kIndexIsTooLarge);
3242
3243   cmp(index, Operand(Smi::FromInt(0)));
3244   Check(ge, kIndexIsNegative);
3245
3246   SmiUntag(index, index);
3247 }
3248
3249
3250 void MacroAssembler::PrepareCallCFunction(int num_reg_arguments,
3251                                           int num_double_arguments,
3252                                           Register scratch) {
3253   int frame_alignment = ActivationFrameAlignment();
3254   int stack_passed_arguments = CalculateStackPassedWords(
3255       num_reg_arguments, num_double_arguments);
3256   if (frame_alignment > kPointerSize) {
3257     // Make stack end at alignment and make room for num_arguments - 4 words
3258     // and the original value of sp.
3259     mov(scratch, sp);
3260     sub(sp, sp, Operand((stack_passed_arguments + 1) * kPointerSize));
3261     DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
3262     and_(sp, sp, Operand(-frame_alignment));
3263     str(scratch, MemOperand(sp, stack_passed_arguments * kPointerSize));
3264   } else {
3265     sub(sp, sp, Operand(stack_passed_arguments * kPointerSize));
3266   }
3267 }
3268
3269
3270 void MacroAssembler::PrepareCallCFunction(int num_reg_arguments,
3271                                           Register scratch) {
3272   PrepareCallCFunction(num_reg_arguments, 0, scratch);
3273 }
3274
3275
3276 void MacroAssembler::MovToFloatParameter(DwVfpRegister src) {
3277   DCHECK(src.is(d0));
3278   if (!use_eabi_hardfloat()) {
3279     vmov(r0, r1, src);
3280   }
3281 }
3282
3283
3284 // On ARM this is just a synonym to make the purpose clear.
3285 void MacroAssembler::MovToFloatResult(DwVfpRegister src) {
3286   MovToFloatParameter(src);
3287 }
3288
3289
3290 void MacroAssembler::MovToFloatParameters(DwVfpRegister src1,
3291                                           DwVfpRegister src2) {
3292   DCHECK(src1.is(d0));
3293   DCHECK(src2.is(d1));
3294   if (!use_eabi_hardfloat()) {
3295     vmov(r0, r1, src1);
3296     vmov(r2, r3, src2);
3297   }
3298 }
3299
3300
3301 void MacroAssembler::CallCFunction(ExternalReference function,
3302                                    int num_reg_arguments,
3303                                    int num_double_arguments) {
3304   mov(ip, Operand(function));
3305   CallCFunctionHelper(ip, num_reg_arguments, num_double_arguments);
3306 }
3307
3308
3309 void MacroAssembler::CallCFunction(Register function,
3310                                    int num_reg_arguments,
3311                                    int num_double_arguments) {
3312   CallCFunctionHelper(function, num_reg_arguments, num_double_arguments);
3313 }
3314
3315
3316 void MacroAssembler::CallCFunction(ExternalReference function,
3317                                    int num_arguments) {
3318   CallCFunction(function, num_arguments, 0);
3319 }
3320
3321
3322 void MacroAssembler::CallCFunction(Register function,
3323                                    int num_arguments) {
3324   CallCFunction(function, num_arguments, 0);
3325 }
3326
3327
3328 void MacroAssembler::CallCFunctionHelper(Register function,
3329                                          int num_reg_arguments,
3330                                          int num_double_arguments) {
3331   DCHECK(has_frame());
3332   // Make sure that the stack is aligned before calling a C function unless
3333   // running in the simulator. The simulator has its own alignment check which
3334   // provides more information.
3335 #if V8_HOST_ARCH_ARM
3336   if (emit_debug_code()) {
3337     int frame_alignment = base::OS::ActivationFrameAlignment();
3338     int frame_alignment_mask = frame_alignment - 1;
3339     if (frame_alignment > kPointerSize) {
3340       DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
3341       Label alignment_as_expected;
3342       tst(sp, Operand(frame_alignment_mask));
3343       b(eq, &alignment_as_expected);
3344       // Don't use Check here, as it will call Runtime_Abort possibly
3345       // re-entering here.
3346       stop("Unexpected alignment");
3347       bind(&alignment_as_expected);
3348     }
3349   }
3350 #endif
3351
3352   // Just call directly. The function called cannot cause a GC, or
3353   // allow preemption, so the return address in the link register
3354   // stays correct.
3355   Call(function);
3356   int stack_passed_arguments = CalculateStackPassedWords(
3357       num_reg_arguments, num_double_arguments);
3358   if (ActivationFrameAlignment() > kPointerSize) {
3359     ldr(sp, MemOperand(sp, stack_passed_arguments * kPointerSize));
3360   } else {
3361     add(sp, sp, Operand(stack_passed_arguments * sizeof(kPointerSize)));
3362   }
3363 }
3364
3365
3366 void MacroAssembler::GetRelocatedValueLocation(Register ldr_location,
3367                                                Register result,
3368                                                Register scratch) {
3369   Label small_constant_pool_load, load_result;
3370   ldr(result, MemOperand(ldr_location));
3371
3372   if (FLAG_enable_ool_constant_pool) {
3373     // Check if this is an extended constant pool load.
3374     and_(scratch, result, Operand(GetConsantPoolLoadMask()));
3375     teq(scratch, Operand(GetConsantPoolLoadPattern()));
3376     b(eq, &small_constant_pool_load);
3377     if (emit_debug_code()) {
3378       // Check that the instruction sequence is:
3379       //   movw reg, #offset_low
3380       //   movt reg, #offset_high
3381       //   ldr reg, [pp, reg]
3382       Instr patterns[] = {GetMovWPattern(), GetMovTPattern(),
3383                           GetLdrPpRegOffsetPattern()};
3384       for (int i = 0; i < 3; i++) {
3385         ldr(result, MemOperand(ldr_location, i * kInstrSize));
3386         and_(result, result, Operand(patterns[i]));
3387         cmp(result, Operand(patterns[i]));
3388         Check(eq, kTheInstructionToPatchShouldBeALoadFromConstantPool);
3389       }
3390       // Result was clobbered. Restore it.
3391       ldr(result, MemOperand(ldr_location));
3392     }
3393
3394     // Get the offset into the constant pool.  First extract movw immediate into
3395     // result.
3396     and_(scratch, result, Operand(0xfff));
3397     mov(ip, Operand(result, LSR, 4));
3398     and_(ip, ip, Operand(0xf000));
3399     orr(result, scratch, Operand(ip));
3400     // Then extract movt immediate and or into result.
3401     ldr(scratch, MemOperand(ldr_location, kInstrSize));
3402     and_(ip, scratch, Operand(0xf0000));
3403     orr(result, result, Operand(ip, LSL, 12));
3404     and_(scratch, scratch, Operand(0xfff));
3405     orr(result, result, Operand(scratch, LSL, 16));
3406
3407     b(&load_result);
3408   }
3409
3410   bind(&small_constant_pool_load);
3411   if (emit_debug_code()) {
3412     // Check that the instruction is a ldr reg, [<pc or pp> + offset] .
3413     and_(result, result, Operand(GetConsantPoolLoadPattern()));
3414     cmp(result, Operand(GetConsantPoolLoadPattern()));
3415     Check(eq, kTheInstructionToPatchShouldBeALoadFromConstantPool);
3416     // Result was clobbered. Restore it.
3417     ldr(result, MemOperand(ldr_location));
3418   }
3419
3420   // Get the offset into the constant pool.
3421   const uint32_t kLdrOffsetMask = (1 << 12) - 1;
3422   and_(result, result, Operand(kLdrOffsetMask));
3423
3424   bind(&load_result);
3425   // Get the address of the constant.
3426   if (FLAG_enable_ool_constant_pool) {
3427     add(result, pp, Operand(result));
3428   } else {
3429     add(result, ldr_location, Operand(result));
3430     add(result, result, Operand(Instruction::kPCReadOffset));
3431   }
3432 }
3433
3434
3435 void MacroAssembler::CheckPageFlag(
3436     Register object,
3437     Register scratch,
3438     int mask,
3439     Condition cc,
3440     Label* condition_met) {
3441   Bfc(scratch, object, 0, kPageSizeBits);
3442   ldr(scratch, MemOperand(scratch, MemoryChunk::kFlagsOffset));
3443   tst(scratch, Operand(mask));
3444   b(cc, condition_met);
3445 }
3446
3447
3448 void MacroAssembler::JumpIfBlack(Register object,
3449                                  Register scratch0,
3450                                  Register scratch1,
3451                                  Label* on_black) {
3452   HasColor(object, scratch0, scratch1, on_black, 1, 0);  // kBlackBitPattern.
3453   DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
3454 }
3455
3456
3457 void MacroAssembler::HasColor(Register object,
3458                               Register bitmap_scratch,
3459                               Register mask_scratch,
3460                               Label* has_color,
3461                               int first_bit,
3462                               int second_bit) {
3463   DCHECK(!AreAliased(object, bitmap_scratch, mask_scratch, no_reg));
3464
3465   GetMarkBits(object, bitmap_scratch, mask_scratch);
3466
3467   Label other_color, word_boundary;
3468   ldr(ip, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
3469   tst(ip, Operand(mask_scratch));
3470   b(first_bit == 1 ? eq : ne, &other_color);
3471   // Shift left 1 by adding.
3472   add(mask_scratch, mask_scratch, Operand(mask_scratch), SetCC);
3473   b(eq, &word_boundary);
3474   tst(ip, Operand(mask_scratch));
3475   b(second_bit == 1 ? ne : eq, has_color);
3476   jmp(&other_color);
3477
3478   bind(&word_boundary);
3479   ldr(ip, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize + kPointerSize));
3480   tst(ip, Operand(1));
3481   b(second_bit == 1 ? ne : eq, has_color);
3482   bind(&other_color);
3483 }
3484
3485
3486 // Detect some, but not all, common pointer-free objects.  This is used by the
3487 // incremental write barrier which doesn't care about oddballs (they are always
3488 // marked black immediately so this code is not hit).
3489 void MacroAssembler::JumpIfDataObject(Register value,
3490                                       Register scratch,
3491                                       Label* not_data_object) {
3492   Label is_data_object;
3493   ldr(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
3494   CompareRoot(scratch, Heap::kHeapNumberMapRootIndex);
3495   b(eq, &is_data_object);
3496   DCHECK(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
3497   DCHECK(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
3498   // If it's a string and it's not a cons string then it's an object containing
3499   // no GC pointers.
3500   ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
3501   tst(scratch, Operand(kIsIndirectStringMask | kIsNotStringMask));
3502   b(ne, not_data_object);
3503   bind(&is_data_object);
3504 }
3505
3506
3507 void MacroAssembler::GetMarkBits(Register addr_reg,
3508                                  Register bitmap_reg,
3509                                  Register mask_reg) {
3510   DCHECK(!AreAliased(addr_reg, bitmap_reg, mask_reg, no_reg));
3511   and_(bitmap_reg, addr_reg, Operand(~Page::kPageAlignmentMask));
3512   Ubfx(mask_reg, addr_reg, kPointerSizeLog2, Bitmap::kBitsPerCellLog2);
3513   const int kLowBits = kPointerSizeLog2 + Bitmap::kBitsPerCellLog2;
3514   Ubfx(ip, addr_reg, kLowBits, kPageSizeBits - kLowBits);
3515   add(bitmap_reg, bitmap_reg, Operand(ip, LSL, kPointerSizeLog2));
3516   mov(ip, Operand(1));
3517   mov(mask_reg, Operand(ip, LSL, mask_reg));
3518 }
3519
3520
3521 void MacroAssembler::EnsureNotWhite(
3522     Register value,
3523     Register bitmap_scratch,
3524     Register mask_scratch,
3525     Register load_scratch,
3526     Label* value_is_white_and_not_data) {
3527   DCHECK(!AreAliased(value, bitmap_scratch, mask_scratch, ip));
3528   GetMarkBits(value, bitmap_scratch, mask_scratch);
3529
3530   // If the value is black or grey we don't need to do anything.
3531   DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
3532   DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
3533   DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
3534   DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
3535
3536   Label done;
3537
3538   // Since both black and grey have a 1 in the first position and white does
3539   // not have a 1 there we only need to check one bit.
3540   ldr(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
3541   tst(mask_scratch, load_scratch);
3542   b(ne, &done);
3543
3544   if (emit_debug_code()) {
3545     // Check for impossible bit pattern.
3546     Label ok;
3547     // LSL may overflow, making the check conservative.
3548     tst(load_scratch, Operand(mask_scratch, LSL, 1));
3549     b(eq, &ok);
3550     stop("Impossible marking bit pattern");
3551     bind(&ok);
3552   }
3553
3554   // Value is white.  We check whether it is data that doesn't need scanning.
3555   // Currently only checks for HeapNumber and non-cons strings.
3556   Register map = load_scratch;  // Holds map while checking type.
3557   Register length = load_scratch;  // Holds length of object after testing type.
3558   Label is_data_object;
3559
3560   // Check for heap-number
3561   ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
3562   CompareRoot(map, Heap::kHeapNumberMapRootIndex);
3563   mov(length, Operand(HeapNumber::kSize), LeaveCC, eq);
3564   b(eq, &is_data_object);
3565
3566   // Check for strings.
3567   DCHECK(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
3568   DCHECK(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
3569   // If it's a string and it's not a cons string then it's an object containing
3570   // no GC pointers.
3571   Register instance_type = load_scratch;
3572   ldrb(instance_type, FieldMemOperand(map, Map::kInstanceTypeOffset));
3573   tst(instance_type, Operand(kIsIndirectStringMask | kIsNotStringMask));
3574   b(ne, value_is_white_and_not_data);
3575   // It's a non-indirect (non-cons and non-slice) string.
3576   // If it's external, the length is just ExternalString::kSize.
3577   // Otherwise it's String::kHeaderSize + string->length() * (1 or 2).
3578   // External strings are the only ones with the kExternalStringTag bit
3579   // set.
3580   DCHECK_EQ(0, kSeqStringTag & kExternalStringTag);
3581   DCHECK_EQ(0, kConsStringTag & kExternalStringTag);
3582   tst(instance_type, Operand(kExternalStringTag));
3583   mov(length, Operand(ExternalString::kSize), LeaveCC, ne);
3584   b(ne, &is_data_object);
3585
3586   // Sequential string, either Latin1 or UC16.
3587   // For Latin1 (char-size of 1) we shift the smi tag away to get the length.
3588   // For UC16 (char-size of 2) we just leave the smi tag in place, thereby
3589   // getting the length multiplied by 2.
3590   DCHECK(kOneByteStringTag == 4 && kStringEncodingMask == 4);
3591   DCHECK(kSmiTag == 0 && kSmiTagSize == 1);
3592   ldr(ip, FieldMemOperand(value, String::kLengthOffset));
3593   tst(instance_type, Operand(kStringEncodingMask));
3594   mov(ip, Operand(ip, LSR, 1), LeaveCC, ne);
3595   add(length, ip, Operand(SeqString::kHeaderSize + kObjectAlignmentMask));
3596   and_(length, length, Operand(~kObjectAlignmentMask));
3597
3598   bind(&is_data_object);
3599   // Value is a data object, and it is white.  Mark it black.  Since we know
3600   // that the object is white we can make it black by flipping one bit.
3601   ldr(ip, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
3602   orr(ip, ip, Operand(mask_scratch));
3603   str(ip, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
3604
3605   and_(bitmap_scratch, bitmap_scratch, Operand(~Page::kPageAlignmentMask));
3606   ldr(ip, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
3607   add(ip, ip, Operand(length));
3608   str(ip, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
3609
3610   bind(&done);
3611 }
3612
3613
3614 void MacroAssembler::ClampUint8(Register output_reg, Register input_reg) {
3615   Usat(output_reg, 8, Operand(input_reg));
3616 }
3617
3618
3619 void MacroAssembler::ClampDoubleToUint8(Register result_reg,
3620                                         DwVfpRegister input_reg,
3621                                         LowDwVfpRegister double_scratch) {
3622   Label done;
3623
3624   // Handle inputs >= 255 (including +infinity).
3625   Vmov(double_scratch, 255.0, result_reg);
3626   mov(result_reg, Operand(255));
3627   VFPCompareAndSetFlags(input_reg, double_scratch);
3628   b(ge, &done);
3629
3630   // For inputs < 255 (including negative) vcvt_u32_f64 with round-to-nearest
3631   // rounding mode will provide the correct result.
3632   vcvt_u32_f64(double_scratch.low(), input_reg, kFPSCRRounding);
3633   vmov(result_reg, double_scratch.low());
3634
3635   bind(&done);
3636 }
3637
3638
3639 void MacroAssembler::LoadInstanceDescriptors(Register map,
3640                                              Register descriptors) {
3641   ldr(descriptors, FieldMemOperand(map, Map::kDescriptorsOffset));
3642 }
3643
3644
3645 void MacroAssembler::NumberOfOwnDescriptors(Register dst, Register map) {
3646   ldr(dst, FieldMemOperand(map, Map::kBitField3Offset));
3647   DecodeField<Map::NumberOfOwnDescriptorsBits>(dst);
3648 }
3649
3650
3651 void MacroAssembler::EnumLength(Register dst, Register map) {
3652   STATIC_ASSERT(Map::EnumLengthBits::kShift == 0);
3653   ldr(dst, FieldMemOperand(map, Map::kBitField3Offset));
3654   and_(dst, dst, Operand(Map::EnumLengthBits::kMask));
3655   SmiTag(dst);
3656 }
3657
3658
3659 void MacroAssembler::LoadAccessor(Register dst, Register holder,
3660                                   int accessor_index,
3661                                   AccessorComponent accessor) {
3662   ldr(dst, FieldMemOperand(holder, HeapObject::kMapOffset));
3663   LoadInstanceDescriptors(dst, dst);
3664   ldr(dst,
3665       FieldMemOperand(dst, DescriptorArray::GetValueOffset(accessor_index)));
3666   int offset = accessor == ACCESSOR_GETTER ? AccessorPair::kGetterOffset
3667                                            : AccessorPair::kSetterOffset;
3668   ldr(dst, FieldMemOperand(dst, offset));
3669 }
3670
3671
3672 void MacroAssembler::CheckEnumCache(Register null_value, Label* call_runtime) {
3673   Register  empty_fixed_array_value = r6;
3674   LoadRoot(empty_fixed_array_value, Heap::kEmptyFixedArrayRootIndex);
3675   Label next, start;
3676   mov(r2, r0);
3677
3678   // Check if the enum length field is properly initialized, indicating that
3679   // there is an enum cache.
3680   ldr(r1, FieldMemOperand(r2, HeapObject::kMapOffset));
3681
3682   EnumLength(r3, r1);
3683   cmp(r3, Operand(Smi::FromInt(kInvalidEnumCacheSentinel)));
3684   b(eq, call_runtime);
3685
3686   jmp(&start);
3687
3688   bind(&next);
3689   ldr(r1, FieldMemOperand(r2, HeapObject::kMapOffset));
3690
3691   // For all objects but the receiver, check that the cache is empty.
3692   EnumLength(r3, r1);
3693   cmp(r3, Operand(Smi::FromInt(0)));
3694   b(ne, call_runtime);
3695
3696   bind(&start);
3697
3698   // Check that there are no elements. Register r2 contains the current JS
3699   // object we've reached through the prototype chain.
3700   Label no_elements;
3701   ldr(r2, FieldMemOperand(r2, JSObject::kElementsOffset));
3702   cmp(r2, empty_fixed_array_value);
3703   b(eq, &no_elements);
3704
3705   // Second chance, the object may be using the empty slow element dictionary.
3706   CompareRoot(r2, Heap::kEmptySlowElementDictionaryRootIndex);
3707   b(ne, call_runtime);
3708
3709   bind(&no_elements);
3710   ldr(r2, FieldMemOperand(r1, Map::kPrototypeOffset));
3711   cmp(r2, null_value);
3712   b(ne, &next);
3713 }
3714
3715
3716 void MacroAssembler::TestJSArrayForAllocationMemento(
3717     Register receiver_reg,
3718     Register scratch_reg,
3719     Label* no_memento_found) {
3720   ExternalReference new_space_start =
3721       ExternalReference::new_space_start(isolate());
3722   ExternalReference new_space_allocation_top =
3723       ExternalReference::new_space_allocation_top_address(isolate());
3724   add(scratch_reg, receiver_reg,
3725       Operand(JSArray::kSize + AllocationMemento::kSize - kHeapObjectTag));
3726   cmp(scratch_reg, Operand(new_space_start));
3727   b(lt, no_memento_found);
3728   mov(ip, Operand(new_space_allocation_top));
3729   ldr(ip, MemOperand(ip));
3730   cmp(scratch_reg, ip);
3731   b(gt, no_memento_found);
3732   ldr(scratch_reg, MemOperand(scratch_reg, -AllocationMemento::kSize));
3733   cmp(scratch_reg,
3734       Operand(isolate()->factory()->allocation_memento_map()));
3735 }
3736
3737
3738 Register GetRegisterThatIsNotOneOf(Register reg1,
3739                                    Register reg2,
3740                                    Register reg3,
3741                                    Register reg4,
3742                                    Register reg5,
3743                                    Register reg6) {
3744   RegList regs = 0;
3745   if (reg1.is_valid()) regs |= reg1.bit();
3746   if (reg2.is_valid()) regs |= reg2.bit();
3747   if (reg3.is_valid()) regs |= reg3.bit();
3748   if (reg4.is_valid()) regs |= reg4.bit();
3749   if (reg5.is_valid()) regs |= reg5.bit();
3750   if (reg6.is_valid()) regs |= reg6.bit();
3751
3752   for (int i = 0; i < Register::NumAllocatableRegisters(); i++) {
3753     Register candidate = Register::FromAllocationIndex(i);
3754     if (regs & candidate.bit()) continue;
3755     return candidate;
3756   }
3757   UNREACHABLE();
3758   return no_reg;
3759 }
3760
3761
3762 void MacroAssembler::JumpIfDictionaryInPrototypeChain(
3763     Register object,
3764     Register scratch0,
3765     Register scratch1,
3766     Label* found) {
3767   DCHECK(!scratch1.is(scratch0));
3768   Factory* factory = isolate()->factory();
3769   Register current = scratch0;
3770   Label loop_again;
3771
3772   // scratch contained elements pointer.
3773   mov(current, object);
3774
3775   // Loop based on the map going up the prototype chain.
3776   bind(&loop_again);
3777   ldr(current, FieldMemOperand(current, HeapObject::kMapOffset));
3778   ldr(scratch1, FieldMemOperand(current, Map::kBitField2Offset));
3779   DecodeField<Map::ElementsKindBits>(scratch1);
3780   cmp(scratch1, Operand(DICTIONARY_ELEMENTS));
3781   b(eq, found);
3782   ldr(current, FieldMemOperand(current, Map::kPrototypeOffset));
3783   cmp(current, Operand(factory->null_value()));
3784   b(ne, &loop_again);
3785 }
3786
3787
3788 #ifdef DEBUG
3789 bool AreAliased(Register reg1,
3790                 Register reg2,
3791                 Register reg3,
3792                 Register reg4,
3793                 Register reg5,
3794                 Register reg6,
3795                 Register reg7,
3796                 Register reg8) {
3797   int n_of_valid_regs = reg1.is_valid() + reg2.is_valid() +
3798       reg3.is_valid() + reg4.is_valid() + reg5.is_valid() + reg6.is_valid() +
3799       reg7.is_valid() + reg8.is_valid();
3800
3801   RegList regs = 0;
3802   if (reg1.is_valid()) regs |= reg1.bit();
3803   if (reg2.is_valid()) regs |= reg2.bit();
3804   if (reg3.is_valid()) regs |= reg3.bit();
3805   if (reg4.is_valid()) regs |= reg4.bit();
3806   if (reg5.is_valid()) regs |= reg5.bit();
3807   if (reg6.is_valid()) regs |= reg6.bit();
3808   if (reg7.is_valid()) regs |= reg7.bit();
3809   if (reg8.is_valid()) regs |= reg8.bit();
3810   int n_of_non_aliasing_regs = NumRegs(regs);
3811
3812   return n_of_valid_regs != n_of_non_aliasing_regs;
3813 }
3814 #endif
3815
3816
3817 CodePatcher::CodePatcher(byte* address,
3818                          int instructions,
3819                          FlushICache flush_cache)
3820     : address_(address),
3821       size_(instructions * Assembler::kInstrSize),
3822       masm_(NULL, address, size_ + Assembler::kGap),
3823       flush_cache_(flush_cache) {
3824   // Create a new macro assembler pointing to the address of the code to patch.
3825   // The size is adjusted with kGap on order for the assembler to generate size
3826   // bytes of instructions without failing with buffer size constraints.
3827   DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
3828 }
3829
3830
3831 CodePatcher::~CodePatcher() {
3832   // Indicate that code has changed.
3833   if (flush_cache_ == FLUSH) {
3834     CpuFeatures::FlushICache(address_, size_);
3835   }
3836
3837   // Check that the code was patched as expected.
3838   DCHECK(masm_.pc_ == address_ + size_);
3839   DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
3840 }
3841
3842
3843 void CodePatcher::Emit(Instr instr) {
3844   masm()->emit(instr);
3845 }
3846
3847
3848 void CodePatcher::Emit(Address addr) {
3849   masm()->emit(reinterpret_cast<Instr>(addr));
3850 }
3851
3852
3853 void CodePatcher::EmitCondition(Condition cond) {
3854   Instr instr = Assembler::instr_at(masm_.pc_);
3855   instr = (instr & ~kCondMask) | cond;
3856   masm_.emit(instr);
3857 }
3858
3859
3860 void MacroAssembler::TruncatingDiv(Register result,
3861                                    Register dividend,
3862                                    int32_t divisor) {
3863   DCHECK(!dividend.is(result));
3864   DCHECK(!dividend.is(ip));
3865   DCHECK(!result.is(ip));
3866   base::MagicNumbersForDivision<uint32_t> mag =
3867       base::SignedDivisionByConstant(bit_cast<uint32_t>(divisor));
3868   mov(ip, Operand(mag.multiplier));
3869   bool neg = (mag.multiplier & (1U << 31)) != 0;
3870   if (divisor > 0 && neg) {
3871     smmla(result, dividend, ip, dividend);
3872   } else {
3873     smmul(result, dividend, ip);
3874     if (divisor < 0 && !neg && mag.multiplier > 0) {
3875       sub(result, result, Operand(dividend));
3876     }
3877   }
3878   if (mag.shift > 0) mov(result, Operand(result, ASR, mag.shift));
3879   add(result, result, Operand(dividend, LSR, 31));
3880 }
3881
3882 }  // namespace internal
3883 }  // namespace v8
3884
3885 #endif  // V8_TARGET_ARCH_ARM