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