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