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