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