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