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