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