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