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