42a0bbe58bc12a2689f49586a577e2046b1a2ee1
[platform/upstream/nodejs.git] / deps / v8 / src / mips / builtins-mips.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
6
7 #include "src/v8.h"
8
9 #if V8_TARGET_ARCH_MIPS
10
11 #include "src/codegen.h"
12 #include "src/debug.h"
13 #include "src/deoptimizer.h"
14 #include "src/full-codegen.h"
15 #include "src/runtime/runtime.h"
16
17
18 namespace v8 {
19 namespace internal {
20
21
22 #define __ ACCESS_MASM(masm)
23
24
25 void Builtins::Generate_Adaptor(MacroAssembler* masm,
26                                 CFunctionId id,
27                                 BuiltinExtraArguments extra_args) {
28   // ----------- S t a t e -------------
29   //  -- a0                 : number of arguments excluding receiver
30   //  -- a1                 : called function (only guaranteed when
31   //  --                      extra_args requires it)
32   //  -- cp                 : context
33   //  -- sp[0]              : last argument
34   //  -- ...
35   //  -- sp[4 * (argc - 1)] : first argument
36   //  -- sp[4 * agrc]       : receiver
37   // -----------------------------------
38
39   // Insert extra arguments.
40   int num_extra_args = 0;
41   if (extra_args == NEEDS_CALLED_FUNCTION) {
42     num_extra_args = 1;
43     __ push(a1);
44   } else {
45     DCHECK(extra_args == NO_EXTRA_ARGUMENTS);
46   }
47
48   // JumpToExternalReference expects a0 to contain the number of arguments
49   // including the receiver and the extra arguments.
50   __ Addu(a0, a0, num_extra_args + 1);
51   __ JumpToExternalReference(ExternalReference(id, masm->isolate()));
52 }
53
54
55 // Load the built-in InternalArray function from the current context.
56 static void GenerateLoadInternalArrayFunction(MacroAssembler* masm,
57                                               Register result) {
58   // Load the native context.
59
60   __ lw(result,
61         MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
62   __ lw(result,
63         FieldMemOperand(result, GlobalObject::kNativeContextOffset));
64   // Load the InternalArray function from the native context.
65   __ lw(result,
66          MemOperand(result,
67                     Context::SlotOffset(
68                         Context::INTERNAL_ARRAY_FUNCTION_INDEX)));
69 }
70
71
72 // Load the built-in Array function from the current context.
73 static void GenerateLoadArrayFunction(MacroAssembler* masm, Register result) {
74   // Load the native context.
75
76   __ lw(result,
77         MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
78   __ lw(result,
79         FieldMemOperand(result, GlobalObject::kNativeContextOffset));
80   // Load the Array function from the native context.
81   __ lw(result,
82         MemOperand(result,
83                    Context::SlotOffset(Context::ARRAY_FUNCTION_INDEX)));
84 }
85
86
87 void Builtins::Generate_InternalArrayCode(MacroAssembler* masm) {
88   // ----------- S t a t e -------------
89   //  -- a0     : number of arguments
90   //  -- ra     : return address
91   //  -- sp[...]: constructor arguments
92   // -----------------------------------
93   Label generic_array_code, one_or_more_arguments, two_or_more_arguments;
94
95   // Get the InternalArray function.
96   GenerateLoadInternalArrayFunction(masm, a1);
97
98   if (FLAG_debug_code) {
99     // Initial map for the builtin InternalArray functions should be maps.
100     __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset));
101     __ SmiTst(a2, t0);
102     __ Assert(ne, kUnexpectedInitialMapForInternalArrayFunction,
103               t0, Operand(zero_reg));
104     __ GetObjectType(a2, a3, t0);
105     __ Assert(eq, kUnexpectedInitialMapForInternalArrayFunction,
106               t0, Operand(MAP_TYPE));
107   }
108
109   // Run the native code for the InternalArray function called as a normal
110   // function.
111   // Tail call a stub.
112   InternalArrayConstructorStub stub(masm->isolate());
113   __ TailCallStub(&stub);
114 }
115
116
117 void Builtins::Generate_ArrayCode(MacroAssembler* masm) {
118   // ----------- S t a t e -------------
119   //  -- a0     : number of arguments
120   //  -- ra     : return address
121   //  -- sp[...]: constructor arguments
122   // -----------------------------------
123   Label generic_array_code;
124
125   // Get the Array function.
126   GenerateLoadArrayFunction(masm, a1);
127
128   if (FLAG_debug_code) {
129     // Initial map for the builtin Array functions should be maps.
130     __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset));
131     __ SmiTst(a2, t0);
132     __ Assert(ne, kUnexpectedInitialMapForArrayFunction1,
133               t0, Operand(zero_reg));
134     __ GetObjectType(a2, a3, t0);
135     __ Assert(eq, kUnexpectedInitialMapForArrayFunction2,
136               t0, Operand(MAP_TYPE));
137   }
138
139   // Run the native code for the Array function called as a normal function.
140   // Tail call a stub.
141   __ mov(a3, a1);
142   __ LoadRoot(a2, Heap::kUndefinedValueRootIndex);
143   ArrayConstructorStub stub(masm->isolate());
144   __ TailCallStub(&stub);
145 }
146
147
148 void Builtins::Generate_StringConstructCode(MacroAssembler* masm) {
149   // ----------- S t a t e -------------
150   //  -- a0                     : number of arguments
151   //  -- a1                     : constructor function
152   //  -- ra                     : return address
153   //  -- sp[(argc - n - 1) * 4] : arg[n] (zero based)
154   //  -- sp[argc * 4]           : receiver
155   // -----------------------------------
156   Counters* counters = masm->isolate()->counters();
157   __ IncrementCounter(counters->string_ctor_calls(), 1, a2, a3);
158
159   Register function = a1;
160   if (FLAG_debug_code) {
161     __ LoadGlobalFunction(Context::STRING_FUNCTION_INDEX, a2);
162     __ Assert(eq, kUnexpectedStringFunction, function, Operand(a2));
163   }
164
165   // Load the first arguments in a0 and get rid of the rest.
166   Label no_arguments;
167   __ Branch(&no_arguments, eq, a0, Operand(zero_reg));
168   // First args = sp[(argc - 1) * 4].
169   __ Subu(a0, a0, Operand(1));
170   __ sll(a0, a0, kPointerSizeLog2);
171   __ Addu(sp, a0, sp);
172   __ lw(a0, MemOperand(sp));
173   // sp now point to args[0], drop args[0] + receiver.
174   __ Drop(2);
175
176   Register argument = a2;
177   Label not_cached, argument_is_string;
178   __ LookupNumberStringCache(a0,        // Input.
179                              argument,  // Result.
180                              a3,        // Scratch.
181                              t0,        // Scratch.
182                              t1,        // Scratch.
183                              &not_cached);
184   __ IncrementCounter(counters->string_ctor_cached_number(), 1, a3, t0);
185   __ bind(&argument_is_string);
186
187   // ----------- S t a t e -------------
188   //  -- a2     : argument converted to string
189   //  -- a1     : constructor function
190   //  -- ra     : return address
191   // -----------------------------------
192
193   Label gc_required;
194   __ Allocate(JSValue::kSize,
195               v0,  // Result.
196               a3,  // Scratch.
197               t0,  // Scratch.
198               &gc_required,
199               TAG_OBJECT);
200
201   // Initialising the String Object.
202   Register map = a3;
203   __ LoadGlobalFunctionInitialMap(function, map, t0);
204   if (FLAG_debug_code) {
205     __ lbu(t0, FieldMemOperand(map, Map::kInstanceSizeOffset));
206     __ Assert(eq, kUnexpectedStringWrapperInstanceSize,
207         t0, Operand(JSValue::kSize >> kPointerSizeLog2));
208     __ lbu(t0, FieldMemOperand(map, Map::kUnusedPropertyFieldsOffset));
209     __ Assert(eq, kUnexpectedUnusedPropertiesOfStringWrapper,
210         t0, Operand(zero_reg));
211   }
212   __ sw(map, FieldMemOperand(v0, HeapObject::kMapOffset));
213
214   __ LoadRoot(a3, Heap::kEmptyFixedArrayRootIndex);
215   __ sw(a3, FieldMemOperand(v0, JSObject::kPropertiesOffset));
216   __ sw(a3, FieldMemOperand(v0, JSObject::kElementsOffset));
217
218   __ sw(argument, FieldMemOperand(v0, JSValue::kValueOffset));
219
220   // Ensure the object is fully initialized.
221   STATIC_ASSERT(JSValue::kSize == 4 * kPointerSize);
222
223   __ Ret();
224
225   // The argument was not found in the number to string cache. Check
226   // if it's a string already before calling the conversion builtin.
227   Label convert_argument;
228   __ bind(&not_cached);
229   __ JumpIfSmi(a0, &convert_argument);
230
231   // Is it a String?
232   __ lw(a2, FieldMemOperand(a0, HeapObject::kMapOffset));
233   __ lbu(a3, FieldMemOperand(a2, Map::kInstanceTypeOffset));
234   STATIC_ASSERT(kNotStringTag != 0);
235   __ And(t0, a3, Operand(kIsNotStringMask));
236   __ Branch(&convert_argument, ne, t0, Operand(zero_reg));
237   __ mov(argument, a0);
238   __ IncrementCounter(counters->string_ctor_conversions(), 1, a3, t0);
239   __ Branch(&argument_is_string);
240
241   // Invoke the conversion builtin and put the result into a2.
242   __ bind(&convert_argument);
243   __ push(function);  // Preserve the function.
244   __ IncrementCounter(counters->string_ctor_conversions(), 1, a3, t0);
245   {
246     FrameScope scope(masm, StackFrame::INTERNAL);
247     __ push(a0);
248     __ InvokeBuiltin(Builtins::TO_STRING, CALL_FUNCTION);
249   }
250   __ pop(function);
251   __ mov(argument, v0);
252   __ Branch(&argument_is_string);
253
254   // Load the empty string into a2, remove the receiver from the
255   // stack, and jump back to the case where the argument is a string.
256   __ bind(&no_arguments);
257   __ LoadRoot(argument, Heap::kempty_stringRootIndex);
258   __ Drop(1);
259   __ Branch(&argument_is_string);
260
261   // At this point the argument is already a string. Call runtime to
262   // create a string wrapper.
263   __ bind(&gc_required);
264   __ IncrementCounter(counters->string_ctor_gc_required(), 1, a3, t0);
265   {
266     FrameScope scope(masm, StackFrame::INTERNAL);
267     __ push(argument);
268     __ CallRuntime(Runtime::kNewStringWrapper, 1);
269   }
270   __ Ret();
271 }
272
273
274 static void CallRuntimePassFunction(
275     MacroAssembler* masm, Runtime::FunctionId function_id) {
276   FrameScope scope(masm, StackFrame::INTERNAL);
277   // Push a copy of the function onto the stack.
278   // Push call kind information and function as parameter to the runtime call.
279   __ Push(a1, a1);
280
281   __ CallRuntime(function_id, 1);
282   // Restore call kind information and receiver.
283   __ Pop(a1);
284 }
285
286
287 static void GenerateTailCallToSharedCode(MacroAssembler* masm) {
288   __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
289   __ lw(a2, FieldMemOperand(a2, SharedFunctionInfo::kCodeOffset));
290   __ Addu(at, a2, Operand(Code::kHeaderSize - kHeapObjectTag));
291   __ Jump(at);
292 }
293
294
295 static void GenerateTailCallToReturnedCode(MacroAssembler* masm) {
296   __ Addu(at, v0, Operand(Code::kHeaderSize - kHeapObjectTag));
297   __ Jump(at);
298 }
299
300
301 void Builtins::Generate_InOptimizationQueue(MacroAssembler* masm) {
302   // Checking whether the queued function is ready for install is optional,
303   // since we come across interrupts and stack checks elsewhere.  However,
304   // not checking may delay installing ready functions, and always checking
305   // would be quite expensive.  A good compromise is to first check against
306   // stack limit as a cue for an interrupt signal.
307   Label ok;
308   __ LoadRoot(t0, Heap::kStackLimitRootIndex);
309   __ Branch(&ok, hs, sp, Operand(t0));
310
311   CallRuntimePassFunction(masm, Runtime::kTryInstallOptimizedCode);
312   GenerateTailCallToReturnedCode(masm);
313
314   __ bind(&ok);
315   GenerateTailCallToSharedCode(masm);
316 }
317
318
319 static void Generate_Runtime_NewObject(MacroAssembler* masm,
320                                        bool create_memento,
321                                        Register original_constructor,
322                                        Label* count_incremented,
323                                        Label* allocated) {
324   if (create_memento) {
325     // Get the cell or allocation site.
326     __ lw(a2, MemOperand(sp, 2 * kPointerSize));
327     __ push(a2);
328   }
329
330   __ push(a1);                    // argument for Runtime_NewObject
331   __ push(original_constructor);  // original constructor
332   if (create_memento) {
333     __ CallRuntime(Runtime::kNewObjectWithAllocationSite, 3);
334   } else {
335     __ CallRuntime(Runtime::kNewObject, 2);
336   }
337   __ mov(t4, v0);
338
339   // Runtime_NewObjectWithAllocationSite increments allocation count.
340   // Skip the increment.
341   if (create_memento) {
342     __ jmp(count_incremented);
343   } else {
344     __ jmp(allocated);
345   }
346 }
347
348
349 static void Generate_JSConstructStubHelper(MacroAssembler* masm,
350                                            bool is_api_function,
351                                            bool create_memento) {
352   // ----------- S t a t e -------------
353   //  -- a0     : number of arguments
354   //  -- a1     : constructor function
355   //  -- a2     : allocation site or undefined
356   //  -- a3     : original constructor
357   //  -- ra     : return address
358   //  -- sp[...]: constructor arguments
359   // -----------------------------------
360
361   // Should never create mementos for api functions.
362   DCHECK(!is_api_function || !create_memento);
363
364   Isolate* isolate = masm->isolate();
365
366   // ----------- S t a t e -------------
367   //  -- a0     : number of arguments
368   //  -- a1     : constructor function
369   //  -- ra     : return address
370   //  -- sp[...]: constructor arguments
371   // -----------------------------------
372
373   // Enter a construct frame.
374   {
375     FrameScope scope(masm, StackFrame::CONSTRUCT);
376
377     if (create_memento) {
378       __ AssertUndefinedOrAllocationSite(a2, t0);
379       __ push(a2);
380     }
381
382     // Preserve the two incoming parameters on the stack.
383     __ sll(a0, a0, kSmiTagSize);  // Tag arguments count.
384     __ MultiPushReversed(a0.bit() | a1.bit());
385
386     Label rt_call, allocated, normal_new, count_incremented;
387     __ Branch(&normal_new, eq, a1, Operand(a3));
388
389     // Original constructor and function are different.
390     Generate_Runtime_NewObject(masm, create_memento, a3, &count_incremented,
391                                &allocated);
392     __ bind(&normal_new);
393
394     // Try to allocate the object without transitioning into C code. If any of
395     // the preconditions is not met, the code bails out to the runtime call.
396     if (FLAG_inline_new) {
397       Label undo_allocation;
398       ExternalReference debug_step_in_fp =
399           ExternalReference::debug_step_in_fp_address(isolate);
400       __ li(a2, Operand(debug_step_in_fp));
401       __ lw(a2, MemOperand(a2));
402       __ Branch(&rt_call, ne, a2, Operand(zero_reg));
403
404       // Load the initial map and verify that it is in fact a map.
405       // a1: constructor function
406       __ lw(a2, FieldMemOperand(a1, JSFunction::kPrototypeOrInitialMapOffset));
407       __ JumpIfSmi(a2, &rt_call);
408       __ GetObjectType(a2, a3, t4);
409       __ Branch(&rt_call, ne, t4, Operand(MAP_TYPE));
410
411       // Check that the constructor is not constructing a JSFunction (see
412       // comments in Runtime_NewObject in runtime.cc). In which case the
413       // initial map's instance type would be JS_FUNCTION_TYPE.
414       // a1: constructor function
415       // a2: initial map
416       __ lbu(a3, FieldMemOperand(a2, Map::kInstanceTypeOffset));
417       __ Branch(&rt_call, eq, a3, Operand(JS_FUNCTION_TYPE));
418
419       if (!is_api_function) {
420         Label allocate;
421         MemOperand bit_field3 = FieldMemOperand(a2, Map::kBitField3Offset);
422         // Check if slack tracking is enabled.
423         __ lw(t0, bit_field3);
424         __ DecodeField<Map::Counter>(t2, t0);
425         __ Branch(&allocate, lt, t2, Operand(Map::kSlackTrackingCounterEnd));
426         // Decrease generous allocation count.
427         __ Subu(t0, t0, Operand(1 << Map::Counter::kShift));
428         __ Branch(USE_DELAY_SLOT, &allocate, ne, t2,
429                   Operand(Map::kSlackTrackingCounterEnd));
430         __ sw(t0, bit_field3);  // In delay slot.
431
432         __ Push(a1, a2, a1);  // a1 = Constructor.
433         __ CallRuntime(Runtime::kFinalizeInstanceSize, 1);
434
435         __ Pop(a1, a2);
436         // Slack tracking counter is Map::kSlackTrackingCounterEnd after runtime
437         // call.
438         __ li(t2, Map::kSlackTrackingCounterEnd);
439
440         __ bind(&allocate);
441       }
442
443       // Now allocate the JSObject on the heap.
444       // a1: constructor function
445       // a2: initial map
446       __ lbu(a3, FieldMemOperand(a2, Map::kInstanceSizeOffset));
447       if (create_memento) {
448         __ Addu(a3, a3, Operand(AllocationMemento::kSize / kPointerSize));
449       }
450
451       __ Allocate(a3, t4, t5, t6, &rt_call, SIZE_IN_WORDS);
452
453       // Allocated the JSObject, now initialize the fields. Map is set to
454       // initial map and properties and elements are set to empty fixed array.
455       // a1: constructor function
456       // a2: initial map
457       // a3: object size (not including memento if create_memento)
458       // t4: JSObject (not tagged)
459       __ LoadRoot(t6, Heap::kEmptyFixedArrayRootIndex);
460       __ mov(t5, t4);
461       __ sw(a2, MemOperand(t5, JSObject::kMapOffset));
462       __ sw(t6, MemOperand(t5, JSObject::kPropertiesOffset));
463       __ sw(t6, MemOperand(t5, JSObject::kElementsOffset));
464       __ Addu(t5, t5, Operand(3*kPointerSize));
465       DCHECK_EQ(0 * kPointerSize, JSObject::kMapOffset);
466       DCHECK_EQ(1 * kPointerSize, JSObject::kPropertiesOffset);
467       DCHECK_EQ(2 * kPointerSize, JSObject::kElementsOffset);
468
469       // Fill all the in-object properties with appropriate filler.
470       // a1: constructor function
471       // a2: initial map
472       // a3: object size (in words, including memento if create_memento)
473       // t4: JSObject (not tagged)
474       // t5: First in-object property of JSObject (not tagged)
475       // t2: slack tracking counter (non-API function case)
476       DCHECK_EQ(3 * kPointerSize, JSObject::kHeaderSize);
477
478       // Use t7 to hold undefined, which is used in several places below.
479       __ LoadRoot(t7, Heap::kUndefinedValueRootIndex);
480
481       if (!is_api_function) {
482         Label no_inobject_slack_tracking;
483
484         // Check if slack tracking is enabled.
485         __ Branch(&no_inobject_slack_tracking, lt, t2,
486                   Operand(Map::kSlackTrackingCounterEnd));
487
488         // Allocate object with a slack.
489         __ lbu(a0, FieldMemOperand(a2, Map::kPreAllocatedPropertyFieldsOffset));
490         __ sll(at, a0, kPointerSizeLog2);
491         __ addu(a0, t5, at);
492         // a0: offset of first field after pre-allocated fields
493         if (FLAG_debug_code) {
494           __ sll(at, a3, kPointerSizeLog2);
495           __ Addu(t6, t4, Operand(at));   // End of object.
496           __ Assert(le, kUnexpectedNumberOfPreAllocatedPropertyFields,
497               a0, Operand(t6));
498         }
499         __ InitializeFieldsWithFiller(t5, a0, t7);
500         // To allow for truncation.
501         __ LoadRoot(t7, Heap::kOnePointerFillerMapRootIndex);
502         // Fill the remaining fields with one pointer filler map.
503
504         __ bind(&no_inobject_slack_tracking);
505       }
506
507       if (create_memento) {
508         __ Subu(a0, a3, Operand(AllocationMemento::kSize / kPointerSize));
509         __ sll(a0, a0, kPointerSizeLog2);
510         __ Addu(a0, t4, Operand(a0));  // End of object.
511         __ InitializeFieldsWithFiller(t5, a0, t7);
512
513         // Fill in memento fields.
514         // t5: points to the allocated but uninitialized memento.
515         __ LoadRoot(t7, Heap::kAllocationMementoMapRootIndex);
516         DCHECK_EQ(0 * kPointerSize, AllocationMemento::kMapOffset);
517         __ sw(t7, MemOperand(t5));
518         __ Addu(t5, t5, kPointerSize);
519         // Load the AllocationSite.
520         __ lw(t7, MemOperand(sp, 2 * kPointerSize));
521         DCHECK_EQ(1 * kPointerSize, AllocationMemento::kAllocationSiteOffset);
522         __ sw(t7, MemOperand(t5));
523         __ Addu(t5, t5, kPointerSize);
524       } else {
525         __ sll(at, a3, kPointerSizeLog2);
526         __ Addu(a0, t4, Operand(at));  // End of object.
527         __ InitializeFieldsWithFiller(t5, a0, t7);
528       }
529
530       // Add the object tag to make the JSObject real, so that we can continue
531       // and jump into the continuation code at any time from now on. Any
532       // failures need to undo the allocation, so that the heap is in a
533       // consistent state and verifiable.
534       __ Addu(t4, t4, Operand(kHeapObjectTag));
535
536       // Check if a non-empty properties array is needed. Continue with
537       // allocated object if not fall through to runtime call if it is.
538       // a1: constructor function
539       // t4: JSObject
540       // t5: start of next object (not tagged)
541       __ lbu(a3, FieldMemOperand(a2, Map::kUnusedPropertyFieldsOffset));
542       // The field instance sizes contains both pre-allocated property fields
543       // and in-object properties.
544       __ lbu(t6, FieldMemOperand(a2, Map::kPreAllocatedPropertyFieldsOffset));
545       __ Addu(a3, a3, Operand(t6));
546       __ lbu(t6, FieldMemOperand(a2, Map::kInObjectPropertiesOffset));
547       __ subu(a3, a3, t6);
548
549       // Done if no extra properties are to be allocated.
550       __ Branch(&allocated, eq, a3, Operand(zero_reg));
551       __ Assert(greater_equal, kPropertyAllocationCountFailed,
552           a3, Operand(zero_reg));
553
554       // Scale the number of elements by pointer size and add the header for
555       // FixedArrays to the start of the next object calculation from above.
556       // a1: constructor
557       // a3: number of elements in properties array
558       // t4: JSObject
559       // t5: start of next object
560       __ Addu(a0, a3, Operand(FixedArray::kHeaderSize / kPointerSize));
561       __ Allocate(
562           a0,
563           t5,
564           t6,
565           a2,
566           &undo_allocation,
567           static_cast<AllocationFlags>(RESULT_CONTAINS_TOP | SIZE_IN_WORDS));
568
569       // Initialize the FixedArray.
570       // a1: constructor
571       // a3: number of elements in properties array (untagged)
572       // t4: JSObject
573       // t5: start of next object
574       __ LoadRoot(t6, Heap::kFixedArrayMapRootIndex);
575       __ mov(a2, t5);
576       __ sw(t6, MemOperand(a2, JSObject::kMapOffset));
577       __ sll(a0, a3, kSmiTagSize);
578       __ sw(a0, MemOperand(a2, FixedArray::kLengthOffset));
579       __ Addu(a2, a2, Operand(2 * kPointerSize));
580
581       DCHECK_EQ(0 * kPointerSize, JSObject::kMapOffset);
582       DCHECK_EQ(1 * kPointerSize, FixedArray::kLengthOffset);
583
584       // Initialize the fields to undefined.
585       // a1: constructor
586       // a2: First element of FixedArray (not tagged)
587       // a3: number of elements in properties array
588       // t4: JSObject
589       // t5: FixedArray (not tagged)
590       __ sll(t3, a3, kPointerSizeLog2);
591       __ addu(t6, a2, t3);  // End of object.
592       DCHECK_EQ(2 * kPointerSize, FixedArray::kHeaderSize);
593       { Label loop, entry;
594         if (!is_api_function || create_memento) {
595           __ LoadRoot(t7, Heap::kUndefinedValueRootIndex);
596         } else if (FLAG_debug_code) {
597           __ LoadRoot(t2, Heap::kUndefinedValueRootIndex);
598           __ Assert(eq, kUndefinedValueNotLoaded, t7, Operand(t2));
599         }
600         __ jmp(&entry);
601         __ bind(&loop);
602         __ sw(t7, MemOperand(a2));
603         __ addiu(a2, a2, kPointerSize);
604         __ bind(&entry);
605         __ Branch(&loop, less, a2, Operand(t6));
606       }
607
608       // Store the initialized FixedArray into the properties field of
609       // the JSObject.
610       // a1: constructor function
611       // t4: JSObject
612       // t5: FixedArray (not tagged)
613       __ Addu(t5, t5, Operand(kHeapObjectTag));  // Add the heap tag.
614       __ sw(t5, FieldMemOperand(t4, JSObject::kPropertiesOffset));
615
616       // Continue with JSObject being successfully allocated.
617       // a1: constructor function
618       // a4: JSObject
619       __ jmp(&allocated);
620
621       // Undo the setting of the new top so that the heap is verifiable. For
622       // example, the map's unused properties potentially do not match the
623       // allocated objects unused properties.
624       // t4: JSObject (previous new top)
625       __ bind(&undo_allocation);
626       __ UndoAllocationInNewSpace(t4, t5);
627     }
628
629     // Allocate the new receiver object using the runtime call.
630     // a1: constructor function
631     __ bind(&rt_call);
632     Generate_Runtime_NewObject(masm, create_memento, a1, &count_incremented,
633                                &allocated);
634
635     // Receiver for constructor call allocated.
636     // t4: JSObject
637     __ bind(&allocated);
638
639     if (create_memento) {
640       __ lw(a2, MemOperand(sp, kPointerSize * 2));
641       __ LoadRoot(t5, Heap::kUndefinedValueRootIndex);
642       __ Branch(&count_incremented, eq, a2, Operand(t5));
643       // a2 is an AllocationSite. We are creating a memento from it, so we
644       // need to increment the memento create count.
645       __ lw(a3, FieldMemOperand(a2,
646                                 AllocationSite::kPretenureCreateCountOffset));
647       __ Addu(a3, a3, Operand(Smi::FromInt(1)));
648       __ sw(a3, FieldMemOperand(a2,
649                                 AllocationSite::kPretenureCreateCountOffset));
650       __ bind(&count_incremented);
651     }
652
653     __ Push(t4, t4);
654
655     // Reload the number of arguments from the stack.
656     // sp[0]: receiver
657     // sp[1]: receiver
658     // sp[2]: constructor function
659     // sp[3]: number of arguments (smi-tagged)
660     __ lw(a1, MemOperand(sp, 2 * kPointerSize));
661     __ lw(a3, MemOperand(sp, 3 * kPointerSize));
662
663     // Set up pointer to last argument.
664     __ Addu(a2, fp, Operand(StandardFrameConstants::kCallerSPOffset));
665
666     // Set up number of arguments for function call below.
667     __ srl(a0, a3, kSmiTagSize);
668
669     // Copy arguments and receiver to the expression stack.
670     // a0: number of arguments
671     // a1: constructor function
672     // a2: address of last argument (caller sp)
673     // a3: number of arguments (smi-tagged)
674     // sp[0]: receiver
675     // sp[1]: receiver
676     // sp[2]: constructor function
677     // sp[3]: number of arguments (smi-tagged)
678     Label loop, entry;
679     __ jmp(&entry);
680     __ bind(&loop);
681     __ sll(t0, a3, kPointerSizeLog2 - kSmiTagSize);
682     __ Addu(t0, a2, Operand(t0));
683     __ lw(t1, MemOperand(t0));
684     __ push(t1);
685     __ bind(&entry);
686     __ Addu(a3, a3, Operand(-2));
687     __ Branch(&loop, greater_equal, a3, Operand(zero_reg));
688
689     // Call the function.
690     // a0: number of arguments
691     // a1: constructor function
692     if (is_api_function) {
693       __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
694       Handle<Code> code =
695           masm->isolate()->builtins()->HandleApiCallConstruct();
696       __ Call(code, RelocInfo::CODE_TARGET);
697     } else {
698       ParameterCount actual(a0);
699       __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper());
700     }
701
702     // Store offset of return address for deoptimizer.
703     if (!is_api_function) {
704       masm->isolate()->heap()->SetConstructStubDeoptPCOffset(masm->pc_offset());
705     }
706
707     // Restore context from the frame.
708     __ lw(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
709
710     // If the result is an object (in the ECMA sense), we should get rid
711     // of the receiver and use the result; see ECMA-262 section 13.2.2-7
712     // on page 74.
713     Label use_receiver, exit;
714
715     // If the result is a smi, it is *not* an object in the ECMA sense.
716     // v0: result
717     // sp[0]: receiver (newly allocated object)
718     // sp[1]: constructor function
719     // sp[2]: number of arguments (smi-tagged)
720     __ JumpIfSmi(v0, &use_receiver);
721
722     // If the type of the result (stored in its map) is less than
723     // FIRST_SPEC_OBJECT_TYPE, it is not an object in the ECMA sense.
724     __ GetObjectType(v0, a1, a3);
725     __ Branch(&exit, greater_equal, a3, Operand(FIRST_SPEC_OBJECT_TYPE));
726
727     // Throw away the result of the constructor invocation and use the
728     // on-stack receiver as the result.
729     __ bind(&use_receiver);
730     __ lw(v0, MemOperand(sp));
731
732     // Remove receiver from the stack, remove caller arguments, and
733     // return.
734     __ bind(&exit);
735     // v0: result
736     // sp[0]: receiver (newly allocated object)
737     // sp[1]: constructor function
738     // sp[2]: number of arguments (smi-tagged)
739     __ lw(a1, MemOperand(sp, 2 * kPointerSize));
740
741     // Leave construct frame.
742   }
743
744   __ sll(t0, a1, kPointerSizeLog2 - 1);
745   __ Addu(sp, sp, t0);
746   __ Addu(sp, sp, kPointerSize);
747   __ IncrementCounter(isolate->counters()->constructed_objects(), 1, a1, a2);
748   __ Ret();
749 }
750
751
752 void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) {
753   Generate_JSConstructStubHelper(masm, false, FLAG_pretenuring_call_new);
754 }
755
756
757 void Builtins::Generate_JSConstructStubApi(MacroAssembler* masm) {
758   Generate_JSConstructStubHelper(masm, true, false);
759 }
760
761
762 void Builtins::Generate_JSConstructStubForDerived(MacroAssembler* masm) {
763   // ----------- S t a t e -------------
764   //  -- a0     : number of arguments
765   //  -- a1     : constructor function
766   //  -- a2     : allocation site or undefined
767   //  -- a3     : original constructor
768   //  -- ra     : return address
769   //  -- sp[...]: constructor arguments
770   // -----------------------------------
771
772   // TODO(dslomov): support pretenuring
773   CHECK(!FLAG_pretenuring_call_new);
774
775   {
776     FrameScope frame_scope(masm, StackFrame::CONSTRUCT);
777
778     __ mov(t0, a0);
779     __ SmiTag(t0);
780     __ push(t0);  // Smi-tagged arguments count.
781
782     // Push new.target.
783     __ push(a3);
784
785     // receiver is the hole.
786     __ LoadRoot(at, Heap::kTheHoleValueRootIndex);
787     __ push(at);
788
789     // Set up pointer to last argument.
790     __ Addu(a2, fp, Operand(StandardFrameConstants::kCallerSPOffset));
791
792     // Copy arguments and receiver to the expression stack.
793     // a0: number of arguments
794     // a1: constructor function
795     // a2: address of last argument (caller sp)
796     // t0: number of arguments (smi-tagged)
797     // sp[0]: receiver
798     // sp[1]: new.target
799     // sp[2]: number of arguments (smi-tagged)
800     Label loop, entry;
801     __ Branch(&entry);
802     __ bind(&loop);
803     __ sll(at, t0, kPointerSizeLog2 - 1);
804     __ Addu(at, a2, Operand(at));
805     __ lw(at, MemOperand(at));
806     __ push(at);
807     __ bind(&entry);
808     __ Subu(t0, t0, Operand(2));
809     __ Branch(&loop, ge, t0, Operand(zero_reg));
810
811     __ Addu(a0, a0, Operand(1));
812
813     // Handle step in.
814     Label skip_step_in;
815     ExternalReference debug_step_in_fp =
816         ExternalReference::debug_step_in_fp_address(masm->isolate());
817     __ li(a2, Operand(debug_step_in_fp));
818     __ lw(a2, MemOperand(a2));
819     __ Branch(&skip_step_in, eq, a2, Operand(zero_reg));
820
821     __ Push(a0, a1, a1);
822     __ CallRuntime(Runtime::kHandleStepInForDerivedConstructors, 1);
823     __ Pop(a0, a1);
824
825     __ bind(&skip_step_in);
826
827     // Call the function.
828     // a0: number of arguments
829     // a1: constructor function
830     ParameterCount actual(a0);
831     __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper());
832
833     // Restore context from the frame.
834     // v0: result
835     // sp[0]: number of arguments (smi-tagged)
836     __ lw(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
837     __ lw(a1, MemOperand(sp, 0));
838
839     // Leave construct frame.
840   }
841
842   __ sll(at, a1, kPointerSizeLog2 - 1);
843   __ Addu(sp, sp, Operand(at));
844   __ Addu(sp, sp, Operand(kPointerSize));
845   __ Jump(ra);
846 }
847
848
849 static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm,
850                                              bool is_construct) {
851   // Called from JSEntryStub::GenerateBody
852
853   // ----------- S t a t e -------------
854   //  -- a0: code entry
855   //  -- a1: function
856   //  -- a2: receiver_pointer
857   //  -- a3: argc
858   //  -- s0: argv
859   // -----------------------------------
860   ProfileEntryHookStub::MaybeCallEntryHook(masm);
861
862   // Clear the context before we push it when entering the JS frame.
863   __ mov(cp, zero_reg);
864
865   // Enter an internal frame.
866   {
867     FrameScope scope(masm, StackFrame::INTERNAL);
868
869     // Set up the context from the function argument.
870     __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
871
872     // Push the function and the receiver onto the stack.
873     __ Push(a1, a2);
874
875     // Copy arguments to the stack in a loop.
876     // a3: argc
877     // s0: argv, i.e. points to first arg
878     Label loop, entry;
879     __ sll(t0, a3, kPointerSizeLog2);
880     __ addu(t2, s0, t0);
881     __ b(&entry);
882     __ nop();   // Branch delay slot nop.
883     // t2 points past last arg.
884     __ bind(&loop);
885     __ lw(t0, MemOperand(s0));  // Read next parameter.
886     __ addiu(s0, s0, kPointerSize);
887     __ lw(t0, MemOperand(t0));  // Dereference handle.
888     __ push(t0);  // Push parameter.
889     __ bind(&entry);
890     __ Branch(&loop, ne, s0, Operand(t2));
891
892     // Initialize all JavaScript callee-saved registers, since they will be seen
893     // by the garbage collector as part of handlers.
894     __ LoadRoot(t0, Heap::kUndefinedValueRootIndex);
895     __ mov(s1, t0);
896     __ mov(s2, t0);
897     __ mov(s3, t0);
898     __ mov(s4, t0);
899     __ mov(s5, t0);
900     // s6 holds the root address. Do not clobber.
901     // s7 is cp. Do not init.
902
903     // Invoke the code and pass argc as a0.
904     __ mov(a0, a3);
905     if (is_construct) {
906       // No type feedback cell is available
907       __ LoadRoot(a2, Heap::kUndefinedValueRootIndex);
908       CallConstructStub stub(masm->isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
909       __ CallStub(&stub);
910     } else {
911       ParameterCount actual(a0);
912       __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper());
913     }
914
915     // Leave internal frame.
916   }
917
918   __ Jump(ra);
919 }
920
921
922 void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) {
923   Generate_JSEntryTrampolineHelper(masm, false);
924 }
925
926
927 void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) {
928   Generate_JSEntryTrampolineHelper(masm, true);
929 }
930
931
932 void Builtins::Generate_CompileLazy(MacroAssembler* masm) {
933   CallRuntimePassFunction(masm, Runtime::kCompileLazy);
934   GenerateTailCallToReturnedCode(masm);
935 }
936
937
938 static void CallCompileOptimized(MacroAssembler* masm, bool concurrent) {
939   FrameScope scope(masm, StackFrame::INTERNAL);
940   // Push a copy of the function onto the stack.
941   // Push function as parameter to the runtime call.
942   __ Push(a1, a1);
943   // Whether to compile in a background thread.
944   __ Push(masm->isolate()->factory()->ToBoolean(concurrent));
945
946   __ CallRuntime(Runtime::kCompileOptimized, 2);
947   // Restore receiver.
948   __ Pop(a1);
949 }
950
951
952 void Builtins::Generate_CompileOptimized(MacroAssembler* masm) {
953   CallCompileOptimized(masm, false);
954   GenerateTailCallToReturnedCode(masm);
955 }
956
957
958 void Builtins::Generate_CompileOptimizedConcurrent(MacroAssembler* masm) {
959   CallCompileOptimized(masm, true);
960   GenerateTailCallToReturnedCode(masm);
961 }
962
963
964
965 static void GenerateMakeCodeYoungAgainCommon(MacroAssembler* masm) {
966   // For now, we are relying on the fact that make_code_young doesn't do any
967   // garbage collection which allows us to save/restore the registers without
968   // worrying about which of them contain pointers. We also don't build an
969   // internal frame to make the code faster, since we shouldn't have to do stack
970   // crawls in MakeCodeYoung. This seems a bit fragile.
971
972   // Set a0 to point to the head of the PlatformCodeAge sequence.
973   __ Subu(a0, a0,
974       Operand(kNoCodeAgeSequenceLength - Assembler::kInstrSize));
975
976   // The following registers must be saved and restored when calling through to
977   // the runtime:
978   //   a0 - contains return address (beginning of patch sequence)
979   //   a1 - isolate
980   RegList saved_regs =
981       (a0.bit() | a1.bit() | ra.bit() | fp.bit()) & ~sp.bit();
982   FrameScope scope(masm, StackFrame::MANUAL);
983   __ MultiPush(saved_regs);
984   __ PrepareCallCFunction(2, 0, a2);
985   __ li(a1, Operand(ExternalReference::isolate_address(masm->isolate())));
986   __ CallCFunction(
987       ExternalReference::get_make_code_young_function(masm->isolate()), 2);
988   __ MultiPop(saved_regs);
989   __ Jump(a0);
990 }
991
992 #define DEFINE_CODE_AGE_BUILTIN_GENERATOR(C)                 \
993 void Builtins::Generate_Make##C##CodeYoungAgainEvenMarking(  \
994     MacroAssembler* masm) {                                  \
995   GenerateMakeCodeYoungAgainCommon(masm);                    \
996 }                                                            \
997 void Builtins::Generate_Make##C##CodeYoungAgainOddMarking(   \
998     MacroAssembler* masm) {                                  \
999   GenerateMakeCodeYoungAgainCommon(masm);                    \
1000 }
1001 CODE_AGE_LIST(DEFINE_CODE_AGE_BUILTIN_GENERATOR)
1002 #undef DEFINE_CODE_AGE_BUILTIN_GENERATOR
1003
1004
1005 void Builtins::Generate_MarkCodeAsExecutedOnce(MacroAssembler* masm) {
1006   // For now, as in GenerateMakeCodeYoungAgainCommon, we are relying on the fact
1007   // that make_code_young doesn't do any garbage collection which allows us to
1008   // save/restore the registers without worrying about which of them contain
1009   // pointers.
1010
1011   // Set a0 to point to the head of the PlatformCodeAge sequence.
1012   __ Subu(a0, a0,
1013       Operand(kNoCodeAgeSequenceLength - Assembler::kInstrSize));
1014
1015   // The following registers must be saved and restored when calling through to
1016   // the runtime:
1017   //   a0 - contains return address (beginning of patch sequence)
1018   //   a1 - isolate
1019   RegList saved_regs =
1020       (a0.bit() | a1.bit() | ra.bit() | fp.bit()) & ~sp.bit();
1021   FrameScope scope(masm, StackFrame::MANUAL);
1022   __ MultiPush(saved_regs);
1023   __ PrepareCallCFunction(2, 0, a2);
1024   __ li(a1, Operand(ExternalReference::isolate_address(masm->isolate())));
1025   __ CallCFunction(
1026       ExternalReference::get_mark_code_as_executed_function(masm->isolate()),
1027       2);
1028   __ MultiPop(saved_regs);
1029
1030   // Perform prologue operations usually performed by the young code stub.
1031   __ Push(ra, fp, cp, a1);
1032   __ Addu(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
1033
1034   // Jump to point after the code-age stub.
1035   __ Addu(a0, a0, Operand(kNoCodeAgeSequenceLength));
1036   __ Jump(a0);
1037 }
1038
1039
1040 void Builtins::Generate_MarkCodeAsExecutedTwice(MacroAssembler* masm) {
1041   GenerateMakeCodeYoungAgainCommon(masm);
1042 }
1043
1044
1045 static void Generate_NotifyStubFailureHelper(MacroAssembler* masm,
1046                                              SaveFPRegsMode save_doubles) {
1047   {
1048     FrameScope scope(masm, StackFrame::INTERNAL);
1049
1050     // Preserve registers across notification, this is important for compiled
1051     // stubs that tail call the runtime on deopts passing their parameters in
1052     // registers.
1053     __ MultiPush(kJSCallerSaved | kCalleeSaved);
1054     // Pass the function and deoptimization type to the runtime system.
1055     __ CallRuntime(Runtime::kNotifyStubFailure, 0, save_doubles);
1056     __ MultiPop(kJSCallerSaved | kCalleeSaved);
1057   }
1058
1059   __ Addu(sp, sp, Operand(kPointerSize));  // Ignore state
1060   __ Jump(ra);  // Jump to miss handler
1061 }
1062
1063
1064 void Builtins::Generate_NotifyStubFailure(MacroAssembler* masm) {
1065   Generate_NotifyStubFailureHelper(masm, kDontSaveFPRegs);
1066 }
1067
1068
1069 void Builtins::Generate_NotifyStubFailureSaveDoubles(MacroAssembler* masm) {
1070   Generate_NotifyStubFailureHelper(masm, kSaveFPRegs);
1071 }
1072
1073
1074 static void Generate_NotifyDeoptimizedHelper(MacroAssembler* masm,
1075                                              Deoptimizer::BailoutType type) {
1076   {
1077     FrameScope scope(masm, StackFrame::INTERNAL);
1078     // Pass the function and deoptimization type to the runtime system.
1079     __ li(a0, Operand(Smi::FromInt(static_cast<int>(type))));
1080     __ push(a0);
1081     __ CallRuntime(Runtime::kNotifyDeoptimized, 1);
1082   }
1083
1084   // Get the full codegen state from the stack and untag it -> t2.
1085   __ lw(t2, MemOperand(sp, 0 * kPointerSize));
1086   __ SmiUntag(t2);
1087   // Switch on the state.
1088   Label with_tos_register, unknown_state;
1089   __ Branch(&with_tos_register,
1090             ne, t2, Operand(FullCodeGenerator::NO_REGISTERS));
1091   __ Ret(USE_DELAY_SLOT);
1092   // Safe to fill delay slot Addu will emit one instruction.
1093   __ Addu(sp, sp, Operand(1 * kPointerSize));  // Remove state.
1094
1095   __ bind(&with_tos_register);
1096   __ lw(v0, MemOperand(sp, 1 * kPointerSize));
1097   __ Branch(&unknown_state, ne, t2, Operand(FullCodeGenerator::TOS_REG));
1098
1099   __ Ret(USE_DELAY_SLOT);
1100   // Safe to fill delay slot Addu will emit one instruction.
1101   __ Addu(sp, sp, Operand(2 * kPointerSize));  // Remove state.
1102
1103   __ bind(&unknown_state);
1104   __ stop("no cases left");
1105 }
1106
1107
1108 void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) {
1109   Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::EAGER);
1110 }
1111
1112
1113 void Builtins::Generate_NotifySoftDeoptimized(MacroAssembler* masm) {
1114   Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::SOFT);
1115 }
1116
1117
1118 void Builtins::Generate_NotifyLazyDeoptimized(MacroAssembler* masm) {
1119   Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::LAZY);
1120 }
1121
1122
1123 void Builtins::Generate_OnStackReplacement(MacroAssembler* masm) {
1124   // Lookup the function in the JavaScript frame.
1125   __ lw(a0, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
1126   {
1127     FrameScope scope(masm, StackFrame::INTERNAL);
1128     // Pass function as argument.
1129     __ push(a0);
1130     __ CallRuntime(Runtime::kCompileForOnStackReplacement, 1);
1131   }
1132
1133   // If the code object is null, just return to the unoptimized code.
1134   __ Ret(eq, v0, Operand(Smi::FromInt(0)));
1135
1136   // Load deoptimization data from the code object.
1137   // <deopt_data> = <code>[#deoptimization_data_offset]
1138   __ lw(a1, MemOperand(v0, Code::kDeoptimizationDataOffset - kHeapObjectTag));
1139
1140   // Load the OSR entrypoint offset from the deoptimization data.
1141   // <osr_offset> = <deopt_data>[#header_size + #osr_pc_offset]
1142   __ lw(a1, MemOperand(a1, FixedArray::OffsetOfElementAt(
1143       DeoptimizationInputData::kOsrPcOffsetIndex) - kHeapObjectTag));
1144   __ SmiUntag(a1);
1145
1146   // Compute the target address = code_obj + header_size + osr_offset
1147   // <entry_addr> = <code_obj> + #header_size + <osr_offset>
1148   __ addu(v0, v0, a1);
1149   __ addiu(ra, v0, Code::kHeaderSize - kHeapObjectTag);
1150
1151   // And "return" to the OSR entry point of the function.
1152   __ Ret();
1153 }
1154
1155
1156 void Builtins::Generate_OsrAfterStackCheck(MacroAssembler* masm) {
1157   // We check the stack limit as indicator that recompilation might be done.
1158   Label ok;
1159   __ LoadRoot(at, Heap::kStackLimitRootIndex);
1160   __ Branch(&ok, hs, sp, Operand(at));
1161   {
1162     FrameScope scope(masm, StackFrame::INTERNAL);
1163     __ CallRuntime(Runtime::kStackGuard, 0);
1164   }
1165   __ Jump(masm->isolate()->builtins()->OnStackReplacement(),
1166           RelocInfo::CODE_TARGET);
1167
1168   __ bind(&ok);
1169   __ Ret();
1170 }
1171
1172
1173 void Builtins::Generate_FunctionCall(MacroAssembler* masm) {
1174   // 1. Make sure we have at least one argument.
1175   // a0: actual number of arguments
1176   { Label done;
1177     __ Branch(&done, ne, a0, Operand(zero_reg));
1178     __ LoadRoot(t2, Heap::kUndefinedValueRootIndex);
1179     __ push(t2);
1180     __ Addu(a0, a0, Operand(1));
1181     __ bind(&done);
1182   }
1183
1184   // 2. Get the function to call (passed as receiver) from the stack, check
1185   //    if it is a function.
1186   // a0: actual number of arguments
1187   Label slow, non_function;
1188   __ sll(at, a0, kPointerSizeLog2);
1189   __ addu(at, sp, at);
1190   __ lw(a1, MemOperand(at));
1191   __ JumpIfSmi(a1, &non_function);
1192   __ GetObjectType(a1, a2, a2);
1193   __ Branch(&slow, ne, a2, Operand(JS_FUNCTION_TYPE));
1194
1195   // 3a. Patch the first argument if necessary when calling a function.
1196   // a0: actual number of arguments
1197   // a1: function
1198   Label shift_arguments;
1199   __ li(t0, Operand(0, RelocInfo::NONE32));  // Indicate regular JS_FUNCTION.
1200   { Label convert_to_object, use_global_proxy, patch_receiver;
1201     // Change context eagerly in case we need the global receiver.
1202     __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
1203
1204     // Do not transform the receiver for strict mode functions.
1205     __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
1206     __ lw(a3, FieldMemOperand(a2, SharedFunctionInfo::kCompilerHintsOffset));
1207     __ And(t3, a3, Operand(1 << (SharedFunctionInfo::kStrictModeFunction +
1208                                  kSmiTagSize)));
1209     __ Branch(&shift_arguments, ne, t3, Operand(zero_reg));
1210
1211     // Do not transform the receiver for native (Compilerhints already in a3).
1212     __ And(t3, a3, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize)));
1213     __ Branch(&shift_arguments, ne, t3, Operand(zero_reg));
1214
1215     // Compute the receiver in sloppy mode.
1216     // Load first argument in a2. a2 = -kPointerSize(sp + n_args << 2).
1217     __ sll(at, a0, kPointerSizeLog2);
1218     __ addu(a2, sp, at);
1219     __ lw(a2, MemOperand(a2, -kPointerSize));
1220     // a0: actual number of arguments
1221     // a1: function
1222     // a2: first argument
1223     __ JumpIfSmi(a2, &convert_to_object, t2);
1224
1225     __ LoadRoot(a3, Heap::kUndefinedValueRootIndex);
1226     __ Branch(&use_global_proxy, eq, a2, Operand(a3));
1227     __ LoadRoot(a3, Heap::kNullValueRootIndex);
1228     __ Branch(&use_global_proxy, eq, a2, Operand(a3));
1229
1230     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
1231     __ GetObjectType(a2, a3, a3);
1232     __ Branch(&shift_arguments, ge, a3, Operand(FIRST_SPEC_OBJECT_TYPE));
1233
1234     __ bind(&convert_to_object);
1235     // Enter an internal frame in order to preserve argument count.
1236     {
1237       FrameScope scope(masm, StackFrame::INTERNAL);
1238       __ sll(a0, a0, kSmiTagSize);  // Smi tagged.
1239       __ Push(a0, a2);
1240       __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1241       __ mov(a2, v0);
1242
1243       __ pop(a0);
1244       __ sra(a0, a0, kSmiTagSize);  // Un-tag.
1245       // Leave internal frame.
1246     }
1247
1248     // Restore the function to a1, and the flag to t0.
1249     __ sll(at, a0, kPointerSizeLog2);
1250     __ addu(at, sp, at);
1251     __ lw(a1, MemOperand(at));
1252     __ Branch(USE_DELAY_SLOT, &patch_receiver);
1253     __ li(t0, Operand(0, RelocInfo::NONE32));  // In delay slot.
1254
1255     __ bind(&use_global_proxy);
1256     __ lw(a2, ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX));
1257     __ lw(a2, FieldMemOperand(a2, GlobalObject::kGlobalProxyOffset));
1258
1259     __ bind(&patch_receiver);
1260     __ sll(at, a0, kPointerSizeLog2);
1261     __ addu(a3, sp, at);
1262     __ sw(a2, MemOperand(a3, -kPointerSize));
1263
1264     __ Branch(&shift_arguments);
1265   }
1266
1267   // 3b. Check for function proxy.
1268   __ bind(&slow);
1269   __ li(t0, Operand(1, RelocInfo::NONE32));  // Indicate function proxy.
1270   __ Branch(&shift_arguments, eq, a2, Operand(JS_FUNCTION_PROXY_TYPE));
1271
1272   __ bind(&non_function);
1273   __ li(t0, Operand(2, RelocInfo::NONE32));  // Indicate non-function.
1274
1275   // 3c. Patch the first argument when calling a non-function.  The
1276   //     CALL_NON_FUNCTION builtin expects the non-function callee as
1277   //     receiver, so overwrite the first argument which will ultimately
1278   //     become the receiver.
1279   // a0: actual number of arguments
1280   // a1: function
1281   // t0: call type (0: JS function, 1: function proxy, 2: non-function)
1282   __ sll(at, a0, kPointerSizeLog2);
1283   __ addu(a2, sp, at);
1284   __ sw(a1, MemOperand(a2, -kPointerSize));
1285
1286   // 4. Shift arguments and return address one slot down on the stack
1287   //    (overwriting the original receiver).  Adjust argument count to make
1288   //    the original first argument the new receiver.
1289   // a0: actual number of arguments
1290   // a1: function
1291   // t0: call type (0: JS function, 1: function proxy, 2: non-function)
1292   __ bind(&shift_arguments);
1293   { Label loop;
1294     // Calculate the copy start address (destination). Copy end address is sp.
1295     __ sll(at, a0, kPointerSizeLog2);
1296     __ addu(a2, sp, at);
1297
1298     __ bind(&loop);
1299     __ lw(at, MemOperand(a2, -kPointerSize));
1300     __ sw(at, MemOperand(a2));
1301     __ Subu(a2, a2, Operand(kPointerSize));
1302     __ Branch(&loop, ne, a2, Operand(sp));
1303     // Adjust the actual number of arguments and remove the top element
1304     // (which is a copy of the last argument).
1305     __ Subu(a0, a0, Operand(1));
1306     __ Pop();
1307   }
1308
1309   // 5a. Call non-function via tail call to CALL_NON_FUNCTION builtin,
1310   //     or a function proxy via CALL_FUNCTION_PROXY.
1311   // a0: actual number of arguments
1312   // a1: function
1313   // t0: call type (0: JS function, 1: function proxy, 2: non-function)
1314   { Label function, non_proxy;
1315     __ Branch(&function, eq, t0, Operand(zero_reg));
1316     // Expected number of arguments is 0 for CALL_NON_FUNCTION.
1317     __ mov(a2, zero_reg);
1318     __ Branch(&non_proxy, ne, t0, Operand(1));
1319
1320     __ push(a1);  // Re-add proxy object as additional argument.
1321     __ Addu(a0, a0, Operand(1));
1322     __ GetBuiltinFunction(a1, Builtins::CALL_FUNCTION_PROXY);
1323     __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
1324             RelocInfo::CODE_TARGET);
1325
1326     __ bind(&non_proxy);
1327     __ GetBuiltinFunction(a1, Builtins::CALL_NON_FUNCTION);
1328     __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
1329             RelocInfo::CODE_TARGET);
1330     __ bind(&function);
1331   }
1332
1333   // 5b. Get the code to call from the function and check that the number of
1334   //     expected arguments matches what we're providing.  If so, jump
1335   //     (tail-call) to the code in register edx without checking arguments.
1336   // a0: actual number of arguments
1337   // a1: function
1338   __ lw(a3, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
1339   __ lw(a2,
1340          FieldMemOperand(a3, SharedFunctionInfo::kFormalParameterCountOffset));
1341   __ sra(a2, a2, kSmiTagSize);
1342   // Check formal and actual parameter counts.
1343   __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
1344           RelocInfo::CODE_TARGET, ne, a2, Operand(a0));
1345
1346   __ lw(a3, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
1347   ParameterCount expected(0);
1348   __ InvokeCode(a3, expected, expected, JUMP_FUNCTION, NullCallWrapper());
1349 }
1350
1351
1352 void Builtins::Generate_FunctionApply(MacroAssembler* masm) {
1353   const int kIndexOffset    =
1354       StandardFrameConstants::kExpressionsOffset - (2 * kPointerSize);
1355   const int kLimitOffset    =
1356       StandardFrameConstants::kExpressionsOffset - (1 * kPointerSize);
1357   const int kArgsOffset     = 2 * kPointerSize;
1358   const int kRecvOffset     = 3 * kPointerSize;
1359   const int kFunctionOffset = 4 * kPointerSize;
1360
1361   {
1362     FrameScope frame_scope(masm, StackFrame::INTERNAL);
1363     __ lw(a0, MemOperand(fp, kFunctionOffset));  // Get the function.
1364     __ push(a0);
1365     __ lw(a0, MemOperand(fp, kArgsOffset));  // Get the args array.
1366     __ push(a0);
1367     // Returns (in v0) number of arguments to copy to stack as Smi.
1368     __ InvokeBuiltin(Builtins::APPLY_PREPARE, CALL_FUNCTION);
1369
1370     // Check the stack for overflow. We are not trying to catch
1371     // interruptions (e.g. debug break and preemption) here, so the "real stack
1372     // limit" is checked.
1373     Label okay;
1374     __ LoadRoot(a2, Heap::kRealStackLimitRootIndex);
1375     // Make a2 the space we have left. The stack might already be overflowed
1376     // here which will cause a2 to become negative.
1377     __ subu(a2, sp, a2);
1378     // Check if the arguments will overflow the stack.
1379     __ sll(t3, v0, kPointerSizeLog2 - kSmiTagSize);
1380     __ Branch(&okay, gt, a2, Operand(t3));  // Signed comparison.
1381
1382     // Out of stack space.
1383     __ lw(a1, MemOperand(fp, kFunctionOffset));
1384     __ Push(a1, v0);
1385     __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
1386     // End of stack check.
1387
1388     // Push current limit and index.
1389     __ bind(&okay);
1390     __ mov(a1, zero_reg);
1391     __ Push(v0, a1);  // Limit and initial index.
1392
1393     // Get the receiver.
1394     __ lw(a0, MemOperand(fp, kRecvOffset));
1395
1396     // Check that the function is a JS function (otherwise it must be a proxy).
1397     Label push_receiver;
1398     __ lw(a1, MemOperand(fp, kFunctionOffset));
1399     __ GetObjectType(a1, a2, a2);
1400     __ Branch(&push_receiver, ne, a2, Operand(JS_FUNCTION_TYPE));
1401
1402     // Change context eagerly to get the right global object if necessary.
1403     __ lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
1404     // Load the shared function info while the function is still in a1.
1405     __ lw(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
1406
1407     // Compute the receiver.
1408     // Do not transform the receiver for strict mode functions.
1409     Label call_to_object, use_global_proxy;
1410     __ lw(a2, FieldMemOperand(a2, SharedFunctionInfo::kCompilerHintsOffset));
1411     __ And(t3, a2, Operand(1 << (SharedFunctionInfo::kStrictModeFunction +
1412                                  kSmiTagSize)));
1413     __ Branch(&push_receiver, ne, t3, Operand(zero_reg));
1414
1415     // Do not transform the receiver for native (Compilerhints already in a2).
1416     __ And(t3, a2, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize)));
1417     __ Branch(&push_receiver, ne, t3, Operand(zero_reg));
1418
1419     // Compute the receiver in sloppy mode.
1420     __ JumpIfSmi(a0, &call_to_object);
1421     __ LoadRoot(a1, Heap::kNullValueRootIndex);
1422     __ Branch(&use_global_proxy, eq, a0, Operand(a1));
1423     __ LoadRoot(a2, Heap::kUndefinedValueRootIndex);
1424     __ Branch(&use_global_proxy, eq, a0, Operand(a2));
1425
1426     // Check if the receiver is already a JavaScript object.
1427     // a0: receiver
1428     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
1429     __ GetObjectType(a0, a1, a1);
1430     __ Branch(&push_receiver, ge, a1, Operand(FIRST_SPEC_OBJECT_TYPE));
1431
1432     // Convert the receiver to a regular object.
1433     // a0: receiver
1434     __ bind(&call_to_object);
1435     __ push(a0);
1436     __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1437     __ mov(a0, v0);  // Put object in a0 to match other paths to push_receiver.
1438     __ Branch(&push_receiver);
1439
1440     __ bind(&use_global_proxy);
1441     __ lw(a0, ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX));
1442     __ lw(a0, FieldMemOperand(a0, GlobalObject::kGlobalProxyOffset));
1443
1444     // Push the receiver.
1445     // a0: receiver
1446     __ bind(&push_receiver);
1447     __ push(a0);
1448
1449     // Copy all arguments from the array to the stack.
1450     Label entry, loop;
1451     __ lw(a0, MemOperand(fp, kIndexOffset));
1452     __ Branch(&entry);
1453
1454     // Load the current argument from the arguments array and push it to the
1455     // stack.
1456     // a0: current argument index
1457     __ bind(&loop);
1458     __ lw(a1, MemOperand(fp, kArgsOffset));
1459     __ Push(a1, a0);
1460
1461     // Call the runtime to access the property in the arguments array.
1462     __ CallRuntime(Runtime::kGetProperty, 2);
1463     __ push(v0);
1464
1465     // Use inline caching to access the arguments.
1466     __ lw(a0, MemOperand(fp, kIndexOffset));
1467     __ Addu(a0, a0, Operand(1 << kSmiTagSize));
1468     __ sw(a0, MemOperand(fp, kIndexOffset));
1469
1470     // Test if the copy loop has finished copying all the elements from the
1471     // arguments object.
1472     __ bind(&entry);
1473     __ lw(a1, MemOperand(fp, kLimitOffset));
1474     __ Branch(&loop, ne, a0, Operand(a1));
1475
1476     // Call the function.
1477     Label call_proxy;
1478     ParameterCount actual(a0);
1479     __ sra(a0, a0, kSmiTagSize);
1480     __ lw(a1, MemOperand(fp, kFunctionOffset));
1481     __ GetObjectType(a1, a2, a2);
1482     __ Branch(&call_proxy, ne, a2, Operand(JS_FUNCTION_TYPE));
1483
1484     __ InvokeFunction(a1, actual, CALL_FUNCTION, NullCallWrapper());
1485
1486     frame_scope.GenerateLeaveFrame();
1487     __ Ret(USE_DELAY_SLOT);
1488     __ Addu(sp, sp, Operand(3 * kPointerSize));  // In delay slot.
1489
1490     // Call the function proxy.
1491     __ bind(&call_proxy);
1492     __ push(a1);  // Add function proxy as last argument.
1493     __ Addu(a0, a0, Operand(1));
1494     __ li(a2, Operand(0, RelocInfo::NONE32));
1495     __ GetBuiltinFunction(a1, Builtins::CALL_FUNCTION_PROXY);
1496     __ Call(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
1497             RelocInfo::CODE_TARGET);
1498     // Tear down the internal frame and remove function, receiver and args.
1499   }
1500
1501   __ Ret(USE_DELAY_SLOT);
1502   __ Addu(sp, sp, Operand(3 * kPointerSize));  // In delay slot.
1503 }
1504
1505
1506 static void ArgumentAdaptorStackCheck(MacroAssembler* masm,
1507                                       Label* stack_overflow) {
1508   // ----------- S t a t e -------------
1509   //  -- a0 : actual number of arguments
1510   //  -- a1 : function (passed through to callee)
1511   //  -- a2 : expected number of arguments
1512   // -----------------------------------
1513   // Check the stack for overflow. We are not trying to catch
1514   // interruptions (e.g. debug break and preemption) here, so the "real stack
1515   // limit" is checked.
1516   __ LoadRoot(t1, Heap::kRealStackLimitRootIndex);
1517   // Make t1 the space we have left. The stack might already be overflowed
1518   // here which will cause t1 to become negative.
1519   __ subu(t1, sp, t1);
1520   // Check if the arguments will overflow the stack.
1521   __ sll(at, a2, kPointerSizeLog2);
1522   // Signed comparison.
1523   __ Branch(stack_overflow, le, t1, Operand(at));
1524 }
1525
1526
1527 static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) {
1528   __ sll(a0, a0, kSmiTagSize);
1529   __ li(t0, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1530   __ MultiPush(a0.bit() | a1.bit() | t0.bit() | fp.bit() | ra.bit());
1531   __ Addu(fp, sp,
1532       Operand(StandardFrameConstants::kFixedFrameSizeFromFp + kPointerSize));
1533 }
1534
1535
1536 static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) {
1537   // ----------- S t a t e -------------
1538   //  -- v0 : result being passed through
1539   // -----------------------------------
1540   // Get the number of arguments passed (as a smi), tear down the frame and
1541   // then tear down the parameters.
1542   __ lw(a1, MemOperand(fp, -(StandardFrameConstants::kFixedFrameSizeFromFp +
1543                              kPointerSize)));
1544   __ mov(sp, fp);
1545   __ MultiPop(fp.bit() | ra.bit());
1546   __ sll(t0, a1, kPointerSizeLog2 - kSmiTagSize);
1547   __ Addu(sp, sp, t0);
1548   // Adjust for the receiver.
1549   __ Addu(sp, sp, Operand(kPointerSize));
1550 }
1551
1552
1553 void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) {
1554   // State setup as expected by MacroAssembler::InvokePrologue.
1555   // ----------- S t a t e -------------
1556   //  -- a0: actual arguments count
1557   //  -- a1: function (passed through to callee)
1558   //  -- a2: expected arguments count
1559   // -----------------------------------
1560
1561   Label stack_overflow;
1562   ArgumentAdaptorStackCheck(masm, &stack_overflow);
1563   Label invoke, dont_adapt_arguments;
1564
1565   Label enough, too_few;
1566   __ lw(a3, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
1567   __ Branch(&dont_adapt_arguments, eq,
1568       a2, Operand(SharedFunctionInfo::kDontAdaptArgumentsSentinel));
1569   // We use Uless as the number of argument should always be greater than 0.
1570   __ Branch(&too_few, Uless, a0, Operand(a2));
1571
1572   {  // Enough parameters: actual >= expected.
1573     // a0: actual number of arguments as a smi
1574     // a1: function
1575     // a2: expected number of arguments
1576     // a3: code entry to call
1577     __ bind(&enough);
1578     EnterArgumentsAdaptorFrame(masm);
1579
1580     // Calculate copy start address into a0 and copy end address into a2.
1581     __ sll(a0, a0, kPointerSizeLog2 - kSmiTagSize);
1582     __ Addu(a0, fp, a0);
1583     // Adjust for return address and receiver.
1584     __ Addu(a0, a0, Operand(2 * kPointerSize));
1585     // Compute copy end address.
1586     __ sll(a2, a2, kPointerSizeLog2);
1587     __ subu(a2, a0, a2);
1588
1589     // Copy the arguments (including the receiver) to the new stack frame.
1590     // a0: copy start address
1591     // a1: function
1592     // a2: copy end address
1593     // a3: code entry to call
1594
1595     Label copy;
1596     __ bind(&copy);
1597     __ lw(t0, MemOperand(a0));
1598     __ push(t0);
1599     __ Branch(USE_DELAY_SLOT, &copy, ne, a0, Operand(a2));
1600     __ addiu(a0, a0, -kPointerSize);  // In delay slot.
1601
1602     __ jmp(&invoke);
1603   }
1604
1605   {  // Too few parameters: Actual < expected.
1606     __ bind(&too_few);
1607     EnterArgumentsAdaptorFrame(masm);
1608
1609     // Calculate copy start address into a0 and copy end address is fp.
1610     // a0: actual number of arguments as a smi
1611     // a1: function
1612     // a2: expected number of arguments
1613     // a3: code entry to call
1614     __ sll(a0, a0, kPointerSizeLog2 - kSmiTagSize);
1615     __ Addu(a0, fp, a0);
1616     // Adjust for return address and receiver.
1617     __ Addu(a0, a0, Operand(2 * kPointerSize));
1618     // Compute copy end address. Also adjust for return address.
1619     __ Addu(t3, fp, kPointerSize);
1620
1621     // Copy the arguments (including the receiver) to the new stack frame.
1622     // a0: copy start address
1623     // a1: function
1624     // a2: expected number of arguments
1625     // a3: code entry to call
1626     // t3: copy end address
1627     Label copy;
1628     __ bind(&copy);
1629     __ lw(t0, MemOperand(a0));  // Adjusted above for return addr and receiver.
1630     __ Subu(sp, sp, kPointerSize);
1631     __ Subu(a0, a0, kPointerSize);
1632     __ Branch(USE_DELAY_SLOT, &copy, ne, a0, Operand(t3));
1633     __ sw(t0, MemOperand(sp));  // In the delay slot.
1634
1635     // Fill the remaining expected arguments with undefined.
1636     // a1: function
1637     // a2: expected number of arguments
1638     // a3: code entry to call
1639     __ LoadRoot(t0, Heap::kUndefinedValueRootIndex);
1640     __ sll(t2, a2, kPointerSizeLog2);
1641     __ Subu(a2, fp, Operand(t2));
1642     // Adjust for frame.
1643     __ Subu(a2, a2, Operand(StandardFrameConstants::kFixedFrameSizeFromFp +
1644                             2 * kPointerSize));
1645
1646     Label fill;
1647     __ bind(&fill);
1648     __ Subu(sp, sp, kPointerSize);
1649     __ Branch(USE_DELAY_SLOT, &fill, ne, sp, Operand(a2));
1650     __ sw(t0, MemOperand(sp));
1651   }
1652
1653   // Call the entry point.
1654   __ bind(&invoke);
1655
1656   __ Call(a3);
1657
1658   // Store offset of return address for deoptimizer.
1659   masm->isolate()->heap()->SetArgumentsAdaptorDeoptPCOffset(masm->pc_offset());
1660
1661   // Exit frame and return.
1662   LeaveArgumentsAdaptorFrame(masm);
1663   __ Ret();
1664
1665
1666   // -------------------------------------------
1667   // Don't adapt arguments.
1668   // -------------------------------------------
1669   __ bind(&dont_adapt_arguments);
1670   __ Jump(a3);
1671
1672   __ bind(&stack_overflow);
1673   {
1674     FrameScope frame(masm, StackFrame::MANUAL);
1675     EnterArgumentsAdaptorFrame(masm);
1676     __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
1677     __ break_(0xCC);
1678   }
1679 }
1680
1681
1682 #undef __
1683
1684 } }  // namespace v8::internal
1685
1686 #endif  // V8_TARGET_ARCH_MIPS