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