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