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