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