ecd2082cd02cba0796870e78c90864d9e9563c12
[platform/upstream/v8.git] / src / arm / code-stubs-arm.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/v8.h"
6
7 #if V8_TARGET_ARCH_ARM
8
9 #include "src/base/bits.h"
10 #include "src/bootstrapper.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/ic/handler-compiler.h"
14 #include "src/ic/ic.h"
15 #include "src/ic/stub-cache.h"
16 #include "src/isolate.h"
17 #include "src/jsregexp.h"
18 #include "src/regexp-macro-assembler.h"
19 #include "src/runtime/runtime.h"
20
21 namespace v8 {
22 namespace internal {
23
24
25 static void InitializeArrayConstructorDescriptor(
26     Isolate* isolate, CodeStubDescriptor* descriptor,
27     int constant_stack_parameter_count) {
28   Address deopt_handler = Runtime::FunctionForId(
29       Runtime::kArrayConstructor)->entry;
30
31   if (constant_stack_parameter_count == 0) {
32     descriptor->Initialize(deopt_handler, constant_stack_parameter_count,
33                            JS_FUNCTION_STUB_MODE);
34   } else {
35     descriptor->Initialize(r0, deopt_handler, constant_stack_parameter_count,
36                            JS_FUNCTION_STUB_MODE, PASS_ARGUMENTS);
37   }
38 }
39
40
41 static void InitializeInternalArrayConstructorDescriptor(
42     Isolate* isolate, CodeStubDescriptor* descriptor,
43     int constant_stack_parameter_count) {
44   Address deopt_handler = Runtime::FunctionForId(
45       Runtime::kInternalArrayConstructor)->entry;
46
47   if (constant_stack_parameter_count == 0) {
48     descriptor->Initialize(deopt_handler, constant_stack_parameter_count,
49                            JS_FUNCTION_STUB_MODE);
50   } else {
51     descriptor->Initialize(r0, deopt_handler, constant_stack_parameter_count,
52                            JS_FUNCTION_STUB_MODE, PASS_ARGUMENTS);
53   }
54 }
55
56
57 void ArrayNoArgumentConstructorStub::InitializeDescriptor(
58     CodeStubDescriptor* descriptor) {
59   InitializeArrayConstructorDescriptor(isolate(), descriptor, 0);
60 }
61
62
63 void ArraySingleArgumentConstructorStub::InitializeDescriptor(
64     CodeStubDescriptor* descriptor) {
65   InitializeArrayConstructorDescriptor(isolate(), descriptor, 1);
66 }
67
68
69 void ArrayNArgumentsConstructorStub::InitializeDescriptor(
70     CodeStubDescriptor* descriptor) {
71   InitializeArrayConstructorDescriptor(isolate(), descriptor, -1);
72 }
73
74
75 void InternalArrayNoArgumentConstructorStub::InitializeDescriptor(
76     CodeStubDescriptor* descriptor) {
77   InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, 0);
78 }
79
80
81 void InternalArraySingleArgumentConstructorStub::InitializeDescriptor(
82     CodeStubDescriptor* descriptor) {
83   InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, 1);
84 }
85
86
87 void InternalArrayNArgumentsConstructorStub::InitializeDescriptor(
88     CodeStubDescriptor* descriptor) {
89   InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, -1);
90 }
91
92
93 #define __ ACCESS_MASM(masm)
94
95
96 static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow,
97                                           Condition cond, bool strong);
98 static void EmitSmiNonsmiComparison(MacroAssembler* masm,
99                                     Register lhs,
100                                     Register rhs,
101                                     Label* lhs_not_nan,
102                                     Label* slow,
103                                     bool strict);
104 static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm,
105                                            Register lhs,
106                                            Register rhs);
107
108
109 void HydrogenCodeStub::GenerateLightweightMiss(MacroAssembler* masm,
110                                                ExternalReference miss) {
111   // Update the static counter each time a new code stub is generated.
112   isolate()->counters()->code_stubs()->Increment();
113
114   CallInterfaceDescriptor descriptor = GetCallInterfaceDescriptor();
115   int param_count = descriptor.GetEnvironmentParameterCount();
116   {
117     // Call the runtime system in a fresh internal frame.
118     FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
119     DCHECK(param_count == 0 ||
120            r0.is(descriptor.GetEnvironmentParameterRegister(param_count - 1)));
121     // Push arguments
122     for (int i = 0; i < param_count; ++i) {
123       __ push(descriptor.GetEnvironmentParameterRegister(i));
124     }
125     __ CallExternalReference(miss, param_count);
126   }
127
128   __ Ret();
129 }
130
131
132 void DoubleToIStub::Generate(MacroAssembler* masm) {
133   Label out_of_range, only_low, negate, done;
134   Register input_reg = source();
135   Register result_reg = destination();
136   DCHECK(is_truncating());
137
138   int double_offset = offset();
139   // Account for saved regs if input is sp.
140   if (input_reg.is(sp)) double_offset += 3 * kPointerSize;
141
142   Register scratch = GetRegisterThatIsNotOneOf(input_reg, result_reg);
143   Register scratch_low =
144       GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch);
145   Register scratch_high =
146       GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch, scratch_low);
147   LowDwVfpRegister double_scratch = kScratchDoubleReg;
148
149   __ Push(scratch_high, scratch_low, scratch);
150
151   if (!skip_fastpath()) {
152     // Load double input.
153     __ vldr(double_scratch, MemOperand(input_reg, double_offset));
154     __ vmov(scratch_low, scratch_high, double_scratch);
155
156     // Do fast-path convert from double to int.
157     __ vcvt_s32_f64(double_scratch.low(), double_scratch);
158     __ vmov(result_reg, double_scratch.low());
159
160     // If result is not saturated (0x7fffffff or 0x80000000), we are done.
161     __ sub(scratch, result_reg, Operand(1));
162     __ cmp(scratch, Operand(0x7ffffffe));
163     __ b(lt, &done);
164   } else {
165     // We've already done MacroAssembler::TryFastTruncatedDoubleToILoad, so we
166     // know exponent > 31, so we can skip the vcvt_s32_f64 which will saturate.
167     if (double_offset == 0) {
168       __ ldm(ia, input_reg, scratch_low.bit() | scratch_high.bit());
169     } else {
170       __ ldr(scratch_low, MemOperand(input_reg, double_offset));
171       __ ldr(scratch_high, MemOperand(input_reg, double_offset + kIntSize));
172     }
173   }
174
175   __ Ubfx(scratch, scratch_high,
176          HeapNumber::kExponentShift, HeapNumber::kExponentBits);
177   // Load scratch with exponent - 1. This is faster than loading
178   // with exponent because Bias + 1 = 1024 which is an *ARM* immediate value.
179   STATIC_ASSERT(HeapNumber::kExponentBias + 1 == 1024);
180   __ sub(scratch, scratch, Operand(HeapNumber::kExponentBias + 1));
181   // If exponent is greater than or equal to 84, the 32 less significant
182   // bits are 0s (2^84 = 1, 52 significant bits, 32 uncoded bits),
183   // the result is 0.
184   // Compare exponent with 84 (compare exponent - 1 with 83).
185   __ cmp(scratch, Operand(83));
186   __ b(ge, &out_of_range);
187
188   // If we reach this code, 31 <= exponent <= 83.
189   // So, we don't have to handle cases where 0 <= exponent <= 20 for
190   // which we would need to shift right the high part of the mantissa.
191   // Scratch contains exponent - 1.
192   // Load scratch with 52 - exponent (load with 51 - (exponent - 1)).
193   __ rsb(scratch, scratch, Operand(51), SetCC);
194   __ b(ls, &only_low);
195   // 21 <= exponent <= 51, shift scratch_low and scratch_high
196   // to generate the result.
197   __ mov(scratch_low, Operand(scratch_low, LSR, scratch));
198   // Scratch contains: 52 - exponent.
199   // We needs: exponent - 20.
200   // So we use: 32 - scratch = 32 - 52 + exponent = exponent - 20.
201   __ rsb(scratch, scratch, Operand(32));
202   __ Ubfx(result_reg, scratch_high,
203           0, HeapNumber::kMantissaBitsInTopWord);
204   // Set the implicit 1 before the mantissa part in scratch_high.
205   __ orr(result_reg, result_reg,
206          Operand(1 << HeapNumber::kMantissaBitsInTopWord));
207   __ orr(result_reg, scratch_low, Operand(result_reg, LSL, scratch));
208   __ b(&negate);
209
210   __ bind(&out_of_range);
211   __ mov(result_reg, Operand::Zero());
212   __ b(&done);
213
214   __ bind(&only_low);
215   // 52 <= exponent <= 83, shift only scratch_low.
216   // On entry, scratch contains: 52 - exponent.
217   __ rsb(scratch, scratch, Operand::Zero());
218   __ mov(result_reg, Operand(scratch_low, LSL, scratch));
219
220   __ bind(&negate);
221   // If input was positive, scratch_high ASR 31 equals 0 and
222   // scratch_high LSR 31 equals zero.
223   // New result = (result eor 0) + 0 = result.
224   // If the input was negative, we have to negate the result.
225   // Input_high ASR 31 equals 0xffffffff and scratch_high LSR 31 equals 1.
226   // New result = (result eor 0xffffffff) + 1 = 0 - result.
227   __ eor(result_reg, result_reg, Operand(scratch_high, ASR, 31));
228   __ add(result_reg, result_reg, Operand(scratch_high, LSR, 31));
229
230   __ bind(&done);
231
232   __ Pop(scratch_high, scratch_low, scratch);
233   __ Ret();
234 }
235
236
237 // Handle the case where the lhs and rhs are the same object.
238 // Equality is almost reflexive (everything but NaN), so this is a test
239 // for "identity and not NaN".
240 static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow,
241                                           Condition cond, bool strong) {
242   Label not_identical;
243   Label heap_number, return_equal;
244   __ cmp(r0, r1);
245   __ b(ne, &not_identical);
246
247   // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
248   // so we do the second best thing - test it ourselves.
249   // They are both equal and they are not both Smis so both of them are not
250   // Smis.  If it's not a heap number, then return equal.
251   if (cond == lt || cond == gt) {
252     // Call runtime on identical JSObjects.
253     __ CompareObjectType(r0, r4, r4, FIRST_SPEC_OBJECT_TYPE);
254     __ b(ge, slow);
255     // Call runtime on identical symbols since we need to throw a TypeError.
256     __ cmp(r4, Operand(SYMBOL_TYPE));
257     __ b(eq, slow);
258     if (strong) {
259       // Call the runtime on anything that is converted in the semantics, since
260       // we need to throw a TypeError. Smis have already been ruled out.
261       __ cmp(r4, Operand(HEAP_NUMBER_TYPE));
262       __ b(eq, &return_equal);
263       __ tst(r4, Operand(kIsNotStringMask));
264       __ b(ne, slow);
265     }
266   } else {
267     __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
268     __ b(eq, &heap_number);
269     // Comparing JS objects with <=, >= is complicated.
270     if (cond != eq) {
271       __ cmp(r4, Operand(FIRST_SPEC_OBJECT_TYPE));
272       __ b(ge, slow);
273       // Call runtime on identical symbols since we need to throw a TypeError.
274       __ cmp(r4, Operand(SYMBOL_TYPE));
275       __ b(eq, slow);
276       if (strong) {
277         // Call the runtime on anything that is converted in the semantics,
278         // since we need to throw a TypeError. Smis and heap numbers have
279         // already been ruled out.
280         __ tst(r4, Operand(kIsNotStringMask));
281         __ b(ne, slow);
282       }
283       // Normally here we fall through to return_equal, but undefined is
284       // special: (undefined == undefined) == true, but
285       // (undefined <= undefined) == false!  See ECMAScript 11.8.5.
286       if (cond == le || cond == ge) {
287         __ cmp(r4, Operand(ODDBALL_TYPE));
288         __ b(ne, &return_equal);
289         __ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
290         __ cmp(r0, r2);
291         __ b(ne, &return_equal);
292         if (cond == le) {
293           // undefined <= undefined should fail.
294           __ mov(r0, Operand(GREATER));
295         } else  {
296           // undefined >= undefined should fail.
297           __ mov(r0, Operand(LESS));
298         }
299         __ Ret();
300       }
301     }
302   }
303
304   __ bind(&return_equal);
305   if (cond == lt) {
306     __ mov(r0, Operand(GREATER));  // Things aren't less than themselves.
307   } else if (cond == gt) {
308     __ mov(r0, Operand(LESS));     // Things aren't greater than themselves.
309   } else {
310     __ mov(r0, Operand(EQUAL));    // Things are <=, >=, ==, === themselves.
311   }
312   __ Ret();
313
314   // For less and greater we don't have to check for NaN since the result of
315   // x < x is false regardless.  For the others here is some code to check
316   // for NaN.
317   if (cond != lt && cond != gt) {
318     __ bind(&heap_number);
319     // It is a heap number, so return non-equal if it's NaN and equal if it's
320     // not NaN.
321
322     // The representation of NaN values has all exponent bits (52..62) set,
323     // and not all mantissa bits (0..51) clear.
324     // Read top bits of double representation (second word of value).
325     __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
326     // Test that exponent bits are all set.
327     __ Sbfx(r3, r2, HeapNumber::kExponentShift, HeapNumber::kExponentBits);
328     // NaNs have all-one exponents so they sign extend to -1.
329     __ cmp(r3, Operand(-1));
330     __ b(ne, &return_equal);
331
332     // Shift out flag and all exponent bits, retaining only mantissa.
333     __ mov(r2, Operand(r2, LSL, HeapNumber::kNonMantissaBitsInTopWord));
334     // Or with all low-bits of mantissa.
335     __ ldr(r3, FieldMemOperand(r0, HeapNumber::kMantissaOffset));
336     __ orr(r0, r3, Operand(r2), SetCC);
337     // For equal we already have the right value in r0:  Return zero (equal)
338     // if all bits in mantissa are zero (it's an Infinity) and non-zero if
339     // not (it's a NaN).  For <= and >= we need to load r0 with the failing
340     // value if it's a NaN.
341     if (cond != eq) {
342       // All-zero means Infinity means equal.
343       __ Ret(eq);
344       if (cond == le) {
345         __ mov(r0, Operand(GREATER));  // NaN <= NaN should fail.
346       } else {
347         __ mov(r0, Operand(LESS));     // NaN >= NaN should fail.
348       }
349     }
350     __ Ret();
351   }
352   // No fall through here.
353
354   __ bind(&not_identical);
355 }
356
357
358 // See comment at call site.
359 static void EmitSmiNonsmiComparison(MacroAssembler* masm,
360                                     Register lhs,
361                                     Register rhs,
362                                     Label* lhs_not_nan,
363                                     Label* slow,
364                                     bool strict) {
365   DCHECK((lhs.is(r0) && rhs.is(r1)) ||
366          (lhs.is(r1) && rhs.is(r0)));
367
368   Label rhs_is_smi;
369   __ JumpIfSmi(rhs, &rhs_is_smi);
370
371   // Lhs is a Smi.  Check whether the rhs is a heap number.
372   __ CompareObjectType(rhs, r4, r4, HEAP_NUMBER_TYPE);
373   if (strict) {
374     // If rhs is not a number and lhs is a Smi then strict equality cannot
375     // succeed.  Return non-equal
376     // If rhs is r0 then there is already a non zero value in it.
377     if (!rhs.is(r0)) {
378       __ mov(r0, Operand(NOT_EQUAL), LeaveCC, ne);
379     }
380     __ Ret(ne);
381   } else {
382     // Smi compared non-strictly with a non-Smi non-heap-number.  Call
383     // the runtime.
384     __ b(ne, slow);
385   }
386
387   // Lhs is a smi, rhs is a number.
388   // Convert lhs to a double in d7.
389   __ SmiToDouble(d7, lhs);
390   // Load the double from rhs, tagged HeapNumber r0, to d6.
391   __ vldr(d6, rhs, HeapNumber::kValueOffset - kHeapObjectTag);
392
393   // We now have both loaded as doubles but we can skip the lhs nan check
394   // since it's a smi.
395   __ jmp(lhs_not_nan);
396
397   __ bind(&rhs_is_smi);
398   // Rhs is a smi.  Check whether the non-smi lhs is a heap number.
399   __ CompareObjectType(lhs, r4, r4, HEAP_NUMBER_TYPE);
400   if (strict) {
401     // If lhs is not a number and rhs is a smi then strict equality cannot
402     // succeed.  Return non-equal.
403     // If lhs is r0 then there is already a non zero value in it.
404     if (!lhs.is(r0)) {
405       __ mov(r0, Operand(NOT_EQUAL), LeaveCC, ne);
406     }
407     __ Ret(ne);
408   } else {
409     // Smi compared non-strictly with a non-smi non-heap-number.  Call
410     // the runtime.
411     __ b(ne, slow);
412   }
413
414   // Rhs is a smi, lhs is a heap number.
415   // Load the double from lhs, tagged HeapNumber r1, to d7.
416   __ vldr(d7, lhs, HeapNumber::kValueOffset - kHeapObjectTag);
417   // Convert rhs to a double in d6              .
418   __ SmiToDouble(d6, rhs);
419   // Fall through to both_loaded_as_doubles.
420 }
421
422
423 // See comment at call site.
424 static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm,
425                                            Register lhs,
426                                            Register rhs) {
427     DCHECK((lhs.is(r0) && rhs.is(r1)) ||
428            (lhs.is(r1) && rhs.is(r0)));
429
430     // If either operand is a JS object or an oddball value, then they are
431     // not equal since their pointers are different.
432     // There is no test for undetectability in strict equality.
433     STATIC_ASSERT(LAST_TYPE == LAST_SPEC_OBJECT_TYPE);
434     Label first_non_object;
435     // Get the type of the first operand into r2 and compare it with
436     // FIRST_SPEC_OBJECT_TYPE.
437     __ CompareObjectType(rhs, r2, r2, FIRST_SPEC_OBJECT_TYPE);
438     __ b(lt, &first_non_object);
439
440     // Return non-zero (r0 is not zero)
441     Label return_not_equal;
442     __ bind(&return_not_equal);
443     __ Ret();
444
445     __ bind(&first_non_object);
446     // Check for oddballs: true, false, null, undefined.
447     __ cmp(r2, Operand(ODDBALL_TYPE));
448     __ b(eq, &return_not_equal);
449
450     __ CompareObjectType(lhs, r3, r3, FIRST_SPEC_OBJECT_TYPE);
451     __ b(ge, &return_not_equal);
452
453     // Check for oddballs: true, false, null, undefined.
454     __ cmp(r3, Operand(ODDBALL_TYPE));
455     __ b(eq, &return_not_equal);
456
457     // Now that we have the types we might as well check for
458     // internalized-internalized.
459     STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
460     __ orr(r2, r2, Operand(r3));
461     __ tst(r2, Operand(kIsNotStringMask | kIsNotInternalizedMask));
462     __ b(eq, &return_not_equal);
463 }
464
465
466 // See comment at call site.
467 static void EmitCheckForTwoHeapNumbers(MacroAssembler* masm,
468                                        Register lhs,
469                                        Register rhs,
470                                        Label* both_loaded_as_doubles,
471                                        Label* not_heap_numbers,
472                                        Label* slow) {
473   DCHECK((lhs.is(r0) && rhs.is(r1)) ||
474          (lhs.is(r1) && rhs.is(r0)));
475
476   __ CompareObjectType(rhs, r3, r2, HEAP_NUMBER_TYPE);
477   __ b(ne, not_heap_numbers);
478   __ ldr(r2, FieldMemOperand(lhs, HeapObject::kMapOffset));
479   __ cmp(r2, r3);
480   __ b(ne, slow);  // First was a heap number, second wasn't.  Go slow case.
481
482   // Both are heap numbers.  Load them up then jump to the code we have
483   // for that.
484   __ vldr(d6, rhs, HeapNumber::kValueOffset - kHeapObjectTag);
485   __ vldr(d7, lhs, HeapNumber::kValueOffset - kHeapObjectTag);
486   __ jmp(both_loaded_as_doubles);
487 }
488
489
490 // Fast negative check for internalized-to-internalized equality.
491 static void EmitCheckForInternalizedStringsOrObjects(MacroAssembler* masm,
492                                                      Register lhs,
493                                                      Register rhs,
494                                                      Label* possible_strings,
495                                                      Label* not_both_strings) {
496   DCHECK((lhs.is(r0) && rhs.is(r1)) ||
497          (lhs.is(r1) && rhs.is(r0)));
498
499   // r2 is object type of rhs.
500   Label object_test;
501   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
502   __ tst(r2, Operand(kIsNotStringMask));
503   __ b(ne, &object_test);
504   __ tst(r2, Operand(kIsNotInternalizedMask));
505   __ b(ne, possible_strings);
506   __ CompareObjectType(lhs, r3, r3, FIRST_NONSTRING_TYPE);
507   __ b(ge, not_both_strings);
508   __ tst(r3, Operand(kIsNotInternalizedMask));
509   __ b(ne, possible_strings);
510
511   // Both are internalized.  We already checked they weren't the same pointer
512   // so they are not equal.
513   __ mov(r0, Operand(NOT_EQUAL));
514   __ Ret();
515
516   __ bind(&object_test);
517   __ cmp(r2, Operand(FIRST_SPEC_OBJECT_TYPE));
518   __ b(lt, not_both_strings);
519   __ CompareObjectType(lhs, r2, r3, FIRST_SPEC_OBJECT_TYPE);
520   __ b(lt, not_both_strings);
521   // If both objects are undetectable, they are equal. Otherwise, they
522   // are not equal, since they are different objects and an object is not
523   // equal to undefined.
524   __ ldr(r3, FieldMemOperand(rhs, HeapObject::kMapOffset));
525   __ ldrb(r2, FieldMemOperand(r2, Map::kBitFieldOffset));
526   __ ldrb(r3, FieldMemOperand(r3, Map::kBitFieldOffset));
527   __ and_(r0, r2, Operand(r3));
528   __ and_(r0, r0, Operand(1 << Map::kIsUndetectable));
529   __ eor(r0, r0, Operand(1 << Map::kIsUndetectable));
530   __ Ret();
531 }
532
533
534 static void CompareICStub_CheckInputType(MacroAssembler* masm, Register input,
535                                          Register scratch,
536                                          CompareICState::State expected,
537                                          Label* fail) {
538   Label ok;
539   if (expected == CompareICState::SMI) {
540     __ JumpIfNotSmi(input, fail);
541   } else if (expected == CompareICState::NUMBER) {
542     __ JumpIfSmi(input, &ok);
543     __ CheckMap(input, scratch, Heap::kHeapNumberMapRootIndex, fail,
544                 DONT_DO_SMI_CHECK);
545   }
546   // We could be strict about internalized/non-internalized here, but as long as
547   // hydrogen doesn't care, the stub doesn't have to care either.
548   __ bind(&ok);
549 }
550
551
552 // On entry r1 and r2 are the values to be compared.
553 // On exit r0 is 0, positive or negative to indicate the result of
554 // the comparison.
555 void CompareICStub::GenerateGeneric(MacroAssembler* masm) {
556   Register lhs = r1;
557   Register rhs = r0;
558   Condition cc = GetCondition();
559
560   Label miss;
561   CompareICStub_CheckInputType(masm, lhs, r2, left(), &miss);
562   CompareICStub_CheckInputType(masm, rhs, r3, right(), &miss);
563
564   Label slow;  // Call builtin.
565   Label not_smis, both_loaded_as_doubles, lhs_not_nan;
566
567   Label not_two_smis, smi_done;
568   __ orr(r2, r1, r0);
569   __ JumpIfNotSmi(r2, &not_two_smis);
570   __ mov(r1, Operand(r1, ASR, 1));
571   __ sub(r0, r1, Operand(r0, ASR, 1));
572   __ Ret();
573   __ bind(&not_two_smis);
574
575   // NOTICE! This code is only reached after a smi-fast-case check, so
576   // it is certain that at least one operand isn't a smi.
577
578   // Handle the case where the objects are identical.  Either returns the answer
579   // or goes to slow.  Only falls through if the objects were not identical.
580   EmitIdenticalObjectComparison(masm, &slow, cc, strong());
581
582   // If either is a Smi (we know that not both are), then they can only
583   // be strictly equal if the other is a HeapNumber.
584   STATIC_ASSERT(kSmiTag == 0);
585   DCHECK_EQ(static_cast<Smi*>(0), Smi::FromInt(0));
586   __ and_(r2, lhs, Operand(rhs));
587   __ JumpIfNotSmi(r2, &not_smis);
588   // One operand is a smi.  EmitSmiNonsmiComparison generates code that can:
589   // 1) Return the answer.
590   // 2) Go to slow.
591   // 3) Fall through to both_loaded_as_doubles.
592   // 4) Jump to lhs_not_nan.
593   // In cases 3 and 4 we have found out we were dealing with a number-number
594   // comparison.  If VFP3 is supported the double values of the numbers have
595   // been loaded into d7 and d6.  Otherwise, the double values have been loaded
596   // into r0, r1, r2, and r3.
597   EmitSmiNonsmiComparison(masm, lhs, rhs, &lhs_not_nan, &slow, strict());
598
599   __ bind(&both_loaded_as_doubles);
600   // The arguments have been converted to doubles and stored in d6 and d7, if
601   // VFP3 is supported, or in r0, r1, r2, and r3.
602   __ bind(&lhs_not_nan);
603   Label no_nan;
604   // ARMv7 VFP3 instructions to implement double precision comparison.
605   __ VFPCompareAndSetFlags(d7, d6);
606   Label nan;
607   __ b(vs, &nan);
608   __ mov(r0, Operand(EQUAL), LeaveCC, eq);
609   __ mov(r0, Operand(LESS), LeaveCC, lt);
610   __ mov(r0, Operand(GREATER), LeaveCC, gt);
611   __ Ret();
612
613   __ bind(&nan);
614   // If one of the sides was a NaN then the v flag is set.  Load r0 with
615   // whatever it takes to make the comparison fail, since comparisons with NaN
616   // always fail.
617   if (cc == lt || cc == le) {
618     __ mov(r0, Operand(GREATER));
619   } else {
620     __ mov(r0, Operand(LESS));
621   }
622   __ Ret();
623
624   __ bind(&not_smis);
625   // At this point we know we are dealing with two different objects,
626   // and neither of them is a Smi.  The objects are in rhs_ and lhs_.
627   if (strict()) {
628     // This returns non-equal for some object types, or falls through if it
629     // was not lucky.
630     EmitStrictTwoHeapObjectCompare(masm, lhs, rhs);
631   }
632
633   Label check_for_internalized_strings;
634   Label flat_string_check;
635   // Check for heap-number-heap-number comparison.  Can jump to slow case,
636   // or load both doubles into r0, r1, r2, r3 and jump to the code that handles
637   // that case.  If the inputs are not doubles then jumps to
638   // check_for_internalized_strings.
639   // In this case r2 will contain the type of rhs_.  Never falls through.
640   EmitCheckForTwoHeapNumbers(masm,
641                              lhs,
642                              rhs,
643                              &both_loaded_as_doubles,
644                              &check_for_internalized_strings,
645                              &flat_string_check);
646
647   __ bind(&check_for_internalized_strings);
648   // In the strict case the EmitStrictTwoHeapObjectCompare already took care of
649   // internalized strings.
650   if (cc == eq && !strict()) {
651     // Returns an answer for two internalized strings or two detectable objects.
652     // Otherwise jumps to string case or not both strings case.
653     // Assumes that r2 is the type of rhs_ on entry.
654     EmitCheckForInternalizedStringsOrObjects(
655         masm, lhs, rhs, &flat_string_check, &slow);
656   }
657
658   // Check for both being sequential one-byte strings,
659   // and inline if that is the case.
660   __ bind(&flat_string_check);
661
662   __ JumpIfNonSmisNotBothSequentialOneByteStrings(lhs, rhs, r2, r3, &slow);
663
664   __ IncrementCounter(isolate()->counters()->string_compare_native(), 1, r2,
665                       r3);
666   if (cc == eq) {
667     StringHelper::GenerateFlatOneByteStringEquals(masm, lhs, rhs, r2, r3, r4);
668   } else {
669     StringHelper::GenerateCompareFlatOneByteStrings(masm, lhs, rhs, r2, r3, r4,
670                                                     r5);
671   }
672   // Never falls through to here.
673
674   __ bind(&slow);
675
676   __ Push(lhs, rhs);
677   // Figure out which native to call and setup the arguments.
678   Builtins::JavaScript native;
679   if (cc == eq) {
680     native = strict() ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
681   } else {
682     native = strong() ? Builtins::COMPARE_STRONG : Builtins::COMPARE;
683     int ncr;  // NaN compare result
684     if (cc == lt || cc == le) {
685       ncr = GREATER;
686     } else {
687       DCHECK(cc == gt || cc == ge);  // remaining cases
688       ncr = LESS;
689     }
690     __ mov(r0, Operand(Smi::FromInt(ncr)));
691     __ push(r0);
692   }
693
694   // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
695   // tagged as a small integer.
696   __ InvokeBuiltin(native, JUMP_FUNCTION);
697
698   __ bind(&miss);
699   GenerateMiss(masm);
700 }
701
702
703 void StoreBufferOverflowStub::Generate(MacroAssembler* masm) {
704   // We don't allow a GC during a store buffer overflow so there is no need to
705   // store the registers in any particular way, but we do have to store and
706   // restore them.
707   __ stm(db_w, sp, kCallerSaved | lr.bit());
708
709   const Register scratch = r1;
710
711   if (save_doubles()) {
712     __ SaveFPRegs(sp, scratch);
713   }
714   const int argument_count = 1;
715   const int fp_argument_count = 0;
716
717   AllowExternalCallThatCantCauseGC scope(masm);
718   __ PrepareCallCFunction(argument_count, fp_argument_count, scratch);
719   __ mov(r0, Operand(ExternalReference::isolate_address(isolate())));
720   __ CallCFunction(
721       ExternalReference::store_buffer_overflow_function(isolate()),
722       argument_count);
723   if (save_doubles()) {
724     __ RestoreFPRegs(sp, scratch);
725   }
726   __ ldm(ia_w, sp, kCallerSaved | pc.bit());  // Also pop pc to get Ret(0).
727 }
728
729
730 void MathPowStub::Generate(MacroAssembler* masm) {
731   const Register base = r1;
732   const Register exponent = MathPowTaggedDescriptor::exponent();
733   DCHECK(exponent.is(r2));
734   const Register heapnumbermap = r5;
735   const Register heapnumber = r0;
736   const DwVfpRegister double_base = d0;
737   const DwVfpRegister double_exponent = d1;
738   const DwVfpRegister double_result = d2;
739   const DwVfpRegister double_scratch = d3;
740   const SwVfpRegister single_scratch = s6;
741   const Register scratch = r9;
742   const Register scratch2 = r4;
743
744   Label call_runtime, done, int_exponent;
745   if (exponent_type() == ON_STACK) {
746     Label base_is_smi, unpack_exponent;
747     // The exponent and base are supplied as arguments on the stack.
748     // This can only happen if the stub is called from non-optimized code.
749     // Load input parameters from stack to double registers.
750     __ ldr(base, MemOperand(sp, 1 * kPointerSize));
751     __ ldr(exponent, MemOperand(sp, 0 * kPointerSize));
752
753     __ LoadRoot(heapnumbermap, Heap::kHeapNumberMapRootIndex);
754
755     __ UntagAndJumpIfSmi(scratch, base, &base_is_smi);
756     __ ldr(scratch, FieldMemOperand(base, JSObject::kMapOffset));
757     __ cmp(scratch, heapnumbermap);
758     __ b(ne, &call_runtime);
759
760     __ vldr(double_base, FieldMemOperand(base, HeapNumber::kValueOffset));
761     __ jmp(&unpack_exponent);
762
763     __ bind(&base_is_smi);
764     __ vmov(single_scratch, scratch);
765     __ vcvt_f64_s32(double_base, single_scratch);
766     __ bind(&unpack_exponent);
767
768     __ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
769
770     __ ldr(scratch, FieldMemOperand(exponent, JSObject::kMapOffset));
771     __ cmp(scratch, heapnumbermap);
772     __ b(ne, &call_runtime);
773     __ vldr(double_exponent,
774             FieldMemOperand(exponent, HeapNumber::kValueOffset));
775   } else if (exponent_type() == TAGGED) {
776     // Base is already in double_base.
777     __ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
778
779     __ vldr(double_exponent,
780             FieldMemOperand(exponent, HeapNumber::kValueOffset));
781   }
782
783   if (exponent_type() != INTEGER) {
784     Label int_exponent_convert;
785     // Detect integer exponents stored as double.
786     __ vcvt_u32_f64(single_scratch, double_exponent);
787     // We do not check for NaN or Infinity here because comparing numbers on
788     // ARM correctly distinguishes NaNs.  We end up calling the built-in.
789     __ vcvt_f64_u32(double_scratch, single_scratch);
790     __ VFPCompareAndSetFlags(double_scratch, double_exponent);
791     __ b(eq, &int_exponent_convert);
792
793     if (exponent_type() == ON_STACK) {
794       // Detect square root case.  Crankshaft detects constant +/-0.5 at
795       // compile time and uses DoMathPowHalf instead.  We then skip this check
796       // for non-constant cases of +/-0.5 as these hardly occur.
797       Label not_plus_half;
798
799       // Test for 0.5.
800       __ vmov(double_scratch, 0.5, scratch);
801       __ VFPCompareAndSetFlags(double_exponent, double_scratch);
802       __ b(ne, &not_plus_half);
803
804       // Calculates square root of base.  Check for the special case of
805       // Math.pow(-Infinity, 0.5) == Infinity (ECMA spec, 15.8.2.13).
806       __ vmov(double_scratch, -V8_INFINITY, scratch);
807       __ VFPCompareAndSetFlags(double_base, double_scratch);
808       __ vneg(double_result, double_scratch, eq);
809       __ b(eq, &done);
810
811       // Add +0 to convert -0 to +0.
812       __ vadd(double_scratch, double_base, kDoubleRegZero);
813       __ vsqrt(double_result, double_scratch);
814       __ jmp(&done);
815
816       __ bind(&not_plus_half);
817       __ vmov(double_scratch, -0.5, scratch);
818       __ VFPCompareAndSetFlags(double_exponent, double_scratch);
819       __ b(ne, &call_runtime);
820
821       // Calculates square root of base.  Check for the special case of
822       // Math.pow(-Infinity, -0.5) == 0 (ECMA spec, 15.8.2.13).
823       __ vmov(double_scratch, -V8_INFINITY, scratch);
824       __ VFPCompareAndSetFlags(double_base, double_scratch);
825       __ vmov(double_result, kDoubleRegZero, eq);
826       __ b(eq, &done);
827
828       // Add +0 to convert -0 to +0.
829       __ vadd(double_scratch, double_base, kDoubleRegZero);
830       __ vmov(double_result, 1.0, scratch);
831       __ vsqrt(double_scratch, double_scratch);
832       __ vdiv(double_result, double_result, double_scratch);
833       __ jmp(&done);
834     }
835
836     __ push(lr);
837     {
838       AllowExternalCallThatCantCauseGC scope(masm);
839       __ PrepareCallCFunction(0, 2, scratch);
840       __ MovToFloatParameters(double_base, double_exponent);
841       __ CallCFunction(
842           ExternalReference::power_double_double_function(isolate()),
843           0, 2);
844     }
845     __ pop(lr);
846     __ MovFromFloatResult(double_result);
847     __ jmp(&done);
848
849     __ bind(&int_exponent_convert);
850     __ vcvt_u32_f64(single_scratch, double_exponent);
851     __ vmov(scratch, single_scratch);
852   }
853
854   // Calculate power with integer exponent.
855   __ bind(&int_exponent);
856
857   // Get two copies of exponent in the registers scratch and exponent.
858   if (exponent_type() == INTEGER) {
859     __ mov(scratch, exponent);
860   } else {
861     // Exponent has previously been stored into scratch as untagged integer.
862     __ mov(exponent, scratch);
863   }
864   __ vmov(double_scratch, double_base);  // Back up base.
865   __ vmov(double_result, 1.0, scratch2);
866
867   // Get absolute value of exponent.
868   __ cmp(scratch, Operand::Zero());
869   __ mov(scratch2, Operand::Zero(), LeaveCC, mi);
870   __ sub(scratch, scratch2, scratch, LeaveCC, mi);
871
872   Label while_true;
873   __ bind(&while_true);
874   __ mov(scratch, Operand(scratch, ASR, 1), SetCC);
875   __ vmul(double_result, double_result, double_scratch, cs);
876   __ vmul(double_scratch, double_scratch, double_scratch, ne);
877   __ b(ne, &while_true);
878
879   __ cmp(exponent, Operand::Zero());
880   __ b(ge, &done);
881   __ vmov(double_scratch, 1.0, scratch);
882   __ vdiv(double_result, double_scratch, double_result);
883   // Test whether result is zero.  Bail out to check for subnormal result.
884   // Due to subnormals, x^-y == (1/x)^y does not hold in all cases.
885   __ VFPCompareAndSetFlags(double_result, 0.0);
886   __ b(ne, &done);
887   // double_exponent may not containe the exponent value if the input was a
888   // smi.  We set it with exponent value before bailing out.
889   __ vmov(single_scratch, exponent);
890   __ vcvt_f64_s32(double_exponent, single_scratch);
891
892   // Returning or bailing out.
893   Counters* counters = isolate()->counters();
894   if (exponent_type() == ON_STACK) {
895     // The arguments are still on the stack.
896     __ bind(&call_runtime);
897     __ TailCallRuntime(Runtime::kMathPowRT, 2, 1);
898
899     // The stub is called from non-optimized code, which expects the result
900     // as heap number in exponent.
901     __ bind(&done);
902     __ AllocateHeapNumber(
903         heapnumber, scratch, scratch2, heapnumbermap, &call_runtime);
904     __ vstr(double_result,
905             FieldMemOperand(heapnumber, HeapNumber::kValueOffset));
906     DCHECK(heapnumber.is(r0));
907     __ IncrementCounter(counters->math_pow(), 1, scratch, scratch2);
908     __ Ret(2);
909   } else {
910     __ push(lr);
911     {
912       AllowExternalCallThatCantCauseGC scope(masm);
913       __ PrepareCallCFunction(0, 2, scratch);
914       __ MovToFloatParameters(double_base, double_exponent);
915       __ CallCFunction(
916           ExternalReference::power_double_double_function(isolate()),
917           0, 2);
918     }
919     __ pop(lr);
920     __ MovFromFloatResult(double_result);
921
922     __ bind(&done);
923     __ IncrementCounter(counters->math_pow(), 1, scratch, scratch2);
924     __ Ret();
925   }
926 }
927
928
929 bool CEntryStub::NeedsImmovableCode() {
930   return true;
931 }
932
933
934 void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) {
935   CEntryStub::GenerateAheadOfTime(isolate);
936   StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(isolate);
937   StubFailureTrampolineStub::GenerateAheadOfTime(isolate);
938   ArrayConstructorStubBase::GenerateStubsAheadOfTime(isolate);
939   CreateAllocationSiteStub::GenerateAheadOfTime(isolate);
940   CreateWeakCellStub::GenerateAheadOfTime(isolate);
941   BinaryOpICStub::GenerateAheadOfTime(isolate);
942   BinaryOpICWithAllocationSiteStub::GenerateAheadOfTime(isolate);
943   StoreFastElementStub::GenerateAheadOfTime(isolate);
944   TypeofStub::GenerateAheadOfTime(isolate);
945 }
946
947
948 void CodeStub::GenerateFPStubs(Isolate* isolate) {
949   // Generate if not already in cache.
950   SaveFPRegsMode mode = kSaveFPRegs;
951   CEntryStub(isolate, 1, mode).GetCode();
952   StoreBufferOverflowStub(isolate, mode).GetCode();
953   isolate->set_fp_stubs_generated(true);
954 }
955
956
957 void CEntryStub::GenerateAheadOfTime(Isolate* isolate) {
958   CEntryStub stub(isolate, 1, kDontSaveFPRegs);
959   stub.GetCode();
960 }
961
962
963 void CEntryStub::Generate(MacroAssembler* masm) {
964   // Called from JavaScript; parameters are on stack as if calling JS function.
965   // r0: number of arguments including receiver
966   // r1: pointer to builtin function
967   // fp: frame pointer  (restored after C call)
968   // sp: stack pointer  (restored as callee's sp after C call)
969   // cp: current context  (C callee-saved)
970
971   ProfileEntryHookStub::MaybeCallEntryHook(masm);
972
973   __ mov(r5, Operand(r1));
974
975   // Compute the argv pointer in a callee-saved register.
976   __ add(r1, sp, Operand(r0, LSL, kPointerSizeLog2));
977   __ sub(r1, r1, Operand(kPointerSize));
978
979   // Enter the exit frame that transitions from JavaScript to C++.
980   FrameScope scope(masm, StackFrame::MANUAL);
981   __ EnterExitFrame(save_doubles());
982
983   // Store a copy of argc in callee-saved registers for later.
984   __ mov(r4, Operand(r0));
985
986   // r0, r4: number of arguments including receiver  (C callee-saved)
987   // r1: pointer to the first argument (C callee-saved)
988   // r5: pointer to builtin function  (C callee-saved)
989
990   // Result returned in r0 or r0+r1 by default.
991
992 #if V8_HOST_ARCH_ARM
993   int frame_alignment = MacroAssembler::ActivationFrameAlignment();
994   int frame_alignment_mask = frame_alignment - 1;
995   if (FLAG_debug_code) {
996     if (frame_alignment > kPointerSize) {
997       Label alignment_as_expected;
998       DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
999       __ tst(sp, Operand(frame_alignment_mask));
1000       __ b(eq, &alignment_as_expected);
1001       // Don't use Check here, as it will call Runtime_Abort re-entering here.
1002       __ stop("Unexpected alignment");
1003       __ bind(&alignment_as_expected);
1004     }
1005   }
1006 #endif
1007
1008   // Call C built-in.
1009   // r0 = argc, r1 = argv
1010   __ mov(r2, Operand(ExternalReference::isolate_address(isolate())));
1011
1012   // To let the GC traverse the return address of the exit frames, we need to
1013   // know where the return address is. The CEntryStub is unmovable, so
1014   // we can store the address on the stack to be able to find it again and
1015   // we never have to restore it, because it will not change.
1016   // Compute the return address in lr to return to after the jump below. Pc is
1017   // already at '+ 8' from the current instruction but return is after three
1018   // instructions so add another 4 to pc to get the return address.
1019   {
1020     // Prevent literal pool emission before return address.
1021     Assembler::BlockConstPoolScope block_const_pool(masm);
1022     __ add(lr, pc, Operand(4));
1023     __ str(lr, MemOperand(sp, 0));
1024     __ Call(r5);
1025   }
1026
1027   __ VFPEnsureFPSCRState(r2);
1028
1029   // Check result for exception sentinel.
1030   Label exception_returned;
1031   __ CompareRoot(r0, Heap::kExceptionRootIndex);
1032   __ b(eq, &exception_returned);
1033
1034   // Check that there is no pending exception, otherwise we
1035   // should have returned the exception sentinel.
1036   if (FLAG_debug_code) {
1037     Label okay;
1038     ExternalReference pending_exception_address(
1039         Isolate::kPendingExceptionAddress, isolate());
1040     __ mov(r2, Operand(pending_exception_address));
1041     __ ldr(r2, MemOperand(r2));
1042     __ CompareRoot(r2, Heap::kTheHoleValueRootIndex);
1043     // Cannot use check here as it attempts to generate call into runtime.
1044     __ b(eq, &okay);
1045     __ stop("Unexpected pending exception");
1046     __ bind(&okay);
1047   }
1048
1049   // Exit C frame and return.
1050   // r0:r1: result
1051   // sp: stack pointer
1052   // fp: frame pointer
1053   // Callee-saved register r4 still holds argc.
1054   __ LeaveExitFrame(save_doubles(), r4, true);
1055   __ mov(pc, lr);
1056
1057   // Handling of exception.
1058   __ bind(&exception_returned);
1059
1060   ExternalReference pending_handler_context_address(
1061       Isolate::kPendingHandlerContextAddress, isolate());
1062   ExternalReference pending_handler_code_address(
1063       Isolate::kPendingHandlerCodeAddress, isolate());
1064   ExternalReference pending_handler_offset_address(
1065       Isolate::kPendingHandlerOffsetAddress, isolate());
1066   ExternalReference pending_handler_fp_address(
1067       Isolate::kPendingHandlerFPAddress, isolate());
1068   ExternalReference pending_handler_sp_address(
1069       Isolate::kPendingHandlerSPAddress, isolate());
1070
1071   // Ask the runtime for help to determine the handler. This will set r0 to
1072   // contain the current pending exception, don't clobber it.
1073   ExternalReference find_handler(Runtime::kUnwindAndFindExceptionHandler,
1074                                  isolate());
1075   {
1076     FrameScope scope(masm, StackFrame::MANUAL);
1077     __ PrepareCallCFunction(3, 0, r0);
1078     __ mov(r0, Operand(0));
1079     __ mov(r1, Operand(0));
1080     __ mov(r2, Operand(ExternalReference::isolate_address(isolate())));
1081     __ CallCFunction(find_handler, 3);
1082   }
1083
1084   // Retrieve the handler context, SP and FP.
1085   __ mov(cp, Operand(pending_handler_context_address));
1086   __ ldr(cp, MemOperand(cp));
1087   __ mov(sp, Operand(pending_handler_sp_address));
1088   __ ldr(sp, MemOperand(sp));
1089   __ mov(fp, Operand(pending_handler_fp_address));
1090   __ ldr(fp, MemOperand(fp));
1091
1092   // If the handler is a JS frame, restore the context to the frame. Note that
1093   // the context will be set to (cp == 0) for non-JS frames.
1094   __ cmp(cp, Operand(0));
1095   __ str(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
1096
1097   // Compute the handler entry address and jump to it.
1098   ConstantPoolUnavailableScope constant_pool_unavailable(masm);
1099   __ mov(r1, Operand(pending_handler_code_address));
1100   __ ldr(r1, MemOperand(r1));
1101   __ mov(r2, Operand(pending_handler_offset_address));
1102   __ ldr(r2, MemOperand(r2));
1103   if (FLAG_enable_embedded_constant_pool) {
1104     __ LoadConstantPoolPointerRegisterFromCodeTargetAddress(r1);
1105   }
1106   __ add(r1, r1, Operand(Code::kHeaderSize - kHeapObjectTag));
1107   __ add(pc, r1, r2);
1108 }
1109
1110
1111 void JSEntryStub::Generate(MacroAssembler* masm) {
1112   // r0: code entry
1113   // r1: function
1114   // r2: receiver
1115   // r3: argc
1116   // [sp+0]: argv
1117
1118   Label invoke, handler_entry, exit;
1119
1120   ProfileEntryHookStub::MaybeCallEntryHook(masm);
1121
1122   // Called from C, so do not pop argc and args on exit (preserve sp)
1123   // No need to save register-passed args
1124   // Save callee-saved registers (incl. cp and fp), sp, and lr
1125   __ stm(db_w, sp, kCalleeSaved | lr.bit());
1126
1127   // Save callee-saved vfp registers.
1128   __ vstm(db_w, sp, kFirstCalleeSavedDoubleReg, kLastCalleeSavedDoubleReg);
1129   // Set up the reserved register for 0.0.
1130   __ vmov(kDoubleRegZero, 0.0);
1131   __ VFPEnsureFPSCRState(r4);
1132
1133   // Get address of argv, see stm above.
1134   // r0: code entry
1135   // r1: function
1136   // r2: receiver
1137   // r3: argc
1138
1139   // Set up argv in r4.
1140   int offset_to_argv = (kNumCalleeSaved + 1) * kPointerSize;
1141   offset_to_argv += kNumDoubleCalleeSaved * kDoubleSize;
1142   __ ldr(r4, MemOperand(sp, offset_to_argv));
1143
1144   // Push a frame with special values setup to mark it as an entry frame.
1145   // r0: code entry
1146   // r1: function
1147   // r2: receiver
1148   // r3: argc
1149   // r4: argv
1150   int marker = type();
1151   if (FLAG_enable_embedded_constant_pool) {
1152     __ mov(r8, Operand::Zero());
1153   }
1154   __ mov(r7, Operand(Smi::FromInt(marker)));
1155   __ mov(r6, Operand(Smi::FromInt(marker)));
1156   __ mov(r5,
1157          Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
1158   __ ldr(r5, MemOperand(r5));
1159   __ mov(ip, Operand(-1));  // Push a bad frame pointer to fail if it is used.
1160   __ stm(db_w, sp, r5.bit() | r6.bit() | r7.bit() |
1161                        (FLAG_enable_embedded_constant_pool ? r8.bit() : 0) |
1162                        ip.bit());
1163
1164   // Set up frame pointer for the frame to be pushed.
1165   __ add(fp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
1166
1167   // If this is the outermost JS call, set js_entry_sp value.
1168   Label non_outermost_js;
1169   ExternalReference js_entry_sp(Isolate::kJSEntrySPAddress, isolate());
1170   __ mov(r5, Operand(ExternalReference(js_entry_sp)));
1171   __ ldr(r6, MemOperand(r5));
1172   __ cmp(r6, Operand::Zero());
1173   __ b(ne, &non_outermost_js);
1174   __ str(fp, MemOperand(r5));
1175   __ mov(ip, Operand(Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME)));
1176   Label cont;
1177   __ b(&cont);
1178   __ bind(&non_outermost_js);
1179   __ mov(ip, Operand(Smi::FromInt(StackFrame::INNER_JSENTRY_FRAME)));
1180   __ bind(&cont);
1181   __ push(ip);
1182
1183   // Jump to a faked try block that does the invoke, with a faked catch
1184   // block that sets the pending exception.
1185   __ jmp(&invoke);
1186
1187   // Block literal pool emission whilst taking the position of the handler
1188   // entry. This avoids making the assumption that literal pools are always
1189   // emitted after an instruction is emitted, rather than before.
1190   {
1191     Assembler::BlockConstPoolScope block_const_pool(masm);
1192     __ bind(&handler_entry);
1193     handler_offset_ = handler_entry.pos();
1194     // Caught exception: Store result (exception) in the pending exception
1195     // field in the JSEnv and return a failure sentinel.  Coming in here the
1196     // fp will be invalid because the PushStackHandler below sets it to 0 to
1197     // signal the existence of the JSEntry frame.
1198     __ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
1199                                          isolate())));
1200   }
1201   __ str(r0, MemOperand(ip));
1202   __ LoadRoot(r0, Heap::kExceptionRootIndex);
1203   __ b(&exit);
1204
1205   // Invoke: Link this frame into the handler chain.
1206   __ bind(&invoke);
1207   // Must preserve r0-r4, r5-r6 are available.
1208   __ PushStackHandler();
1209   // If an exception not caught by another handler occurs, this handler
1210   // returns control to the code after the bl(&invoke) above, which
1211   // restores all kCalleeSaved registers (including cp and fp) to their
1212   // saved values before returning a failure to C.
1213
1214   // Clear any pending exceptions.
1215   __ mov(r5, Operand(isolate()->factory()->the_hole_value()));
1216   __ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
1217                                        isolate())));
1218   __ str(r5, MemOperand(ip));
1219
1220   // Invoke the function by calling through JS entry trampoline builtin.
1221   // Notice that we cannot store a reference to the trampoline code directly in
1222   // this stub, because runtime stubs are not traversed when doing GC.
1223
1224   // Expected registers by Builtins::JSEntryTrampoline
1225   // r0: code entry
1226   // r1: function
1227   // r2: receiver
1228   // r3: argc
1229   // r4: argv
1230   if (type() == StackFrame::ENTRY_CONSTRUCT) {
1231     ExternalReference construct_entry(Builtins::kJSConstructEntryTrampoline,
1232                                       isolate());
1233     __ mov(ip, Operand(construct_entry));
1234   } else {
1235     ExternalReference entry(Builtins::kJSEntryTrampoline, isolate());
1236     __ mov(ip, Operand(entry));
1237   }
1238   __ ldr(ip, MemOperand(ip));  // deref address
1239   __ add(ip, ip, Operand(Code::kHeaderSize - kHeapObjectTag));
1240
1241   // Branch and link to JSEntryTrampoline.
1242   __ Call(ip);
1243
1244   // Unlink this frame from the handler chain.
1245   __ PopStackHandler();
1246
1247   __ bind(&exit);  // r0 holds result
1248   // Check if the current stack frame is marked as the outermost JS frame.
1249   Label non_outermost_js_2;
1250   __ pop(r5);
1251   __ cmp(r5, Operand(Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME)));
1252   __ b(ne, &non_outermost_js_2);
1253   __ mov(r6, Operand::Zero());
1254   __ mov(r5, Operand(ExternalReference(js_entry_sp)));
1255   __ str(r6, MemOperand(r5));
1256   __ bind(&non_outermost_js_2);
1257
1258   // Restore the top frame descriptors from the stack.
1259   __ pop(r3);
1260   __ mov(ip,
1261          Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
1262   __ str(r3, MemOperand(ip));
1263
1264   // Reset the stack to the callee saved registers.
1265   __ add(sp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
1266
1267   // Restore callee-saved registers and return.
1268 #ifdef DEBUG
1269   if (FLAG_debug_code) {
1270     __ mov(lr, Operand(pc));
1271   }
1272 #endif
1273
1274   // Restore callee-saved vfp registers.
1275   __ vldm(ia_w, sp, kFirstCalleeSavedDoubleReg, kLastCalleeSavedDoubleReg);
1276
1277   __ ldm(ia_w, sp, kCalleeSaved | pc.bit());
1278 }
1279
1280
1281 // Uses registers r0 to r4.
1282 // Expected input (depending on whether args are in registers or on the stack):
1283 // * object: r0 or at sp + 1 * kPointerSize.
1284 // * function: r1 or at sp.
1285 //
1286 // An inlined call site may have been generated before calling this stub.
1287 // In this case the offset to the inline sites to patch are passed in r5 and r6.
1288 // (See LCodeGen::DoInstanceOfKnownGlobal)
1289 void InstanceofStub::Generate(MacroAssembler* masm) {
1290   // Call site inlining and patching implies arguments in registers.
1291   DCHECK(HasArgsInRegisters() || !HasCallSiteInlineCheck());
1292
1293   // Fixed register usage throughout the stub:
1294   const Register object = r0;  // Object (lhs).
1295   Register map = r3;  // Map of the object.
1296   const Register function = r1;  // Function (rhs).
1297   const Register prototype = r4;  // Prototype of the function.
1298   const Register scratch = r2;
1299
1300   Label slow, loop, is_instance, is_not_instance, not_js_object;
1301
1302   if (!HasArgsInRegisters()) {
1303     __ ldr(object, MemOperand(sp, 1 * kPointerSize));
1304     __ ldr(function, MemOperand(sp, 0));
1305   }
1306
1307   // Check that the left hand is a JS object and load map.
1308   __ JumpIfSmi(object, &not_js_object);
1309   __ IsObjectJSObjectType(object, map, scratch, &not_js_object);
1310
1311   // If there is a call site cache don't look in the global cache, but do the
1312   // real lookup and update the call site cache.
1313   if (!HasCallSiteInlineCheck() && !ReturnTrueFalseObject()) {
1314     Label miss;
1315     __ CompareRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
1316     __ b(ne, &miss);
1317     __ CompareRoot(map, Heap::kInstanceofCacheMapRootIndex);
1318     __ b(ne, &miss);
1319     __ LoadRoot(r0, Heap::kInstanceofCacheAnswerRootIndex);
1320     __ Ret(HasArgsInRegisters() ? 0 : 2);
1321
1322     __ bind(&miss);
1323   }
1324
1325   // Get the prototype of the function.
1326   __ TryGetFunctionPrototype(function, prototype, scratch, &slow, true);
1327
1328   // Check that the function prototype is a JS object.
1329   __ JumpIfSmi(prototype, &slow);
1330   __ IsObjectJSObjectType(prototype, scratch, scratch, &slow);
1331
1332   // Update the global instanceof or call site inlined cache with the current
1333   // map and function. The cached answer will be set when it is known below.
1334   if (!HasCallSiteInlineCheck()) {
1335     __ StoreRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
1336     __ StoreRoot(map, Heap::kInstanceofCacheMapRootIndex);
1337   } else {
1338     DCHECK(HasArgsInRegisters());
1339     // Patch the (relocated) inlined map check.
1340
1341     // The map_load_offset was stored in r5
1342     //   (See LCodeGen::DoDeferredLInstanceOfKnownGlobal).
1343     const Register map_load_offset = r5;
1344     __ sub(r9, lr, map_load_offset);
1345     // Get the map location in r5 and patch it.
1346     __ GetRelocatedValueLocation(r9, map_load_offset, scratch);
1347     __ ldr(map_load_offset, MemOperand(map_load_offset));
1348     __ str(map, FieldMemOperand(map_load_offset, Cell::kValueOffset));
1349
1350     __ mov(r8, map);
1351     // |map_load_offset| points at the beginning of the cell. Calculate the
1352     // field containing the map.
1353     __ add(function, map_load_offset, Operand(Cell::kValueOffset - 1));
1354     __ RecordWriteField(map_load_offset, Cell::kValueOffset, r8, function,
1355                         kLRHasNotBeenSaved, kDontSaveFPRegs,
1356                         OMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
1357   }
1358
1359   // Register mapping: r3 is object map and r4 is function prototype.
1360   // Get prototype of object into r2.
1361   __ ldr(scratch, FieldMemOperand(map, Map::kPrototypeOffset));
1362
1363   // We don't need map any more. Use it as a scratch register.
1364   Register scratch2 = map;
1365   map = no_reg;
1366
1367   // Loop through the prototype chain looking for the function prototype.
1368   __ LoadRoot(scratch2, Heap::kNullValueRootIndex);
1369   __ bind(&loop);
1370   __ cmp(scratch, Operand(prototype));
1371   __ b(eq, &is_instance);
1372   __ cmp(scratch, scratch2);
1373   __ b(eq, &is_not_instance);
1374   __ ldr(scratch, FieldMemOperand(scratch, HeapObject::kMapOffset));
1375   __ ldr(scratch, FieldMemOperand(scratch, Map::kPrototypeOffset));
1376   __ jmp(&loop);
1377   Factory* factory = isolate()->factory();
1378
1379   __ bind(&is_instance);
1380   if (!HasCallSiteInlineCheck()) {
1381     __ mov(r0, Operand(Smi::FromInt(0)));
1382     __ StoreRoot(r0, Heap::kInstanceofCacheAnswerRootIndex);
1383     if (ReturnTrueFalseObject()) {
1384       __ Move(r0, factory->true_value());
1385     }
1386   } else {
1387     // Patch the call site to return true.
1388     __ LoadRoot(r0, Heap::kTrueValueRootIndex);
1389     // The bool_load_offset was stored in r6
1390     //   (See LCodeGen::DoDeferredLInstanceOfKnownGlobal).
1391     const Register bool_load_offset = r6;
1392     __ sub(r9, lr, bool_load_offset);
1393     // Get the boolean result location in scratch and patch it.
1394     __ GetRelocatedValueLocation(r9, scratch, scratch2);
1395     __ str(r0, MemOperand(scratch));
1396
1397     if (!ReturnTrueFalseObject()) {
1398       __ mov(r0, Operand(Smi::FromInt(0)));
1399     }
1400   }
1401   __ Ret(HasArgsInRegisters() ? 0 : 2);
1402
1403   __ bind(&is_not_instance);
1404   if (!HasCallSiteInlineCheck()) {
1405     __ mov(r0, Operand(Smi::FromInt(1)));
1406     __ StoreRoot(r0, Heap::kInstanceofCacheAnswerRootIndex);
1407     if (ReturnTrueFalseObject()) {
1408       __ Move(r0, factory->false_value());
1409     }
1410   } else {
1411     // Patch the call site to return false.
1412     __ LoadRoot(r0, Heap::kFalseValueRootIndex);
1413     // The bool_load_offset was stored in r6
1414     //   (See LCodeGen::DoDeferredLInstanceOfKnownGlobal).
1415     const Register bool_load_offset = r6;
1416     __ sub(r9, lr, bool_load_offset);
1417     ;
1418     // Get the boolean result location in scratch and patch it.
1419     __ GetRelocatedValueLocation(r9, scratch, scratch2);
1420     __ str(r0, MemOperand(scratch));
1421
1422     if (!ReturnTrueFalseObject()) {
1423       __ mov(r0, Operand(Smi::FromInt(1)));
1424     }
1425   }
1426   __ Ret(HasArgsInRegisters() ? 0 : 2);
1427
1428   Label object_not_null, object_not_null_or_smi;
1429   __ bind(&not_js_object);
1430   // Before null, smi and string value checks, check that the rhs is a function
1431   // as for a non-function rhs an exception needs to be thrown.
1432   __ JumpIfSmi(function, &slow);
1433   __ CompareObjectType(function, scratch2, scratch, JS_FUNCTION_TYPE);
1434   __ b(ne, &slow);
1435
1436   // Null is not instance of anything.
1437   __ cmp(object, Operand(isolate()->factory()->null_value()));
1438   __ b(ne, &object_not_null);
1439   if (ReturnTrueFalseObject()) {
1440     __ Move(r0, factory->false_value());
1441   } else {
1442     __ mov(r0, Operand(Smi::FromInt(1)));
1443   }
1444   __ Ret(HasArgsInRegisters() ? 0 : 2);
1445
1446   __ bind(&object_not_null);
1447   // Smi values are not instances of anything.
1448   __ JumpIfNotSmi(object, &object_not_null_or_smi);
1449   if (ReturnTrueFalseObject()) {
1450     __ Move(r0, factory->false_value());
1451   } else {
1452     __ mov(r0, Operand(Smi::FromInt(1)));
1453   }
1454   __ Ret(HasArgsInRegisters() ? 0 : 2);
1455
1456   __ bind(&object_not_null_or_smi);
1457   // String values are not instances of anything.
1458   __ IsObjectJSStringType(object, scratch, &slow);
1459   if (ReturnTrueFalseObject()) {
1460     __ Move(r0, factory->false_value());
1461   } else {
1462     __ mov(r0, Operand(Smi::FromInt(1)));
1463   }
1464   __ Ret(HasArgsInRegisters() ? 0 : 2);
1465
1466   // Slow-case.  Tail call builtin.
1467   __ bind(&slow);
1468   if (!ReturnTrueFalseObject()) {
1469     if (HasArgsInRegisters()) {
1470       __ Push(r0, r1);
1471     }
1472   __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
1473   } else {
1474     {
1475       FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
1476       __ Push(r0, r1);
1477       __ InvokeBuiltin(Builtins::INSTANCE_OF, CALL_FUNCTION);
1478     }
1479     __ cmp(r0, Operand::Zero());
1480     __ LoadRoot(r0, Heap::kTrueValueRootIndex, eq);
1481     __ LoadRoot(r0, Heap::kFalseValueRootIndex, ne);
1482     __ Ret(HasArgsInRegisters() ? 0 : 2);
1483   }
1484 }
1485
1486
1487 void FunctionPrototypeStub::Generate(MacroAssembler* masm) {
1488   Label miss;
1489   Register receiver = LoadDescriptor::ReceiverRegister();
1490   // Ensure that the vector and slot registers won't be clobbered before
1491   // calling the miss handler.
1492   DCHECK(!AreAliased(r4, r5, LoadWithVectorDescriptor::VectorRegister(),
1493                      LoadWithVectorDescriptor::SlotRegister()));
1494
1495   NamedLoadHandlerCompiler::GenerateLoadFunctionPrototype(masm, receiver, r4,
1496                                                           r5, &miss);
1497   __ bind(&miss);
1498   PropertyAccessCompiler::TailCallBuiltin(
1499       masm, PropertyAccessCompiler::MissBuiltin(Code::LOAD_IC));
1500 }
1501
1502
1503 void LoadIndexedStringStub::Generate(MacroAssembler* masm) {
1504   // Return address is in lr.
1505   Label miss;
1506
1507   Register receiver = LoadDescriptor::ReceiverRegister();
1508   Register index = LoadDescriptor::NameRegister();
1509   Register scratch = r5;
1510   Register result = r0;
1511   DCHECK(!scratch.is(receiver) && !scratch.is(index));
1512   DCHECK(!scratch.is(LoadWithVectorDescriptor::VectorRegister()) &&
1513          result.is(LoadWithVectorDescriptor::SlotRegister()));
1514
1515   // StringCharAtGenerator doesn't use the result register until it's passed
1516   // the different miss possibilities. If it did, we would have a conflict
1517   // when FLAG_vector_ics is true.
1518   StringCharAtGenerator char_at_generator(receiver, index, scratch, result,
1519                                           &miss,  // When not a string.
1520                                           &miss,  // When not a number.
1521                                           &miss,  // When index out of range.
1522                                           STRING_INDEX_IS_ARRAY_INDEX,
1523                                           RECEIVER_IS_STRING);
1524   char_at_generator.GenerateFast(masm);
1525   __ Ret();
1526
1527   StubRuntimeCallHelper call_helper;
1528   char_at_generator.GenerateSlow(masm, PART_OF_IC_HANDLER, call_helper);
1529
1530   __ bind(&miss);
1531   PropertyAccessCompiler::TailCallBuiltin(
1532       masm, PropertyAccessCompiler::MissBuiltin(Code::KEYED_LOAD_IC));
1533 }
1534
1535
1536 void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
1537   CHECK(!has_new_target());
1538   // The displacement is the offset of the last parameter (if any)
1539   // relative to the frame pointer.
1540   const int kDisplacement =
1541       StandardFrameConstants::kCallerSPOffset - kPointerSize;
1542   DCHECK(r1.is(ArgumentsAccessReadDescriptor::index()));
1543   DCHECK(r0.is(ArgumentsAccessReadDescriptor::parameter_count()));
1544
1545   // Check that the key is a smi.
1546   Label slow;
1547   __ JumpIfNotSmi(r1, &slow);
1548
1549   // Check if the calling frame is an arguments adaptor frame.
1550   Label adaptor;
1551   __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1552   __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
1553   __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1554   __ b(eq, &adaptor);
1555
1556   // Check index against formal parameters count limit passed in
1557   // through register r0. Use unsigned comparison to get negative
1558   // check for free.
1559   __ cmp(r1, r0);
1560   __ b(hs, &slow);
1561
1562   // Read the argument from the stack and return it.
1563   __ sub(r3, r0, r1);
1564   __ add(r3, fp, Operand::PointerOffsetFromSmiKey(r3));
1565   __ ldr(r0, MemOperand(r3, kDisplacement));
1566   __ Jump(lr);
1567
1568   // Arguments adaptor case: Check index against actual arguments
1569   // limit found in the arguments adaptor frame. Use unsigned
1570   // comparison to get negative check for free.
1571   __ bind(&adaptor);
1572   __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
1573   __ cmp(r1, r0);
1574   __ b(cs, &slow);
1575
1576   // Read the argument from the adaptor frame and return it.
1577   __ sub(r3, r0, r1);
1578   __ add(r3, r2, Operand::PointerOffsetFromSmiKey(r3));
1579   __ ldr(r0, MemOperand(r3, kDisplacement));
1580   __ Jump(lr);
1581
1582   // Slow-case: Handle non-smi or out-of-bounds access to arguments
1583   // by calling the runtime system.
1584   __ bind(&slow);
1585   __ push(r1);
1586   __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
1587 }
1588
1589
1590 void ArgumentsAccessStub::GenerateNewSloppySlow(MacroAssembler* masm) {
1591   // sp[0] : number of parameters
1592   // sp[4] : receiver displacement
1593   // sp[8] : function
1594
1595   CHECK(!has_new_target());
1596
1597   // Check if the calling frame is an arguments adaptor frame.
1598   Label runtime;
1599   __ ldr(r3, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1600   __ ldr(r2, MemOperand(r3, StandardFrameConstants::kContextOffset));
1601   __ cmp(r2, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1602   __ b(ne, &runtime);
1603
1604   // Patch the arguments.length and the parameters pointer in the current frame.
1605   __ ldr(r2, MemOperand(r3, ArgumentsAdaptorFrameConstants::kLengthOffset));
1606   __ str(r2, MemOperand(sp, 0 * kPointerSize));
1607   __ add(r3, r3, Operand(r2, LSL, 1));
1608   __ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
1609   __ str(r3, MemOperand(sp, 1 * kPointerSize));
1610
1611   __ bind(&runtime);
1612   __ TailCallRuntime(Runtime::kNewSloppyArguments, 3, 1);
1613 }
1614
1615
1616 void ArgumentsAccessStub::GenerateNewSloppyFast(MacroAssembler* masm) {
1617   // Stack layout:
1618   //  sp[0] : number of parameters (tagged)
1619   //  sp[4] : address of receiver argument
1620   //  sp[8] : function
1621   // Registers used over whole function:
1622   //  r6 : allocated object (tagged)
1623   //  r9 : mapped parameter count (tagged)
1624
1625   CHECK(!has_new_target());
1626
1627   __ ldr(r1, MemOperand(sp, 0 * kPointerSize));
1628   // r1 = parameter count (tagged)
1629
1630   // Check if the calling frame is an arguments adaptor frame.
1631   Label runtime;
1632   Label adaptor_frame, try_allocate;
1633   __ ldr(r3, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1634   __ ldr(r2, MemOperand(r3, StandardFrameConstants::kContextOffset));
1635   __ cmp(r2, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1636   __ b(eq, &adaptor_frame);
1637
1638   // No adaptor, parameter count = argument count.
1639   __ mov(r2, r1);
1640   __ b(&try_allocate);
1641
1642   // We have an adaptor frame. Patch the parameters pointer.
1643   __ bind(&adaptor_frame);
1644   __ ldr(r2, MemOperand(r3, ArgumentsAdaptorFrameConstants::kLengthOffset));
1645   __ add(r3, r3, Operand(r2, LSL, 1));
1646   __ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
1647   __ str(r3, MemOperand(sp, 1 * kPointerSize));
1648
1649   // r1 = parameter count (tagged)
1650   // r2 = argument count (tagged)
1651   // Compute the mapped parameter count = min(r1, r2) in r1.
1652   __ cmp(r1, Operand(r2));
1653   __ mov(r1, Operand(r2), LeaveCC, gt);
1654
1655   __ bind(&try_allocate);
1656
1657   // Compute the sizes of backing store, parameter map, and arguments object.
1658   // 1. Parameter map, has 2 extra words containing context and backing store.
1659   const int kParameterMapHeaderSize =
1660       FixedArray::kHeaderSize + 2 * kPointerSize;
1661   // If there are no mapped parameters, we do not need the parameter_map.
1662   __ cmp(r1, Operand(Smi::FromInt(0)));
1663   __ mov(r9, Operand::Zero(), LeaveCC, eq);
1664   __ mov(r9, Operand(r1, LSL, 1), LeaveCC, ne);
1665   __ add(r9, r9, Operand(kParameterMapHeaderSize), LeaveCC, ne);
1666
1667   // 2. Backing store.
1668   __ add(r9, r9, Operand(r2, LSL, 1));
1669   __ add(r9, r9, Operand(FixedArray::kHeaderSize));
1670
1671   // 3. Arguments object.
1672   __ add(r9, r9, Operand(Heap::kSloppyArgumentsObjectSize));
1673
1674   // Do the allocation of all three objects in one go.
1675   __ Allocate(r9, r0, r3, r4, &runtime, TAG_OBJECT);
1676
1677   // r0 = address of new object(s) (tagged)
1678   // r2 = argument count (smi-tagged)
1679   // Get the arguments boilerplate from the current native context into r4.
1680   const int kNormalOffset =
1681       Context::SlotOffset(Context::SLOPPY_ARGUMENTS_MAP_INDEX);
1682   const int kAliasedOffset =
1683       Context::SlotOffset(Context::ALIASED_ARGUMENTS_MAP_INDEX);
1684
1685   __ ldr(r4, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
1686   __ ldr(r4, FieldMemOperand(r4, GlobalObject::kNativeContextOffset));
1687   __ cmp(r1, Operand::Zero());
1688   __ ldr(r4, MemOperand(r4, kNormalOffset), eq);
1689   __ ldr(r4, MemOperand(r4, kAliasedOffset), ne);
1690
1691   // r0 = address of new object (tagged)
1692   // r1 = mapped parameter count (tagged)
1693   // r2 = argument count (smi-tagged)
1694   // r4 = address of arguments map (tagged)
1695   __ str(r4, FieldMemOperand(r0, JSObject::kMapOffset));
1696   __ LoadRoot(r3, Heap::kEmptyFixedArrayRootIndex);
1697   __ str(r3, FieldMemOperand(r0, JSObject::kPropertiesOffset));
1698   __ str(r3, FieldMemOperand(r0, JSObject::kElementsOffset));
1699
1700   // Set up the callee in-object property.
1701   STATIC_ASSERT(Heap::kArgumentsCalleeIndex == 1);
1702   __ ldr(r3, MemOperand(sp, 2 * kPointerSize));
1703   __ AssertNotSmi(r3);
1704   const int kCalleeOffset = JSObject::kHeaderSize +
1705       Heap::kArgumentsCalleeIndex * kPointerSize;
1706   __ str(r3, FieldMemOperand(r0, kCalleeOffset));
1707
1708   // Use the length (smi tagged) and set that as an in-object property too.
1709   __ AssertSmi(r2);
1710   STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0);
1711   const int kLengthOffset = JSObject::kHeaderSize +
1712       Heap::kArgumentsLengthIndex * kPointerSize;
1713   __ str(r2, FieldMemOperand(r0, kLengthOffset));
1714
1715   // Set up the elements pointer in the allocated arguments object.
1716   // If we allocated a parameter map, r4 will point there, otherwise
1717   // it will point to the backing store.
1718   __ add(r4, r0, Operand(Heap::kSloppyArgumentsObjectSize));
1719   __ str(r4, FieldMemOperand(r0, JSObject::kElementsOffset));
1720
1721   // r0 = address of new object (tagged)
1722   // r1 = mapped parameter count (tagged)
1723   // r2 = argument count (tagged)
1724   // r4 = address of parameter map or backing store (tagged)
1725   // Initialize parameter map. If there are no mapped arguments, we're done.
1726   Label skip_parameter_map;
1727   __ cmp(r1, Operand(Smi::FromInt(0)));
1728   // Move backing store address to r3, because it is
1729   // expected there when filling in the unmapped arguments.
1730   __ mov(r3, r4, LeaveCC, eq);
1731   __ b(eq, &skip_parameter_map);
1732
1733   __ LoadRoot(r6, Heap::kSloppyArgumentsElementsMapRootIndex);
1734   __ str(r6, FieldMemOperand(r4, FixedArray::kMapOffset));
1735   __ add(r6, r1, Operand(Smi::FromInt(2)));
1736   __ str(r6, FieldMemOperand(r4, FixedArray::kLengthOffset));
1737   __ str(cp, FieldMemOperand(r4, FixedArray::kHeaderSize + 0 * kPointerSize));
1738   __ add(r6, r4, Operand(r1, LSL, 1));
1739   __ add(r6, r6, Operand(kParameterMapHeaderSize));
1740   __ str(r6, FieldMemOperand(r4, FixedArray::kHeaderSize + 1 * kPointerSize));
1741
1742   // Copy the parameter slots and the holes in the arguments.
1743   // We need to fill in mapped_parameter_count slots. They index the context,
1744   // where parameters are stored in reverse order, at
1745   //   MIN_CONTEXT_SLOTS .. MIN_CONTEXT_SLOTS+parameter_count-1
1746   // The mapped parameter thus need to get indices
1747   //   MIN_CONTEXT_SLOTS+parameter_count-1 ..
1748   //       MIN_CONTEXT_SLOTS+parameter_count-mapped_parameter_count
1749   // We loop from right to left.
1750   Label parameters_loop, parameters_test;
1751   __ mov(r6, r1);
1752   __ ldr(r9, MemOperand(sp, 0 * kPointerSize));
1753   __ add(r9, r9, Operand(Smi::FromInt(Context::MIN_CONTEXT_SLOTS)));
1754   __ sub(r9, r9, Operand(r1));
1755   __ LoadRoot(r5, Heap::kTheHoleValueRootIndex);
1756   __ add(r3, r4, Operand(r6, LSL, 1));
1757   __ add(r3, r3, Operand(kParameterMapHeaderSize));
1758
1759   // r6 = loop variable (tagged)
1760   // r1 = mapping index (tagged)
1761   // r3 = address of backing store (tagged)
1762   // r4 = address of parameter map (tagged), which is also the address of new
1763   //      object + Heap::kSloppyArgumentsObjectSize (tagged)
1764   // r0 = temporary scratch (a.o., for address calculation)
1765   // r5 = the hole value
1766   __ jmp(&parameters_test);
1767
1768   __ bind(&parameters_loop);
1769   __ sub(r6, r6, Operand(Smi::FromInt(1)));
1770   __ mov(r0, Operand(r6, LSL, 1));
1771   __ add(r0, r0, Operand(kParameterMapHeaderSize - kHeapObjectTag));
1772   __ str(r9, MemOperand(r4, r0));
1773   __ sub(r0, r0, Operand(kParameterMapHeaderSize - FixedArray::kHeaderSize));
1774   __ str(r5, MemOperand(r3, r0));
1775   __ add(r9, r9, Operand(Smi::FromInt(1)));
1776   __ bind(&parameters_test);
1777   __ cmp(r6, Operand(Smi::FromInt(0)));
1778   __ b(ne, &parameters_loop);
1779
1780   // Restore r0 = new object (tagged)
1781   __ sub(r0, r4, Operand(Heap::kSloppyArgumentsObjectSize));
1782
1783   __ bind(&skip_parameter_map);
1784   // r0 = address of new object (tagged)
1785   // r2 = argument count (tagged)
1786   // r3 = address of backing store (tagged)
1787   // r5 = scratch
1788   // Copy arguments header and remaining slots (if there are any).
1789   __ LoadRoot(r5, Heap::kFixedArrayMapRootIndex);
1790   __ str(r5, FieldMemOperand(r3, FixedArray::kMapOffset));
1791   __ str(r2, FieldMemOperand(r3, FixedArray::kLengthOffset));
1792
1793   Label arguments_loop, arguments_test;
1794   __ mov(r9, r1);
1795   __ ldr(r4, MemOperand(sp, 1 * kPointerSize));
1796   __ sub(r4, r4, Operand(r9, LSL, 1));
1797   __ jmp(&arguments_test);
1798
1799   __ bind(&arguments_loop);
1800   __ sub(r4, r4, Operand(kPointerSize));
1801   __ ldr(r6, MemOperand(r4, 0));
1802   __ add(r5, r3, Operand(r9, LSL, 1));
1803   __ str(r6, FieldMemOperand(r5, FixedArray::kHeaderSize));
1804   __ add(r9, r9, Operand(Smi::FromInt(1)));
1805
1806   __ bind(&arguments_test);
1807   __ cmp(r9, Operand(r2));
1808   __ b(lt, &arguments_loop);
1809
1810   // Return and remove the on-stack parameters.
1811   __ add(sp, sp, Operand(3 * kPointerSize));
1812   __ Ret();
1813
1814   // Do the runtime call to allocate the arguments object.
1815   // r0 = address of new object (tagged)
1816   // r2 = argument count (tagged)
1817   __ bind(&runtime);
1818   __ str(r2, MemOperand(sp, 0 * kPointerSize));  // Patch argument count.
1819   __ TailCallRuntime(Runtime::kNewSloppyArguments, 3, 1);
1820 }
1821
1822
1823 void LoadIndexedInterceptorStub::Generate(MacroAssembler* masm) {
1824   // Return address is in lr.
1825   Label slow;
1826
1827   Register receiver = LoadDescriptor::ReceiverRegister();
1828   Register key = LoadDescriptor::NameRegister();
1829
1830   // Check that the key is an array index, that is Uint32.
1831   __ NonNegativeSmiTst(key);
1832   __ b(ne, &slow);
1833
1834   // Everything is fine, call runtime.
1835   __ Push(receiver, key);  // Receiver, key.
1836
1837   // Perform tail call to the entry.
1838   __ TailCallExternalReference(
1839       ExternalReference(IC_Utility(IC::kLoadElementWithInterceptor),
1840                         masm->isolate()),
1841       2, 1);
1842
1843   __ bind(&slow);
1844   PropertyAccessCompiler::TailCallBuiltin(
1845       masm, PropertyAccessCompiler::MissBuiltin(Code::KEYED_LOAD_IC));
1846 }
1847
1848
1849 void ArgumentsAccessStub::GenerateNewStrict(MacroAssembler* masm) {
1850   // sp[0] : number of parameters
1851   // sp[4] : receiver displacement
1852   // sp[8] : function
1853   // Check if the calling frame is an arguments adaptor frame.
1854   Label adaptor_frame, try_allocate, runtime;
1855   __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1856   __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
1857   __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1858   __ b(eq, &adaptor_frame);
1859
1860   // Get the length from the frame.
1861   __ ldr(r1, MemOperand(sp, 0));
1862   __ b(&try_allocate);
1863
1864   // Patch the arguments.length and the parameters pointer.
1865   __ bind(&adaptor_frame);
1866   __ ldr(r1, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
1867   if (has_new_target()) {
1868     __ cmp(r1, Operand(Smi::FromInt(0)));
1869     Label skip_decrement;
1870     __ b(eq, &skip_decrement);
1871     // Subtract 1 from smi-tagged arguments count.
1872     __ sub(r1, r1, Operand(2));
1873     __ bind(&skip_decrement);
1874   }
1875   __ str(r1, MemOperand(sp, 0));
1876   __ add(r3, r2, Operand::PointerOffsetFromSmiKey(r1));
1877   __ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
1878   __ str(r3, MemOperand(sp, 1 * kPointerSize));
1879
1880   // Try the new space allocation. Start out with computing the size
1881   // of the arguments object and the elements array in words.
1882   Label add_arguments_object;
1883   __ bind(&try_allocate);
1884   __ SmiUntag(r1, SetCC);
1885   __ b(eq, &add_arguments_object);
1886   __ add(r1, r1, Operand(FixedArray::kHeaderSize / kPointerSize));
1887   __ bind(&add_arguments_object);
1888   __ add(r1, r1, Operand(Heap::kStrictArgumentsObjectSize / kPointerSize));
1889
1890   // Do the allocation of both objects in one go.
1891   __ Allocate(r1, r0, r2, r3, &runtime,
1892               static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS));
1893
1894   // Get the arguments boilerplate from the current native context.
1895   __ ldr(r4, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
1896   __ ldr(r4, FieldMemOperand(r4, GlobalObject::kNativeContextOffset));
1897   __ ldr(r4, MemOperand(
1898                  r4, Context::SlotOffset(Context::STRICT_ARGUMENTS_MAP_INDEX)));
1899
1900   __ str(r4, FieldMemOperand(r0, JSObject::kMapOffset));
1901   __ LoadRoot(r3, Heap::kEmptyFixedArrayRootIndex);
1902   __ str(r3, FieldMemOperand(r0, JSObject::kPropertiesOffset));
1903   __ str(r3, FieldMemOperand(r0, JSObject::kElementsOffset));
1904
1905   // Get the length (smi tagged) and set that as an in-object property too.
1906   STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0);
1907   __ ldr(r1, MemOperand(sp, 0 * kPointerSize));
1908   __ AssertSmi(r1);
1909   __ str(r1, FieldMemOperand(r0, JSObject::kHeaderSize +
1910       Heap::kArgumentsLengthIndex * kPointerSize));
1911
1912   // If there are no actual arguments, we're done.
1913   Label done;
1914   __ cmp(r1, Operand::Zero());
1915   __ b(eq, &done);
1916
1917   // Get the parameters pointer from the stack.
1918   __ ldr(r2, MemOperand(sp, 1 * kPointerSize));
1919
1920   // Set up the elements pointer in the allocated arguments object and
1921   // initialize the header in the elements fixed array.
1922   __ add(r4, r0, Operand(Heap::kStrictArgumentsObjectSize));
1923   __ str(r4, FieldMemOperand(r0, JSObject::kElementsOffset));
1924   __ LoadRoot(r3, Heap::kFixedArrayMapRootIndex);
1925   __ str(r3, FieldMemOperand(r4, FixedArray::kMapOffset));
1926   __ str(r1, FieldMemOperand(r4, FixedArray::kLengthOffset));
1927   __ SmiUntag(r1);
1928
1929   // Copy the fixed array slots.
1930   Label loop;
1931   // Set up r4 to point to the first array slot.
1932   __ add(r4, r4, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
1933   __ bind(&loop);
1934   // Pre-decrement r2 with kPointerSize on each iteration.
1935   // Pre-decrement in order to skip receiver.
1936   __ ldr(r3, MemOperand(r2, kPointerSize, NegPreIndex));
1937   // Post-increment r4 with kPointerSize on each iteration.
1938   __ str(r3, MemOperand(r4, kPointerSize, PostIndex));
1939   __ sub(r1, r1, Operand(1));
1940   __ cmp(r1, Operand::Zero());
1941   __ b(ne, &loop);
1942
1943   // Return and remove the on-stack parameters.
1944   __ bind(&done);
1945   __ add(sp, sp, Operand(3 * kPointerSize));
1946   __ Ret();
1947
1948   // Do the runtime call to allocate the arguments object.
1949   __ bind(&runtime);
1950   __ TailCallRuntime(Runtime::kNewStrictArguments, 3, 1);
1951 }
1952
1953
1954 void RestParamAccessStub::GenerateNew(MacroAssembler* masm) {
1955   // Stack layout on entry.
1956   //  sp[0] : language mode
1957   //  sp[4] : index of rest parameter
1958   //  sp[8] : number of parameters
1959   //  sp[12] : receiver displacement
1960
1961   Label runtime;
1962   __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1963   __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
1964   __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1965   __ b(ne, &runtime);
1966
1967   // Patch the arguments.length and the parameters pointer.
1968   __ ldr(r1, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
1969   __ str(r1, MemOperand(sp, 2 * kPointerSize));
1970   __ add(r3, r2, Operand::PointerOffsetFromSmiKey(r1));
1971   __ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
1972   __ str(r3, MemOperand(sp, 3 * kPointerSize));
1973
1974   __ bind(&runtime);
1975   __ TailCallRuntime(Runtime::kNewRestParam, 4, 1);
1976 }
1977
1978
1979 void RegExpExecStub::Generate(MacroAssembler* masm) {
1980   // Just jump directly to runtime if native RegExp is not selected at compile
1981   // time or if regexp entry in generated code is turned off runtime switch or
1982   // at compilation.
1983 #ifdef V8_INTERPRETED_REGEXP
1984   __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
1985 #else  // V8_INTERPRETED_REGEXP
1986
1987   // Stack frame on entry.
1988   //  sp[0]: last_match_info (expected JSArray)
1989   //  sp[4]: previous index
1990   //  sp[8]: subject string
1991   //  sp[12]: JSRegExp object
1992
1993   const int kLastMatchInfoOffset = 0 * kPointerSize;
1994   const int kPreviousIndexOffset = 1 * kPointerSize;
1995   const int kSubjectOffset = 2 * kPointerSize;
1996   const int kJSRegExpOffset = 3 * kPointerSize;
1997
1998   Label runtime;
1999   // Allocation of registers for this function. These are in callee save
2000   // registers and will be preserved by the call to the native RegExp code, as
2001   // this code is called using the normal C calling convention. When calling
2002   // directly from generated code the native RegExp code will not do a GC and
2003   // therefore the content of these registers are safe to use after the call.
2004   Register subject = r4;
2005   Register regexp_data = r5;
2006   Register last_match_info_elements = no_reg;  // will be r6;
2007
2008   // Ensure that a RegExp stack is allocated.
2009   ExternalReference address_of_regexp_stack_memory_address =
2010       ExternalReference::address_of_regexp_stack_memory_address(isolate());
2011   ExternalReference address_of_regexp_stack_memory_size =
2012       ExternalReference::address_of_regexp_stack_memory_size(isolate());
2013   __ mov(r0, Operand(address_of_regexp_stack_memory_size));
2014   __ ldr(r0, MemOperand(r0, 0));
2015   __ cmp(r0, Operand::Zero());
2016   __ b(eq, &runtime);
2017
2018   // Check that the first argument is a JSRegExp object.
2019   __ ldr(r0, MemOperand(sp, kJSRegExpOffset));
2020   __ JumpIfSmi(r0, &runtime);
2021   __ CompareObjectType(r0, r1, r1, JS_REGEXP_TYPE);
2022   __ b(ne, &runtime);
2023
2024   // Check that the RegExp has been compiled (data contains a fixed array).
2025   __ ldr(regexp_data, FieldMemOperand(r0, JSRegExp::kDataOffset));
2026   if (FLAG_debug_code) {
2027     __ SmiTst(regexp_data);
2028     __ Check(ne, kUnexpectedTypeForRegExpDataFixedArrayExpected);
2029     __ CompareObjectType(regexp_data, r0, r0, FIXED_ARRAY_TYPE);
2030     __ Check(eq, kUnexpectedTypeForRegExpDataFixedArrayExpected);
2031   }
2032
2033   // regexp_data: RegExp data (FixedArray)
2034   // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
2035   __ ldr(r0, FieldMemOperand(regexp_data, JSRegExp::kDataTagOffset));
2036   __ cmp(r0, Operand(Smi::FromInt(JSRegExp::IRREGEXP)));
2037   __ b(ne, &runtime);
2038
2039   // regexp_data: RegExp data (FixedArray)
2040   // Check that the number of captures fit in the static offsets vector buffer.
2041   __ ldr(r2,
2042          FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
2043   // Check (number_of_captures + 1) * 2 <= offsets vector size
2044   // Or          number_of_captures * 2 <= offsets vector size - 2
2045   // Multiplying by 2 comes for free since r2 is smi-tagged.
2046   STATIC_ASSERT(kSmiTag == 0);
2047   STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
2048   STATIC_ASSERT(Isolate::kJSRegexpStaticOffsetsVectorSize >= 2);
2049   __ cmp(r2, Operand(Isolate::kJSRegexpStaticOffsetsVectorSize - 2));
2050   __ b(hi, &runtime);
2051
2052   // Reset offset for possibly sliced string.
2053   __ mov(r9, Operand::Zero());
2054   __ ldr(subject, MemOperand(sp, kSubjectOffset));
2055   __ JumpIfSmi(subject, &runtime);
2056   __ mov(r3, subject);  // Make a copy of the original subject string.
2057   __ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
2058   __ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
2059   // subject: subject string
2060   // r3: subject string
2061   // r0: subject string instance type
2062   // regexp_data: RegExp data (FixedArray)
2063   // Handle subject string according to its encoding and representation:
2064   // (1) Sequential string?  If yes, go to (5).
2065   // (2) Anything but sequential or cons?  If yes, go to (6).
2066   // (3) Cons string.  If the string is flat, replace subject with first string.
2067   //     Otherwise bailout.
2068   // (4) Is subject external?  If yes, go to (7).
2069   // (5) Sequential string.  Load regexp code according to encoding.
2070   // (E) Carry on.
2071   /// [...]
2072
2073   // Deferred code at the end of the stub:
2074   // (6) Not a long external string?  If yes, go to (8).
2075   // (7) External string.  Make it, offset-wise, look like a sequential string.
2076   //     Go to (5).
2077   // (8) Short external string or not a string?  If yes, bail out to runtime.
2078   // (9) Sliced string.  Replace subject with parent.  Go to (4).
2079
2080   Label seq_string /* 5 */, external_string /* 7 */,
2081         check_underlying /* 4 */, not_seq_nor_cons /* 6 */,
2082         not_long_external /* 8 */;
2083
2084   // (1) Sequential string?  If yes, go to (5).
2085   __ and_(r1,
2086           r0,
2087           Operand(kIsNotStringMask |
2088                   kStringRepresentationMask |
2089                   kShortExternalStringMask),
2090           SetCC);
2091   STATIC_ASSERT((kStringTag | kSeqStringTag) == 0);
2092   __ b(eq, &seq_string);  // Go to (5).
2093
2094   // (2) Anything but sequential or cons?  If yes, go to (6).
2095   STATIC_ASSERT(kConsStringTag < kExternalStringTag);
2096   STATIC_ASSERT(kSlicedStringTag > kExternalStringTag);
2097   STATIC_ASSERT(kIsNotStringMask > kExternalStringTag);
2098   STATIC_ASSERT(kShortExternalStringTag > kExternalStringTag);
2099   __ cmp(r1, Operand(kExternalStringTag));
2100   __ b(ge, &not_seq_nor_cons);  // Go to (6).
2101
2102   // (3) Cons string.  Check that it's flat.
2103   // Replace subject with first string and reload instance type.
2104   __ ldr(r0, FieldMemOperand(subject, ConsString::kSecondOffset));
2105   __ CompareRoot(r0, Heap::kempty_stringRootIndex);
2106   __ b(ne, &runtime);
2107   __ ldr(subject, FieldMemOperand(subject, ConsString::kFirstOffset));
2108
2109   // (4) Is subject external?  If yes, go to (7).
2110   __ bind(&check_underlying);
2111   __ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
2112   __ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
2113   STATIC_ASSERT(kSeqStringTag == 0);
2114   __ tst(r0, Operand(kStringRepresentationMask));
2115   // The underlying external string is never a short external string.
2116   STATIC_ASSERT(ExternalString::kMaxShortLength < ConsString::kMinLength);
2117   STATIC_ASSERT(ExternalString::kMaxShortLength < SlicedString::kMinLength);
2118   __ b(ne, &external_string);  // Go to (7).
2119
2120   // (5) Sequential string.  Load regexp code according to encoding.
2121   __ bind(&seq_string);
2122   // subject: sequential subject string (or look-alike, external string)
2123   // r3: original subject string
2124   // Load previous index and check range before r3 is overwritten.  We have to
2125   // use r3 instead of subject here because subject might have been only made
2126   // to look like a sequential string when it actually is an external string.
2127   __ ldr(r1, MemOperand(sp, kPreviousIndexOffset));
2128   __ JumpIfNotSmi(r1, &runtime);
2129   __ ldr(r3, FieldMemOperand(r3, String::kLengthOffset));
2130   __ cmp(r3, Operand(r1));
2131   __ b(ls, &runtime);
2132   __ SmiUntag(r1);
2133
2134   STATIC_ASSERT(4 == kOneByteStringTag);
2135   STATIC_ASSERT(kTwoByteStringTag == 0);
2136   __ and_(r0, r0, Operand(kStringEncodingMask));
2137   __ mov(r3, Operand(r0, ASR, 2), SetCC);
2138   __ ldr(r6, FieldMemOperand(regexp_data, JSRegExp::kDataOneByteCodeOffset),
2139          ne);
2140   __ ldr(r6, FieldMemOperand(regexp_data, JSRegExp::kDataUC16CodeOffset), eq);
2141
2142   // (E) Carry on.  String handling is done.
2143   // r6: irregexp code
2144   // Check that the irregexp code has been generated for the actual string
2145   // encoding. If it has, the field contains a code object otherwise it contains
2146   // a smi (code flushing support).
2147   __ JumpIfSmi(r6, &runtime);
2148
2149   // r1: previous index
2150   // r3: encoding of subject string (1 if one_byte, 0 if two_byte);
2151   // r6: code
2152   // subject: Subject string
2153   // regexp_data: RegExp data (FixedArray)
2154   // All checks done. Now push arguments for native regexp code.
2155   __ IncrementCounter(isolate()->counters()->regexp_entry_native(), 1, r0, r2);
2156
2157   // Isolates: note we add an additional parameter here (isolate pointer).
2158   const int kRegExpExecuteArguments = 9;
2159   const int kParameterRegisters = 4;
2160   __ EnterExitFrame(false, kRegExpExecuteArguments - kParameterRegisters);
2161
2162   // Stack pointer now points to cell where return address is to be written.
2163   // Arguments are before that on the stack or in registers.
2164
2165   // Argument 9 (sp[20]): Pass current isolate address.
2166   __ mov(r0, Operand(ExternalReference::isolate_address(isolate())));
2167   __ str(r0, MemOperand(sp, 5 * kPointerSize));
2168
2169   // Argument 8 (sp[16]): Indicate that this is a direct call from JavaScript.
2170   __ mov(r0, Operand(1));
2171   __ str(r0, MemOperand(sp, 4 * kPointerSize));
2172
2173   // Argument 7 (sp[12]): Start (high end) of backtracking stack memory area.
2174   __ mov(r0, Operand(address_of_regexp_stack_memory_address));
2175   __ ldr(r0, MemOperand(r0, 0));
2176   __ mov(r2, Operand(address_of_regexp_stack_memory_size));
2177   __ ldr(r2, MemOperand(r2, 0));
2178   __ add(r0, r0, Operand(r2));
2179   __ str(r0, MemOperand(sp, 3 * kPointerSize));
2180
2181   // Argument 6: Set the number of capture registers to zero to force global
2182   // regexps to behave as non-global.  This does not affect non-global regexps.
2183   __ mov(r0, Operand::Zero());
2184   __ str(r0, MemOperand(sp, 2 * kPointerSize));
2185
2186   // Argument 5 (sp[4]): static offsets vector buffer.
2187   __ mov(r0,
2188          Operand(ExternalReference::address_of_static_offsets_vector(
2189              isolate())));
2190   __ str(r0, MemOperand(sp, 1 * kPointerSize));
2191
2192   // For arguments 4 and 3 get string length, calculate start of string data and
2193   // calculate the shift of the index (0 for one-byte and 1 for two-byte).
2194   __ add(r7, subject, Operand(SeqString::kHeaderSize - kHeapObjectTag));
2195   __ eor(r3, r3, Operand(1));
2196   // Load the length from the original subject string from the previous stack
2197   // frame. Therefore we have to use fp, which points exactly to two pointer
2198   // sizes below the previous sp. (Because creating a new stack frame pushes
2199   // the previous fp onto the stack and moves up sp by 2 * kPointerSize.)
2200   __ ldr(subject, MemOperand(fp, kSubjectOffset + 2 * kPointerSize));
2201   // If slice offset is not 0, load the length from the original sliced string.
2202   // Argument 4, r3: End of string data
2203   // Argument 3, r2: Start of string data
2204   // Prepare start and end index of the input.
2205   __ add(r9, r7, Operand(r9, LSL, r3));
2206   __ add(r2, r9, Operand(r1, LSL, r3));
2207
2208   __ ldr(r7, FieldMemOperand(subject, String::kLengthOffset));
2209   __ SmiUntag(r7);
2210   __ add(r3, r9, Operand(r7, LSL, r3));
2211
2212   // Argument 2 (r1): Previous index.
2213   // Already there
2214
2215   // Argument 1 (r0): Subject string.
2216   __ mov(r0, subject);
2217
2218   // Locate the code entry and call it.
2219   __ add(r6, r6, Operand(Code::kHeaderSize - kHeapObjectTag));
2220   DirectCEntryStub stub(isolate());
2221   stub.GenerateCall(masm, r6);
2222
2223   __ LeaveExitFrame(false, no_reg, true);
2224
2225   last_match_info_elements = r6;
2226
2227   // r0: result
2228   // subject: subject string (callee saved)
2229   // regexp_data: RegExp data (callee saved)
2230   // last_match_info_elements: Last match info elements (callee saved)
2231   // Check the result.
2232   Label success;
2233   __ cmp(r0, Operand(1));
2234   // We expect exactly one result since we force the called regexp to behave
2235   // as non-global.
2236   __ b(eq, &success);
2237   Label failure;
2238   __ cmp(r0, Operand(NativeRegExpMacroAssembler::FAILURE));
2239   __ b(eq, &failure);
2240   __ cmp(r0, Operand(NativeRegExpMacroAssembler::EXCEPTION));
2241   // If not exception it can only be retry. Handle that in the runtime system.
2242   __ b(ne, &runtime);
2243   // Result must now be exception. If there is no pending exception already a
2244   // stack overflow (on the backtrack stack) was detected in RegExp code but
2245   // haven't created the exception yet. Handle that in the runtime system.
2246   // TODO(592): Rerunning the RegExp to get the stack overflow exception.
2247   __ mov(r1, Operand(isolate()->factory()->the_hole_value()));
2248   __ mov(r2, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
2249                                        isolate())));
2250   __ ldr(r0, MemOperand(r2, 0));
2251   __ cmp(r0, r1);
2252   __ b(eq, &runtime);
2253
2254   // For exception, throw the exception again.
2255   __ TailCallRuntime(Runtime::kRegExpExecReThrow, 4, 1);
2256
2257   __ bind(&failure);
2258   // For failure and exception return null.
2259   __ mov(r0, Operand(isolate()->factory()->null_value()));
2260   __ add(sp, sp, Operand(4 * kPointerSize));
2261   __ Ret();
2262
2263   // Process the result from the native regexp code.
2264   __ bind(&success);
2265   __ ldr(r1,
2266          FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
2267   // Calculate number of capture registers (number_of_captures + 1) * 2.
2268   // Multiplying by 2 comes for free since r1 is smi-tagged.
2269   STATIC_ASSERT(kSmiTag == 0);
2270   STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
2271   __ add(r1, r1, Operand(2));  // r1 was a smi.
2272
2273   __ ldr(r0, MemOperand(sp, kLastMatchInfoOffset));
2274   __ JumpIfSmi(r0, &runtime);
2275   __ CompareObjectType(r0, r2, r2, JS_ARRAY_TYPE);
2276   __ b(ne, &runtime);
2277   // Check that the JSArray is in fast case.
2278   __ ldr(last_match_info_elements,
2279          FieldMemOperand(r0, JSArray::kElementsOffset));
2280   __ ldr(r0, FieldMemOperand(last_match_info_elements, HeapObject::kMapOffset));
2281   __ CompareRoot(r0, Heap::kFixedArrayMapRootIndex);
2282   __ b(ne, &runtime);
2283   // Check that the last match info has space for the capture registers and the
2284   // additional information.
2285   __ ldr(r0,
2286          FieldMemOperand(last_match_info_elements, FixedArray::kLengthOffset));
2287   __ add(r2, r1, Operand(RegExpImpl::kLastMatchOverhead));
2288   __ cmp(r2, Operand::SmiUntag(r0));
2289   __ b(gt, &runtime);
2290
2291   // r1: number of capture registers
2292   // r4: subject string
2293   // Store the capture count.
2294   __ SmiTag(r2, r1);
2295   __ str(r2, FieldMemOperand(last_match_info_elements,
2296                              RegExpImpl::kLastCaptureCountOffset));
2297   // Store last subject and last input.
2298   __ str(subject,
2299          FieldMemOperand(last_match_info_elements,
2300                          RegExpImpl::kLastSubjectOffset));
2301   __ mov(r2, subject);
2302   __ RecordWriteField(last_match_info_elements,
2303                       RegExpImpl::kLastSubjectOffset,
2304                       subject,
2305                       r3,
2306                       kLRHasNotBeenSaved,
2307                       kDontSaveFPRegs);
2308   __ mov(subject, r2);
2309   __ str(subject,
2310          FieldMemOperand(last_match_info_elements,
2311                          RegExpImpl::kLastInputOffset));
2312   __ RecordWriteField(last_match_info_elements,
2313                       RegExpImpl::kLastInputOffset,
2314                       subject,
2315                       r3,
2316                       kLRHasNotBeenSaved,
2317                       kDontSaveFPRegs);
2318
2319   // Get the static offsets vector filled by the native regexp code.
2320   ExternalReference address_of_static_offsets_vector =
2321       ExternalReference::address_of_static_offsets_vector(isolate());
2322   __ mov(r2, Operand(address_of_static_offsets_vector));
2323
2324   // r1: number of capture registers
2325   // r2: offsets vector
2326   Label next_capture, done;
2327   // Capture register counter starts from number of capture registers and
2328   // counts down until wraping after zero.
2329   __ add(r0,
2330          last_match_info_elements,
2331          Operand(RegExpImpl::kFirstCaptureOffset - kHeapObjectTag));
2332   __ bind(&next_capture);
2333   __ sub(r1, r1, Operand(1), SetCC);
2334   __ b(mi, &done);
2335   // Read the value from the static offsets vector buffer.
2336   __ ldr(r3, MemOperand(r2, kPointerSize, PostIndex));
2337   // Store the smi value in the last match info.
2338   __ SmiTag(r3);
2339   __ str(r3, MemOperand(r0, kPointerSize, PostIndex));
2340   __ jmp(&next_capture);
2341   __ bind(&done);
2342
2343   // Return last match info.
2344   __ ldr(r0, MemOperand(sp, kLastMatchInfoOffset));
2345   __ add(sp, sp, Operand(4 * kPointerSize));
2346   __ Ret();
2347
2348   // Do the runtime call to execute the regexp.
2349   __ bind(&runtime);
2350   __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
2351
2352   // Deferred code for string handling.
2353   // (6) Not a long external string?  If yes, go to (8).
2354   __ bind(&not_seq_nor_cons);
2355   // Compare flags are still set.
2356   __ b(gt, &not_long_external);  // Go to (8).
2357
2358   // (7) External string.  Make it, offset-wise, look like a sequential string.
2359   __ bind(&external_string);
2360   __ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
2361   __ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
2362   if (FLAG_debug_code) {
2363     // Assert that we do not have a cons or slice (indirect strings) here.
2364     // Sequential strings have already been ruled out.
2365     __ tst(r0, Operand(kIsIndirectStringMask));
2366     __ Assert(eq, kExternalStringExpectedButNotFound);
2367   }
2368   __ ldr(subject,
2369          FieldMemOperand(subject, ExternalString::kResourceDataOffset));
2370   // Move the pointer so that offset-wise, it looks like a sequential string.
2371   STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
2372   __ sub(subject,
2373          subject,
2374          Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
2375   __ jmp(&seq_string);    // Go to (5).
2376
2377   // (8) Short external string or not a string?  If yes, bail out to runtime.
2378   __ bind(&not_long_external);
2379   STATIC_ASSERT(kNotStringTag != 0 && kShortExternalStringTag !=0);
2380   __ tst(r1, Operand(kIsNotStringMask | kShortExternalStringMask));
2381   __ b(ne, &runtime);
2382
2383   // (9) Sliced string.  Replace subject with parent.  Go to (4).
2384   // Load offset into r9 and replace subject string with parent.
2385   __ ldr(r9, FieldMemOperand(subject, SlicedString::kOffsetOffset));
2386   __ SmiUntag(r9);
2387   __ ldr(subject, FieldMemOperand(subject, SlicedString::kParentOffset));
2388   __ jmp(&check_underlying);  // Go to (4).
2389 #endif  // V8_INTERPRETED_REGEXP
2390 }
2391
2392
2393 static void CallStubInRecordCallTarget(MacroAssembler* masm, CodeStub* stub) {
2394   // r0 : number of arguments to the construct function
2395   // r2 : Feedback vector
2396   // r3 : slot in feedback vector (Smi)
2397   // r1 : the function to call
2398   FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
2399
2400   // Number-of-arguments register must be smi-tagged to call out.
2401   __ SmiTag(r0);
2402   __ Push(r3, r2, r1, r0);
2403
2404   __ CallStub(stub);
2405
2406   __ Pop(r3, r2, r1, r0);
2407   __ SmiUntag(r0);
2408 }
2409
2410
2411 static void GenerateRecordCallTarget(MacroAssembler* masm) {
2412   // Cache the called function in a feedback vector slot.  Cache states
2413   // are uninitialized, monomorphic (indicated by a JSFunction), and
2414   // megamorphic.
2415   // r0 : number of arguments to the construct function
2416   // r1 : the function to call
2417   // r2 : Feedback vector
2418   // r3 : slot in feedback vector (Smi)
2419   Label initialize, done, miss, megamorphic, not_array_function;
2420
2421   DCHECK_EQ(*TypeFeedbackVector::MegamorphicSentinel(masm->isolate()),
2422             masm->isolate()->heap()->megamorphic_symbol());
2423   DCHECK_EQ(*TypeFeedbackVector::UninitializedSentinel(masm->isolate()),
2424             masm->isolate()->heap()->uninitialized_symbol());
2425
2426   // Load the cache state into r4.
2427   __ add(r4, r2, Operand::PointerOffsetFromSmiKey(r3));
2428   __ ldr(r4, FieldMemOperand(r4, FixedArray::kHeaderSize));
2429
2430   // A monomorphic cache hit or an already megamorphic state: invoke the
2431   // function without changing the state.
2432   // We don't know if r4 is a WeakCell or a Symbol, but it's harmless to read at
2433   // this position in a symbol (see static asserts in type-feedback-vector.h).
2434   Label check_allocation_site;
2435   Register feedback_map = r5;
2436   Register weak_value = r8;
2437   __ ldr(weak_value, FieldMemOperand(r4, WeakCell::kValueOffset));
2438   __ cmp(r1, weak_value);
2439   __ b(eq, &done);
2440   __ CompareRoot(r4, Heap::kmegamorphic_symbolRootIndex);
2441   __ b(eq, &done);
2442   __ ldr(feedback_map, FieldMemOperand(r4, HeapObject::kMapOffset));
2443   __ CompareRoot(feedback_map, Heap::kWeakCellMapRootIndex);
2444   __ b(ne, FLAG_pretenuring_call_new ? &miss : &check_allocation_site);
2445
2446   // If the weak cell is cleared, we have a new chance to become monomorphic.
2447   __ JumpIfSmi(weak_value, &initialize);
2448   __ jmp(&megamorphic);
2449
2450   if (!FLAG_pretenuring_call_new) {
2451     __ bind(&check_allocation_site);
2452     // If we came here, we need to see if we are the array function.
2453     // If we didn't have a matching function, and we didn't find the megamorph
2454     // sentinel, then we have in the slot either some other function or an
2455     // AllocationSite.
2456     __ CompareRoot(feedback_map, Heap::kAllocationSiteMapRootIndex);
2457     __ b(ne, &miss);
2458
2459     // Make sure the function is the Array() function
2460     __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r4);
2461     __ cmp(r1, r4);
2462     __ b(ne, &megamorphic);
2463     __ jmp(&done);
2464   }
2465
2466   __ bind(&miss);
2467
2468   // A monomorphic miss (i.e, here the cache is not uninitialized) goes
2469   // megamorphic.
2470   __ CompareRoot(r4, Heap::kuninitialized_symbolRootIndex);
2471   __ b(eq, &initialize);
2472   // MegamorphicSentinel is an immortal immovable object (undefined) so no
2473   // write-barrier is needed.
2474   __ bind(&megamorphic);
2475   __ add(r4, r2, Operand::PointerOffsetFromSmiKey(r3));
2476   __ LoadRoot(ip, Heap::kmegamorphic_symbolRootIndex);
2477   __ str(ip, FieldMemOperand(r4, FixedArray::kHeaderSize));
2478   __ jmp(&done);
2479
2480   // An uninitialized cache is patched with the function
2481   __ bind(&initialize);
2482
2483   if (!FLAG_pretenuring_call_new) {
2484     // Make sure the function is the Array() function
2485     __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r4);
2486     __ cmp(r1, r4);
2487     __ b(ne, &not_array_function);
2488
2489     // The target function is the Array constructor,
2490     // Create an AllocationSite if we don't already have it, store it in the
2491     // slot.
2492     CreateAllocationSiteStub create_stub(masm->isolate());
2493     CallStubInRecordCallTarget(masm, &create_stub);
2494     __ b(&done);
2495
2496     __ bind(&not_array_function);
2497   }
2498
2499   CreateWeakCellStub create_stub(masm->isolate());
2500   CallStubInRecordCallTarget(masm, &create_stub);
2501   __ bind(&done);
2502 }
2503
2504
2505 static void EmitContinueIfStrictOrNative(MacroAssembler* masm, Label* cont) {
2506   // Do not transform the receiver for strict mode functions.
2507   __ ldr(r3, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
2508   __ ldr(r4, FieldMemOperand(r3, SharedFunctionInfo::kCompilerHintsOffset));
2509   __ tst(r4, Operand(1 << (SharedFunctionInfo::kStrictModeFunction +
2510                            kSmiTagSize)));
2511   __ b(ne, cont);
2512
2513   // Do not transform the receiver for native (Compilerhints already in r3).
2514   __ tst(r4, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize)));
2515   __ b(ne, cont);
2516 }
2517
2518
2519 static void EmitSlowCase(MacroAssembler* masm,
2520                          int argc,
2521                          Label* non_function) {
2522   // Check for function proxy.
2523   __ cmp(r4, Operand(JS_FUNCTION_PROXY_TYPE));
2524   __ b(ne, non_function);
2525   __ push(r1);  // put proxy as additional argument
2526   __ mov(r0, Operand(argc + 1, RelocInfo::NONE32));
2527   __ mov(r2, Operand::Zero());
2528   __ GetBuiltinFunction(r1, Builtins::CALL_FUNCTION_PROXY);
2529   {
2530     Handle<Code> adaptor =
2531         masm->isolate()->builtins()->ArgumentsAdaptorTrampoline();
2532     __ Jump(adaptor, RelocInfo::CODE_TARGET);
2533   }
2534
2535   // CALL_NON_FUNCTION expects the non-function callee as receiver (instead
2536   // of the original receiver from the call site).
2537   __ bind(non_function);
2538   __ str(r1, MemOperand(sp, argc * kPointerSize));
2539   __ mov(r0, Operand(argc));  // Set up the number of arguments.
2540   __ mov(r2, Operand::Zero());
2541   __ GetBuiltinFunction(r1, Builtins::CALL_NON_FUNCTION);
2542   __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
2543           RelocInfo::CODE_TARGET);
2544 }
2545
2546
2547 static void EmitWrapCase(MacroAssembler* masm, int argc, Label* cont) {
2548   // Wrap the receiver and patch it back onto the stack.
2549   { FrameAndConstantPoolScope frame_scope(masm, StackFrame::INTERNAL);
2550     __ Push(r1, r3);
2551     __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
2552     __ pop(r1);
2553   }
2554   __ str(r0, MemOperand(sp, argc * kPointerSize));
2555   __ jmp(cont);
2556 }
2557
2558
2559 static void CallFunctionNoFeedback(MacroAssembler* masm,
2560                                    int argc, bool needs_checks,
2561                                    bool call_as_method) {
2562   // r1 : the function to call
2563   Label slow, non_function, wrap, cont;
2564
2565   if (needs_checks) {
2566     // Check that the function is really a JavaScript function.
2567     // r1: pushed function (to be verified)
2568     __ JumpIfSmi(r1, &non_function);
2569
2570     // Goto slow case if we do not have a function.
2571     __ CompareObjectType(r1, r4, r4, JS_FUNCTION_TYPE);
2572     __ b(ne, &slow);
2573   }
2574
2575   // Fast-case: Invoke the function now.
2576   // r1: pushed function
2577   ParameterCount actual(argc);
2578
2579   if (call_as_method) {
2580     if (needs_checks) {
2581       EmitContinueIfStrictOrNative(masm, &cont);
2582     }
2583
2584     // Compute the receiver in sloppy mode.
2585     __ ldr(r3, MemOperand(sp, argc * kPointerSize));
2586
2587     if (needs_checks) {
2588       __ JumpIfSmi(r3, &wrap);
2589       __ CompareObjectType(r3, r4, r4, FIRST_SPEC_OBJECT_TYPE);
2590       __ b(lt, &wrap);
2591     } else {
2592       __ jmp(&wrap);
2593     }
2594
2595     __ bind(&cont);
2596   }
2597
2598   __ InvokeFunction(r1, actual, JUMP_FUNCTION, NullCallWrapper());
2599
2600   if (needs_checks) {
2601     // Slow-case: Non-function called.
2602     __ bind(&slow);
2603     EmitSlowCase(masm, argc, &non_function);
2604   }
2605
2606   if (call_as_method) {
2607     __ bind(&wrap);
2608     EmitWrapCase(masm, argc, &cont);
2609   }
2610 }
2611
2612
2613 void CallFunctionStub::Generate(MacroAssembler* masm) {
2614   CallFunctionNoFeedback(masm, argc(), NeedsChecks(), CallAsMethod());
2615 }
2616
2617
2618 void CallConstructStub::Generate(MacroAssembler* masm) {
2619   // r0 : number of arguments
2620   // r1 : the function to call
2621   // r2 : feedback vector
2622   // r3 : (only if r2 is not the megamorphic symbol) slot in feedback
2623   //      vector (Smi)
2624   Label slow, non_function_call;
2625
2626   // Check that the function is not a smi.
2627   __ JumpIfSmi(r1, &non_function_call);
2628   // Check that the function is a JSFunction.
2629   __ CompareObjectType(r1, r4, r4, JS_FUNCTION_TYPE);
2630   __ b(ne, &slow);
2631
2632   if (RecordCallTarget()) {
2633     GenerateRecordCallTarget(masm);
2634
2635     __ add(r5, r2, Operand::PointerOffsetFromSmiKey(r3));
2636     if (FLAG_pretenuring_call_new) {
2637       // Put the AllocationSite from the feedback vector into r2.
2638       // By adding kPointerSize we encode that we know the AllocationSite
2639       // entry is at the feedback vector slot given by r3 + 1.
2640       __ ldr(r2, FieldMemOperand(r5, FixedArray::kHeaderSize + kPointerSize));
2641     } else {
2642       Label feedback_register_initialized;
2643       // Put the AllocationSite from the feedback vector into r2, or undefined.
2644       __ ldr(r2, FieldMemOperand(r5, FixedArray::kHeaderSize));
2645       __ ldr(r5, FieldMemOperand(r2, AllocationSite::kMapOffset));
2646       __ CompareRoot(r5, Heap::kAllocationSiteMapRootIndex);
2647       __ b(eq, &feedback_register_initialized);
2648       __ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
2649       __ bind(&feedback_register_initialized);
2650     }
2651
2652     __ AssertUndefinedOrAllocationSite(r2, r5);
2653   }
2654
2655   // Pass function as original constructor.
2656   if (IsSuperConstructorCall()) {
2657     __ mov(r4, Operand(1 * kPointerSize));
2658     __ add(r4, r4, Operand(r0, LSL, kPointerSizeLog2));
2659     __ ldr(r3, MemOperand(sp, r4));
2660   } else {
2661     __ mov(r3, r1);
2662   }
2663
2664   // Jump to the function-specific construct stub.
2665   Register jmp_reg = r4;
2666   __ ldr(jmp_reg, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
2667   __ ldr(jmp_reg, FieldMemOperand(jmp_reg,
2668                                   SharedFunctionInfo::kConstructStubOffset));
2669   __ add(pc, jmp_reg, Operand(Code::kHeaderSize - kHeapObjectTag));
2670
2671   // r0: number of arguments
2672   // r1: called object
2673   // r4: object type
2674   Label do_call;
2675   __ bind(&slow);
2676   __ cmp(r4, Operand(JS_FUNCTION_PROXY_TYPE));
2677   __ b(ne, &non_function_call);
2678   __ GetBuiltinFunction(r1, Builtins::CALL_FUNCTION_PROXY_AS_CONSTRUCTOR);
2679   __ jmp(&do_call);
2680
2681   __ bind(&non_function_call);
2682   __ GetBuiltinFunction(r1, Builtins::CALL_NON_FUNCTION_AS_CONSTRUCTOR);
2683   __ bind(&do_call);
2684   // Set expected number of arguments to zero (not changing r0).
2685   __ mov(r2, Operand::Zero());
2686   __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
2687           RelocInfo::CODE_TARGET);
2688 }
2689
2690
2691 static void EmitLoadTypeFeedbackVector(MacroAssembler* masm, Register vector) {
2692   __ ldr(vector, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
2693   __ ldr(vector, FieldMemOperand(vector,
2694                                  JSFunction::kSharedFunctionInfoOffset));
2695   __ ldr(vector, FieldMemOperand(vector,
2696                                  SharedFunctionInfo::kFeedbackVectorOffset));
2697 }
2698
2699
2700 void CallIC_ArrayStub::Generate(MacroAssembler* masm) {
2701   // r1 - function
2702   // r3 - slot id
2703   // r2 - vector
2704   Label miss;
2705   int argc = arg_count();
2706   ParameterCount actual(argc);
2707
2708   __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r4);
2709   __ cmp(r1, r4);
2710   __ b(ne, &miss);
2711
2712   __ mov(r0, Operand(arg_count()));
2713   __ add(r4, r2, Operand::PointerOffsetFromSmiKey(r3));
2714   __ ldr(r4, FieldMemOperand(r4, FixedArray::kHeaderSize));
2715
2716   // Verify that r4 contains an AllocationSite
2717   __ ldr(r5, FieldMemOperand(r4, HeapObject::kMapOffset));
2718   __ CompareRoot(r5, Heap::kAllocationSiteMapRootIndex);
2719   __ b(ne, &miss);
2720
2721   __ mov(r2, r4);
2722   __ mov(r3, r1);
2723   ArrayConstructorStub stub(masm->isolate(), arg_count());
2724   __ TailCallStub(&stub);
2725
2726   __ bind(&miss);
2727   GenerateMiss(masm);
2728
2729   // The slow case, we need this no matter what to complete a call after a miss.
2730   CallFunctionNoFeedback(masm,
2731                          arg_count(),
2732                          true,
2733                          CallAsMethod());
2734
2735   // Unreachable.
2736   __ stop("Unexpected code address");
2737 }
2738
2739
2740 void CallICStub::Generate(MacroAssembler* masm) {
2741   // r1 - function
2742   // r3 - slot id (Smi)
2743   // r2 - vector
2744   const int with_types_offset =
2745       FixedArray::OffsetOfElementAt(TypeFeedbackVector::kWithTypesIndex);
2746   const int generic_offset =
2747       FixedArray::OffsetOfElementAt(TypeFeedbackVector::kGenericCountIndex);
2748   Label extra_checks_or_miss, slow_start;
2749   Label slow, non_function, wrap, cont;
2750   Label have_js_function;
2751   int argc = arg_count();
2752   ParameterCount actual(argc);
2753
2754   // The checks. First, does r1 match the recorded monomorphic target?
2755   __ add(r4, r2, Operand::PointerOffsetFromSmiKey(r3));
2756   __ ldr(r4, FieldMemOperand(r4, FixedArray::kHeaderSize));
2757
2758   // We don't know that we have a weak cell. We might have a private symbol
2759   // or an AllocationSite, but the memory is safe to examine.
2760   // AllocationSite::kTransitionInfoOffset - contains a Smi or pointer to
2761   // FixedArray.
2762   // WeakCell::kValueOffset - contains a JSFunction or Smi(0)
2763   // Symbol::kHashFieldSlot - if the low bit is 1, then the hash is not
2764   // computed, meaning that it can't appear to be a pointer. If the low bit is
2765   // 0, then hash is computed, but the 0 bit prevents the field from appearing
2766   // to be a pointer.
2767   STATIC_ASSERT(WeakCell::kSize >= kPointerSize);
2768   STATIC_ASSERT(AllocationSite::kTransitionInfoOffset ==
2769                     WeakCell::kValueOffset &&
2770                 WeakCell::kValueOffset == Symbol::kHashFieldSlot);
2771
2772   __ ldr(r5, FieldMemOperand(r4, WeakCell::kValueOffset));
2773   __ cmp(r1, r5);
2774   __ b(ne, &extra_checks_or_miss);
2775
2776   // The compare above could have been a SMI/SMI comparison. Guard against this
2777   // convincing us that we have a monomorphic JSFunction.
2778   __ JumpIfSmi(r1, &extra_checks_or_miss);
2779
2780   __ bind(&have_js_function);
2781   if (CallAsMethod()) {
2782     EmitContinueIfStrictOrNative(masm, &cont);
2783     // Compute the receiver in sloppy mode.
2784     __ ldr(r3, MemOperand(sp, argc * kPointerSize));
2785
2786     __ JumpIfSmi(r3, &wrap);
2787     __ CompareObjectType(r3, r4, r4, FIRST_SPEC_OBJECT_TYPE);
2788     __ b(lt, &wrap);
2789
2790     __ bind(&cont);
2791   }
2792
2793   __ InvokeFunction(r1, actual, JUMP_FUNCTION, NullCallWrapper());
2794
2795   __ bind(&slow);
2796   EmitSlowCase(masm, argc, &non_function);
2797
2798   if (CallAsMethod()) {
2799     __ bind(&wrap);
2800     EmitWrapCase(masm, argc, &cont);
2801   }
2802
2803   __ bind(&extra_checks_or_miss);
2804   Label uninitialized, miss;
2805
2806   __ CompareRoot(r4, Heap::kmegamorphic_symbolRootIndex);
2807   __ b(eq, &slow_start);
2808
2809   // The following cases attempt to handle MISS cases without going to the
2810   // runtime.
2811   if (FLAG_trace_ic) {
2812     __ jmp(&miss);
2813   }
2814
2815   __ CompareRoot(r4, Heap::kuninitialized_symbolRootIndex);
2816   __ b(eq, &uninitialized);
2817
2818   // We are going megamorphic. If the feedback is a JSFunction, it is fine
2819   // to handle it here. More complex cases are dealt with in the runtime.
2820   __ AssertNotSmi(r4);
2821   __ CompareObjectType(r4, r5, r5, JS_FUNCTION_TYPE);
2822   __ b(ne, &miss);
2823   __ add(r4, r2, Operand::PointerOffsetFromSmiKey(r3));
2824   __ LoadRoot(ip, Heap::kmegamorphic_symbolRootIndex);
2825   __ str(ip, FieldMemOperand(r4, FixedArray::kHeaderSize));
2826   // We have to update statistics for runtime profiling.
2827   __ ldr(r4, FieldMemOperand(r2, with_types_offset));
2828   __ sub(r4, r4, Operand(Smi::FromInt(1)));
2829   __ str(r4, FieldMemOperand(r2, with_types_offset));
2830   __ ldr(r4, FieldMemOperand(r2, generic_offset));
2831   __ add(r4, r4, Operand(Smi::FromInt(1)));
2832   __ str(r4, FieldMemOperand(r2, generic_offset));
2833   __ jmp(&slow_start);
2834
2835   __ bind(&uninitialized);
2836
2837   // We are going monomorphic, provided we actually have a JSFunction.
2838   __ JumpIfSmi(r1, &miss);
2839
2840   // Goto miss case if we do not have a function.
2841   __ CompareObjectType(r1, r4, r4, JS_FUNCTION_TYPE);
2842   __ b(ne, &miss);
2843
2844   // Make sure the function is not the Array() function, which requires special
2845   // behavior on MISS.
2846   __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r4);
2847   __ cmp(r1, r4);
2848   __ b(eq, &miss);
2849
2850   // Update stats.
2851   __ ldr(r4, FieldMemOperand(r2, with_types_offset));
2852   __ add(r4, r4, Operand(Smi::FromInt(1)));
2853   __ str(r4, FieldMemOperand(r2, with_types_offset));
2854
2855   // Store the function. Use a stub since we need a frame for allocation.
2856   // r2 - vector
2857   // r3 - slot
2858   // r1 - function
2859   {
2860     FrameScope scope(masm, StackFrame::INTERNAL);
2861     CreateWeakCellStub create_stub(masm->isolate());
2862     __ Push(r1);
2863     __ CallStub(&create_stub);
2864     __ Pop(r1);
2865   }
2866
2867   __ jmp(&have_js_function);
2868
2869   // We are here because tracing is on or we encountered a MISS case we can't
2870   // handle here.
2871   __ bind(&miss);
2872   GenerateMiss(masm);
2873
2874   // the slow case
2875   __ bind(&slow_start);
2876   // Check that the function is really a JavaScript function.
2877   // r1: pushed function (to be verified)
2878   __ JumpIfSmi(r1, &non_function);
2879
2880   // Goto slow case if we do not have a function.
2881   __ CompareObjectType(r1, r4, r4, JS_FUNCTION_TYPE);
2882   __ b(ne, &slow);
2883   __ jmp(&have_js_function);
2884 }
2885
2886
2887 void CallICStub::GenerateMiss(MacroAssembler* masm) {
2888   FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
2889
2890   // Push the receiver and the function and feedback info.
2891   __ Push(r1, r2, r3);
2892
2893   // Call the entry.
2894   IC::UtilityId id = GetICState() == DEFAULT ? IC::kCallIC_Miss
2895                                              : IC::kCallIC_Customization_Miss;
2896
2897   ExternalReference miss = ExternalReference(IC_Utility(id), masm->isolate());
2898   __ CallExternalReference(miss, 3);
2899
2900   // Move result to edi and exit the internal frame.
2901   __ mov(r1, r0);
2902 }
2903
2904
2905 // StringCharCodeAtGenerator
2906 void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
2907   // If the receiver is a smi trigger the non-string case.
2908   if (check_mode_ == RECEIVER_IS_UNKNOWN) {
2909     __ JumpIfSmi(object_, receiver_not_string_);
2910
2911     // Fetch the instance type of the receiver into result register.
2912     __ ldr(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
2913     __ ldrb(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
2914     // If the receiver is not a string trigger the non-string case.
2915     __ tst(result_, Operand(kIsNotStringMask));
2916     __ b(ne, receiver_not_string_);
2917   }
2918
2919   // If the index is non-smi trigger the non-smi case.
2920   __ JumpIfNotSmi(index_, &index_not_smi_);
2921   __ bind(&got_smi_index_);
2922
2923   // Check for index out of range.
2924   __ ldr(ip, FieldMemOperand(object_, String::kLengthOffset));
2925   __ cmp(ip, Operand(index_));
2926   __ b(ls, index_out_of_range_);
2927
2928   __ SmiUntag(index_);
2929
2930   StringCharLoadGenerator::Generate(masm,
2931                                     object_,
2932                                     index_,
2933                                     result_,
2934                                     &call_runtime_);
2935
2936   __ SmiTag(result_);
2937   __ bind(&exit_);
2938 }
2939
2940
2941 void StringCharCodeAtGenerator::GenerateSlow(
2942     MacroAssembler* masm, EmbedMode embed_mode,
2943     const RuntimeCallHelper& call_helper) {
2944   __ Abort(kUnexpectedFallthroughToCharCodeAtSlowCase);
2945
2946   // Index is not a smi.
2947   __ bind(&index_not_smi_);
2948   // If index is a heap number, try converting it to an integer.
2949   __ CheckMap(index_,
2950               result_,
2951               Heap::kHeapNumberMapRootIndex,
2952               index_not_number_,
2953               DONT_DO_SMI_CHECK);
2954   call_helper.BeforeCall(masm);
2955   if (embed_mode == PART_OF_IC_HANDLER) {
2956     __ Push(LoadWithVectorDescriptor::VectorRegister(),
2957             LoadWithVectorDescriptor::SlotRegister(), object_, index_);
2958   } else {
2959     // index_ is consumed by runtime conversion function.
2960     __ Push(object_, index_);
2961   }
2962   if (index_flags_ == STRING_INDEX_IS_NUMBER) {
2963     __ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
2964   } else {
2965     DCHECK(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
2966     // NumberToSmi discards numbers that are not exact integers.
2967     __ CallRuntime(Runtime::kNumberToSmi, 1);
2968   }
2969   // Save the conversion result before the pop instructions below
2970   // have a chance to overwrite it.
2971   __ Move(index_, r0);
2972   if (embed_mode == PART_OF_IC_HANDLER) {
2973     __ Pop(LoadWithVectorDescriptor::VectorRegister(),
2974            LoadWithVectorDescriptor::SlotRegister(), object_);
2975   } else {
2976     __ pop(object_);
2977   }
2978   // Reload the instance type.
2979   __ ldr(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
2980   __ ldrb(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
2981   call_helper.AfterCall(masm);
2982   // If index is still not a smi, it must be out of range.
2983   __ JumpIfNotSmi(index_, index_out_of_range_);
2984   // Otherwise, return to the fast path.
2985   __ jmp(&got_smi_index_);
2986
2987   // Call runtime. We get here when the receiver is a string and the
2988   // index is a number, but the code of getting the actual character
2989   // is too complex (e.g., when the string needs to be flattened).
2990   __ bind(&call_runtime_);
2991   call_helper.BeforeCall(masm);
2992   __ SmiTag(index_);
2993   __ Push(object_, index_);
2994   __ CallRuntime(Runtime::kStringCharCodeAtRT, 2);
2995   __ Move(result_, r0);
2996   call_helper.AfterCall(masm);
2997   __ jmp(&exit_);
2998
2999   __ Abort(kUnexpectedFallthroughFromCharCodeAtSlowCase);
3000 }
3001
3002
3003 // -------------------------------------------------------------------------
3004 // StringCharFromCodeGenerator
3005
3006 void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
3007   // Fast case of Heap::LookupSingleCharacterStringFromCode.
3008   STATIC_ASSERT(kSmiTag == 0);
3009   STATIC_ASSERT(kSmiShiftSize == 0);
3010   DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCode + 1));
3011   __ tst(code_,
3012          Operand(kSmiTagMask |
3013                  ((~String::kMaxOneByteCharCode) << kSmiTagSize)));
3014   __ b(ne, &slow_case_);
3015
3016   __ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex);
3017   // At this point code register contains smi tagged one-byte char code.
3018   __ add(result_, result_, Operand::PointerOffsetFromSmiKey(code_));
3019   __ ldr(result_, FieldMemOperand(result_, FixedArray::kHeaderSize));
3020   __ CompareRoot(result_, Heap::kUndefinedValueRootIndex);
3021   __ b(eq, &slow_case_);
3022   __ bind(&exit_);
3023 }
3024
3025
3026 void StringCharFromCodeGenerator::GenerateSlow(
3027     MacroAssembler* masm,
3028     const RuntimeCallHelper& call_helper) {
3029   __ Abort(kUnexpectedFallthroughToCharFromCodeSlowCase);
3030
3031   __ bind(&slow_case_);
3032   call_helper.BeforeCall(masm);
3033   __ push(code_);
3034   __ CallRuntime(Runtime::kCharFromCode, 1);
3035   __ Move(result_, r0);
3036   call_helper.AfterCall(masm);
3037   __ jmp(&exit_);
3038
3039   __ Abort(kUnexpectedFallthroughFromCharFromCodeSlowCase);
3040 }
3041
3042
3043 enum CopyCharactersFlags { COPY_ONE_BYTE = 1, DEST_ALWAYS_ALIGNED = 2 };
3044
3045
3046 void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
3047                                           Register dest,
3048                                           Register src,
3049                                           Register count,
3050                                           Register scratch,
3051                                           String::Encoding encoding) {
3052   if (FLAG_debug_code) {
3053     // Check that destination is word aligned.
3054     __ tst(dest, Operand(kPointerAlignmentMask));
3055     __ Check(eq, kDestinationOfCopyNotAligned);
3056   }
3057
3058   // Assumes word reads and writes are little endian.
3059   // Nothing to do for zero characters.
3060   Label done;
3061   if (encoding == String::TWO_BYTE_ENCODING) {
3062     __ add(count, count, Operand(count), SetCC);
3063   }
3064
3065   Register limit = count;  // Read until dest equals this.
3066   __ add(limit, dest, Operand(count));
3067
3068   Label loop_entry, loop;
3069   // Copy bytes from src to dest until dest hits limit.
3070   __ b(&loop_entry);
3071   __ bind(&loop);
3072   __ ldrb(scratch, MemOperand(src, 1, PostIndex), lt);
3073   __ strb(scratch, MemOperand(dest, 1, PostIndex));
3074   __ bind(&loop_entry);
3075   __ cmp(dest, Operand(limit));
3076   __ b(lt, &loop);
3077
3078   __ bind(&done);
3079 }
3080
3081
3082 void SubStringStub::Generate(MacroAssembler* masm) {
3083   Label runtime;
3084
3085   // Stack frame on entry.
3086   //  lr: return address
3087   //  sp[0]: to
3088   //  sp[4]: from
3089   //  sp[8]: string
3090
3091   // This stub is called from the native-call %_SubString(...), so
3092   // nothing can be assumed about the arguments. It is tested that:
3093   //  "string" is a sequential string,
3094   //  both "from" and "to" are smis, and
3095   //  0 <= from <= to <= string.length.
3096   // If any of these assumptions fail, we call the runtime system.
3097
3098   const int kToOffset = 0 * kPointerSize;
3099   const int kFromOffset = 1 * kPointerSize;
3100   const int kStringOffset = 2 * kPointerSize;
3101
3102   __ Ldrd(r2, r3, MemOperand(sp, kToOffset));
3103   STATIC_ASSERT(kFromOffset == kToOffset + 4);
3104   STATIC_ASSERT(kSmiTag == 0);
3105   STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
3106
3107   // Arithmetic shift right by one un-smi-tags. In this case we rotate right
3108   // instead because we bail out on non-smi values: ROR and ASR are equivalent
3109   // for smis but they set the flags in a way that's easier to optimize.
3110   __ mov(r2, Operand(r2, ROR, 1), SetCC);
3111   __ mov(r3, Operand(r3, ROR, 1), SetCC, cc);
3112   // If either to or from had the smi tag bit set, then C is set now, and N
3113   // has the same value: we rotated by 1, so the bottom bit is now the top bit.
3114   // We want to bailout to runtime here if From is negative.  In that case, the
3115   // next instruction is not executed and we fall through to bailing out to
3116   // runtime.
3117   // Executed if both r2 and r3 are untagged integers.
3118   __ sub(r2, r2, Operand(r3), SetCC, cc);
3119   // One of the above un-smis or the above SUB could have set N==1.
3120   __ b(mi, &runtime);  // Either "from" or "to" is not an smi, or from > to.
3121
3122   // Make sure first argument is a string.
3123   __ ldr(r0, MemOperand(sp, kStringOffset));
3124   __ JumpIfSmi(r0, &runtime);
3125   Condition is_string = masm->IsObjectStringType(r0, r1);
3126   __ b(NegateCondition(is_string), &runtime);
3127
3128   Label single_char;
3129   __ cmp(r2, Operand(1));
3130   __ b(eq, &single_char);
3131
3132   // Short-cut for the case of trivial substring.
3133   Label return_r0;
3134   // r0: original string
3135   // r2: result string length
3136   __ ldr(r4, FieldMemOperand(r0, String::kLengthOffset));
3137   __ cmp(r2, Operand(r4, ASR, 1));
3138   // Return original string.
3139   __ b(eq, &return_r0);
3140   // Longer than original string's length or negative: unsafe arguments.
3141   __ b(hi, &runtime);
3142   // Shorter than original string's length: an actual substring.
3143
3144   // Deal with different string types: update the index if necessary
3145   // and put the underlying string into r5.
3146   // r0: original string
3147   // r1: instance type
3148   // r2: length
3149   // r3: from index (untagged)
3150   Label underlying_unpacked, sliced_string, seq_or_external_string;
3151   // If the string is not indirect, it can only be sequential or external.
3152   STATIC_ASSERT(kIsIndirectStringMask == (kSlicedStringTag & kConsStringTag));
3153   STATIC_ASSERT(kIsIndirectStringMask != 0);
3154   __ tst(r1, Operand(kIsIndirectStringMask));
3155   __ b(eq, &seq_or_external_string);
3156
3157   __ tst(r1, Operand(kSlicedNotConsMask));
3158   __ b(ne, &sliced_string);
3159   // Cons string.  Check whether it is flat, then fetch first part.
3160   __ ldr(r5, FieldMemOperand(r0, ConsString::kSecondOffset));
3161   __ CompareRoot(r5, Heap::kempty_stringRootIndex);
3162   __ b(ne, &runtime);
3163   __ ldr(r5, FieldMemOperand(r0, ConsString::kFirstOffset));
3164   // Update instance type.
3165   __ ldr(r1, FieldMemOperand(r5, HeapObject::kMapOffset));
3166   __ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
3167   __ jmp(&underlying_unpacked);
3168
3169   __ bind(&sliced_string);
3170   // Sliced string.  Fetch parent and correct start index by offset.
3171   __ ldr(r5, FieldMemOperand(r0, SlicedString::kParentOffset));
3172   __ ldr(r4, FieldMemOperand(r0, SlicedString::kOffsetOffset));
3173   __ add(r3, r3, Operand(r4, ASR, 1));  // Add offset to index.
3174   // Update instance type.
3175   __ ldr(r1, FieldMemOperand(r5, HeapObject::kMapOffset));
3176   __ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
3177   __ jmp(&underlying_unpacked);
3178
3179   __ bind(&seq_or_external_string);
3180   // Sequential or external string.  Just move string to the expected register.
3181   __ mov(r5, r0);
3182
3183   __ bind(&underlying_unpacked);
3184
3185   if (FLAG_string_slices) {
3186     Label copy_routine;
3187     // r5: underlying subject string
3188     // r1: instance type of underlying subject string
3189     // r2: length
3190     // r3: adjusted start index (untagged)
3191     __ cmp(r2, Operand(SlicedString::kMinLength));
3192     // Short slice.  Copy instead of slicing.
3193     __ b(lt, &copy_routine);
3194     // Allocate new sliced string.  At this point we do not reload the instance
3195     // type including the string encoding because we simply rely on the info
3196     // provided by the original string.  It does not matter if the original
3197     // string's encoding is wrong because we always have to recheck encoding of
3198     // the newly created string's parent anyways due to externalized strings.
3199     Label two_byte_slice, set_slice_header;
3200     STATIC_ASSERT((kStringEncodingMask & kOneByteStringTag) != 0);
3201     STATIC_ASSERT((kStringEncodingMask & kTwoByteStringTag) == 0);
3202     __ tst(r1, Operand(kStringEncodingMask));
3203     __ b(eq, &two_byte_slice);
3204     __ AllocateOneByteSlicedString(r0, r2, r6, r4, &runtime);
3205     __ jmp(&set_slice_header);
3206     __ bind(&two_byte_slice);
3207     __ AllocateTwoByteSlicedString(r0, r2, r6, r4, &runtime);
3208     __ bind(&set_slice_header);
3209     __ mov(r3, Operand(r3, LSL, 1));
3210     __ str(r5, FieldMemOperand(r0, SlicedString::kParentOffset));
3211     __ str(r3, FieldMemOperand(r0, SlicedString::kOffsetOffset));
3212     __ jmp(&return_r0);
3213
3214     __ bind(&copy_routine);
3215   }
3216
3217   // r5: underlying subject string
3218   // r1: instance type of underlying subject string
3219   // r2: length
3220   // r3: adjusted start index (untagged)
3221   Label two_byte_sequential, sequential_string, allocate_result;
3222   STATIC_ASSERT(kExternalStringTag != 0);
3223   STATIC_ASSERT(kSeqStringTag == 0);
3224   __ tst(r1, Operand(kExternalStringTag));
3225   __ b(eq, &sequential_string);
3226
3227   // Handle external string.
3228   // Rule out short external strings.
3229   STATIC_ASSERT(kShortExternalStringTag != 0);
3230   __ tst(r1, Operand(kShortExternalStringTag));
3231   __ b(ne, &runtime);
3232   __ ldr(r5, FieldMemOperand(r5, ExternalString::kResourceDataOffset));
3233   // r5 already points to the first character of underlying string.
3234   __ jmp(&allocate_result);
3235
3236   __ bind(&sequential_string);
3237   // Locate first character of underlying subject string.
3238   STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
3239   __ add(r5, r5, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
3240
3241   __ bind(&allocate_result);
3242   // Sequential acii string.  Allocate the result.
3243   STATIC_ASSERT((kOneByteStringTag & kStringEncodingMask) != 0);
3244   __ tst(r1, Operand(kStringEncodingMask));
3245   __ b(eq, &two_byte_sequential);
3246
3247   // Allocate and copy the resulting one-byte string.
3248   __ AllocateOneByteString(r0, r2, r4, r6, r1, &runtime);
3249
3250   // Locate first character of substring to copy.
3251   __ add(r5, r5, r3);
3252   // Locate first character of result.
3253   __ add(r1, r0, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
3254
3255   // r0: result string
3256   // r1: first character of result string
3257   // r2: result string length
3258   // r5: first character of substring to copy
3259   STATIC_ASSERT((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
3260   StringHelper::GenerateCopyCharacters(
3261       masm, r1, r5, r2, r3, String::ONE_BYTE_ENCODING);
3262   __ jmp(&return_r0);
3263
3264   // Allocate and copy the resulting two-byte string.
3265   __ bind(&two_byte_sequential);
3266   __ AllocateTwoByteString(r0, r2, r4, r6, r1, &runtime);
3267
3268   // Locate first character of substring to copy.
3269   STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
3270   __ add(r5, r5, Operand(r3, LSL, 1));
3271   // Locate first character of result.
3272   __ add(r1, r0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3273
3274   // r0: result string.
3275   // r1: first character of result.
3276   // r2: result length.
3277   // r5: first character of substring to copy.
3278   STATIC_ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
3279   StringHelper::GenerateCopyCharacters(
3280       masm, r1, r5, r2, r3, String::TWO_BYTE_ENCODING);
3281
3282   __ bind(&return_r0);
3283   Counters* counters = isolate()->counters();
3284   __ IncrementCounter(counters->sub_string_native(), 1, r3, r4);
3285   __ Drop(3);
3286   __ Ret();
3287
3288   // Just jump to runtime to create the sub string.
3289   __ bind(&runtime);
3290   __ TailCallRuntime(Runtime::kSubStringRT, 3, 1);
3291
3292   __ bind(&single_char);
3293   // r0: original string
3294   // r1: instance type
3295   // r2: length
3296   // r3: from index (untagged)
3297   __ SmiTag(r3, r3);
3298   StringCharAtGenerator generator(r0, r3, r2, r0, &runtime, &runtime, &runtime,
3299                                   STRING_INDEX_IS_NUMBER, RECEIVER_IS_STRING);
3300   generator.GenerateFast(masm);
3301   __ Drop(3);
3302   __ Ret();
3303   generator.SkipSlow(masm, &runtime);
3304 }
3305
3306
3307 void ToNumberStub::Generate(MacroAssembler* masm) {
3308   // The ToNumber stub takes one argument in r0.
3309   Label not_smi;
3310   __ JumpIfNotSmi(r0, &not_smi);
3311   __ Ret();
3312   __ bind(&not_smi);
3313
3314   Label not_heap_number;
3315   __ ldr(r1, FieldMemOperand(r0, HeapObject::kMapOffset));
3316   __ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
3317   // r0: object
3318   // r1: instance type.
3319   __ cmp(r1, Operand(HEAP_NUMBER_TYPE));
3320   __ b(ne, &not_heap_number);
3321   __ Ret();
3322   __ bind(&not_heap_number);
3323
3324   Label not_string, slow_string;
3325   __ cmp(r1, Operand(FIRST_NONSTRING_TYPE));
3326   __ b(hs, &not_string);
3327   // Check if string has a cached array index.
3328   __ ldr(r2, FieldMemOperand(r0, String::kHashFieldOffset));
3329   __ tst(r2, Operand(String::kContainsCachedArrayIndexMask));
3330   __ b(ne, &slow_string);
3331   __ IndexFromHash(r2, r0);
3332   __ Ret();
3333   __ bind(&slow_string);
3334   __ push(r0);  // Push argument.
3335   __ TailCallRuntime(Runtime::kStringToNumber, 1, 1);
3336   __ bind(&not_string);
3337
3338   Label not_oddball;
3339   __ cmp(r1, Operand(ODDBALL_TYPE));
3340   __ b(ne, &not_oddball);
3341   __ ldr(r0, FieldMemOperand(r0, Oddball::kToNumberOffset));
3342   __ Ret();
3343   __ bind(&not_oddball);
3344
3345   __ push(r0);  // Push argument.
3346   __ InvokeBuiltin(Builtins::TO_NUMBER, JUMP_FUNCTION);
3347 }
3348
3349
3350 void StringHelper::GenerateFlatOneByteStringEquals(
3351     MacroAssembler* masm, Register left, Register right, Register scratch1,
3352     Register scratch2, Register scratch3) {
3353   Register length = scratch1;
3354
3355   // Compare lengths.
3356   Label strings_not_equal, check_zero_length;
3357   __ ldr(length, FieldMemOperand(left, String::kLengthOffset));
3358   __ ldr(scratch2, FieldMemOperand(right, String::kLengthOffset));
3359   __ cmp(length, scratch2);
3360   __ b(eq, &check_zero_length);
3361   __ bind(&strings_not_equal);
3362   __ mov(r0, Operand(Smi::FromInt(NOT_EQUAL)));
3363   __ Ret();
3364
3365   // Check if the length is zero.
3366   Label compare_chars;
3367   __ bind(&check_zero_length);
3368   STATIC_ASSERT(kSmiTag == 0);
3369   __ cmp(length, Operand::Zero());
3370   __ b(ne, &compare_chars);
3371   __ mov(r0, Operand(Smi::FromInt(EQUAL)));
3372   __ Ret();
3373
3374   // Compare characters.
3375   __ bind(&compare_chars);
3376   GenerateOneByteCharsCompareLoop(masm, left, right, length, scratch2, scratch3,
3377                                   &strings_not_equal);
3378
3379   // Characters are equal.
3380   __ mov(r0, Operand(Smi::FromInt(EQUAL)));
3381   __ Ret();
3382 }
3383
3384
3385 void StringHelper::GenerateCompareFlatOneByteStrings(
3386     MacroAssembler* masm, Register left, Register right, Register scratch1,
3387     Register scratch2, Register scratch3, Register scratch4) {
3388   Label result_not_equal, compare_lengths;
3389   // Find minimum length and length difference.
3390   __ ldr(scratch1, FieldMemOperand(left, String::kLengthOffset));
3391   __ ldr(scratch2, FieldMemOperand(right, String::kLengthOffset));
3392   __ sub(scratch3, scratch1, Operand(scratch2), SetCC);
3393   Register length_delta = scratch3;
3394   __ mov(scratch1, scratch2, LeaveCC, gt);
3395   Register min_length = scratch1;
3396   STATIC_ASSERT(kSmiTag == 0);
3397   __ cmp(min_length, Operand::Zero());
3398   __ b(eq, &compare_lengths);
3399
3400   // Compare loop.
3401   GenerateOneByteCharsCompareLoop(masm, left, right, min_length, scratch2,
3402                                   scratch4, &result_not_equal);
3403
3404   // Compare lengths - strings up to min-length are equal.
3405   __ bind(&compare_lengths);
3406   DCHECK(Smi::FromInt(EQUAL) == static_cast<Smi*>(0));
3407   // Use length_delta as result if it's zero.
3408   __ mov(r0, Operand(length_delta), SetCC);
3409   __ bind(&result_not_equal);
3410   // Conditionally update the result based either on length_delta or
3411   // the last comparion performed in the loop above.
3412   __ mov(r0, Operand(Smi::FromInt(GREATER)), LeaveCC, gt);
3413   __ mov(r0, Operand(Smi::FromInt(LESS)), LeaveCC, lt);
3414   __ Ret();
3415 }
3416
3417
3418 void StringHelper::GenerateOneByteCharsCompareLoop(
3419     MacroAssembler* masm, Register left, Register right, Register length,
3420     Register scratch1, Register scratch2, Label* chars_not_equal) {
3421   // Change index to run from -length to -1 by adding length to string
3422   // start. This means that loop ends when index reaches zero, which
3423   // doesn't need an additional compare.
3424   __ SmiUntag(length);
3425   __ add(scratch1, length,
3426          Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
3427   __ add(left, left, Operand(scratch1));
3428   __ add(right, right, Operand(scratch1));
3429   __ rsb(length, length, Operand::Zero());
3430   Register index = length;  // index = -length;
3431
3432   // Compare loop.
3433   Label loop;
3434   __ bind(&loop);
3435   __ ldrb(scratch1, MemOperand(left, index));
3436   __ ldrb(scratch2, MemOperand(right, index));
3437   __ cmp(scratch1, scratch2);
3438   __ b(ne, chars_not_equal);
3439   __ add(index, index, Operand(1), SetCC);
3440   __ b(ne, &loop);
3441 }
3442
3443
3444 void StringCompareStub::Generate(MacroAssembler* masm) {
3445   Label runtime;
3446
3447   Counters* counters = isolate()->counters();
3448
3449   // Stack frame on entry.
3450   //  sp[0]: right string
3451   //  sp[4]: left string
3452   __ Ldrd(r0 , r1, MemOperand(sp));  // Load right in r0, left in r1.
3453
3454   Label not_same;
3455   __ cmp(r0, r1);
3456   __ b(ne, &not_same);
3457   STATIC_ASSERT(EQUAL == 0);
3458   STATIC_ASSERT(kSmiTag == 0);
3459   __ mov(r0, Operand(Smi::FromInt(EQUAL)));
3460   __ IncrementCounter(counters->string_compare_native(), 1, r1, r2);
3461   __ add(sp, sp, Operand(2 * kPointerSize));
3462   __ Ret();
3463
3464   __ bind(&not_same);
3465
3466   // Check that both objects are sequential one-byte strings.
3467   __ JumpIfNotBothSequentialOneByteStrings(r1, r0, r2, r3, &runtime);
3468
3469   // Compare flat one-byte strings natively. Remove arguments from stack first.
3470   __ IncrementCounter(counters->string_compare_native(), 1, r2, r3);
3471   __ add(sp, sp, Operand(2 * kPointerSize));
3472   StringHelper::GenerateCompareFlatOneByteStrings(masm, r1, r0, r2, r3, r4, r5);
3473
3474   // Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
3475   // tagged as a small integer.
3476   __ bind(&runtime);
3477   __ TailCallRuntime(Runtime::kStringCompareRT, 2, 1);
3478 }
3479
3480
3481 void BinaryOpICWithAllocationSiteStub::Generate(MacroAssembler* masm) {
3482   // ----------- S t a t e -------------
3483   //  -- r1    : left
3484   //  -- r0    : right
3485   //  -- lr    : return address
3486   // -----------------------------------
3487
3488   // Load r2 with the allocation site.  We stick an undefined dummy value here
3489   // and replace it with the real allocation site later when we instantiate this
3490   // stub in BinaryOpICWithAllocationSiteStub::GetCodeCopyFromTemplate().
3491   __ Move(r2, handle(isolate()->heap()->undefined_value()));
3492
3493   // Make sure that we actually patched the allocation site.
3494   if (FLAG_debug_code) {
3495     __ tst(r2, Operand(kSmiTagMask));
3496     __ Assert(ne, kExpectedAllocationSite);
3497     __ push(r2);
3498     __ ldr(r2, FieldMemOperand(r2, HeapObject::kMapOffset));
3499     __ LoadRoot(ip, Heap::kAllocationSiteMapRootIndex);
3500     __ cmp(r2, ip);
3501     __ pop(r2);
3502     __ Assert(eq, kExpectedAllocationSite);
3503   }
3504
3505   // Tail call into the stub that handles binary operations with allocation
3506   // sites.
3507   BinaryOpWithAllocationSiteStub stub(isolate(), state());
3508   __ TailCallStub(&stub);
3509 }
3510
3511
3512 void CompareICStub::GenerateSmis(MacroAssembler* masm) {
3513   DCHECK(state() == CompareICState::SMI);
3514   Label miss;
3515   __ orr(r2, r1, r0);
3516   __ JumpIfNotSmi(r2, &miss);
3517
3518   if (GetCondition() == eq) {
3519     // For equality we do not care about the sign of the result.
3520     __ sub(r0, r0, r1, SetCC);
3521   } else {
3522     // Untag before subtracting to avoid handling overflow.
3523     __ SmiUntag(r1);
3524     __ sub(r0, r1, Operand::SmiUntag(r0));
3525   }
3526   __ Ret();
3527
3528   __ bind(&miss);
3529   GenerateMiss(masm);
3530 }
3531
3532
3533 void CompareICStub::GenerateNumbers(MacroAssembler* masm) {
3534   DCHECK(state() == CompareICState::NUMBER);
3535
3536   Label generic_stub;
3537   Label unordered, maybe_undefined1, maybe_undefined2;
3538   Label miss;
3539
3540   if (left() == CompareICState::SMI) {
3541     __ JumpIfNotSmi(r1, &miss);
3542   }
3543   if (right() == CompareICState::SMI) {
3544     __ JumpIfNotSmi(r0, &miss);
3545   }
3546
3547   // Inlining the double comparison and falling back to the general compare
3548   // stub if NaN is involved.
3549   // Load left and right operand.
3550   Label done, left, left_smi, right_smi;
3551   __ JumpIfSmi(r0, &right_smi);
3552   __ CheckMap(r0, r2, Heap::kHeapNumberMapRootIndex, &maybe_undefined1,
3553               DONT_DO_SMI_CHECK);
3554   __ sub(r2, r0, Operand(kHeapObjectTag));
3555   __ vldr(d1, r2, HeapNumber::kValueOffset);
3556   __ b(&left);
3557   __ bind(&right_smi);
3558   __ SmiToDouble(d1, r0);
3559
3560   __ bind(&left);
3561   __ JumpIfSmi(r1, &left_smi);
3562   __ CheckMap(r1, r2, Heap::kHeapNumberMapRootIndex, &maybe_undefined2,
3563               DONT_DO_SMI_CHECK);
3564   __ sub(r2, r1, Operand(kHeapObjectTag));
3565   __ vldr(d0, r2, HeapNumber::kValueOffset);
3566   __ b(&done);
3567   __ bind(&left_smi);
3568   __ SmiToDouble(d0, r1);
3569
3570   __ bind(&done);
3571   // Compare operands.
3572   __ VFPCompareAndSetFlags(d0, d1);
3573
3574   // Don't base result on status bits when a NaN is involved.
3575   __ b(vs, &unordered);
3576
3577   // Return a result of -1, 0, or 1, based on status bits.
3578   __ mov(r0, Operand(EQUAL), LeaveCC, eq);
3579   __ mov(r0, Operand(LESS), LeaveCC, lt);
3580   __ mov(r0, Operand(GREATER), LeaveCC, gt);
3581   __ Ret();
3582
3583   __ bind(&unordered);
3584   __ bind(&generic_stub);
3585   CompareICStub stub(isolate(), op(), strong(), CompareICState::GENERIC,
3586                      CompareICState::GENERIC, CompareICState::GENERIC);
3587   __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
3588
3589   __ bind(&maybe_undefined1);
3590   if (Token::IsOrderedRelationalCompareOp(op())) {
3591     __ CompareRoot(r0, Heap::kUndefinedValueRootIndex);
3592     __ b(ne, &miss);
3593     __ JumpIfSmi(r1, &unordered);
3594     __ CompareObjectType(r1, r2, r2, HEAP_NUMBER_TYPE);
3595     __ b(ne, &maybe_undefined2);
3596     __ jmp(&unordered);
3597   }
3598
3599   __ bind(&maybe_undefined2);
3600   if (Token::IsOrderedRelationalCompareOp(op())) {
3601     __ CompareRoot(r1, Heap::kUndefinedValueRootIndex);
3602     __ b(eq, &unordered);
3603   }
3604
3605   __ bind(&miss);
3606   GenerateMiss(masm);
3607 }
3608
3609
3610 void CompareICStub::GenerateInternalizedStrings(MacroAssembler* masm) {
3611   DCHECK(state() == CompareICState::INTERNALIZED_STRING);
3612   Label miss;
3613
3614   // Registers containing left and right operands respectively.
3615   Register left = r1;
3616   Register right = r0;
3617   Register tmp1 = r2;
3618   Register tmp2 = r3;
3619
3620   // Check that both operands are heap objects.
3621   __ JumpIfEitherSmi(left, right, &miss);
3622
3623   // Check that both operands are internalized strings.
3624   __ ldr(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
3625   __ ldr(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
3626   __ ldrb(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
3627   __ ldrb(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
3628   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
3629   __ orr(tmp1, tmp1, Operand(tmp2));
3630   __ tst(tmp1, Operand(kIsNotStringMask | kIsNotInternalizedMask));
3631   __ b(ne, &miss);
3632
3633   // Internalized strings are compared by identity.
3634   __ cmp(left, right);
3635   // Make sure r0 is non-zero. At this point input operands are
3636   // guaranteed to be non-zero.
3637   DCHECK(right.is(r0));
3638   STATIC_ASSERT(EQUAL == 0);
3639   STATIC_ASSERT(kSmiTag == 0);
3640   __ mov(r0, Operand(Smi::FromInt(EQUAL)), LeaveCC, eq);
3641   __ Ret();
3642
3643   __ bind(&miss);
3644   GenerateMiss(masm);
3645 }
3646
3647
3648 void CompareICStub::GenerateUniqueNames(MacroAssembler* masm) {
3649   DCHECK(state() == CompareICState::UNIQUE_NAME);
3650   DCHECK(GetCondition() == eq);
3651   Label miss;
3652
3653   // Registers containing left and right operands respectively.
3654   Register left = r1;
3655   Register right = r0;
3656   Register tmp1 = r2;
3657   Register tmp2 = r3;
3658
3659   // Check that both operands are heap objects.
3660   __ JumpIfEitherSmi(left, right, &miss);
3661
3662   // Check that both operands are unique names. This leaves the instance
3663   // types loaded in tmp1 and tmp2.
3664   __ ldr(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
3665   __ ldr(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
3666   __ ldrb(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
3667   __ ldrb(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
3668
3669   __ JumpIfNotUniqueNameInstanceType(tmp1, &miss);
3670   __ JumpIfNotUniqueNameInstanceType(tmp2, &miss);
3671
3672   // Unique names are compared by identity.
3673   __ cmp(left, right);
3674   // Make sure r0 is non-zero. At this point input operands are
3675   // guaranteed to be non-zero.
3676   DCHECK(right.is(r0));
3677   STATIC_ASSERT(EQUAL == 0);
3678   STATIC_ASSERT(kSmiTag == 0);
3679   __ mov(r0, Operand(Smi::FromInt(EQUAL)), LeaveCC, eq);
3680   __ Ret();
3681
3682   __ bind(&miss);
3683   GenerateMiss(masm);
3684 }
3685
3686
3687 void CompareICStub::GenerateStrings(MacroAssembler* masm) {
3688   DCHECK(state() == CompareICState::STRING);
3689   Label miss;
3690
3691   bool equality = Token::IsEqualityOp(op());
3692
3693   // Registers containing left and right operands respectively.
3694   Register left = r1;
3695   Register right = r0;
3696   Register tmp1 = r2;
3697   Register tmp2 = r3;
3698   Register tmp3 = r4;
3699   Register tmp4 = r5;
3700
3701   // Check that both operands are heap objects.
3702   __ JumpIfEitherSmi(left, right, &miss);
3703
3704   // Check that both operands are strings. This leaves the instance
3705   // types loaded in tmp1 and tmp2.
3706   __ ldr(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
3707   __ ldr(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
3708   __ ldrb(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
3709   __ ldrb(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
3710   STATIC_ASSERT(kNotStringTag != 0);
3711   __ orr(tmp3, tmp1, tmp2);
3712   __ tst(tmp3, Operand(kIsNotStringMask));
3713   __ b(ne, &miss);
3714
3715   // Fast check for identical strings.
3716   __ cmp(left, right);
3717   STATIC_ASSERT(EQUAL == 0);
3718   STATIC_ASSERT(kSmiTag == 0);
3719   __ mov(r0, Operand(Smi::FromInt(EQUAL)), LeaveCC, eq);
3720   __ Ret(eq);
3721
3722   // Handle not identical strings.
3723
3724   // Check that both strings are internalized strings. If they are, we're done
3725   // because we already know they are not identical. We know they are both
3726   // strings.
3727   if (equality) {
3728     DCHECK(GetCondition() == eq);
3729     STATIC_ASSERT(kInternalizedTag == 0);
3730     __ orr(tmp3, tmp1, Operand(tmp2));
3731     __ tst(tmp3, Operand(kIsNotInternalizedMask));
3732     // Make sure r0 is non-zero. At this point input operands are
3733     // guaranteed to be non-zero.
3734     DCHECK(right.is(r0));
3735     __ Ret(eq);
3736   }
3737
3738   // Check that both strings are sequential one-byte.
3739   Label runtime;
3740   __ JumpIfBothInstanceTypesAreNotSequentialOneByte(tmp1, tmp2, tmp3, tmp4,
3741                                                     &runtime);
3742
3743   // Compare flat one-byte strings. Returns when done.
3744   if (equality) {
3745     StringHelper::GenerateFlatOneByteStringEquals(masm, left, right, tmp1, tmp2,
3746                                                   tmp3);
3747   } else {
3748     StringHelper::GenerateCompareFlatOneByteStrings(masm, left, right, tmp1,
3749                                                     tmp2, tmp3, tmp4);
3750   }
3751
3752   // Handle more complex cases in runtime.
3753   __ bind(&runtime);
3754   __ Push(left, right);
3755   if (equality) {
3756     __ TailCallRuntime(Runtime::kStringEquals, 2, 1);
3757   } else {
3758     __ TailCallRuntime(Runtime::kStringCompareRT, 2, 1);
3759   }
3760
3761   __ bind(&miss);
3762   GenerateMiss(masm);
3763 }
3764
3765
3766 void CompareICStub::GenerateObjects(MacroAssembler* masm) {
3767   DCHECK(state() == CompareICState::OBJECT);
3768   Label miss;
3769   __ and_(r2, r1, Operand(r0));
3770   __ JumpIfSmi(r2, &miss);
3771
3772   __ CompareObjectType(r0, r2, r2, JS_OBJECT_TYPE);
3773   __ b(ne, &miss);
3774   __ CompareObjectType(r1, r2, r2, JS_OBJECT_TYPE);
3775   __ b(ne, &miss);
3776
3777   DCHECK(GetCondition() == eq);
3778   __ sub(r0, r0, Operand(r1));
3779   __ Ret();
3780
3781   __ bind(&miss);
3782   GenerateMiss(masm);
3783 }
3784
3785
3786 void CompareICStub::GenerateKnownObjects(MacroAssembler* masm) {
3787   Label miss;
3788   Handle<WeakCell> cell = Map::WeakCellForMap(known_map_);
3789   __ and_(r2, r1, Operand(r0));
3790   __ JumpIfSmi(r2, &miss);
3791   __ GetWeakValue(r4, cell);
3792   __ ldr(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
3793   __ ldr(r3, FieldMemOperand(r1, HeapObject::kMapOffset));
3794   __ cmp(r2, r4);
3795   __ b(ne, &miss);
3796   __ cmp(r3, r4);
3797   __ b(ne, &miss);
3798
3799   __ sub(r0, r0, Operand(r1));
3800   __ Ret();
3801
3802   __ bind(&miss);
3803   GenerateMiss(masm);
3804 }
3805
3806
3807 void CompareICStub::GenerateMiss(MacroAssembler* masm) {
3808   {
3809     // Call the runtime system in a fresh internal frame.
3810     ExternalReference miss =
3811         ExternalReference(IC_Utility(IC::kCompareIC_Miss), isolate());
3812
3813     FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
3814     __ Push(r1, r0);
3815     __ Push(lr, r1, r0);
3816     __ mov(ip, Operand(Smi::FromInt(op())));
3817     __ push(ip);
3818     __ CallExternalReference(miss, 3);
3819     // Compute the entry point of the rewritten stub.
3820     __ add(r2, r0, Operand(Code::kHeaderSize - kHeapObjectTag));
3821     // Restore registers.
3822     __ pop(lr);
3823     __ Pop(r1, r0);
3824   }
3825
3826   __ Jump(r2);
3827 }
3828
3829
3830 void DirectCEntryStub::Generate(MacroAssembler* masm) {
3831   // Place the return address on the stack, making the call
3832   // GC safe. The RegExp backend also relies on this.
3833   __ str(lr, MemOperand(sp, 0));
3834   __ blx(ip);  // Call the C++ function.
3835   __ VFPEnsureFPSCRState(r2);
3836   __ ldr(pc, MemOperand(sp, 0));
3837 }
3838
3839
3840 void DirectCEntryStub::GenerateCall(MacroAssembler* masm,
3841                                     Register target) {
3842   intptr_t code =
3843       reinterpret_cast<intptr_t>(GetCode().location());
3844   __ Move(ip, target);
3845   __ mov(lr, Operand(code, RelocInfo::CODE_TARGET));
3846   __ blx(lr);  // Call the stub.
3847 }
3848
3849
3850 void NameDictionaryLookupStub::GenerateNegativeLookup(MacroAssembler* masm,
3851                                                       Label* miss,
3852                                                       Label* done,
3853                                                       Register receiver,
3854                                                       Register properties,
3855                                                       Handle<Name> name,
3856                                                       Register scratch0) {
3857   DCHECK(name->IsUniqueName());
3858   // If names of slots in range from 1 to kProbes - 1 for the hash value are
3859   // not equal to the name and kProbes-th slot is not used (its name is the
3860   // undefined value), it guarantees the hash table doesn't contain the
3861   // property. It's true even if some slots represent deleted properties
3862   // (their names are the hole value).
3863   for (int i = 0; i < kInlinedProbes; i++) {
3864     // scratch0 points to properties hash.
3865     // Compute the masked index: (hash + i + i * i) & mask.
3866     Register index = scratch0;
3867     // Capacity is smi 2^n.
3868     __ ldr(index, FieldMemOperand(properties, kCapacityOffset));
3869     __ sub(index, index, Operand(1));
3870     __ and_(index, index, Operand(
3871         Smi::FromInt(name->Hash() + NameDictionary::GetProbeOffset(i))));
3872
3873     // Scale the index by multiplying by the entry size.
3874     STATIC_ASSERT(NameDictionary::kEntrySize == 3);
3875     __ add(index, index, Operand(index, LSL, 1));  // index *= 3.
3876
3877     Register entity_name = scratch0;
3878     // Having undefined at this place means the name is not contained.
3879     DCHECK_EQ(kSmiTagSize, 1);
3880     Register tmp = properties;
3881     __ add(tmp, properties, Operand(index, LSL, 1));
3882     __ ldr(entity_name, FieldMemOperand(tmp, kElementsStartOffset));
3883
3884     DCHECK(!tmp.is(entity_name));
3885     __ LoadRoot(tmp, Heap::kUndefinedValueRootIndex);
3886     __ cmp(entity_name, tmp);
3887     __ b(eq, done);
3888
3889     // Load the hole ready for use below:
3890     __ LoadRoot(tmp, Heap::kTheHoleValueRootIndex);
3891
3892     // Stop if found the property.
3893     __ cmp(entity_name, Operand(Handle<Name>(name)));
3894     __ b(eq, miss);
3895
3896     Label good;
3897     __ cmp(entity_name, tmp);
3898     __ b(eq, &good);
3899
3900     // Check if the entry name is not a unique name.
3901     __ ldr(entity_name, FieldMemOperand(entity_name, HeapObject::kMapOffset));
3902     __ ldrb(entity_name,
3903             FieldMemOperand(entity_name, Map::kInstanceTypeOffset));
3904     __ JumpIfNotUniqueNameInstanceType(entity_name, miss);
3905     __ bind(&good);
3906
3907     // Restore the properties.
3908     __ ldr(properties,
3909            FieldMemOperand(receiver, JSObject::kPropertiesOffset));
3910   }
3911
3912   const int spill_mask =
3913       (lr.bit() | r6.bit() | r5.bit() | r4.bit() | r3.bit() |
3914        r2.bit() | r1.bit() | r0.bit());
3915
3916   __ stm(db_w, sp, spill_mask);
3917   __ ldr(r0, FieldMemOperand(receiver, JSObject::kPropertiesOffset));
3918   __ mov(r1, Operand(Handle<Name>(name)));
3919   NameDictionaryLookupStub stub(masm->isolate(), NEGATIVE_LOOKUP);
3920   __ CallStub(&stub);
3921   __ cmp(r0, Operand::Zero());
3922   __ ldm(ia_w, sp, spill_mask);
3923
3924   __ b(eq, done);
3925   __ b(ne, miss);
3926 }
3927
3928
3929 // Probe the name dictionary in the |elements| register. Jump to the
3930 // |done| label if a property with the given name is found. Jump to
3931 // the |miss| label otherwise.
3932 // If lookup was successful |scratch2| will be equal to elements + 4 * index.
3933 void NameDictionaryLookupStub::GeneratePositiveLookup(MacroAssembler* masm,
3934                                                       Label* miss,
3935                                                       Label* done,
3936                                                       Register elements,
3937                                                       Register name,
3938                                                       Register scratch1,
3939                                                       Register scratch2) {
3940   DCHECK(!elements.is(scratch1));
3941   DCHECK(!elements.is(scratch2));
3942   DCHECK(!name.is(scratch1));
3943   DCHECK(!name.is(scratch2));
3944
3945   __ AssertName(name);
3946
3947   // Compute the capacity mask.
3948   __ ldr(scratch1, FieldMemOperand(elements, kCapacityOffset));
3949   __ SmiUntag(scratch1);
3950   __ sub(scratch1, scratch1, Operand(1));
3951
3952   // Generate an unrolled loop that performs a few probes before
3953   // giving up. Measurements done on Gmail indicate that 2 probes
3954   // cover ~93% of loads from dictionaries.
3955   for (int i = 0; i < kInlinedProbes; i++) {
3956     // Compute the masked index: (hash + i + i * i) & mask.
3957     __ ldr(scratch2, FieldMemOperand(name, Name::kHashFieldOffset));
3958     if (i > 0) {
3959       // Add the probe offset (i + i * i) left shifted to avoid right shifting
3960       // the hash in a separate instruction. The value hash + i + i * i is right
3961       // shifted in the following and instruction.
3962       DCHECK(NameDictionary::GetProbeOffset(i) <
3963              1 << (32 - Name::kHashFieldOffset));
3964       __ add(scratch2, scratch2, Operand(
3965           NameDictionary::GetProbeOffset(i) << Name::kHashShift));
3966     }
3967     __ and_(scratch2, scratch1, Operand(scratch2, LSR, Name::kHashShift));
3968
3969     // Scale the index by multiplying by the element size.
3970     DCHECK(NameDictionary::kEntrySize == 3);
3971     // scratch2 = scratch2 * 3.
3972     __ add(scratch2, scratch2, Operand(scratch2, LSL, 1));
3973
3974     // Check if the key is identical to the name.
3975     __ add(scratch2, elements, Operand(scratch2, LSL, 2));
3976     __ ldr(ip, FieldMemOperand(scratch2, kElementsStartOffset));
3977     __ cmp(name, Operand(ip));
3978     __ b(eq, done);
3979   }
3980
3981   const int spill_mask =
3982       (lr.bit() | r6.bit() | r5.bit() | r4.bit() |
3983        r3.bit() | r2.bit() | r1.bit() | r0.bit()) &
3984       ~(scratch1.bit() | scratch2.bit());
3985
3986   __ stm(db_w, sp, spill_mask);
3987   if (name.is(r0)) {
3988     DCHECK(!elements.is(r1));
3989     __ Move(r1, name);
3990     __ Move(r0, elements);
3991   } else {
3992     __ Move(r0, elements);
3993     __ Move(r1, name);
3994   }
3995   NameDictionaryLookupStub stub(masm->isolate(), POSITIVE_LOOKUP);
3996   __ CallStub(&stub);
3997   __ cmp(r0, Operand::Zero());
3998   __ mov(scratch2, Operand(r2));
3999   __ ldm(ia_w, sp, spill_mask);
4000
4001   __ b(ne, done);
4002   __ b(eq, miss);
4003 }
4004
4005
4006 void NameDictionaryLookupStub::Generate(MacroAssembler* masm) {
4007   // This stub overrides SometimesSetsUpAFrame() to return false.  That means
4008   // we cannot call anything that could cause a GC from this stub.
4009   // Registers:
4010   //  result: NameDictionary to probe
4011   //  r1: key
4012   //  dictionary: NameDictionary to probe.
4013   //  index: will hold an index of entry if lookup is successful.
4014   //         might alias with result_.
4015   // Returns:
4016   //  result_ is zero if lookup failed, non zero otherwise.
4017
4018   Register result = r0;
4019   Register dictionary = r0;
4020   Register key = r1;
4021   Register index = r2;
4022   Register mask = r3;
4023   Register hash = r4;
4024   Register undefined = r5;
4025   Register entry_key = r6;
4026
4027   Label in_dictionary, maybe_in_dictionary, not_in_dictionary;
4028
4029   __ ldr(mask, FieldMemOperand(dictionary, kCapacityOffset));
4030   __ SmiUntag(mask);
4031   __ sub(mask, mask, Operand(1));
4032
4033   __ ldr(hash, FieldMemOperand(key, Name::kHashFieldOffset));
4034
4035   __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
4036
4037   for (int i = kInlinedProbes; i < kTotalProbes; i++) {
4038     // Compute the masked index: (hash + i + i * i) & mask.
4039     // Capacity is smi 2^n.
4040     if (i > 0) {
4041       // Add the probe offset (i + i * i) left shifted to avoid right shifting
4042       // the hash in a separate instruction. The value hash + i + i * i is right
4043       // shifted in the following and instruction.
4044       DCHECK(NameDictionary::GetProbeOffset(i) <
4045              1 << (32 - Name::kHashFieldOffset));
4046       __ add(index, hash, Operand(
4047           NameDictionary::GetProbeOffset(i) << Name::kHashShift));
4048     } else {
4049       __ mov(index, Operand(hash));
4050     }
4051     __ and_(index, mask, Operand(index, LSR, Name::kHashShift));
4052
4053     // Scale the index by multiplying by the entry size.
4054     DCHECK(NameDictionary::kEntrySize == 3);
4055     __ add(index, index, Operand(index, LSL, 1));  // index *= 3.
4056
4057     DCHECK_EQ(kSmiTagSize, 1);
4058     __ add(index, dictionary, Operand(index, LSL, 2));
4059     __ ldr(entry_key, FieldMemOperand(index, kElementsStartOffset));
4060
4061     // Having undefined at this place means the name is not contained.
4062     __ cmp(entry_key, Operand(undefined));
4063     __ b(eq, &not_in_dictionary);
4064
4065     // Stop if found the property.
4066     __ cmp(entry_key, Operand(key));
4067     __ b(eq, &in_dictionary);
4068
4069     if (i != kTotalProbes - 1 && mode() == NEGATIVE_LOOKUP) {
4070       // Check if the entry name is not a unique name.
4071       __ ldr(entry_key, FieldMemOperand(entry_key, HeapObject::kMapOffset));
4072       __ ldrb(entry_key,
4073               FieldMemOperand(entry_key, Map::kInstanceTypeOffset));
4074       __ JumpIfNotUniqueNameInstanceType(entry_key, &maybe_in_dictionary);
4075     }
4076   }
4077
4078   __ bind(&maybe_in_dictionary);
4079   // If we are doing negative lookup then probing failure should be
4080   // treated as a lookup success. For positive lookup probing failure
4081   // should be treated as lookup failure.
4082   if (mode() == POSITIVE_LOOKUP) {
4083     __ mov(result, Operand::Zero());
4084     __ Ret();
4085   }
4086
4087   __ bind(&in_dictionary);
4088   __ mov(result, Operand(1));
4089   __ Ret();
4090
4091   __ bind(&not_in_dictionary);
4092   __ mov(result, Operand::Zero());
4093   __ Ret();
4094 }
4095
4096
4097 void StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(
4098     Isolate* isolate) {
4099   StoreBufferOverflowStub stub1(isolate, kDontSaveFPRegs);
4100   stub1.GetCode();
4101   // Hydrogen code stubs need stub2 at snapshot time.
4102   StoreBufferOverflowStub stub2(isolate, kSaveFPRegs);
4103   stub2.GetCode();
4104 }
4105
4106
4107 // Takes the input in 3 registers: address_ value_ and object_.  A pointer to
4108 // the value has just been written into the object, now this stub makes sure
4109 // we keep the GC informed.  The word in the object where the value has been
4110 // written is in the address register.
4111 void RecordWriteStub::Generate(MacroAssembler* masm) {
4112   Label skip_to_incremental_noncompacting;
4113   Label skip_to_incremental_compacting;
4114
4115   // The first two instructions are generated with labels so as to get the
4116   // offset fixed up correctly by the bind(Label*) call.  We patch it back and
4117   // forth between a compare instructions (a nop in this position) and the
4118   // real branch when we start and stop incremental heap marking.
4119   // See RecordWriteStub::Patch for details.
4120   {
4121     // Block literal pool emission, as the position of these two instructions
4122     // is assumed by the patching code.
4123     Assembler::BlockConstPoolScope block_const_pool(masm);
4124     __ b(&skip_to_incremental_noncompacting);
4125     __ b(&skip_to_incremental_compacting);
4126   }
4127
4128   if (remembered_set_action() == EMIT_REMEMBERED_SET) {
4129     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4130                            MacroAssembler::kReturnAtEnd);
4131   }
4132   __ Ret();
4133
4134   __ bind(&skip_to_incremental_noncompacting);
4135   GenerateIncremental(masm, INCREMENTAL);
4136
4137   __ bind(&skip_to_incremental_compacting);
4138   GenerateIncremental(masm, INCREMENTAL_COMPACTION);
4139
4140   // Initial mode of the stub is expected to be STORE_BUFFER_ONLY.
4141   // Will be checked in IncrementalMarking::ActivateGeneratedStub.
4142   DCHECK(Assembler::GetBranchOffset(masm->instr_at(0)) < (1 << 12));
4143   DCHECK(Assembler::GetBranchOffset(masm->instr_at(4)) < (1 << 12));
4144   PatchBranchIntoNop(masm, 0);
4145   PatchBranchIntoNop(masm, Assembler::kInstrSize);
4146 }
4147
4148
4149 void RecordWriteStub::GenerateIncremental(MacroAssembler* masm, Mode mode) {
4150   regs_.Save(masm);
4151
4152   if (remembered_set_action() == EMIT_REMEMBERED_SET) {
4153     Label dont_need_remembered_set;
4154
4155     __ ldr(regs_.scratch0(), MemOperand(regs_.address(), 0));
4156     __ JumpIfNotInNewSpace(regs_.scratch0(),  // Value.
4157                            regs_.scratch0(),
4158                            &dont_need_remembered_set);
4159
4160     __ CheckPageFlag(regs_.object(),
4161                      regs_.scratch0(),
4162                      1 << MemoryChunk::SCAN_ON_SCAVENGE,
4163                      ne,
4164                      &dont_need_remembered_set);
4165
4166     // First notify the incremental marker if necessary, then update the
4167     // remembered set.
4168     CheckNeedsToInformIncrementalMarker(
4169         masm, kUpdateRememberedSetOnNoNeedToInformIncrementalMarker, mode);
4170     InformIncrementalMarker(masm);
4171     regs_.Restore(masm);
4172     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4173                            MacroAssembler::kReturnAtEnd);
4174
4175     __ bind(&dont_need_remembered_set);
4176   }
4177
4178   CheckNeedsToInformIncrementalMarker(
4179       masm, kReturnOnNoNeedToInformIncrementalMarker, mode);
4180   InformIncrementalMarker(masm);
4181   regs_.Restore(masm);
4182   __ Ret();
4183 }
4184
4185
4186 void RecordWriteStub::InformIncrementalMarker(MacroAssembler* masm) {
4187   regs_.SaveCallerSaveRegisters(masm, save_fp_regs_mode());
4188   int argument_count = 3;
4189   __ PrepareCallCFunction(argument_count, regs_.scratch0());
4190   Register address =
4191       r0.is(regs_.address()) ? regs_.scratch0() : regs_.address();
4192   DCHECK(!address.is(regs_.object()));
4193   DCHECK(!address.is(r0));
4194   __ Move(address, regs_.address());
4195   __ Move(r0, regs_.object());
4196   __ Move(r1, address);
4197   __ mov(r2, Operand(ExternalReference::isolate_address(isolate())));
4198
4199   AllowExternalCallThatCantCauseGC scope(masm);
4200   __ CallCFunction(
4201       ExternalReference::incremental_marking_record_write_function(isolate()),
4202       argument_count);
4203   regs_.RestoreCallerSaveRegisters(masm, save_fp_regs_mode());
4204 }
4205
4206
4207 void RecordWriteStub::CheckNeedsToInformIncrementalMarker(
4208     MacroAssembler* masm,
4209     OnNoNeedToInformIncrementalMarker on_no_need,
4210     Mode mode) {
4211   Label on_black;
4212   Label need_incremental;
4213   Label need_incremental_pop_scratch;
4214
4215   __ and_(regs_.scratch0(), regs_.object(), Operand(~Page::kPageAlignmentMask));
4216   __ ldr(regs_.scratch1(),
4217          MemOperand(regs_.scratch0(),
4218                     MemoryChunk::kWriteBarrierCounterOffset));
4219   __ sub(regs_.scratch1(), regs_.scratch1(), Operand(1), SetCC);
4220   __ str(regs_.scratch1(),
4221          MemOperand(regs_.scratch0(),
4222                     MemoryChunk::kWriteBarrierCounterOffset));
4223   __ b(mi, &need_incremental);
4224
4225   // Let's look at the color of the object:  If it is not black we don't have
4226   // to inform the incremental marker.
4227   __ JumpIfBlack(regs_.object(), regs_.scratch0(), regs_.scratch1(), &on_black);
4228
4229   regs_.Restore(masm);
4230   if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
4231     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4232                            MacroAssembler::kReturnAtEnd);
4233   } else {
4234     __ Ret();
4235   }
4236
4237   __ bind(&on_black);
4238
4239   // Get the value from the slot.
4240   __ ldr(regs_.scratch0(), MemOperand(regs_.address(), 0));
4241
4242   if (mode == INCREMENTAL_COMPACTION) {
4243     Label ensure_not_white;
4244
4245     __ CheckPageFlag(regs_.scratch0(),  // Contains value.
4246                      regs_.scratch1(),  // Scratch.
4247                      MemoryChunk::kEvacuationCandidateMask,
4248                      eq,
4249                      &ensure_not_white);
4250
4251     __ CheckPageFlag(regs_.object(),
4252                      regs_.scratch1(),  // Scratch.
4253                      MemoryChunk::kSkipEvacuationSlotsRecordingMask,
4254                      eq,
4255                      &need_incremental);
4256
4257     __ bind(&ensure_not_white);
4258   }
4259
4260   // We need extra registers for this, so we push the object and the address
4261   // register temporarily.
4262   __ Push(regs_.object(), regs_.address());
4263   __ EnsureNotWhite(regs_.scratch0(),  // The value.
4264                     regs_.scratch1(),  // Scratch.
4265                     regs_.object(),  // Scratch.
4266                     regs_.address(),  // Scratch.
4267                     &need_incremental_pop_scratch);
4268   __ Pop(regs_.object(), regs_.address());
4269
4270   regs_.Restore(masm);
4271   if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
4272     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4273                            MacroAssembler::kReturnAtEnd);
4274   } else {
4275     __ Ret();
4276   }
4277
4278   __ bind(&need_incremental_pop_scratch);
4279   __ Pop(regs_.object(), regs_.address());
4280
4281   __ bind(&need_incremental);
4282
4283   // Fall through when we need to inform the incremental marker.
4284 }
4285
4286
4287 void StoreArrayLiteralElementStub::Generate(MacroAssembler* masm) {
4288   // ----------- S t a t e -------------
4289   //  -- r0    : element value to store
4290   //  -- r3    : element index as smi
4291   //  -- sp[0] : array literal index in function as smi
4292   //  -- sp[4] : array literal
4293   // clobbers r1, r2, r4
4294   // -----------------------------------
4295
4296   Label element_done;
4297   Label double_elements;
4298   Label smi_element;
4299   Label slow_elements;
4300   Label fast_elements;
4301
4302   // Get array literal index, array literal and its map.
4303   __ ldr(r4, MemOperand(sp, 0 * kPointerSize));
4304   __ ldr(r1, MemOperand(sp, 1 * kPointerSize));
4305   __ ldr(r2, FieldMemOperand(r1, JSObject::kMapOffset));
4306
4307   __ CheckFastElements(r2, r5, &double_elements);
4308   // FAST_*_SMI_ELEMENTS or FAST_*_ELEMENTS
4309   __ JumpIfSmi(r0, &smi_element);
4310   __ CheckFastSmiElements(r2, r5, &fast_elements);
4311
4312   // Store into the array literal requires a elements transition. Call into
4313   // the runtime.
4314   __ bind(&slow_elements);
4315   // call.
4316   __ Push(r1, r3, r0);
4317   __ ldr(r5, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
4318   __ ldr(r5, FieldMemOperand(r5, JSFunction::kLiteralsOffset));
4319   __ Push(r5, r4);
4320   __ TailCallRuntime(Runtime::kStoreArrayLiteralElement, 5, 1);
4321
4322   // Array literal has ElementsKind of FAST_*_ELEMENTS and value is an object.
4323   __ bind(&fast_elements);
4324   __ ldr(r5, FieldMemOperand(r1, JSObject::kElementsOffset));
4325   __ add(r6, r5, Operand::PointerOffsetFromSmiKey(r3));
4326   __ add(r6, r6, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4327   __ str(r0, MemOperand(r6, 0));
4328   // Update the write barrier for the array store.
4329   __ RecordWrite(r5, r6, r0, kLRHasNotBeenSaved, kDontSaveFPRegs,
4330                  EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
4331   __ Ret();
4332
4333   // Array literal has ElementsKind of FAST_*_SMI_ELEMENTS or FAST_*_ELEMENTS,
4334   // and value is Smi.
4335   __ bind(&smi_element);
4336   __ ldr(r5, FieldMemOperand(r1, JSObject::kElementsOffset));
4337   __ add(r6, r5, Operand::PointerOffsetFromSmiKey(r3));
4338   __ str(r0, FieldMemOperand(r6, FixedArray::kHeaderSize));
4339   __ Ret();
4340
4341   // Array literal has ElementsKind of FAST_DOUBLE_ELEMENTS.
4342   __ bind(&double_elements);
4343   __ ldr(r5, FieldMemOperand(r1, JSObject::kElementsOffset));
4344   __ StoreNumberToDoubleElements(r0, r3, r5, r6, d0, &slow_elements);
4345   __ Ret();
4346 }
4347
4348
4349 void StubFailureTrampolineStub::Generate(MacroAssembler* masm) {
4350   CEntryStub ces(isolate(), 1, kSaveFPRegs);
4351   __ Call(ces.GetCode(), RelocInfo::CODE_TARGET);
4352   int parameter_count_offset =
4353       StubFailureTrampolineFrame::kCallerStackParameterCountFrameOffset;
4354   __ ldr(r1, MemOperand(fp, parameter_count_offset));
4355   if (function_mode() == JS_FUNCTION_STUB_MODE) {
4356     __ add(r1, r1, Operand(1));
4357   }
4358   masm->LeaveFrame(StackFrame::STUB_FAILURE_TRAMPOLINE);
4359   __ mov(r1, Operand(r1, LSL, kPointerSizeLog2));
4360   __ add(sp, sp, r1);
4361   __ Ret();
4362 }
4363
4364
4365 void LoadICTrampolineStub::Generate(MacroAssembler* masm) {
4366   EmitLoadTypeFeedbackVector(masm, LoadWithVectorDescriptor::VectorRegister());
4367   LoadICStub stub(isolate(), state());
4368   stub.GenerateForTrampoline(masm);
4369 }
4370
4371
4372 void KeyedLoadICTrampolineStub::Generate(MacroAssembler* masm) {
4373   EmitLoadTypeFeedbackVector(masm, LoadWithVectorDescriptor::VectorRegister());
4374   KeyedLoadICStub stub(isolate());
4375   stub.GenerateForTrampoline(masm);
4376 }
4377
4378
4379 void CallICTrampolineStub::Generate(MacroAssembler* masm) {
4380   EmitLoadTypeFeedbackVector(masm, r2);
4381   CallICStub stub(isolate(), state());
4382   __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
4383 }
4384
4385
4386 void CallIC_ArrayTrampolineStub::Generate(MacroAssembler* masm) {
4387   EmitLoadTypeFeedbackVector(masm, r2);
4388   CallIC_ArrayStub stub(isolate(), state());
4389   __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
4390 }
4391
4392
4393 void LoadICStub::Generate(MacroAssembler* masm) { GenerateImpl(masm, false); }
4394
4395
4396 void LoadICStub::GenerateForTrampoline(MacroAssembler* masm) {
4397   GenerateImpl(masm, true);
4398 }
4399
4400
4401 static void HandleArrayCases(MacroAssembler* masm, Register receiver,
4402                              Register key, Register vector, Register slot,
4403                              Register feedback, Register receiver_map,
4404                              Register scratch1, Register scratch2,
4405                              bool is_polymorphic, Label* miss) {
4406   // feedback initially contains the feedback array
4407   Label next_loop, prepare_next;
4408   Label start_polymorphic;
4409
4410   Register cached_map = scratch1;
4411
4412   __ ldr(cached_map,
4413          FieldMemOperand(feedback, FixedArray::OffsetOfElementAt(0)));
4414   __ ldr(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
4415   __ cmp(receiver_map, cached_map);
4416   __ b(ne, &start_polymorphic);
4417   // found, now call handler.
4418   Register handler = feedback;
4419   __ ldr(handler, FieldMemOperand(feedback, FixedArray::OffsetOfElementAt(1)));
4420   __ add(pc, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
4421
4422
4423   Register length = scratch2;
4424   __ bind(&start_polymorphic);
4425   __ ldr(length, FieldMemOperand(feedback, FixedArray::kLengthOffset));
4426   if (!is_polymorphic) {
4427     // If the IC could be monomorphic we have to make sure we don't go past the
4428     // end of the feedback array.
4429     __ cmp(length, Operand(Smi::FromInt(2)));
4430     __ b(eq, miss);
4431   }
4432
4433   Register too_far = length;
4434   Register pointer_reg = feedback;
4435
4436   // +-----+------+------+-----+-----+ ... ----+
4437   // | map | len  | wm0  | h0  | wm1 |      hN |
4438   // +-----+------+------+-----+-----+ ... ----+
4439   //                 0      1     2        len-1
4440   //                              ^              ^
4441   //                              |              |
4442   //                         pointer_reg      too_far
4443   //                         aka feedback     scratch2
4444   // also need receiver_map
4445   // use cached_map (scratch1) to look in the weak map values.
4446   __ add(too_far, feedback, Operand::PointerOffsetFromSmiKey(length));
4447   __ add(too_far, too_far, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4448   __ add(pointer_reg, feedback,
4449          Operand(FixedArray::OffsetOfElementAt(2) - kHeapObjectTag));
4450
4451   __ bind(&next_loop);
4452   __ ldr(cached_map, MemOperand(pointer_reg));
4453   __ ldr(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
4454   __ cmp(receiver_map, cached_map);
4455   __ b(ne, &prepare_next);
4456   __ ldr(handler, MemOperand(pointer_reg, kPointerSize));
4457   __ add(pc, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
4458
4459   __ bind(&prepare_next);
4460   __ add(pointer_reg, pointer_reg, Operand(kPointerSize * 2));
4461   __ cmp(pointer_reg, too_far);
4462   __ b(lt, &next_loop);
4463
4464   // We exhausted our array of map handler pairs.
4465   __ jmp(miss);
4466 }
4467
4468
4469 static void HandleMonomorphicCase(MacroAssembler* masm, Register receiver,
4470                                   Register receiver_map, Register feedback,
4471                                   Register vector, Register slot,
4472                                   Register scratch, Label* compare_map,
4473                                   Label* load_smi_map, Label* try_array) {
4474   __ JumpIfSmi(receiver, load_smi_map);
4475   __ ldr(receiver_map, FieldMemOperand(receiver, HeapObject::kMapOffset));
4476   __ bind(compare_map);
4477   Register cached_map = scratch;
4478   // Move the weak map into the weak_cell register.
4479   __ ldr(cached_map, FieldMemOperand(feedback, WeakCell::kValueOffset));
4480   __ cmp(cached_map, receiver_map);
4481   __ b(ne, try_array);
4482   Register handler = feedback;
4483   __ add(handler, vector, Operand::PointerOffsetFromSmiKey(slot));
4484   __ ldr(handler,
4485          FieldMemOperand(handler, FixedArray::kHeaderSize + kPointerSize));
4486   __ add(pc, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
4487 }
4488
4489
4490 void LoadICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4491   Register receiver = LoadWithVectorDescriptor::ReceiverRegister();  // r1
4492   Register name = LoadWithVectorDescriptor::NameRegister();          // r2
4493   Register vector = LoadWithVectorDescriptor::VectorRegister();      // r3
4494   Register slot = LoadWithVectorDescriptor::SlotRegister();          // r0
4495   Register feedback = r4;
4496   Register receiver_map = r5;
4497   Register scratch1 = r8;
4498
4499   __ add(feedback, vector, Operand::PointerOffsetFromSmiKey(slot));
4500   __ ldr(feedback, FieldMemOperand(feedback, FixedArray::kHeaderSize));
4501
4502   // Try to quickly handle the monomorphic case without knowing for sure
4503   // if we have a weak cell in feedback. We do know it's safe to look
4504   // at WeakCell::kValueOffset.
4505   Label try_array, load_smi_map, compare_map;
4506   Label not_array, miss;
4507   HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
4508                         scratch1, &compare_map, &load_smi_map, &try_array);
4509
4510   // Is it a fixed array?
4511   __ bind(&try_array);
4512   __ ldr(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
4513   __ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
4514   __ b(ne, &not_array);
4515   HandleArrayCases(masm, receiver, name, vector, slot, feedback, receiver_map,
4516                    scratch1, r9, true, &miss);
4517
4518   __ bind(&not_array);
4519   __ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
4520   __ b(ne, &miss);
4521   Code::Flags code_flags = Code::RemoveTypeAndHolderFromFlags(
4522       Code::ComputeHandlerFlags(Code::LOAD_IC));
4523   masm->isolate()->stub_cache()->GenerateProbe(masm, Code::LOAD_IC, code_flags,
4524                                                false, receiver, name, feedback,
4525                                                receiver_map, scratch1, r9);
4526
4527   __ bind(&miss);
4528   LoadIC::GenerateMiss(masm);
4529
4530
4531   __ bind(&load_smi_map);
4532   __ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
4533   __ jmp(&compare_map);
4534 }
4535
4536
4537 void KeyedLoadICStub::Generate(MacroAssembler* masm) {
4538   GenerateImpl(masm, false);
4539 }
4540
4541
4542 void KeyedLoadICStub::GenerateForTrampoline(MacroAssembler* masm) {
4543   GenerateImpl(masm, true);
4544 }
4545
4546
4547 void KeyedLoadICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4548   Register receiver = LoadWithVectorDescriptor::ReceiverRegister();  // r1
4549   Register key = LoadWithVectorDescriptor::NameRegister();           // r2
4550   Register vector = LoadWithVectorDescriptor::VectorRegister();      // r3
4551   Register slot = LoadWithVectorDescriptor::SlotRegister();          // r0
4552   Register feedback = r4;
4553   Register receiver_map = r5;
4554   Register scratch1 = r8;
4555
4556   __ add(feedback, vector, Operand::PointerOffsetFromSmiKey(slot));
4557   __ ldr(feedback, FieldMemOperand(feedback, FixedArray::kHeaderSize));
4558
4559   // Try to quickly handle the monomorphic case without knowing for sure
4560   // if we have a weak cell in feedback. We do know it's safe to look
4561   // at WeakCell::kValueOffset.
4562   Label try_array, load_smi_map, compare_map;
4563   Label not_array, miss;
4564   HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
4565                         scratch1, &compare_map, &load_smi_map, &try_array);
4566
4567   __ bind(&try_array);
4568   // Is it a fixed array?
4569   __ ldr(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
4570   __ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
4571   __ b(ne, &not_array);
4572
4573   // We have a polymorphic element handler.
4574   Label polymorphic, try_poly_name;
4575   __ bind(&polymorphic);
4576   HandleArrayCases(masm, receiver, key, vector, slot, feedback, receiver_map,
4577                    scratch1, r9, true, &miss);
4578
4579   __ bind(&not_array);
4580   // Is it generic?
4581   __ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
4582   __ b(ne, &try_poly_name);
4583   Handle<Code> megamorphic_stub =
4584       KeyedLoadIC::ChooseMegamorphicStub(masm->isolate());
4585   __ Jump(megamorphic_stub, RelocInfo::CODE_TARGET);
4586
4587   __ bind(&try_poly_name);
4588   // We might have a name in feedback, and a fixed array in the next slot.
4589   __ cmp(key, feedback);
4590   __ b(ne, &miss);
4591   // If the name comparison succeeded, we know we have a fixed array with
4592   // at least one map/handler pair.
4593   __ add(feedback, vector, Operand::PointerOffsetFromSmiKey(slot));
4594   __ ldr(feedback,
4595          FieldMemOperand(feedback, FixedArray::kHeaderSize + kPointerSize));
4596   HandleArrayCases(masm, receiver, key, vector, slot, feedback, receiver_map,
4597                    scratch1, r9, false, &miss);
4598
4599   __ bind(&miss);
4600   KeyedLoadIC::GenerateMiss(masm);
4601
4602   __ bind(&load_smi_map);
4603   __ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
4604   __ jmp(&compare_map);
4605 }
4606
4607
4608 void VectorStoreICTrampolineStub::Generate(MacroAssembler* masm) {
4609   EmitLoadTypeFeedbackVector(masm, VectorStoreICDescriptor::VectorRegister());
4610   VectorStoreICStub stub(isolate(), state());
4611   stub.GenerateForTrampoline(masm);
4612 }
4613
4614
4615 void VectorKeyedStoreICTrampolineStub::Generate(MacroAssembler* masm) {
4616   EmitLoadTypeFeedbackVector(masm, VectorStoreICDescriptor::VectorRegister());
4617   VectorKeyedStoreICStub stub(isolate(), state());
4618   stub.GenerateForTrampoline(masm);
4619 }
4620
4621
4622 void VectorStoreICStub::Generate(MacroAssembler* masm) {
4623   GenerateImpl(masm, false);
4624 }
4625
4626
4627 void VectorStoreICStub::GenerateForTrampoline(MacroAssembler* masm) {
4628   GenerateImpl(masm, true);
4629 }
4630
4631
4632 void VectorStoreICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4633   Label miss;
4634
4635   // TODO(mvstanton): Implement.
4636   __ bind(&miss);
4637   StoreIC::GenerateMiss(masm);
4638 }
4639
4640
4641 void VectorKeyedStoreICStub::Generate(MacroAssembler* masm) {
4642   GenerateImpl(masm, false);
4643 }
4644
4645
4646 void VectorKeyedStoreICStub::GenerateForTrampoline(MacroAssembler* masm) {
4647   GenerateImpl(masm, true);
4648 }
4649
4650
4651 void VectorKeyedStoreICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4652   Label miss;
4653
4654   // TODO(mvstanton): Implement.
4655   __ bind(&miss);
4656   KeyedStoreIC::GenerateMiss(masm);
4657 }
4658
4659
4660 void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) {
4661   if (masm->isolate()->function_entry_hook() != NULL) {
4662     ProfileEntryHookStub stub(masm->isolate());
4663     int code_size = masm->CallStubSize(&stub) + 2 * Assembler::kInstrSize;
4664     PredictableCodeSizeScope predictable(masm, code_size);
4665     __ push(lr);
4666     __ CallStub(&stub);
4667     __ pop(lr);
4668   }
4669 }
4670
4671
4672 void ProfileEntryHookStub::Generate(MacroAssembler* masm) {
4673   // The entry hook is a "push lr" instruction, followed by a call.
4674   const int32_t kReturnAddressDistanceFromFunctionStart =
4675       3 * Assembler::kInstrSize;
4676
4677   // This should contain all kCallerSaved registers.
4678   const RegList kSavedRegs =
4679       1 <<  0 |  // r0
4680       1 <<  1 |  // r1
4681       1 <<  2 |  // r2
4682       1 <<  3 |  // r3
4683       1 <<  5 |  // r5
4684       1 <<  9;   // r9
4685   // We also save lr, so the count here is one higher than the mask indicates.
4686   const int32_t kNumSavedRegs = 7;
4687
4688   DCHECK((kCallerSaved & kSavedRegs) == kCallerSaved);
4689
4690   // Save all caller-save registers as this may be called from anywhere.
4691   __ stm(db_w, sp, kSavedRegs | lr.bit());
4692
4693   // Compute the function's address for the first argument.
4694   __ sub(r0, lr, Operand(kReturnAddressDistanceFromFunctionStart));
4695
4696   // The caller's return address is above the saved temporaries.
4697   // Grab that for the second argument to the hook.
4698   __ add(r1, sp, Operand(kNumSavedRegs * kPointerSize));
4699
4700   // Align the stack if necessary.
4701   int frame_alignment = masm->ActivationFrameAlignment();
4702   if (frame_alignment > kPointerSize) {
4703     __ mov(r5, sp);
4704     DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
4705     __ and_(sp, sp, Operand(-frame_alignment));
4706   }
4707
4708 #if V8_HOST_ARCH_ARM
4709   int32_t entry_hook =
4710       reinterpret_cast<int32_t>(isolate()->function_entry_hook());
4711   __ mov(ip, Operand(entry_hook));
4712 #else
4713   // Under the simulator we need to indirect the entry hook through a
4714   // trampoline function at a known address.
4715   // It additionally takes an isolate as a third parameter
4716   __ mov(r2, Operand(ExternalReference::isolate_address(isolate())));
4717
4718   ApiFunction dispatcher(FUNCTION_ADDR(EntryHookTrampoline));
4719   __ mov(ip, Operand(ExternalReference(&dispatcher,
4720                                        ExternalReference::BUILTIN_CALL,
4721                                        isolate())));
4722 #endif
4723   __ Call(ip);
4724
4725   // Restore the stack pointer if needed.
4726   if (frame_alignment > kPointerSize) {
4727     __ mov(sp, r5);
4728   }
4729
4730   // Also pop pc to get Ret(0).
4731   __ ldm(ia_w, sp, kSavedRegs | pc.bit());
4732 }
4733
4734
4735 template<class T>
4736 static void CreateArrayDispatch(MacroAssembler* masm,
4737                                 AllocationSiteOverrideMode mode) {
4738   if (mode == DISABLE_ALLOCATION_SITES) {
4739     T stub(masm->isolate(), GetInitialFastElementsKind(), mode);
4740     __ TailCallStub(&stub);
4741   } else if (mode == DONT_OVERRIDE) {
4742     int last_index = GetSequenceIndexFromFastElementsKind(
4743         TERMINAL_FAST_ELEMENTS_KIND);
4744     for (int i = 0; i <= last_index; ++i) {
4745       ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
4746       __ cmp(r3, Operand(kind));
4747       T stub(masm->isolate(), kind);
4748       __ TailCallStub(&stub, eq);
4749     }
4750
4751     // If we reached this point there is a problem.
4752     __ Abort(kUnexpectedElementsKindInArrayConstructor);
4753   } else {
4754     UNREACHABLE();
4755   }
4756 }
4757
4758
4759 static void CreateArrayDispatchOneArgument(MacroAssembler* masm,
4760                                            AllocationSiteOverrideMode mode) {
4761   // r2 - allocation site (if mode != DISABLE_ALLOCATION_SITES)
4762   // r3 - kind (if mode != DISABLE_ALLOCATION_SITES)
4763   // r0 - number of arguments
4764   // r1 - constructor?
4765   // sp[0] - last argument
4766   Label normal_sequence;
4767   if (mode == DONT_OVERRIDE) {
4768     DCHECK(FAST_SMI_ELEMENTS == 0);
4769     DCHECK(FAST_HOLEY_SMI_ELEMENTS == 1);
4770     DCHECK(FAST_ELEMENTS == 2);
4771     DCHECK(FAST_HOLEY_ELEMENTS == 3);
4772     DCHECK(FAST_DOUBLE_ELEMENTS == 4);
4773     DCHECK(FAST_HOLEY_DOUBLE_ELEMENTS == 5);
4774
4775     // is the low bit set? If so, we are holey and that is good.
4776     __ tst(r3, Operand(1));
4777     __ b(ne, &normal_sequence);
4778   }
4779
4780   // look at the first argument
4781   __ ldr(r5, MemOperand(sp, 0));
4782   __ cmp(r5, Operand::Zero());
4783   __ b(eq, &normal_sequence);
4784
4785   if (mode == DISABLE_ALLOCATION_SITES) {
4786     ElementsKind initial = GetInitialFastElementsKind();
4787     ElementsKind holey_initial = GetHoleyElementsKind(initial);
4788
4789     ArraySingleArgumentConstructorStub stub_holey(masm->isolate(),
4790                                                   holey_initial,
4791                                                   DISABLE_ALLOCATION_SITES);
4792     __ TailCallStub(&stub_holey);
4793
4794     __ bind(&normal_sequence);
4795     ArraySingleArgumentConstructorStub stub(masm->isolate(),
4796                                             initial,
4797                                             DISABLE_ALLOCATION_SITES);
4798     __ TailCallStub(&stub);
4799   } else if (mode == DONT_OVERRIDE) {
4800     // We are going to create a holey array, but our kind is non-holey.
4801     // Fix kind and retry (only if we have an allocation site in the slot).
4802     __ add(r3, r3, Operand(1));
4803
4804     if (FLAG_debug_code) {
4805       __ ldr(r5, FieldMemOperand(r2, 0));
4806       __ CompareRoot(r5, Heap::kAllocationSiteMapRootIndex);
4807       __ Assert(eq, kExpectedAllocationSite);
4808     }
4809
4810     // Save the resulting elements kind in type info. We can't just store r3
4811     // in the AllocationSite::transition_info field because elements kind is
4812     // restricted to a portion of the field...upper bits need to be left alone.
4813     STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
4814     __ ldr(r4, FieldMemOperand(r2, AllocationSite::kTransitionInfoOffset));
4815     __ add(r4, r4, Operand(Smi::FromInt(kFastElementsKindPackedToHoley)));
4816     __ str(r4, FieldMemOperand(r2, AllocationSite::kTransitionInfoOffset));
4817
4818     __ bind(&normal_sequence);
4819     int last_index = GetSequenceIndexFromFastElementsKind(
4820         TERMINAL_FAST_ELEMENTS_KIND);
4821     for (int i = 0; i <= last_index; ++i) {
4822       ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
4823       __ cmp(r3, Operand(kind));
4824       ArraySingleArgumentConstructorStub stub(masm->isolate(), kind);
4825       __ TailCallStub(&stub, eq);
4826     }
4827
4828     // If we reached this point there is a problem.
4829     __ Abort(kUnexpectedElementsKindInArrayConstructor);
4830   } else {
4831     UNREACHABLE();
4832   }
4833 }
4834
4835
4836 template<class T>
4837 static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) {
4838   int to_index = GetSequenceIndexFromFastElementsKind(
4839       TERMINAL_FAST_ELEMENTS_KIND);
4840   for (int i = 0; i <= to_index; ++i) {
4841     ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
4842     T stub(isolate, kind);
4843     stub.GetCode();
4844     if (AllocationSite::GetMode(kind) != DONT_TRACK_ALLOCATION_SITE) {
4845       T stub1(isolate, kind, DISABLE_ALLOCATION_SITES);
4846       stub1.GetCode();
4847     }
4848   }
4849 }
4850
4851
4852 void ArrayConstructorStubBase::GenerateStubsAheadOfTime(Isolate* isolate) {
4853   ArrayConstructorStubAheadOfTimeHelper<ArrayNoArgumentConstructorStub>(
4854       isolate);
4855   ArrayConstructorStubAheadOfTimeHelper<ArraySingleArgumentConstructorStub>(
4856       isolate);
4857   ArrayConstructorStubAheadOfTimeHelper<ArrayNArgumentsConstructorStub>(
4858       isolate);
4859 }
4860
4861
4862 void InternalArrayConstructorStubBase::GenerateStubsAheadOfTime(
4863     Isolate* isolate) {
4864   ElementsKind kinds[2] = { FAST_ELEMENTS, FAST_HOLEY_ELEMENTS };
4865   for (int i = 0; i < 2; i++) {
4866     // For internal arrays we only need a few things
4867     InternalArrayNoArgumentConstructorStub stubh1(isolate, kinds[i]);
4868     stubh1.GetCode();
4869     InternalArraySingleArgumentConstructorStub stubh2(isolate, kinds[i]);
4870     stubh2.GetCode();
4871     InternalArrayNArgumentsConstructorStub stubh3(isolate, kinds[i]);
4872     stubh3.GetCode();
4873   }
4874 }
4875
4876
4877 void ArrayConstructorStub::GenerateDispatchToArrayStub(
4878     MacroAssembler* masm,
4879     AllocationSiteOverrideMode mode) {
4880   if (argument_count() == ANY) {
4881     Label not_zero_case, not_one_case;
4882     __ tst(r0, r0);
4883     __ b(ne, &not_zero_case);
4884     CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
4885
4886     __ bind(&not_zero_case);
4887     __ cmp(r0, Operand(1));
4888     __ b(gt, &not_one_case);
4889     CreateArrayDispatchOneArgument(masm, mode);
4890
4891     __ bind(&not_one_case);
4892     CreateArrayDispatch<ArrayNArgumentsConstructorStub>(masm, mode);
4893   } else if (argument_count() == NONE) {
4894     CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
4895   } else if (argument_count() == ONE) {
4896     CreateArrayDispatchOneArgument(masm, mode);
4897   } else if (argument_count() == MORE_THAN_ONE) {
4898     CreateArrayDispatch<ArrayNArgumentsConstructorStub>(masm, mode);
4899   } else {
4900     UNREACHABLE();
4901   }
4902 }
4903
4904
4905 void ArrayConstructorStub::Generate(MacroAssembler* masm) {
4906   // ----------- S t a t e -------------
4907   //  -- r0 : argc (only if argument_count() == ANY)
4908   //  -- r1 : constructor
4909   //  -- r2 : AllocationSite or undefined
4910   //  -- r3 : original constructor
4911   //  -- sp[0] : return address
4912   //  -- sp[4] : last argument
4913   // -----------------------------------
4914
4915   if (FLAG_debug_code) {
4916     // The array construct code is only set for the global and natives
4917     // builtin Array functions which always have maps.
4918
4919     // Initial map for the builtin Array function should be a map.
4920     __ ldr(r4, FieldMemOperand(r1, JSFunction::kPrototypeOrInitialMapOffset));
4921     // Will both indicate a NULL and a Smi.
4922     __ tst(r4, Operand(kSmiTagMask));
4923     __ Assert(ne, kUnexpectedInitialMapForArrayFunction);
4924     __ CompareObjectType(r4, r4, r5, MAP_TYPE);
4925     __ Assert(eq, kUnexpectedInitialMapForArrayFunction);
4926
4927     // We should either have undefined in r2 or a valid AllocationSite
4928     __ AssertUndefinedOrAllocationSite(r2, r4);
4929   }
4930
4931   Label subclassing;
4932   __ cmp(r3, r1);
4933   __ b(ne, &subclassing);
4934
4935   Label no_info;
4936   // Get the elements kind and case on that.
4937   __ CompareRoot(r2, Heap::kUndefinedValueRootIndex);
4938   __ b(eq, &no_info);
4939
4940   __ ldr(r3, FieldMemOperand(r2, AllocationSite::kTransitionInfoOffset));
4941   __ SmiUntag(r3);
4942   STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
4943   __ and_(r3, r3, Operand(AllocationSite::ElementsKindBits::kMask));
4944   GenerateDispatchToArrayStub(masm, DONT_OVERRIDE);
4945
4946   __ bind(&no_info);
4947   GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES);
4948
4949   __ bind(&subclassing);
4950   __ push(r1);
4951   __ push(r3);
4952
4953   // Adjust argc.
4954   switch (argument_count()) {
4955     case ANY:
4956     case MORE_THAN_ONE:
4957       __ add(r0, r0, Operand(2));
4958       break;
4959     case NONE:
4960       __ mov(r0, Operand(2));
4961       break;
4962     case ONE:
4963       __ mov(r0, Operand(3));
4964       break;
4965   }
4966
4967   __ JumpToExternalReference(
4968       ExternalReference(Runtime::kArrayConstructorWithSubclassing, isolate()));
4969 }
4970
4971
4972 void InternalArrayConstructorStub::GenerateCase(
4973     MacroAssembler* masm, ElementsKind kind) {
4974   __ cmp(r0, Operand(1));
4975
4976   InternalArrayNoArgumentConstructorStub stub0(isolate(), kind);
4977   __ TailCallStub(&stub0, lo);
4978
4979   InternalArrayNArgumentsConstructorStub stubN(isolate(), kind);
4980   __ TailCallStub(&stubN, hi);
4981
4982   if (IsFastPackedElementsKind(kind)) {
4983     // We might need to create a holey array
4984     // look at the first argument
4985     __ ldr(r3, MemOperand(sp, 0));
4986     __ cmp(r3, Operand::Zero());
4987
4988     InternalArraySingleArgumentConstructorStub
4989         stub1_holey(isolate(), GetHoleyElementsKind(kind));
4990     __ TailCallStub(&stub1_holey, ne);
4991   }
4992
4993   InternalArraySingleArgumentConstructorStub stub1(isolate(), kind);
4994   __ TailCallStub(&stub1);
4995 }
4996
4997
4998 void InternalArrayConstructorStub::Generate(MacroAssembler* masm) {
4999   // ----------- S t a t e -------------
5000   //  -- r0 : argc
5001   //  -- r1 : constructor
5002   //  -- sp[0] : return address
5003   //  -- sp[4] : last argument
5004   // -----------------------------------
5005
5006   if (FLAG_debug_code) {
5007     // The array construct code is only set for the global and natives
5008     // builtin Array functions which always have maps.
5009
5010     // Initial map for the builtin Array function should be a map.
5011     __ ldr(r3, FieldMemOperand(r1, JSFunction::kPrototypeOrInitialMapOffset));
5012     // Will both indicate a NULL and a Smi.
5013     __ tst(r3, Operand(kSmiTagMask));
5014     __ Assert(ne, kUnexpectedInitialMapForArrayFunction);
5015     __ CompareObjectType(r3, r3, r4, MAP_TYPE);
5016     __ Assert(eq, kUnexpectedInitialMapForArrayFunction);
5017   }
5018
5019   // Figure out the right elements kind
5020   __ ldr(r3, FieldMemOperand(r1, JSFunction::kPrototypeOrInitialMapOffset));
5021   // Load the map's "bit field 2" into |result|. We only need the first byte,
5022   // but the following bit field extraction takes care of that anyway.
5023   __ ldr(r3, FieldMemOperand(r3, Map::kBitField2Offset));
5024   // Retrieve elements_kind from bit field 2.
5025   __ DecodeField<Map::ElementsKindBits>(r3);
5026
5027   if (FLAG_debug_code) {
5028     Label done;
5029     __ cmp(r3, Operand(FAST_ELEMENTS));
5030     __ b(eq, &done);
5031     __ cmp(r3, Operand(FAST_HOLEY_ELEMENTS));
5032     __ Assert(eq,
5033               kInvalidElementsKindForInternalArrayOrInternalPackedArray);
5034     __ bind(&done);
5035   }
5036
5037   Label fast_elements_case;
5038   __ cmp(r3, Operand(FAST_ELEMENTS));
5039   __ b(eq, &fast_elements_case);
5040   GenerateCase(masm, FAST_HOLEY_ELEMENTS);
5041
5042   __ bind(&fast_elements_case);
5043   GenerateCase(masm, FAST_ELEMENTS);
5044 }
5045
5046
5047 static int AddressOffset(ExternalReference ref0, ExternalReference ref1) {
5048   return ref0.address() - ref1.address();
5049 }
5050
5051
5052 // Calls an API function.  Allocates HandleScope, extracts returned value
5053 // from handle and propagates exceptions.  Restores context.  stack_space
5054 // - space to be unwound on exit (includes the call JS arguments space and
5055 // the additional space allocated for the fast call).
5056 static void CallApiFunctionAndReturn(MacroAssembler* masm,
5057                                      Register function_address,
5058                                      ExternalReference thunk_ref,
5059                                      int stack_space,
5060                                      MemOperand* stack_space_operand,
5061                                      MemOperand return_value_operand,
5062                                      MemOperand* context_restore_operand) {
5063   Isolate* isolate = masm->isolate();
5064   ExternalReference next_address =
5065       ExternalReference::handle_scope_next_address(isolate);
5066   const int kNextOffset = 0;
5067   const int kLimitOffset = AddressOffset(
5068       ExternalReference::handle_scope_limit_address(isolate), next_address);
5069   const int kLevelOffset = AddressOffset(
5070       ExternalReference::handle_scope_level_address(isolate), next_address);
5071
5072   DCHECK(function_address.is(r1) || function_address.is(r2));
5073
5074   Label profiler_disabled;
5075   Label end_profiler_check;
5076   __ mov(r9, Operand(ExternalReference::is_profiling_address(isolate)));
5077   __ ldrb(r9, MemOperand(r9, 0));
5078   __ cmp(r9, Operand(0));
5079   __ b(eq, &profiler_disabled);
5080
5081   // Additional parameter is the address of the actual callback.
5082   __ mov(r3, Operand(thunk_ref));
5083   __ jmp(&end_profiler_check);
5084
5085   __ bind(&profiler_disabled);
5086   __ Move(r3, function_address);
5087   __ bind(&end_profiler_check);
5088
5089   // Allocate HandleScope in callee-save registers.
5090   __ mov(r9, Operand(next_address));
5091   __ ldr(r4, MemOperand(r9, kNextOffset));
5092   __ ldr(r5, MemOperand(r9, kLimitOffset));
5093   __ ldr(r6, MemOperand(r9, kLevelOffset));
5094   __ add(r6, r6, Operand(1));
5095   __ str(r6, MemOperand(r9, kLevelOffset));
5096
5097   if (FLAG_log_timer_events) {
5098     FrameScope frame(masm, StackFrame::MANUAL);
5099     __ PushSafepointRegisters();
5100     __ PrepareCallCFunction(1, r0);
5101     __ mov(r0, Operand(ExternalReference::isolate_address(isolate)));
5102     __ CallCFunction(ExternalReference::log_enter_external_function(isolate),
5103                      1);
5104     __ PopSafepointRegisters();
5105   }
5106
5107   // Native call returns to the DirectCEntry stub which redirects to the
5108   // return address pushed on stack (could have moved after GC).
5109   // DirectCEntry stub itself is generated early and never moves.
5110   DirectCEntryStub stub(isolate);
5111   stub.GenerateCall(masm, r3);
5112
5113   if (FLAG_log_timer_events) {
5114     FrameScope frame(masm, StackFrame::MANUAL);
5115     __ PushSafepointRegisters();
5116     __ PrepareCallCFunction(1, r0);
5117     __ mov(r0, Operand(ExternalReference::isolate_address(isolate)));
5118     __ CallCFunction(ExternalReference::log_leave_external_function(isolate),
5119                      1);
5120     __ PopSafepointRegisters();
5121   }
5122
5123   Label promote_scheduled_exception;
5124   Label delete_allocated_handles;
5125   Label leave_exit_frame;
5126   Label return_value_loaded;
5127
5128   // load value from ReturnValue
5129   __ ldr(r0, return_value_operand);
5130   __ bind(&return_value_loaded);
5131   // No more valid handles (the result handle was the last one). Restore
5132   // previous handle scope.
5133   __ str(r4, MemOperand(r9, kNextOffset));
5134   if (__ emit_debug_code()) {
5135     __ ldr(r1, MemOperand(r9, kLevelOffset));
5136     __ cmp(r1, r6);
5137     __ Check(eq, kUnexpectedLevelAfterReturnFromApiCall);
5138   }
5139   __ sub(r6, r6, Operand(1));
5140   __ str(r6, MemOperand(r9, kLevelOffset));
5141   __ ldr(ip, MemOperand(r9, kLimitOffset));
5142   __ cmp(r5, ip);
5143   __ b(ne, &delete_allocated_handles);
5144
5145   // Leave the API exit frame.
5146   __ bind(&leave_exit_frame);
5147   bool restore_context = context_restore_operand != NULL;
5148   if (restore_context) {
5149     __ ldr(cp, *context_restore_operand);
5150   }
5151   // LeaveExitFrame expects unwind space to be in a register.
5152   if (stack_space_operand != NULL) {
5153     __ ldr(r4, *stack_space_operand);
5154   } else {
5155     __ mov(r4, Operand(stack_space));
5156   }
5157   __ LeaveExitFrame(false, r4, !restore_context, stack_space_operand != NULL);
5158
5159   // Check if the function scheduled an exception.
5160   __ LoadRoot(r4, Heap::kTheHoleValueRootIndex);
5161   __ mov(ip, Operand(ExternalReference::scheduled_exception_address(isolate)));
5162   __ ldr(r5, MemOperand(ip));
5163   __ cmp(r4, r5);
5164   __ b(ne, &promote_scheduled_exception);
5165
5166   __ mov(pc, lr);
5167
5168   // Re-throw by promoting a scheduled exception.
5169   __ bind(&promote_scheduled_exception);
5170   __ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
5171
5172   // HandleScope limit has changed. Delete allocated extensions.
5173   __ bind(&delete_allocated_handles);
5174   __ str(r5, MemOperand(r9, kLimitOffset));
5175   __ mov(r4, r0);
5176   __ PrepareCallCFunction(1, r5);
5177   __ mov(r0, Operand(ExternalReference::isolate_address(isolate)));
5178   __ CallCFunction(ExternalReference::delete_handle_scope_extensions(isolate),
5179                    1);
5180   __ mov(r0, r4);
5181   __ jmp(&leave_exit_frame);
5182 }
5183
5184
5185 static void CallApiFunctionStubHelper(MacroAssembler* masm,
5186                                       const ParameterCount& argc,
5187                                       bool return_first_arg,
5188                                       bool call_data_undefined) {
5189   // ----------- S t a t e -------------
5190   //  -- r0                  : callee
5191   //  -- r4                  : call_data
5192   //  -- r2                  : holder
5193   //  -- r1                  : api_function_address
5194   //  -- r3                  : number of arguments if argc is a register
5195   //  -- cp                  : context
5196   //  --
5197   //  -- sp[0]               : last argument
5198   //  -- ...
5199   //  -- sp[(argc - 1)* 4]   : first argument
5200   //  -- sp[argc * 4]        : receiver
5201   // -----------------------------------
5202
5203   Register callee = r0;
5204   Register call_data = r4;
5205   Register holder = r2;
5206   Register api_function_address = r1;
5207   Register context = cp;
5208
5209   typedef FunctionCallbackArguments FCA;
5210
5211   STATIC_ASSERT(FCA::kContextSaveIndex == 6);
5212   STATIC_ASSERT(FCA::kCalleeIndex == 5);
5213   STATIC_ASSERT(FCA::kDataIndex == 4);
5214   STATIC_ASSERT(FCA::kReturnValueOffset == 3);
5215   STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2);
5216   STATIC_ASSERT(FCA::kIsolateIndex == 1);
5217   STATIC_ASSERT(FCA::kHolderIndex == 0);
5218   STATIC_ASSERT(FCA::kArgsLength == 7);
5219
5220   DCHECK(argc.is_immediate() || r3.is(argc.reg()));
5221
5222   // context save
5223   __ push(context);
5224   // load context from callee
5225   __ ldr(context, FieldMemOperand(callee, JSFunction::kContextOffset));
5226
5227   // callee
5228   __ push(callee);
5229
5230   // call data
5231   __ push(call_data);
5232
5233   Register scratch = call_data;
5234   if (!call_data_undefined) {
5235     __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
5236   }
5237   // return value
5238   __ push(scratch);
5239   // return value default
5240   __ push(scratch);
5241   // isolate
5242   __ mov(scratch, Operand(ExternalReference::isolate_address(masm->isolate())));
5243   __ push(scratch);
5244   // holder
5245   __ push(holder);
5246
5247   // Prepare arguments.
5248   __ mov(scratch, sp);
5249
5250   // Allocate the v8::Arguments structure in the arguments' space since
5251   // it's not controlled by GC.
5252   const int kApiStackSpace = 4;
5253
5254   FrameScope frame_scope(masm, StackFrame::MANUAL);
5255   __ EnterExitFrame(false, kApiStackSpace);
5256
5257   DCHECK(!api_function_address.is(r0) && !scratch.is(r0));
5258   // r0 = FunctionCallbackInfo&
5259   // Arguments is after the return address.
5260   __ add(r0, sp, Operand(1 * kPointerSize));
5261   // FunctionCallbackInfo::implicit_args_
5262   __ str(scratch, MemOperand(r0, 0 * kPointerSize));
5263   if (argc.is_immediate()) {
5264     // FunctionCallbackInfo::values_
5265     __ add(ip, scratch,
5266            Operand((FCA::kArgsLength - 1 + argc.immediate()) * kPointerSize));
5267     __ str(ip, MemOperand(r0, 1 * kPointerSize));
5268     // FunctionCallbackInfo::length_ = argc
5269     __ mov(ip, Operand(argc.immediate()));
5270     __ str(ip, MemOperand(r0, 2 * kPointerSize));
5271     // FunctionCallbackInfo::is_construct_call_ = 0
5272     __ mov(ip, Operand::Zero());
5273     __ str(ip, MemOperand(r0, 3 * kPointerSize));
5274   } else {
5275     // FunctionCallbackInfo::values_
5276     __ add(ip, scratch, Operand(argc.reg(), LSL, kPointerSizeLog2));
5277     __ add(ip, ip, Operand((FCA::kArgsLength - 1) * kPointerSize));
5278     __ str(ip, MemOperand(r0, 1 * kPointerSize));
5279     // FunctionCallbackInfo::length_ = argc
5280     __ str(argc.reg(), MemOperand(r0, 2 * kPointerSize));
5281     // FunctionCallbackInfo::is_construct_call_
5282     __ add(argc.reg(), argc.reg(), Operand(FCA::kArgsLength + 1));
5283     __ mov(ip, Operand(argc.reg(), LSL, kPointerSizeLog2));
5284     __ str(ip, MemOperand(r0, 3 * kPointerSize));
5285   }
5286
5287   ExternalReference thunk_ref =
5288       ExternalReference::invoke_function_callback(masm->isolate());
5289
5290   AllowExternalCallThatCantCauseGC scope(masm);
5291   MemOperand context_restore_operand(
5292       fp, (2 + FCA::kContextSaveIndex) * kPointerSize);
5293   // Stores return the first js argument
5294   int return_value_offset = 0;
5295   if (return_first_arg) {
5296     return_value_offset = 2 + FCA::kArgsLength;
5297   } else {
5298     return_value_offset = 2 + FCA::kReturnValueOffset;
5299   }
5300   MemOperand return_value_operand(fp, return_value_offset * kPointerSize);
5301   int stack_space = 0;
5302   MemOperand is_construct_call_operand = MemOperand(sp, 4 * kPointerSize);
5303   MemOperand* stack_space_operand = &is_construct_call_operand;
5304   if (argc.is_immediate()) {
5305     stack_space = argc.immediate() + FCA::kArgsLength + 1;
5306     stack_space_operand = NULL;
5307   }
5308   CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, stack_space,
5309                            stack_space_operand, return_value_operand,
5310                            &context_restore_operand);
5311 }
5312
5313
5314 void CallApiFunctionStub::Generate(MacroAssembler* masm) {
5315   bool call_data_undefined = this->call_data_undefined();
5316   CallApiFunctionStubHelper(masm, ParameterCount(r3), false,
5317                             call_data_undefined);
5318 }
5319
5320
5321 void CallApiAccessorStub::Generate(MacroAssembler* masm) {
5322   bool is_store = this->is_store();
5323   int argc = this->argc();
5324   bool call_data_undefined = this->call_data_undefined();
5325   CallApiFunctionStubHelper(masm, ParameterCount(argc), is_store,
5326                             call_data_undefined);
5327 }
5328
5329
5330 void CallApiGetterStub::Generate(MacroAssembler* masm) {
5331   // ----------- S t a t e -------------
5332   //  -- sp[0]                  : name
5333   //  -- sp[4 - kArgsLength*4]  : PropertyCallbackArguments object
5334   //  -- ...
5335   //  -- r2                     : api_function_address
5336   // -----------------------------------
5337
5338   Register api_function_address = ApiGetterDescriptor::function_address();
5339   DCHECK(api_function_address.is(r2));
5340
5341   __ mov(r0, sp);  // r0 = Handle<Name>
5342   __ add(r1, r0, Operand(1 * kPointerSize));  // r1 = PCA
5343
5344   const int kApiStackSpace = 1;
5345   FrameScope frame_scope(masm, StackFrame::MANUAL);
5346   __ EnterExitFrame(false, kApiStackSpace);
5347
5348   // Create PropertyAccessorInfo instance on the stack above the exit frame with
5349   // r1 (internal::Object** args_) as the data.
5350   __ str(r1, MemOperand(sp, 1 * kPointerSize));
5351   __ add(r1, sp, Operand(1 * kPointerSize));  // r1 = AccessorInfo&
5352
5353   const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;
5354
5355   ExternalReference thunk_ref =
5356       ExternalReference::invoke_accessor_getter_callback(isolate());
5357   CallApiFunctionAndReturn(masm, api_function_address, thunk_ref,
5358                            kStackUnwindSpace, NULL,
5359                            MemOperand(fp, 6 * kPointerSize), NULL);
5360 }
5361
5362
5363 #undef __
5364
5365 }  // namespace internal
5366 }  // namespace v8
5367
5368 #endif  // V8_TARGET_ARCH_ARM