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