Merge remote-tracking branch ry/v0.10 into master
[platform/upstream/nodejs.git] / deps / v8 / src / ia32 / macro-assembler-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 defined(V8_TARGET_ARCH_IA32)
31
32 #include "bootstrapper.h"
33 #include "codegen.h"
34 #include "debug.h"
35 #include "runtime.h"
36 #include "serialize.h"
37
38 namespace v8 {
39 namespace internal {
40
41 // -------------------------------------------------------------------------
42 // MacroAssembler implementation.
43
44 MacroAssembler::MacroAssembler(Isolate* arg_isolate, void* buffer, int size)
45     : Assembler(arg_isolate, buffer, size),
46       generating_stub_(false),
47       allow_stub_calls_(true),
48       has_frame_(false) {
49   if (isolate() != NULL) {
50     code_object_ = Handle<Object>(isolate()->heap()->undefined_value(),
51                                   isolate());
52   }
53 }
54
55
56 void MacroAssembler::InNewSpace(
57     Register object,
58     Register scratch,
59     Condition cc,
60     Label* condition_met,
61     Label::Distance condition_met_distance) {
62   ASSERT(cc == equal || cc == not_equal);
63   if (scratch.is(object)) {
64     and_(scratch, Immediate(~Page::kPageAlignmentMask));
65   } else {
66     mov(scratch, Immediate(~Page::kPageAlignmentMask));
67     and_(scratch, object);
68   }
69   // Check that we can use a test_b.
70   ASSERT(MemoryChunk::IN_FROM_SPACE < 8);
71   ASSERT(MemoryChunk::IN_TO_SPACE < 8);
72   int mask = (1 << MemoryChunk::IN_FROM_SPACE)
73            | (1 << MemoryChunk::IN_TO_SPACE);
74   // If non-zero, the page belongs to new-space.
75   test_b(Operand(scratch, MemoryChunk::kFlagsOffset),
76          static_cast<uint8_t>(mask));
77   j(cc, condition_met, condition_met_distance);
78 }
79
80
81 void MacroAssembler::RememberedSetHelper(
82     Register object,  // Only used for debug checks.
83     Register addr,
84     Register scratch,
85     SaveFPRegsMode save_fp,
86     MacroAssembler::RememberedSetFinalAction and_then) {
87   Label done;
88   if (emit_debug_code()) {
89     Label ok;
90     JumpIfNotInNewSpace(object, scratch, &ok, Label::kNear);
91     int3();
92     bind(&ok);
93   }
94   // Load store buffer top.
95   ExternalReference store_buffer =
96       ExternalReference::store_buffer_top(isolate());
97   mov(scratch, Operand::StaticVariable(store_buffer));
98   // Store pointer to buffer.
99   mov(Operand(scratch, 0), addr);
100   // Increment buffer top.
101   add(scratch, Immediate(kPointerSize));
102   // Write back new top of buffer.
103   mov(Operand::StaticVariable(store_buffer), scratch);
104   // Call stub on end of buffer.
105   // Check for end of buffer.
106   test(scratch, Immediate(StoreBuffer::kStoreBufferOverflowBit));
107   if (and_then == kReturnAtEnd) {
108     Label buffer_overflowed;
109     j(not_equal, &buffer_overflowed, Label::kNear);
110     ret(0);
111     bind(&buffer_overflowed);
112   } else {
113     ASSERT(and_then == kFallThroughAtEnd);
114     j(equal, &done, Label::kNear);
115   }
116   StoreBufferOverflowStub store_buffer_overflow =
117       StoreBufferOverflowStub(save_fp);
118   CallStub(&store_buffer_overflow);
119   if (and_then == kReturnAtEnd) {
120     ret(0);
121   } else {
122     ASSERT(and_then == kFallThroughAtEnd);
123     bind(&done);
124   }
125 }
126
127
128 void MacroAssembler::ClampDoubleToUint8(XMMRegister input_reg,
129                                         XMMRegister scratch_reg,
130                                         Register result_reg) {
131   Label done;
132   Label conv_failure;
133   pxor(scratch_reg, scratch_reg);
134   cvtsd2si(result_reg, input_reg);
135   test(result_reg, Immediate(0xFFFFFF00));
136   j(zero, &done, Label::kNear);
137   cmp(result_reg, Immediate(0x80000000));
138   j(equal, &conv_failure, Label::kNear);
139   mov(result_reg, Immediate(0));
140   setcc(above, result_reg);
141   sub(result_reg, Immediate(1));
142   and_(result_reg, Immediate(255));
143   jmp(&done, Label::kNear);
144   bind(&conv_failure);
145   Set(result_reg, Immediate(0));
146   ucomisd(input_reg, scratch_reg);
147   j(below, &done, Label::kNear);
148   Set(result_reg, Immediate(255));
149   bind(&done);
150 }
151
152
153 void MacroAssembler::ClampUint8(Register reg) {
154   Label done;
155   test(reg, Immediate(0xFFFFFF00));
156   j(zero, &done, Label::kNear);
157   setcc(negative, reg);  // 1 if negative, 0 if positive.
158   dec_b(reg);  // 0 if negative, 255 if positive.
159   bind(&done);
160 }
161
162
163 static double kUint32Bias =
164     static_cast<double>(static_cast<uint32_t>(0xFFFFFFFF)) + 1;
165
166
167 void MacroAssembler::LoadUint32(XMMRegister dst,
168                                 Register src,
169                                 XMMRegister scratch) {
170   Label done;
171   cmp(src, Immediate(0));
172   movdbl(scratch,
173          Operand(reinterpret_cast<int32_t>(&kUint32Bias), RelocInfo::NONE32));
174   cvtsi2sd(dst, src);
175   j(not_sign, &done, Label::kNear);
176   addsd(dst, scratch);
177   bind(&done);
178 }
179
180
181 void MacroAssembler::RecordWriteArray(Register object,
182                                       Register value,
183                                       Register index,
184                                       SaveFPRegsMode save_fp,
185                                       RememberedSetAction remembered_set_action,
186                                       SmiCheck smi_check) {
187   // First, check if a write barrier is even needed. The tests below
188   // catch stores of Smis.
189   Label done;
190
191   // Skip barrier if writing a smi.
192   if (smi_check == INLINE_SMI_CHECK) {
193     ASSERT_EQ(0, kSmiTag);
194     test(value, Immediate(kSmiTagMask));
195     j(zero, &done);
196   }
197
198   // Array access: calculate the destination address in the same manner as
199   // KeyedStoreIC::GenerateGeneric.  Multiply a smi by 2 to get an offset
200   // into an array of words.
201   Register dst = index;
202   lea(dst, Operand(object, index, times_half_pointer_size,
203                    FixedArray::kHeaderSize - kHeapObjectTag));
204
205   RecordWrite(
206       object, dst, value, save_fp, remembered_set_action, OMIT_SMI_CHECK);
207
208   bind(&done);
209
210   // Clobber clobbered input registers when running with the debug-code flag
211   // turned on to provoke errors.
212   if (emit_debug_code()) {
213     mov(value, Immediate(BitCast<int32_t>(kZapValue)));
214     mov(index, Immediate(BitCast<int32_t>(kZapValue)));
215   }
216 }
217
218
219 void MacroAssembler::RecordWriteField(
220     Register object,
221     int offset,
222     Register value,
223     Register dst,
224     SaveFPRegsMode save_fp,
225     RememberedSetAction remembered_set_action,
226     SmiCheck smi_check) {
227   // First, check if a write barrier is even needed. The tests below
228   // catch stores of Smis.
229   Label done;
230
231   // Skip barrier if writing a smi.
232   if (smi_check == INLINE_SMI_CHECK) {
233     JumpIfSmi(value, &done, Label::kNear);
234   }
235
236   // Although the object register is tagged, the offset is relative to the start
237   // of the object, so so offset must be a multiple of kPointerSize.
238   ASSERT(IsAligned(offset, kPointerSize));
239
240   lea(dst, FieldOperand(object, offset));
241   if (emit_debug_code()) {
242     Label ok;
243     test_b(dst, (1 << kPointerSizeLog2) - 1);
244     j(zero, &ok, Label::kNear);
245     int3();
246     bind(&ok);
247   }
248
249   RecordWrite(
250       object, dst, value, save_fp, remembered_set_action, OMIT_SMI_CHECK);
251
252   bind(&done);
253
254   // Clobber clobbered input registers when running with the debug-code flag
255   // turned on to provoke errors.
256   if (emit_debug_code()) {
257     mov(value, Immediate(BitCast<int32_t>(kZapValue)));
258     mov(dst, Immediate(BitCast<int32_t>(kZapValue)));
259   }
260 }
261
262
263 void MacroAssembler::RecordWriteForMap(
264     Register object,
265     Handle<Map> map,
266     Register scratch1,
267     Register scratch2,
268     SaveFPRegsMode save_fp) {
269   Label done;
270
271   Register address = scratch1;
272   Register value = scratch2;
273   if (emit_debug_code()) {
274     Label ok;
275     lea(address, FieldOperand(object, HeapObject::kMapOffset));
276     test_b(address, (1 << kPointerSizeLog2) - 1);
277     j(zero, &ok, Label::kNear);
278     int3();
279     bind(&ok);
280   }
281
282   ASSERT(!object.is(value));
283   ASSERT(!object.is(address));
284   ASSERT(!value.is(address));
285   AssertNotSmi(object);
286
287   if (!FLAG_incremental_marking) {
288     return;
289   }
290
291   // A single check of the map's pages interesting flag suffices, since it is
292   // only set during incremental collection, and then it's also guaranteed that
293   // the from object's page's interesting flag is also set.  This optimization
294   // relies on the fact that maps can never be in new space.
295   ASSERT(!isolate()->heap()->InNewSpace(*map));
296   CheckPageFlagForMap(map,
297                       MemoryChunk::kPointersToHereAreInterestingMask,
298                       zero,
299                       &done,
300                       Label::kNear);
301
302   // Delay the initialization of |address| and |value| for the stub until it's
303   // known that the will be needed. Up until this point their values are not
304   // needed since they are embedded in the operands of instructions that need
305   // them.
306   lea(address, FieldOperand(object, HeapObject::kMapOffset));
307   mov(value, Immediate(map));
308   RecordWriteStub stub(object, value, address, OMIT_REMEMBERED_SET, save_fp);
309   CallStub(&stub);
310
311   bind(&done);
312
313   // Clobber clobbered input registers when running with the debug-code flag
314   // turned on to provoke errors.
315   if (emit_debug_code()) {
316     mov(value, Immediate(BitCast<int32_t>(kZapValue)));
317     mov(scratch1, Immediate(BitCast<int32_t>(kZapValue)));
318     mov(scratch2, Immediate(BitCast<int32_t>(kZapValue)));
319   }
320 }
321
322
323 void MacroAssembler::RecordWrite(Register object,
324                                  Register address,
325                                  Register value,
326                                  SaveFPRegsMode fp_mode,
327                                  RememberedSetAction remembered_set_action,
328                                  SmiCheck smi_check) {
329   ASSERT(!object.is(value));
330   ASSERT(!object.is(address));
331   ASSERT(!value.is(address));
332   AssertNotSmi(object);
333
334   if (remembered_set_action == OMIT_REMEMBERED_SET &&
335       !FLAG_incremental_marking) {
336     return;
337   }
338
339   if (emit_debug_code()) {
340     Label ok;
341     cmp(value, Operand(address, 0));
342     j(equal, &ok, Label::kNear);
343     int3();
344     bind(&ok);
345   }
346
347   // First, check if a write barrier is even needed. The tests below
348   // catch stores of Smis and stores into young gen.
349   Label done;
350
351   if (smi_check == INLINE_SMI_CHECK) {
352     // Skip barrier if writing a smi.
353     JumpIfSmi(value, &done, Label::kNear);
354   }
355
356   CheckPageFlag(value,
357                 value,  // Used as scratch.
358                 MemoryChunk::kPointersToHereAreInterestingMask,
359                 zero,
360                 &done,
361                 Label::kNear);
362   CheckPageFlag(object,
363                 value,  // Used as scratch.
364                 MemoryChunk::kPointersFromHereAreInterestingMask,
365                 zero,
366                 &done,
367                 Label::kNear);
368
369   RecordWriteStub stub(object, value, address, remembered_set_action, fp_mode);
370   CallStub(&stub);
371
372   bind(&done);
373
374   // Clobber clobbered registers when running with the debug-code flag
375   // turned on to provoke errors.
376   if (emit_debug_code()) {
377     mov(address, Immediate(BitCast<int32_t>(kZapValue)));
378     mov(value, Immediate(BitCast<int32_t>(kZapValue)));
379   }
380 }
381
382
383 #ifdef ENABLE_DEBUGGER_SUPPORT
384 void MacroAssembler::DebugBreak() {
385   Set(eax, Immediate(0));
386   mov(ebx, Immediate(ExternalReference(Runtime::kDebugBreak, isolate())));
387   CEntryStub ces(1);
388   call(ces.GetCode(isolate()), RelocInfo::DEBUG_BREAK);
389 }
390 #endif
391
392
393 void MacroAssembler::Set(Register dst, const Immediate& x) {
394   if (x.is_zero()) {
395     xor_(dst, dst);  // Shorter than mov.
396   } else {
397     mov(dst, x);
398   }
399 }
400
401
402 void MacroAssembler::Set(const Operand& dst, const Immediate& x) {
403   mov(dst, x);
404 }
405
406
407 bool MacroAssembler::IsUnsafeImmediate(const Immediate& x) {
408   static const int kMaxImmediateBits = 17;
409   if (!RelocInfo::IsNone(x.rmode_)) return false;
410   return !is_intn(x.x_, kMaxImmediateBits);
411 }
412
413
414 void MacroAssembler::SafeSet(Register dst, const Immediate& x) {
415   if (IsUnsafeImmediate(x) && jit_cookie() != 0) {
416     Set(dst, Immediate(x.x_ ^ jit_cookie()));
417     xor_(dst, jit_cookie());
418   } else {
419     Set(dst, x);
420   }
421 }
422
423
424 void MacroAssembler::SafePush(const Immediate& x) {
425   if (IsUnsafeImmediate(x) && jit_cookie() != 0) {
426     push(Immediate(x.x_ ^ jit_cookie()));
427     xor_(Operand(esp, 0), Immediate(jit_cookie()));
428   } else {
429     push(x);
430   }
431 }
432
433
434 void MacroAssembler::CompareRoot(Register with, Heap::RootListIndex index) {
435   // see ROOT_ACCESSOR macro in factory.h
436   Handle<Object> value(&isolate()->heap()->roots_array_start()[index]);
437   cmp(with, value);
438 }
439
440
441 void MacroAssembler::CompareRoot(const Operand& with,
442                                  Heap::RootListIndex index) {
443   // see ROOT_ACCESSOR macro in factory.h
444   Handle<Object> value(&isolate()->heap()->roots_array_start()[index]);
445   cmp(with, value);
446 }
447
448
449 void MacroAssembler::CmpObjectType(Register heap_object,
450                                    InstanceType type,
451                                    Register map) {
452   mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
453   CmpInstanceType(map, type);
454 }
455
456
457 void MacroAssembler::CmpInstanceType(Register map, InstanceType type) {
458   cmpb(FieldOperand(map, Map::kInstanceTypeOffset),
459        static_cast<int8_t>(type));
460 }
461
462
463 void MacroAssembler::CheckFastElements(Register map,
464                                        Label* fail,
465                                        Label::Distance distance) {
466   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
467   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
468   STATIC_ASSERT(FAST_ELEMENTS == 2);
469   STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
470   cmpb(FieldOperand(map, Map::kBitField2Offset),
471        Map::kMaximumBitField2FastHoleyElementValue);
472   j(above, fail, distance);
473 }
474
475
476 void MacroAssembler::CheckFastObjectElements(Register map,
477                                              Label* fail,
478                                              Label::Distance distance) {
479   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
480   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
481   STATIC_ASSERT(FAST_ELEMENTS == 2);
482   STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
483   cmpb(FieldOperand(map, Map::kBitField2Offset),
484        Map::kMaximumBitField2FastHoleySmiElementValue);
485   j(below_equal, fail, distance);
486   cmpb(FieldOperand(map, Map::kBitField2Offset),
487        Map::kMaximumBitField2FastHoleyElementValue);
488   j(above, fail, distance);
489 }
490
491
492 void MacroAssembler::CheckFastSmiElements(Register map,
493                                           Label* fail,
494                                           Label::Distance distance) {
495   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
496   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
497   cmpb(FieldOperand(map, Map::kBitField2Offset),
498        Map::kMaximumBitField2FastHoleySmiElementValue);
499   j(above, fail, distance);
500 }
501
502
503 void MacroAssembler::StoreNumberToDoubleElements(
504     Register maybe_number,
505     Register elements,
506     Register key,
507     Register scratch1,
508     XMMRegister scratch2,
509     Label* fail,
510     bool specialize_for_processor,
511     int elements_offset) {
512   Label smi_value, done, maybe_nan, not_nan, is_nan, have_double_value;
513   JumpIfSmi(maybe_number, &smi_value, Label::kNear);
514
515   CheckMap(maybe_number,
516            isolate()->factory()->heap_number_map(),
517            fail,
518            DONT_DO_SMI_CHECK);
519
520   // Double value, canonicalize NaN.
521   uint32_t offset = HeapNumber::kValueOffset + sizeof(kHoleNanLower32);
522   cmp(FieldOperand(maybe_number, offset),
523       Immediate(kNaNOrInfinityLowerBoundUpper32));
524   j(greater_equal, &maybe_nan, Label::kNear);
525
526   bind(&not_nan);
527   ExternalReference canonical_nan_reference =
528       ExternalReference::address_of_canonical_non_hole_nan();
529   if (CpuFeatures::IsSupported(SSE2) && specialize_for_processor) {
530     CpuFeatureScope use_sse2(this, SSE2);
531     movdbl(scratch2, FieldOperand(maybe_number, HeapNumber::kValueOffset));
532     bind(&have_double_value);
533     movdbl(FieldOperand(elements, key, times_4,
534                         FixedDoubleArray::kHeaderSize - elements_offset),
535            scratch2);
536   } else {
537     fld_d(FieldOperand(maybe_number, HeapNumber::kValueOffset));
538     bind(&have_double_value);
539     fstp_d(FieldOperand(elements, key, times_4,
540                         FixedDoubleArray::kHeaderSize - elements_offset));
541   }
542   jmp(&done);
543
544   bind(&maybe_nan);
545   // Could be NaN or Infinity. If fraction is not zero, it's NaN, otherwise
546   // it's an Infinity, and the non-NaN code path applies.
547   j(greater, &is_nan, Label::kNear);
548   cmp(FieldOperand(maybe_number, HeapNumber::kValueOffset), Immediate(0));
549   j(zero, &not_nan);
550   bind(&is_nan);
551   if (CpuFeatures::IsSupported(SSE2) && specialize_for_processor) {
552     CpuFeatureScope use_sse2(this, SSE2);
553     movdbl(scratch2, Operand::StaticVariable(canonical_nan_reference));
554   } else {
555     fld_d(Operand::StaticVariable(canonical_nan_reference));
556   }
557   jmp(&have_double_value, Label::kNear);
558
559   bind(&smi_value);
560   // Value is a smi. Convert to a double and store.
561   // Preserve original value.
562   mov(scratch1, maybe_number);
563   SmiUntag(scratch1);
564   if (CpuFeatures::IsSupported(SSE2) && specialize_for_processor) {
565     CpuFeatureScope fscope(this, SSE2);
566     cvtsi2sd(scratch2, scratch1);
567     movdbl(FieldOperand(elements, key, times_4,
568                         FixedDoubleArray::kHeaderSize - elements_offset),
569            scratch2);
570   } else {
571     push(scratch1);
572     fild_s(Operand(esp, 0));
573     pop(scratch1);
574     fstp_d(FieldOperand(elements, key, times_4,
575                         FixedDoubleArray::kHeaderSize - elements_offset));
576   }
577   bind(&done);
578 }
579
580
581 void MacroAssembler::CompareMap(Register obj,
582                                 Handle<Map> map,
583                                 Label* early_success,
584                                 CompareMapMode mode) {
585   cmp(FieldOperand(obj, HeapObject::kMapOffset), map);
586   if (mode == ALLOW_ELEMENT_TRANSITION_MAPS) {
587     ElementsKind kind = map->elements_kind();
588     if (IsFastElementsKind(kind)) {
589       bool packed = IsFastPackedElementsKind(kind);
590       Map* current_map = *map;
591       while (CanTransitionToMoreGeneralFastElementsKind(kind, packed)) {
592         kind = GetNextMoreGeneralFastElementsKind(kind, packed);
593         current_map = current_map->LookupElementsTransitionMap(kind);
594         if (!current_map) break;
595         j(equal, early_success, Label::kNear);
596         cmp(FieldOperand(obj, HeapObject::kMapOffset),
597             Handle<Map>(current_map));
598       }
599     }
600   }
601 }
602
603
604 void MacroAssembler::CheckMap(Register obj,
605                               Handle<Map> map,
606                               Label* fail,
607                               SmiCheckType smi_check_type,
608                               CompareMapMode mode) {
609   if (smi_check_type == DO_SMI_CHECK) {
610     JumpIfSmi(obj, fail);
611   }
612
613   Label success;
614   CompareMap(obj, map, &success, mode);
615   j(not_equal, fail);
616   bind(&success);
617 }
618
619
620 void MacroAssembler::DispatchMap(Register obj,
621                                  Register unused,
622                                  Handle<Map> map,
623                                  Handle<Code> success,
624                                  SmiCheckType smi_check_type) {
625   Label fail;
626   if (smi_check_type == DO_SMI_CHECK) {
627     JumpIfSmi(obj, &fail);
628   }
629   cmp(FieldOperand(obj, HeapObject::kMapOffset), Immediate(map));
630   j(equal, success);
631
632   bind(&fail);
633 }
634
635
636 Condition MacroAssembler::IsObjectStringType(Register heap_object,
637                                              Register map,
638                                              Register instance_type) {
639   mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
640   movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
641   STATIC_ASSERT(kNotStringTag != 0);
642   test(instance_type, Immediate(kIsNotStringMask));
643   return zero;
644 }
645
646
647 Condition MacroAssembler::IsObjectNameType(Register heap_object,
648                                            Register map,
649                                            Register instance_type) {
650   mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
651   movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
652   cmpb(instance_type, static_cast<uint8_t>(LAST_NAME_TYPE));
653   return below_equal;
654 }
655
656
657 void MacroAssembler::IsObjectJSObjectType(Register heap_object,
658                                           Register map,
659                                           Register scratch,
660                                           Label* fail) {
661   mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
662   IsInstanceJSObjectType(map, scratch, fail);
663 }
664
665
666 void MacroAssembler::IsInstanceJSObjectType(Register map,
667                                             Register scratch,
668                                             Label* fail) {
669   movzx_b(scratch, FieldOperand(map, Map::kInstanceTypeOffset));
670   sub(scratch, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
671   cmp(scratch,
672       LAST_NONCALLABLE_SPEC_OBJECT_TYPE - FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
673   j(above, fail);
674 }
675
676
677 void MacroAssembler::FCmp() {
678   if (CpuFeatures::IsSupported(CMOV)) {
679     fucomip();
680     fstp(0);
681   } else {
682     fucompp();
683     push(eax);
684     fnstsw_ax();
685     sahf();
686     pop(eax);
687   }
688 }
689
690
691 void MacroAssembler::AssertNumber(Register object) {
692   if (emit_debug_code()) {
693     Label ok;
694     JumpIfSmi(object, &ok);
695     cmp(FieldOperand(object, HeapObject::kMapOffset),
696         isolate()->factory()->heap_number_map());
697     Check(equal, "Operand not a number");
698     bind(&ok);
699   }
700 }
701
702
703 void MacroAssembler::AssertSmi(Register object) {
704   if (emit_debug_code()) {
705     test(object, Immediate(kSmiTagMask));
706     Check(equal, "Operand is not a smi");
707   }
708 }
709
710
711 void MacroAssembler::AssertString(Register object) {
712   if (emit_debug_code()) {
713     test(object, Immediate(kSmiTagMask));
714     Check(not_equal, "Operand is a smi and not a string");
715     push(object);
716     mov(object, FieldOperand(object, HeapObject::kMapOffset));
717     CmpInstanceType(object, FIRST_NONSTRING_TYPE);
718     pop(object);
719     Check(below, "Operand is not a string");
720   }
721 }
722
723
724 void MacroAssembler::AssertName(Register object) {
725   if (emit_debug_code()) {
726     test(object, Immediate(kSmiTagMask));
727     Check(not_equal, "Operand is a smi and not a name");
728     push(object);
729     mov(object, FieldOperand(object, HeapObject::kMapOffset));
730     CmpInstanceType(object, LAST_NAME_TYPE);
731     pop(object);
732     Check(below_equal, "Operand is not a name");
733   }
734 }
735
736
737 void MacroAssembler::AssertNotSmi(Register object) {
738   if (emit_debug_code()) {
739     test(object, Immediate(kSmiTagMask));
740     Check(not_equal, "Operand is a smi");
741   }
742 }
743
744
745 void MacroAssembler::EnterFrame(StackFrame::Type type) {
746   push(ebp);
747   mov(ebp, esp);
748   push(esi);
749   push(Immediate(Smi::FromInt(type)));
750   push(Immediate(CodeObject()));
751   if (emit_debug_code()) {
752     cmp(Operand(esp, 0), Immediate(isolate()->factory()->undefined_value()));
753     Check(not_equal, "code object not properly patched");
754   }
755 }
756
757
758 void MacroAssembler::LeaveFrame(StackFrame::Type type) {
759   if (emit_debug_code()) {
760     cmp(Operand(ebp, StandardFrameConstants::kMarkerOffset),
761         Immediate(Smi::FromInt(type)));
762     Check(equal, "stack frame types must match");
763   }
764   leave();
765 }
766
767
768 void MacroAssembler::EnterExitFramePrologue() {
769   // Set up the frame structure on the stack.
770   ASSERT(ExitFrameConstants::kCallerSPDisplacement == +2 * kPointerSize);
771   ASSERT(ExitFrameConstants::kCallerPCOffset == +1 * kPointerSize);
772   ASSERT(ExitFrameConstants::kCallerFPOffset ==  0 * kPointerSize);
773   push(ebp);
774   mov(ebp, esp);
775
776   // Reserve room for entry stack pointer and push the code object.
777   ASSERT(ExitFrameConstants::kSPOffset  == -1 * kPointerSize);
778   push(Immediate(0));  // Saved entry sp, patched before call.
779   push(Immediate(CodeObject()));  // Accessed from ExitFrame::code_slot.
780
781   // Save the frame pointer and the context in top.
782   ExternalReference c_entry_fp_address(Isolate::kCEntryFPAddress,
783                                        isolate());
784   ExternalReference context_address(Isolate::kContextAddress,
785                                     isolate());
786   mov(Operand::StaticVariable(c_entry_fp_address), ebp);
787   mov(Operand::StaticVariable(context_address), esi);
788 }
789
790
791 void MacroAssembler::EnterExitFrameEpilogue(int argc, bool save_doubles) {
792   // Optionally save all XMM registers.
793   if (save_doubles) {
794     CpuFeatureScope scope(this, SSE2);
795     int space = XMMRegister::kNumRegisters * kDoubleSize + argc * kPointerSize;
796     sub(esp, Immediate(space));
797     const int offset = -2 * kPointerSize;
798     for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
799       XMMRegister reg = XMMRegister::from_code(i);
800       movdbl(Operand(ebp, offset - ((i + 1) * kDoubleSize)), reg);
801     }
802   } else {
803     sub(esp, Immediate(argc * kPointerSize));
804   }
805
806   // Get the required frame alignment for the OS.
807   const int kFrameAlignment = OS::ActivationFrameAlignment();
808   if (kFrameAlignment > 0) {
809     ASSERT(IsPowerOf2(kFrameAlignment));
810     and_(esp, -kFrameAlignment);
811   }
812
813   // Patch the saved entry sp.
814   mov(Operand(ebp, ExitFrameConstants::kSPOffset), esp);
815 }
816
817
818 void MacroAssembler::EnterExitFrame(bool save_doubles) {
819   EnterExitFramePrologue();
820
821   // Set up argc and argv in callee-saved registers.
822   int offset = StandardFrameConstants::kCallerSPOffset - kPointerSize;
823   mov(edi, eax);
824   lea(esi, Operand(ebp, eax, times_4, offset));
825
826   // Reserve space for argc, argv and isolate.
827   EnterExitFrameEpilogue(3, save_doubles);
828 }
829
830
831 void MacroAssembler::EnterApiExitFrame(int argc) {
832   EnterExitFramePrologue();
833   EnterExitFrameEpilogue(argc, false);
834 }
835
836
837 void MacroAssembler::LeaveExitFrame(bool save_doubles) {
838   // Optionally restore all XMM registers.
839   if (save_doubles) {
840     CpuFeatureScope scope(this, SSE2);
841     const int offset = -2 * kPointerSize;
842     for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
843       XMMRegister reg = XMMRegister::from_code(i);
844       movdbl(reg, Operand(ebp, offset - ((i + 1) * kDoubleSize)));
845     }
846   }
847
848   // Get the return address from the stack and restore the frame pointer.
849   mov(ecx, Operand(ebp, 1 * kPointerSize));
850   mov(ebp, Operand(ebp, 0 * kPointerSize));
851
852   // Pop the arguments and the receiver from the caller stack.
853   lea(esp, Operand(esi, 1 * kPointerSize));
854
855   // Push the return address to get ready to return.
856   push(ecx);
857
858   LeaveExitFrameEpilogue();
859 }
860
861 void MacroAssembler::LeaveExitFrameEpilogue() {
862   // Restore current context from top and clear it in debug mode.
863   ExternalReference context_address(Isolate::kContextAddress, isolate());
864   mov(esi, Operand::StaticVariable(context_address));
865 #ifdef DEBUG
866   mov(Operand::StaticVariable(context_address), Immediate(0));
867 #endif
868
869   // Clear the top frame.
870   ExternalReference c_entry_fp_address(Isolate::kCEntryFPAddress,
871                                        isolate());
872   mov(Operand::StaticVariable(c_entry_fp_address), Immediate(0));
873 }
874
875
876 void MacroAssembler::LeaveApiExitFrame() {
877   mov(esp, ebp);
878   pop(ebp);
879
880   LeaveExitFrameEpilogue();
881 }
882
883
884 void MacroAssembler::PushTryHandler(StackHandler::Kind kind,
885                                     int handler_index) {
886   // Adjust this code if not the case.
887   STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
888   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
889   STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
890   STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
891   STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
892   STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
893
894   // We will build up the handler from the bottom by pushing on the stack.
895   // First push the frame pointer and context.
896   if (kind == StackHandler::JS_ENTRY) {
897     // The frame pointer does not point to a JS frame so we save NULL for
898     // ebp. We expect the code throwing an exception to check ebp before
899     // dereferencing it to restore the context.
900     push(Immediate(0));  // NULL frame pointer.
901     push(Immediate(Smi::FromInt(0)));  // No context.
902   } else {
903     push(ebp);
904     push(esi);
905   }
906   // Push the state and the code object.
907   unsigned state =
908       StackHandler::IndexField::encode(handler_index) |
909       StackHandler::KindField::encode(kind);
910   push(Immediate(state));
911   Push(CodeObject());
912
913   // Link the current handler as the next handler.
914   ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
915   push(Operand::StaticVariable(handler_address));
916   // Set this new handler as the current one.
917   mov(Operand::StaticVariable(handler_address), esp);
918 }
919
920
921 void MacroAssembler::PopTryHandler() {
922   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
923   ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
924   pop(Operand::StaticVariable(handler_address));
925   add(esp, Immediate(StackHandlerConstants::kSize - kPointerSize));
926 }
927
928
929 void MacroAssembler::JumpToHandlerEntry() {
930   // Compute the handler entry address and jump to it.  The handler table is
931   // a fixed array of (smi-tagged) code offsets.
932   // eax = exception, edi = code object, edx = state.
933   mov(ebx, FieldOperand(edi, Code::kHandlerTableOffset));
934   shr(edx, StackHandler::kKindWidth);
935   mov(edx, FieldOperand(ebx, edx, times_4, FixedArray::kHeaderSize));
936   SmiUntag(edx);
937   lea(edi, FieldOperand(edi, edx, times_1, Code::kHeaderSize));
938   jmp(edi);
939 }
940
941
942 void MacroAssembler::Throw(Register value) {
943   // Adjust this code if not the case.
944   STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
945   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
946   STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
947   STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
948   STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
949   STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
950
951   // The exception is expected in eax.
952   if (!value.is(eax)) {
953     mov(eax, value);
954   }
955   // Drop the stack pointer to the top of the top handler.
956   ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
957   mov(esp, Operand::StaticVariable(handler_address));
958   // Restore the next handler.
959   pop(Operand::StaticVariable(handler_address));
960
961   // Remove the code object and state, compute the handler address in edi.
962   pop(edi);  // Code object.
963   pop(edx);  // Index and state.
964
965   // Restore the context and frame pointer.
966   pop(esi);  // Context.
967   pop(ebp);  // Frame pointer.
968
969   // If the handler is a JS frame, restore the context to the frame.
970   // (kind == ENTRY) == (ebp == 0) == (esi == 0), so we could test either
971   // ebp or esi.
972   Label skip;
973   test(esi, esi);
974   j(zero, &skip, Label::kNear);
975   mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
976   bind(&skip);
977
978   JumpToHandlerEntry();
979 }
980
981
982 void MacroAssembler::ThrowUncatchable(Register value) {
983   // Adjust this code if not the case.
984   STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
985   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
986   STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
987   STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
988   STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
989   STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
990
991   // The exception is expected in eax.
992   if (!value.is(eax)) {
993     mov(eax, value);
994   }
995   // Drop the stack pointer to the top of the top stack handler.
996   ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
997   mov(esp, Operand::StaticVariable(handler_address));
998
999   // Unwind the handlers until the top ENTRY handler is found.
1000   Label fetch_next, check_kind;
1001   jmp(&check_kind, Label::kNear);
1002   bind(&fetch_next);
1003   mov(esp, Operand(esp, StackHandlerConstants::kNextOffset));
1004
1005   bind(&check_kind);
1006   STATIC_ASSERT(StackHandler::JS_ENTRY == 0);
1007   test(Operand(esp, StackHandlerConstants::kStateOffset),
1008        Immediate(StackHandler::KindField::kMask));
1009   j(not_zero, &fetch_next);
1010
1011   // Set the top handler address to next handler past the top ENTRY handler.
1012   pop(Operand::StaticVariable(handler_address));
1013
1014   // Remove the code object and state, compute the handler address in edi.
1015   pop(edi);  // Code object.
1016   pop(edx);  // Index and state.
1017
1018   // Clear the context pointer and frame pointer (0 was saved in the handler).
1019   pop(esi);
1020   pop(ebp);
1021
1022   JumpToHandlerEntry();
1023 }
1024
1025
1026 void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
1027                                             Register scratch1,
1028                                             Register scratch2,
1029                                             Label* miss) {
1030   Label same_contexts;
1031
1032   ASSERT(!holder_reg.is(scratch1));
1033   ASSERT(!holder_reg.is(scratch2));
1034   ASSERT(!scratch1.is(scratch2));
1035
1036   // Load current lexical context from the stack frame.
1037   mov(scratch1, Operand(ebp, StandardFrameConstants::kContextOffset));
1038
1039   // When generating debug code, make sure the lexical context is set.
1040   if (emit_debug_code()) {
1041     cmp(scratch1, Immediate(0));
1042     Check(not_equal, "we should not have an empty lexical context");
1043   }
1044   // Load the native context of the current context.
1045   int offset =
1046       Context::kHeaderSize + Context::GLOBAL_OBJECT_INDEX * kPointerSize;
1047   mov(scratch1, FieldOperand(scratch1, offset));
1048   mov(scratch1, FieldOperand(scratch1, GlobalObject::kNativeContextOffset));
1049
1050   // Check the context is a native context.
1051   if (emit_debug_code()) {
1052     // Read the first word and compare to native_context_map.
1053     cmp(FieldOperand(scratch1, HeapObject::kMapOffset),
1054         isolate()->factory()->native_context_map());
1055     Check(equal, "JSGlobalObject::native_context should be a native context.");
1056   }
1057
1058   // Check if both contexts are the same.
1059   cmp(scratch1, FieldOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
1060   j(equal, &same_contexts);
1061
1062   // Compare security tokens, save holder_reg on the stack so we can use it
1063   // as a temporary register.
1064   //
1065   // Check that the security token in the calling global object is
1066   // compatible with the security token in the receiving global
1067   // object.
1068   mov(scratch2,
1069       FieldOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
1070
1071   // Check the context is a native context.
1072   if (emit_debug_code()) {
1073     cmp(scratch2, isolate()->factory()->null_value());
1074     Check(not_equal, "JSGlobalProxy::context() should not be null.");
1075
1076     // Read the first word and compare to native_context_map(),
1077     cmp(FieldOperand(scratch2, HeapObject::kMapOffset),
1078         isolate()->factory()->native_context_map());
1079     Check(equal, "JSGlobalObject::native_context should be a native context.");
1080   }
1081
1082   int token_offset = Context::kHeaderSize +
1083                      Context::SECURITY_TOKEN_INDEX * kPointerSize;
1084   mov(scratch1, FieldOperand(scratch1, token_offset));
1085   cmp(scratch1, FieldOperand(scratch2, token_offset));
1086   j(not_equal, miss);
1087
1088   bind(&same_contexts);
1089 }
1090
1091
1092 // Compute the hash code from the untagged key.  This must be kept in sync
1093 // with ComputeIntegerHash in utils.h.
1094 //
1095 // Note: r0 will contain hash code
1096 void MacroAssembler::GetNumberHash(Register r0, Register scratch) {
1097   // Xor original key with a seed.
1098   if (Serializer::enabled()) {
1099     ExternalReference roots_array_start =
1100         ExternalReference::roots_array_start(isolate());
1101     mov(scratch, Immediate(Heap::kHashSeedRootIndex));
1102     mov(scratch,
1103         Operand::StaticArray(scratch, times_pointer_size, roots_array_start));
1104     SmiUntag(scratch);
1105     xor_(r0, scratch);
1106   } else {
1107     int32_t seed = isolate()->heap()->HashSeed();
1108     xor_(r0, Immediate(seed));
1109   }
1110
1111   // hash = ~hash + (hash << 15);
1112   mov(scratch, r0);
1113   not_(r0);
1114   shl(scratch, 15);
1115   add(r0, scratch);
1116   // hash = hash ^ (hash >> 12);
1117   mov(scratch, r0);
1118   shr(scratch, 12);
1119   xor_(r0, scratch);
1120   // hash = hash + (hash << 2);
1121   lea(r0, Operand(r0, r0, times_4, 0));
1122   // hash = hash ^ (hash >> 4);
1123   mov(scratch, r0);
1124   shr(scratch, 4);
1125   xor_(r0, scratch);
1126   // hash = hash * 2057;
1127   imul(r0, r0, 2057);
1128   // hash = hash ^ (hash >> 16);
1129   mov(scratch, r0);
1130   shr(scratch, 16);
1131   xor_(r0, scratch);
1132 }
1133
1134
1135
1136 void MacroAssembler::LoadFromNumberDictionary(Label* miss,
1137                                               Register elements,
1138                                               Register key,
1139                                               Register r0,
1140                                               Register r1,
1141                                               Register r2,
1142                                               Register result) {
1143   // Register use:
1144   //
1145   // elements - holds the slow-case elements of the receiver and is unchanged.
1146   //
1147   // key      - holds the smi key on entry and is unchanged.
1148   //
1149   // Scratch registers:
1150   //
1151   // r0 - holds the untagged key on entry and holds the hash once computed.
1152   //
1153   // r1 - used to hold the capacity mask of the dictionary
1154   //
1155   // r2 - used for the index into the dictionary.
1156   //
1157   // result - holds the result on exit if the load succeeds and we fall through.
1158
1159   Label done;
1160
1161   GetNumberHash(r0, r1);
1162
1163   // Compute capacity mask.
1164   mov(r1, FieldOperand(elements, SeededNumberDictionary::kCapacityOffset));
1165   shr(r1, kSmiTagSize);  // convert smi to int
1166   dec(r1);
1167
1168   // Generate an unrolled loop that performs a few probes before giving up.
1169   const int kProbes = 4;
1170   for (int i = 0; i < kProbes; i++) {
1171     // Use r2 for index calculations and keep the hash intact in r0.
1172     mov(r2, r0);
1173     // Compute the masked index: (hash + i + i * i) & mask.
1174     if (i > 0) {
1175       add(r2, Immediate(SeededNumberDictionary::GetProbeOffset(i)));
1176     }
1177     and_(r2, r1);
1178
1179     // Scale the index by multiplying by the entry size.
1180     ASSERT(SeededNumberDictionary::kEntrySize == 3);
1181     lea(r2, Operand(r2, r2, times_2, 0));  // r2 = r2 * 3
1182
1183     // Check if the key matches.
1184     cmp(key, FieldOperand(elements,
1185                           r2,
1186                           times_pointer_size,
1187                           SeededNumberDictionary::kElementsStartOffset));
1188     if (i != (kProbes - 1)) {
1189       j(equal, &done);
1190     } else {
1191       j(not_equal, miss);
1192     }
1193   }
1194
1195   bind(&done);
1196   // Check that the value is a normal propety.
1197   const int kDetailsOffset =
1198       SeededNumberDictionary::kElementsStartOffset + 2 * kPointerSize;
1199   ASSERT_EQ(NORMAL, 0);
1200   test(FieldOperand(elements, r2, times_pointer_size, kDetailsOffset),
1201        Immediate(PropertyDetails::TypeField::kMask << kSmiTagSize));
1202   j(not_zero, miss);
1203
1204   // Get the value at the masked, scaled index.
1205   const int kValueOffset =
1206       SeededNumberDictionary::kElementsStartOffset + kPointerSize;
1207   mov(result, FieldOperand(elements, r2, times_pointer_size, kValueOffset));
1208 }
1209
1210
1211 void MacroAssembler::LoadAllocationTopHelper(Register result,
1212                                              Register scratch,
1213                                              AllocationFlags flags) {
1214   ExternalReference allocation_top =
1215       AllocationUtils::GetAllocationTopReference(isolate(), flags);
1216
1217   // Just return if allocation top is already known.
1218   if ((flags & RESULT_CONTAINS_TOP) != 0) {
1219     // No use of scratch if allocation top is provided.
1220     ASSERT(scratch.is(no_reg));
1221 #ifdef DEBUG
1222     // Assert that result actually contains top on entry.
1223     cmp(result, Operand::StaticVariable(allocation_top));
1224     Check(equal, "Unexpected allocation top");
1225 #endif
1226     return;
1227   }
1228
1229   // Move address of new object to result. Use scratch register if available.
1230   if (scratch.is(no_reg)) {
1231     mov(result, Operand::StaticVariable(allocation_top));
1232   } else {
1233     mov(scratch, Immediate(allocation_top));
1234     mov(result, Operand(scratch, 0));
1235   }
1236 }
1237
1238
1239 void MacroAssembler::UpdateAllocationTopHelper(Register result_end,
1240                                                Register scratch,
1241                                                AllocationFlags flags) {
1242   if (emit_debug_code()) {
1243     test(result_end, Immediate(kObjectAlignmentMask));
1244     Check(zero, "Unaligned allocation in new space");
1245   }
1246
1247   ExternalReference allocation_top =
1248       AllocationUtils::GetAllocationTopReference(isolate(), flags);
1249
1250   // Update new top. Use scratch if available.
1251   if (scratch.is(no_reg)) {
1252     mov(Operand::StaticVariable(allocation_top), result_end);
1253   } else {
1254     mov(Operand(scratch, 0), result_end);
1255   }
1256 }
1257
1258
1259 void MacroAssembler::Allocate(int object_size,
1260                               Register result,
1261                               Register result_end,
1262                               Register scratch,
1263                               Label* gc_required,
1264                               AllocationFlags flags) {
1265   ASSERT((flags & (RESULT_CONTAINS_TOP | SIZE_IN_WORDS)) == 0);
1266   if (!FLAG_inline_new) {
1267     if (emit_debug_code()) {
1268       // Trash the registers to simulate an allocation failure.
1269       mov(result, Immediate(0x7091));
1270       if (result_end.is_valid()) {
1271         mov(result_end, Immediate(0x7191));
1272       }
1273       if (scratch.is_valid()) {
1274         mov(scratch, Immediate(0x7291));
1275       }
1276     }
1277     jmp(gc_required);
1278     return;
1279   }
1280   ASSERT(!result.is(result_end));
1281
1282   // Load address of new object into result.
1283   LoadAllocationTopHelper(result, scratch, flags);
1284
1285   // Align the next allocation. Storing the filler map without checking top is
1286   // always safe because the limit of the heap is always aligned.
1287   if ((flags & DOUBLE_ALIGNMENT) != 0) {
1288     ASSERT((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
1289     ASSERT(kPointerAlignment * 2 == kDoubleAlignment);
1290     Label aligned;
1291     test(result, Immediate(kDoubleAlignmentMask));
1292     j(zero, &aligned, Label::kNear);
1293     mov(Operand(result, 0),
1294         Immediate(isolate()->factory()->one_pointer_filler_map()));
1295     add(result, Immediate(kDoubleSize / 2));
1296     bind(&aligned);
1297   }
1298
1299   Register top_reg = result_end.is_valid() ? result_end : result;
1300
1301   // Calculate new top and bail out if space is exhausted.
1302   ExternalReference allocation_limit =
1303       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
1304
1305   if (!top_reg.is(result)) {
1306     mov(top_reg, result);
1307   }
1308   add(top_reg, Immediate(object_size));
1309   j(carry, gc_required);
1310   cmp(top_reg, Operand::StaticVariable(allocation_limit));
1311   j(above, gc_required);
1312
1313   // Update allocation top.
1314   UpdateAllocationTopHelper(top_reg, scratch, flags);
1315
1316   // Tag result if requested.
1317   bool tag_result = (flags & TAG_OBJECT) != 0;
1318   if (top_reg.is(result)) {
1319     if (tag_result) {
1320       sub(result, Immediate(object_size - kHeapObjectTag));
1321     } else {
1322       sub(result, Immediate(object_size));
1323     }
1324   } else if (tag_result) {
1325     ASSERT(kHeapObjectTag == 1);
1326     inc(result);
1327   }
1328 }
1329
1330
1331 void MacroAssembler::Allocate(int header_size,
1332                               ScaleFactor element_size,
1333                               Register element_count,
1334                               RegisterValueType element_count_type,
1335                               Register result,
1336                               Register result_end,
1337                               Register scratch,
1338                               Label* gc_required,
1339                               AllocationFlags flags) {
1340   ASSERT((flags & SIZE_IN_WORDS) == 0);
1341   if (!FLAG_inline_new) {
1342     if (emit_debug_code()) {
1343       // Trash the registers to simulate an allocation failure.
1344       mov(result, Immediate(0x7091));
1345       mov(result_end, Immediate(0x7191));
1346       if (scratch.is_valid()) {
1347         mov(scratch, Immediate(0x7291));
1348       }
1349       // Register element_count is not modified by the function.
1350     }
1351     jmp(gc_required);
1352     return;
1353   }
1354   ASSERT(!result.is(result_end));
1355
1356   // Load address of new object into result.
1357   LoadAllocationTopHelper(result, scratch, flags);
1358
1359   // Align the next allocation. Storing the filler map without checking top is
1360   // always safe because the limit of the heap is always aligned.
1361   if ((flags & DOUBLE_ALIGNMENT) != 0) {
1362     ASSERT((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
1363     ASSERT(kPointerAlignment * 2 == kDoubleAlignment);
1364     Label aligned;
1365     test(result, Immediate(kDoubleAlignmentMask));
1366     j(zero, &aligned, Label::kNear);
1367     mov(Operand(result, 0),
1368         Immediate(isolate()->factory()->one_pointer_filler_map()));
1369     add(result, Immediate(kDoubleSize / 2));
1370     bind(&aligned);
1371   }
1372
1373   // Calculate new top and bail out if space is exhausted.
1374   ExternalReference allocation_limit =
1375       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
1376
1377   // We assume that element_count*element_size + header_size does not
1378   // overflow.
1379   if (element_count_type == REGISTER_VALUE_IS_SMI) {
1380     STATIC_ASSERT(static_cast<ScaleFactor>(times_2 - 1) == times_1);
1381     STATIC_ASSERT(static_cast<ScaleFactor>(times_4 - 1) == times_2);
1382     STATIC_ASSERT(static_cast<ScaleFactor>(times_8 - 1) == times_4);
1383     ASSERT(element_size >= times_2);
1384     ASSERT(kSmiTagSize == 1);
1385     element_size = static_cast<ScaleFactor>(element_size - 1);
1386   } else {
1387     ASSERT(element_count_type == REGISTER_VALUE_IS_INT32);
1388   }
1389   lea(result_end, Operand(element_count, element_size, header_size));
1390   add(result_end, result);
1391   j(carry, gc_required);
1392   cmp(result_end, Operand::StaticVariable(allocation_limit));
1393   j(above, gc_required);
1394
1395   if ((flags & TAG_OBJECT) != 0) {
1396     ASSERT(kHeapObjectTag == 1);
1397     inc(result);
1398   }
1399
1400   // Update allocation top.
1401   UpdateAllocationTopHelper(result_end, scratch, flags);
1402 }
1403
1404
1405 void MacroAssembler::Allocate(Register object_size,
1406                               Register result,
1407                               Register result_end,
1408                               Register scratch,
1409                               Label* gc_required,
1410                               AllocationFlags flags) {
1411   ASSERT((flags & (RESULT_CONTAINS_TOP | SIZE_IN_WORDS)) == 0);
1412   if (!FLAG_inline_new) {
1413     if (emit_debug_code()) {
1414       // Trash the registers to simulate an allocation failure.
1415       mov(result, Immediate(0x7091));
1416       mov(result_end, Immediate(0x7191));
1417       if (scratch.is_valid()) {
1418         mov(scratch, Immediate(0x7291));
1419       }
1420       // object_size is left unchanged by this function.
1421     }
1422     jmp(gc_required);
1423     return;
1424   }
1425   ASSERT(!result.is(result_end));
1426
1427   // Load address of new object into result.
1428   LoadAllocationTopHelper(result, scratch, flags);
1429
1430   // Align the next allocation. Storing the filler map without checking top is
1431   // always safe because the limit of the heap is always aligned.
1432   if ((flags & DOUBLE_ALIGNMENT) != 0) {
1433     ASSERT((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
1434     ASSERT(kPointerAlignment * 2 == kDoubleAlignment);
1435     Label aligned;
1436     test(result, Immediate(kDoubleAlignmentMask));
1437     j(zero, &aligned, Label::kNear);
1438     mov(Operand(result, 0),
1439         Immediate(isolate()->factory()->one_pointer_filler_map()));
1440     add(result, Immediate(kDoubleSize / 2));
1441     bind(&aligned);
1442   }
1443
1444   // Calculate new top and bail out if space is exhausted.
1445   ExternalReference allocation_limit =
1446       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
1447
1448   if (!object_size.is(result_end)) {
1449     mov(result_end, object_size);
1450   }
1451   add(result_end, result);
1452   j(carry, gc_required);
1453   cmp(result_end, Operand::StaticVariable(allocation_limit));
1454   j(above, gc_required);
1455
1456   // Tag result if requested.
1457   if ((flags & TAG_OBJECT) != 0) {
1458     ASSERT(kHeapObjectTag == 1);
1459     inc(result);
1460   }
1461
1462   // Update allocation top.
1463   UpdateAllocationTopHelper(result_end, scratch, flags);
1464 }
1465
1466
1467 void MacroAssembler::UndoAllocationInNewSpace(Register object) {
1468   ExternalReference new_space_allocation_top =
1469       ExternalReference::new_space_allocation_top_address(isolate());
1470
1471   // Make sure the object has no tag before resetting top.
1472   and_(object, Immediate(~kHeapObjectTagMask));
1473 #ifdef DEBUG
1474   cmp(object, Operand::StaticVariable(new_space_allocation_top));
1475   Check(below, "Undo allocation of non allocated memory");
1476 #endif
1477   mov(Operand::StaticVariable(new_space_allocation_top), object);
1478 }
1479
1480
1481 void MacroAssembler::AllocateHeapNumber(Register result,
1482                                         Register scratch1,
1483                                         Register scratch2,
1484                                         Label* gc_required) {
1485   // Allocate heap number in new space.
1486   Allocate(HeapNumber::kSize, result, scratch1, scratch2, gc_required,
1487            TAG_OBJECT);
1488
1489   // Set the map.
1490   mov(FieldOperand(result, HeapObject::kMapOffset),
1491       Immediate(isolate()->factory()->heap_number_map()));
1492 }
1493
1494
1495 void MacroAssembler::AllocateTwoByteString(Register result,
1496                                            Register length,
1497                                            Register scratch1,
1498                                            Register scratch2,
1499                                            Register scratch3,
1500                                            Label* gc_required) {
1501   // Calculate the number of bytes needed for the characters in the string while
1502   // observing object alignment.
1503   ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
1504   ASSERT(kShortSize == 2);
1505   // scratch1 = length * 2 + kObjectAlignmentMask.
1506   lea(scratch1, Operand(length, length, times_1, kObjectAlignmentMask));
1507   and_(scratch1, Immediate(~kObjectAlignmentMask));
1508
1509   // Allocate two byte string in new space.
1510   Allocate(SeqTwoByteString::kHeaderSize,
1511            times_1,
1512            scratch1,
1513            REGISTER_VALUE_IS_INT32,
1514            result,
1515            scratch2,
1516            scratch3,
1517            gc_required,
1518            TAG_OBJECT);
1519
1520   // Set the map, length and hash field.
1521   mov(FieldOperand(result, HeapObject::kMapOffset),
1522       Immediate(isolate()->factory()->string_map()));
1523   mov(scratch1, length);
1524   SmiTag(scratch1);
1525   mov(FieldOperand(result, String::kLengthOffset), scratch1);
1526   mov(FieldOperand(result, String::kHashFieldOffset),
1527       Immediate(String::kEmptyHashField));
1528 }
1529
1530
1531 void MacroAssembler::AllocateAsciiString(Register result,
1532                                          Register length,
1533                                          Register scratch1,
1534                                          Register scratch2,
1535                                          Register scratch3,
1536                                          Label* gc_required) {
1537   // Calculate the number of bytes needed for the characters in the string while
1538   // observing object alignment.
1539   ASSERT((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
1540   mov(scratch1, length);
1541   ASSERT(kCharSize == 1);
1542   add(scratch1, Immediate(kObjectAlignmentMask));
1543   and_(scratch1, Immediate(~kObjectAlignmentMask));
1544
1545   // Allocate ASCII string in new space.
1546   Allocate(SeqOneByteString::kHeaderSize,
1547            times_1,
1548            scratch1,
1549            REGISTER_VALUE_IS_INT32,
1550            result,
1551            scratch2,
1552            scratch3,
1553            gc_required,
1554            TAG_OBJECT);
1555
1556   // Set the map, length and hash field.
1557   mov(FieldOperand(result, HeapObject::kMapOffset),
1558       Immediate(isolate()->factory()->ascii_string_map()));
1559   mov(scratch1, length);
1560   SmiTag(scratch1);
1561   mov(FieldOperand(result, String::kLengthOffset), scratch1);
1562   mov(FieldOperand(result, String::kHashFieldOffset),
1563       Immediate(String::kEmptyHashField));
1564 }
1565
1566
1567 void MacroAssembler::AllocateAsciiString(Register result,
1568                                          int length,
1569                                          Register scratch1,
1570                                          Register scratch2,
1571                                          Label* gc_required) {
1572   ASSERT(length > 0);
1573
1574   // Allocate ASCII string in new space.
1575   Allocate(SeqOneByteString::SizeFor(length), result, scratch1, scratch2,
1576            gc_required, TAG_OBJECT);
1577
1578   // Set the map, length and hash field.
1579   mov(FieldOperand(result, HeapObject::kMapOffset),
1580       Immediate(isolate()->factory()->ascii_string_map()));
1581   mov(FieldOperand(result, String::kLengthOffset),
1582       Immediate(Smi::FromInt(length)));
1583   mov(FieldOperand(result, String::kHashFieldOffset),
1584       Immediate(String::kEmptyHashField));
1585 }
1586
1587
1588 void MacroAssembler::AllocateTwoByteConsString(Register result,
1589                                         Register scratch1,
1590                                         Register scratch2,
1591                                         Label* gc_required) {
1592   // Allocate heap number in new space.
1593   Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
1594            TAG_OBJECT);
1595
1596   // Set the map. The other fields are left uninitialized.
1597   mov(FieldOperand(result, HeapObject::kMapOffset),
1598       Immediate(isolate()->factory()->cons_string_map()));
1599 }
1600
1601
1602 void MacroAssembler::AllocateAsciiConsString(Register result,
1603                                              Register scratch1,
1604                                              Register scratch2,
1605                                              Label* gc_required) {
1606   Label allocate_new_space, install_map;
1607   AllocationFlags flags = TAG_OBJECT;
1608
1609   ExternalReference high_promotion_mode = ExternalReference::
1610       new_space_high_promotion_mode_active_address(isolate());
1611
1612   test(Operand::StaticVariable(high_promotion_mode), Immediate(1));
1613   j(zero, &allocate_new_space);
1614
1615   Allocate(ConsString::kSize,
1616            result,
1617            scratch1,
1618            scratch2,
1619            gc_required,
1620            static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE));
1621   jmp(&install_map);
1622
1623   bind(&allocate_new_space);
1624   Allocate(ConsString::kSize,
1625            result,
1626            scratch1,
1627            scratch2,
1628            gc_required,
1629            flags);
1630
1631   bind(&install_map);
1632   // Set the map. The other fields are left uninitialized.
1633   mov(FieldOperand(result, HeapObject::kMapOffset),
1634       Immediate(isolate()->factory()->cons_ascii_string_map()));
1635 }
1636
1637
1638 void MacroAssembler::AllocateTwoByteSlicedString(Register result,
1639                                           Register scratch1,
1640                                           Register scratch2,
1641                                           Label* gc_required) {
1642   // Allocate heap number in new space.
1643   Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
1644            TAG_OBJECT);
1645
1646   // Set the map. The other fields are left uninitialized.
1647   mov(FieldOperand(result, HeapObject::kMapOffset),
1648       Immediate(isolate()->factory()->sliced_string_map()));
1649 }
1650
1651
1652 void MacroAssembler::AllocateAsciiSlicedString(Register result,
1653                                                Register scratch1,
1654                                                Register scratch2,
1655                                                Label* gc_required) {
1656   // Allocate heap number in new space.
1657   Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
1658            TAG_OBJECT);
1659
1660   // Set the map. The other fields are left uninitialized.
1661   mov(FieldOperand(result, HeapObject::kMapOffset),
1662       Immediate(isolate()->factory()->sliced_ascii_string_map()));
1663 }
1664
1665
1666 // Copy memory, byte-by-byte, from source to destination.  Not optimized for
1667 // long or aligned copies.  The contents of scratch and length are destroyed.
1668 // Source and destination are incremented by length.
1669 // Many variants of movsb, loop unrolling, word moves, and indexed operands
1670 // have been tried here already, and this is fastest.
1671 // A simpler loop is faster on small copies, but 30% slower on large ones.
1672 // The cld() instruction must have been emitted, to set the direction flag(),
1673 // before calling this function.
1674 void MacroAssembler::CopyBytes(Register source,
1675                                Register destination,
1676                                Register length,
1677                                Register scratch) {
1678   Label loop, done, short_string, short_loop;
1679   // Experimentation shows that the short string loop is faster if length < 10.
1680   cmp(length, Immediate(10));
1681   j(less_equal, &short_string);
1682
1683   ASSERT(source.is(esi));
1684   ASSERT(destination.is(edi));
1685   ASSERT(length.is(ecx));
1686
1687   // Because source is 4-byte aligned in our uses of this function,
1688   // we keep source aligned for the rep_movs call by copying the odd bytes
1689   // at the end of the ranges.
1690   mov(scratch, Operand(source, length, times_1, -4));
1691   mov(Operand(destination, length, times_1, -4), scratch);
1692   mov(scratch, ecx);
1693   shr(ecx, 2);
1694   rep_movs();
1695   and_(scratch, Immediate(0x3));
1696   add(destination, scratch);
1697   jmp(&done);
1698
1699   bind(&short_string);
1700   test(length, length);
1701   j(zero, &done);
1702
1703   bind(&short_loop);
1704   mov_b(scratch, Operand(source, 0));
1705   mov_b(Operand(destination, 0), scratch);
1706   inc(source);
1707   inc(destination);
1708   dec(length);
1709   j(not_zero, &short_loop);
1710
1711   bind(&done);
1712 }
1713
1714
1715 void MacroAssembler::InitializeFieldsWithFiller(Register start_offset,
1716                                                 Register end_offset,
1717                                                 Register filler) {
1718   Label loop, entry;
1719   jmp(&entry);
1720   bind(&loop);
1721   mov(Operand(start_offset, 0), filler);
1722   add(start_offset, Immediate(kPointerSize));
1723   bind(&entry);
1724   cmp(start_offset, end_offset);
1725   j(less, &loop);
1726 }
1727
1728
1729 void MacroAssembler::BooleanBitTest(Register object,
1730                                     int field_offset,
1731                                     int bit_index) {
1732   bit_index += kSmiTagSize + kSmiShiftSize;
1733   ASSERT(IsPowerOf2(kBitsPerByte));
1734   int byte_index = bit_index / kBitsPerByte;
1735   int byte_bit_index = bit_index & (kBitsPerByte - 1);
1736   test_b(FieldOperand(object, field_offset + byte_index),
1737          static_cast<byte>(1 << byte_bit_index));
1738 }
1739
1740
1741
1742 void MacroAssembler::NegativeZeroTest(Register result,
1743                                       Register op,
1744                                       Label* then_label) {
1745   Label ok;
1746   test(result, result);
1747   j(not_zero, &ok);
1748   test(op, op);
1749   j(sign, then_label);
1750   bind(&ok);
1751 }
1752
1753
1754 void MacroAssembler::NegativeZeroTest(Register result,
1755                                       Register op1,
1756                                       Register op2,
1757                                       Register scratch,
1758                                       Label* then_label) {
1759   Label ok;
1760   test(result, result);
1761   j(not_zero, &ok);
1762   mov(scratch, op1);
1763   or_(scratch, op2);
1764   j(sign, then_label);
1765   bind(&ok);
1766 }
1767
1768
1769 void MacroAssembler::TryGetFunctionPrototype(Register function,
1770                                              Register result,
1771                                              Register scratch,
1772                                              Label* miss,
1773                                              bool miss_on_bound_function) {
1774   // Check that the receiver isn't a smi.
1775   JumpIfSmi(function, miss);
1776
1777   // Check that the function really is a function.
1778   CmpObjectType(function, JS_FUNCTION_TYPE, result);
1779   j(not_equal, miss);
1780
1781   if (miss_on_bound_function) {
1782     // If a bound function, go to miss label.
1783     mov(scratch,
1784         FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
1785     BooleanBitTest(scratch, SharedFunctionInfo::kCompilerHintsOffset,
1786                    SharedFunctionInfo::kBoundFunction);
1787     j(not_zero, miss);
1788   }
1789
1790   // Make sure that the function has an instance prototype.
1791   Label non_instance;
1792   movzx_b(scratch, FieldOperand(result, Map::kBitFieldOffset));
1793   test(scratch, Immediate(1 << Map::kHasNonInstancePrototype));
1794   j(not_zero, &non_instance);
1795
1796   // Get the prototype or initial map from the function.
1797   mov(result,
1798       FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
1799
1800   // If the prototype or initial map is the hole, don't return it and
1801   // simply miss the cache instead. This will allow us to allocate a
1802   // prototype object on-demand in the runtime system.
1803   cmp(result, Immediate(isolate()->factory()->the_hole_value()));
1804   j(equal, miss);
1805
1806   // If the function does not have an initial map, we're done.
1807   Label done;
1808   CmpObjectType(result, MAP_TYPE, scratch);
1809   j(not_equal, &done);
1810
1811   // Get the prototype from the initial map.
1812   mov(result, FieldOperand(result, Map::kPrototypeOffset));
1813   jmp(&done);
1814
1815   // Non-instance prototype: Fetch prototype from constructor field
1816   // in initial map.
1817   bind(&non_instance);
1818   mov(result, FieldOperand(result, Map::kConstructorOffset));
1819
1820   // All done.
1821   bind(&done);
1822 }
1823
1824
1825 void MacroAssembler::CallStub(CodeStub* stub, TypeFeedbackId ast_id) {
1826   ASSERT(AllowThisStubCall(stub));  // Calls are not allowed in some stubs.
1827   call(stub->GetCode(isolate()), RelocInfo::CODE_TARGET, ast_id);
1828 }
1829
1830
1831 void MacroAssembler::TailCallStub(CodeStub* stub) {
1832   ASSERT(allow_stub_calls_ ||
1833          stub->CompilingCallsToThisStubIsGCSafe(isolate()));
1834   jmp(stub->GetCode(isolate()), RelocInfo::CODE_TARGET);
1835 }
1836
1837
1838 void MacroAssembler::StubReturn(int argc) {
1839   ASSERT(argc >= 1 && generating_stub());
1840   ret((argc - 1) * kPointerSize);
1841 }
1842
1843
1844 bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
1845   if (!has_frame_ && stub->SometimesSetsUpAFrame()) return false;
1846   return allow_stub_calls_ || stub->CompilingCallsToThisStubIsGCSafe(isolate());
1847 }
1848
1849
1850 void MacroAssembler::IllegalOperation(int num_arguments) {
1851   if (num_arguments > 0) {
1852     add(esp, Immediate(num_arguments * kPointerSize));
1853   }
1854   mov(eax, Immediate(isolate()->factory()->undefined_value()));
1855 }
1856
1857
1858 void MacroAssembler::IndexFromHash(Register hash, Register index) {
1859   // The assert checks that the constants for the maximum number of digits
1860   // for an array index cached in the hash field and the number of bits
1861   // reserved for it does not conflict.
1862   ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
1863          (1 << String::kArrayIndexValueBits));
1864   // We want the smi-tagged index in key.  kArrayIndexValueMask has zeros in
1865   // the low kHashShift bits.
1866   and_(hash, String::kArrayIndexValueMask);
1867   STATIC_ASSERT(String::kHashShift >= kSmiTagSize && kSmiTag == 0);
1868   if (String::kHashShift > kSmiTagSize) {
1869     shr(hash, String::kHashShift - kSmiTagSize);
1870   }
1871   if (!index.is(hash)) {
1872     mov(index, hash);
1873   }
1874 }
1875
1876
1877 void MacroAssembler::CallRuntime(Runtime::FunctionId id, int num_arguments) {
1878   CallRuntime(Runtime::FunctionForId(id), num_arguments);
1879 }
1880
1881
1882 void MacroAssembler::CallRuntimeSaveDoubles(Runtime::FunctionId id) {
1883   const Runtime::Function* function = Runtime::FunctionForId(id);
1884   Set(eax, Immediate(function->nargs));
1885   mov(ebx, Immediate(ExternalReference(function, isolate())));
1886   CEntryStub ces(1, CpuFeatures::IsSupported(SSE2) ? kSaveFPRegs
1887                                                    : kDontSaveFPRegs);
1888   CallStub(&ces);
1889 }
1890
1891
1892 void MacroAssembler::CallRuntime(const Runtime::Function* f,
1893                                  int num_arguments) {
1894   // If the expected number of arguments of the runtime function is
1895   // constant, we check that the actual number of arguments match the
1896   // expectation.
1897   if (f->nargs >= 0 && f->nargs != num_arguments) {
1898     IllegalOperation(num_arguments);
1899     return;
1900   }
1901
1902   // TODO(1236192): Most runtime routines don't need the number of
1903   // arguments passed in because it is constant. At some point we
1904   // should remove this need and make the runtime routine entry code
1905   // smarter.
1906   Set(eax, Immediate(num_arguments));
1907   mov(ebx, Immediate(ExternalReference(f, isolate())));
1908   CEntryStub ces(1);
1909   CallStub(&ces);
1910 }
1911
1912
1913 void MacroAssembler::CallExternalReference(ExternalReference ref,
1914                                            int num_arguments) {
1915   mov(eax, Immediate(num_arguments));
1916   mov(ebx, Immediate(ref));
1917
1918   CEntryStub stub(1);
1919   CallStub(&stub);
1920 }
1921
1922
1923 void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
1924                                                int num_arguments,
1925                                                int result_size) {
1926   // TODO(1236192): Most runtime routines don't need the number of
1927   // arguments passed in because it is constant. At some point we
1928   // should remove this need and make the runtime routine entry code
1929   // smarter.
1930   Set(eax, Immediate(num_arguments));
1931   JumpToExternalReference(ext);
1932 }
1933
1934
1935 void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
1936                                      int num_arguments,
1937                                      int result_size) {
1938   TailCallExternalReference(ExternalReference(fid, isolate()),
1939                             num_arguments,
1940                             result_size);
1941 }
1942
1943
1944 // If true, a Handle<T> returned by value from a function with cdecl calling
1945 // convention will be returned directly as a value of location_ field in a
1946 // register eax.
1947 // If false, it is returned as a pointer to a preallocated by caller memory
1948 // region. Pointer to this region should be passed to a function as an
1949 // implicit first argument.
1950 #if defined(USING_BSD_ABI) || defined(__MINGW32__) || defined(__CYGWIN__)
1951 static const bool kReturnHandlesDirectly = true;
1952 #else
1953 static const bool kReturnHandlesDirectly = false;
1954 #endif
1955
1956
1957 Operand ApiParameterOperand(int index) {
1958   return Operand(
1959       esp, (index + (kReturnHandlesDirectly ? 0 : 1)) * kPointerSize);
1960 }
1961
1962
1963 void MacroAssembler::PrepareCallApiFunction(int argc) {
1964   if (kReturnHandlesDirectly) {
1965     EnterApiExitFrame(argc);
1966     // When handles are returned directly we don't have to allocate extra
1967     // space for and pass an out parameter.
1968     if (emit_debug_code()) {
1969       mov(esi, Immediate(BitCast<int32_t>(kZapValue)));
1970     }
1971   } else {
1972     // We allocate two additional slots: return value and pointer to it.
1973     EnterApiExitFrame(argc + 2);
1974
1975     // The argument slots are filled as follows:
1976     //
1977     //   n + 1: output slot
1978     //   n: arg n
1979     //   ...
1980     //   1: arg1
1981     //   0: pointer to the output slot
1982
1983     lea(esi, Operand(esp, (argc + 1) * kPointerSize));
1984     mov(Operand(esp, 0 * kPointerSize), esi);
1985     if (emit_debug_code()) {
1986       mov(Operand(esi, 0), Immediate(0));
1987     }
1988   }
1989 }
1990
1991
1992 void MacroAssembler::CallApiFunctionAndReturn(Address function_address,
1993                                               int stack_space) {
1994   ExternalReference next_address =
1995       ExternalReference::handle_scope_next_address(isolate());
1996   ExternalReference limit_address =
1997       ExternalReference::handle_scope_limit_address(isolate());
1998   ExternalReference level_address =
1999       ExternalReference::handle_scope_level_address(isolate());
2000
2001   // Allocate HandleScope in callee-save registers.
2002   mov(ebx, Operand::StaticVariable(next_address));
2003   mov(edi, Operand::StaticVariable(limit_address));
2004   add(Operand::StaticVariable(level_address), Immediate(1));
2005
2006   if (FLAG_log_timer_events) {
2007     FrameScope frame(this, StackFrame::MANUAL);
2008     PushSafepointRegisters();
2009     PrepareCallCFunction(1, eax);
2010     mov(Operand(esp, 0),
2011         Immediate(ExternalReference::isolate_address(isolate())));
2012     CallCFunction(ExternalReference::log_enter_external_function(isolate()), 1);
2013     PopSafepointRegisters();
2014   }
2015
2016   // Call the api function.
2017   call(function_address, RelocInfo::RUNTIME_ENTRY);
2018
2019   if (FLAG_log_timer_events) {
2020     FrameScope frame(this, StackFrame::MANUAL);
2021     PushSafepointRegisters();
2022     PrepareCallCFunction(1, eax);
2023     mov(Operand(esp, 0),
2024         Immediate(ExternalReference::isolate_address(isolate())));
2025     CallCFunction(ExternalReference::log_leave_external_function(isolate()), 1);
2026     PopSafepointRegisters();
2027   }
2028
2029   if (!kReturnHandlesDirectly) {
2030     // PrepareCallApiFunction saved pointer to the output slot into
2031     // callee-save register esi.
2032     mov(eax, Operand(esi, 0));
2033   }
2034
2035   Label empty_handle;
2036   Label prologue;
2037   Label promote_scheduled_exception;
2038   Label delete_allocated_handles;
2039   Label leave_exit_frame;
2040
2041   // Check if the result handle holds 0.
2042   test(eax, eax);
2043   j(zero, &empty_handle);
2044   // It was non-zero.  Dereference to get the result value.
2045   mov(eax, Operand(eax, 0));
2046   bind(&prologue);
2047   // No more valid handles (the result handle was the last one). Restore
2048   // previous handle scope.
2049   mov(Operand::StaticVariable(next_address), ebx);
2050   sub(Operand::StaticVariable(level_address), Immediate(1));
2051   Assert(above_equal, "Invalid HandleScope level");
2052   cmp(edi, Operand::StaticVariable(limit_address));
2053   j(not_equal, &delete_allocated_handles);
2054   bind(&leave_exit_frame);
2055
2056   // Check if the function scheduled an exception.
2057   ExternalReference scheduled_exception_address =
2058       ExternalReference::scheduled_exception_address(isolate());
2059   cmp(Operand::StaticVariable(scheduled_exception_address),
2060       Immediate(isolate()->factory()->the_hole_value()));
2061   j(not_equal, &promote_scheduled_exception);
2062
2063 #if ENABLE_EXTRA_CHECKS
2064   // Check if the function returned a valid JavaScript value.
2065   Label ok;
2066   Register return_value = eax;
2067   Register map = ecx;
2068
2069   JumpIfSmi(return_value, &ok, Label::kNear);
2070   mov(map, FieldOperand(return_value, HeapObject::kMapOffset));
2071
2072   CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2073   j(below, &ok, Label::kNear);
2074
2075   CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2076   j(above_equal, &ok, Label::kNear);
2077
2078   cmp(map, isolate()->factory()->heap_number_map());
2079   j(equal, &ok, Label::kNear);
2080
2081   cmp(return_value, isolate()->factory()->undefined_value());
2082   j(equal, &ok, Label::kNear);
2083
2084   cmp(return_value, isolate()->factory()->true_value());
2085   j(equal, &ok, Label::kNear);
2086
2087   cmp(return_value, isolate()->factory()->false_value());
2088   j(equal, &ok, Label::kNear);
2089
2090   cmp(return_value, isolate()->factory()->null_value());
2091   j(equal, &ok, Label::kNear);
2092
2093   Abort("API call returned invalid object");
2094
2095   bind(&ok);
2096 #endif
2097
2098   LeaveApiExitFrame();
2099   ret(stack_space * kPointerSize);
2100
2101   bind(&empty_handle);
2102   // It was zero; the result is undefined.
2103   mov(eax, isolate()->factory()->undefined_value());
2104   jmp(&prologue);
2105
2106   bind(&promote_scheduled_exception);
2107   TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
2108
2109   // HandleScope limit has changed. Delete allocated extensions.
2110   ExternalReference delete_extensions =
2111       ExternalReference::delete_handle_scope_extensions(isolate());
2112   bind(&delete_allocated_handles);
2113   mov(Operand::StaticVariable(limit_address), edi);
2114   mov(edi, eax);
2115   mov(Operand(esp, 0),
2116       Immediate(ExternalReference::isolate_address(isolate())));
2117   mov(eax, Immediate(delete_extensions));
2118   call(eax);
2119   mov(eax, edi);
2120   jmp(&leave_exit_frame);
2121 }
2122
2123
2124 void MacroAssembler::JumpToExternalReference(const ExternalReference& ext) {
2125   // Set the entry point and jump to the C entry runtime stub.
2126   mov(ebx, Immediate(ext));
2127   CEntryStub ces(1);
2128   jmp(ces.GetCode(isolate()), RelocInfo::CODE_TARGET);
2129 }
2130
2131
2132 void MacroAssembler::SetCallKind(Register dst, CallKind call_kind) {
2133   // This macro takes the dst register to make the code more readable
2134   // at the call sites. However, the dst register has to be ecx to
2135   // follow the calling convention which requires the call type to be
2136   // in ecx.
2137   ASSERT(dst.is(ecx));
2138   if (call_kind == CALL_AS_FUNCTION) {
2139     // Set to some non-zero smi by updating the least significant
2140     // byte.
2141     mov_b(dst, 1 << kSmiTagSize);
2142   } else {
2143     // Set to smi zero by clearing the register.
2144     xor_(dst, dst);
2145   }
2146 }
2147
2148
2149 void MacroAssembler::InvokePrologue(const ParameterCount& expected,
2150                                     const ParameterCount& actual,
2151                                     Handle<Code> code_constant,
2152                                     const Operand& code_operand,
2153                                     Label* done,
2154                                     bool* definitely_mismatches,
2155                                     InvokeFlag flag,
2156                                     Label::Distance done_near,
2157                                     const CallWrapper& call_wrapper,
2158                                     CallKind call_kind) {
2159   bool definitely_matches = false;
2160   *definitely_mismatches = false;
2161   Label invoke;
2162   if (expected.is_immediate()) {
2163     ASSERT(actual.is_immediate());
2164     if (expected.immediate() == actual.immediate()) {
2165       definitely_matches = true;
2166     } else {
2167       mov(eax, actual.immediate());
2168       const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
2169       if (expected.immediate() == sentinel) {
2170         // Don't worry about adapting arguments for builtins that
2171         // don't want that done. Skip adaption code by making it look
2172         // like we have a match between expected and actual number of
2173         // arguments.
2174         definitely_matches = true;
2175       } else {
2176         *definitely_mismatches = true;
2177         mov(ebx, expected.immediate());
2178       }
2179     }
2180   } else {
2181     if (actual.is_immediate()) {
2182       // Expected is in register, actual is immediate. This is the
2183       // case when we invoke function values without going through the
2184       // IC mechanism.
2185       cmp(expected.reg(), actual.immediate());
2186       j(equal, &invoke);
2187       ASSERT(expected.reg().is(ebx));
2188       mov(eax, actual.immediate());
2189     } else if (!expected.reg().is(actual.reg())) {
2190       // Both expected and actual are in (different) registers. This
2191       // is the case when we invoke functions using call and apply.
2192       cmp(expected.reg(), actual.reg());
2193       j(equal, &invoke);
2194       ASSERT(actual.reg().is(eax));
2195       ASSERT(expected.reg().is(ebx));
2196     }
2197   }
2198
2199   if (!definitely_matches) {
2200     Handle<Code> adaptor =
2201         isolate()->builtins()->ArgumentsAdaptorTrampoline();
2202     if (!code_constant.is_null()) {
2203       mov(edx, Immediate(code_constant));
2204       add(edx, Immediate(Code::kHeaderSize - kHeapObjectTag));
2205     } else if (!code_operand.is_reg(edx)) {
2206       mov(edx, code_operand);
2207     }
2208
2209     if (flag == CALL_FUNCTION) {
2210       call_wrapper.BeforeCall(CallSize(adaptor, RelocInfo::CODE_TARGET));
2211       SetCallKind(ecx, call_kind);
2212       call(adaptor, RelocInfo::CODE_TARGET);
2213       call_wrapper.AfterCall();
2214       if (!*definitely_mismatches) {
2215         jmp(done, done_near);
2216       }
2217     } else {
2218       SetCallKind(ecx, call_kind);
2219       jmp(adaptor, RelocInfo::CODE_TARGET);
2220     }
2221     bind(&invoke);
2222   }
2223 }
2224
2225
2226 void MacroAssembler::InvokeCode(const Operand& code,
2227                                 const ParameterCount& expected,
2228                                 const ParameterCount& actual,
2229                                 InvokeFlag flag,
2230                                 const CallWrapper& call_wrapper,
2231                                 CallKind call_kind) {
2232   // You can't call a function without a valid frame.
2233   ASSERT(flag == JUMP_FUNCTION || has_frame());
2234
2235   Label done;
2236   bool definitely_mismatches = false;
2237   InvokePrologue(expected, actual, Handle<Code>::null(), code,
2238                  &done, &definitely_mismatches, flag, Label::kNear,
2239                  call_wrapper, call_kind);
2240   if (!definitely_mismatches) {
2241     if (flag == CALL_FUNCTION) {
2242       call_wrapper.BeforeCall(CallSize(code));
2243       SetCallKind(ecx, call_kind);
2244       call(code);
2245       call_wrapper.AfterCall();
2246     } else {
2247       ASSERT(flag == JUMP_FUNCTION);
2248       SetCallKind(ecx, call_kind);
2249       jmp(code);
2250     }
2251     bind(&done);
2252   }
2253 }
2254
2255
2256 void MacroAssembler::InvokeCode(Handle<Code> code,
2257                                 const ParameterCount& expected,
2258                                 const ParameterCount& actual,
2259                                 RelocInfo::Mode rmode,
2260                                 InvokeFlag flag,
2261                                 const CallWrapper& call_wrapper,
2262                                 CallKind call_kind) {
2263   // You can't call a function without a valid frame.
2264   ASSERT(flag == JUMP_FUNCTION || has_frame());
2265
2266   Label done;
2267   Operand dummy(eax, 0);
2268   bool definitely_mismatches = false;
2269   InvokePrologue(expected, actual, code, dummy, &done, &definitely_mismatches,
2270                  flag, Label::kNear, call_wrapper, call_kind);
2271   if (!definitely_mismatches) {
2272     if (flag == CALL_FUNCTION) {
2273       call_wrapper.BeforeCall(CallSize(code, rmode));
2274       SetCallKind(ecx, call_kind);
2275       call(code, rmode);
2276       call_wrapper.AfterCall();
2277     } else {
2278       ASSERT(flag == JUMP_FUNCTION);
2279       SetCallKind(ecx, call_kind);
2280       jmp(code, rmode);
2281     }
2282     bind(&done);
2283   }
2284 }
2285
2286
2287 void MacroAssembler::InvokeFunction(Register fun,
2288                                     const ParameterCount& actual,
2289                                     InvokeFlag flag,
2290                                     const CallWrapper& call_wrapper,
2291                                     CallKind call_kind) {
2292   // You can't call a function without a valid frame.
2293   ASSERT(flag == JUMP_FUNCTION || has_frame());
2294
2295   ASSERT(fun.is(edi));
2296   mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
2297   mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
2298   mov(ebx, FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
2299   SmiUntag(ebx);
2300
2301   ParameterCount expected(ebx);
2302   InvokeCode(FieldOperand(edi, JSFunction::kCodeEntryOffset),
2303              expected, actual, flag, call_wrapper, call_kind);
2304 }
2305
2306
2307 void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
2308                                     const ParameterCount& expected,
2309                                     const ParameterCount& actual,
2310                                     InvokeFlag flag,
2311                                     const CallWrapper& call_wrapper,
2312                                     CallKind call_kind) {
2313   // You can't call a function without a valid frame.
2314   ASSERT(flag == JUMP_FUNCTION || has_frame());
2315
2316   // Get the function and setup the context.
2317   LoadHeapObject(edi, function);
2318   mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
2319
2320   // We call indirectly through the code field in the function to
2321   // allow recompilation to take effect without changing any of the
2322   // call sites.
2323   InvokeCode(FieldOperand(edi, JSFunction::kCodeEntryOffset),
2324              expected, actual, flag, call_wrapper, call_kind);
2325 }
2326
2327
2328 void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
2329                                    InvokeFlag flag,
2330                                    const CallWrapper& call_wrapper) {
2331   // You can't call a builtin without a valid frame.
2332   ASSERT(flag == JUMP_FUNCTION || has_frame());
2333
2334   // Rely on the assertion to check that the number of provided
2335   // arguments match the expected number of arguments. Fake a
2336   // parameter count to avoid emitting code to do the check.
2337   ParameterCount expected(0);
2338   GetBuiltinFunction(edi, id);
2339   InvokeCode(FieldOperand(edi, JSFunction::kCodeEntryOffset),
2340              expected, expected, flag, call_wrapper, CALL_AS_METHOD);
2341 }
2342
2343
2344 void MacroAssembler::GetBuiltinFunction(Register target,
2345                                         Builtins::JavaScript id) {
2346   // Load the JavaScript builtin function from the builtins object.
2347   mov(target, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2348   mov(target, FieldOperand(target, GlobalObject::kBuiltinsOffset));
2349   mov(target, FieldOperand(target,
2350                            JSBuiltinsObject::OffsetOfFunctionWithId(id)));
2351 }
2352
2353
2354 void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
2355   ASSERT(!target.is(edi));
2356   // Load the JavaScript builtin function from the builtins object.
2357   GetBuiltinFunction(edi, id);
2358   // Load the code entry point from the function into the target register.
2359   mov(target, FieldOperand(edi, JSFunction::kCodeEntryOffset));
2360 }
2361
2362
2363 void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
2364   if (context_chain_length > 0) {
2365     // Move up the chain of contexts to the context containing the slot.
2366     mov(dst, Operand(esi, Context::SlotOffset(Context::PREVIOUS_INDEX)));
2367     for (int i = 1; i < context_chain_length; i++) {
2368       mov(dst, Operand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
2369     }
2370   } else {
2371     // Slot is in the current function context.  Move it into the
2372     // destination register in case we store into it (the write barrier
2373     // cannot be allowed to destroy the context in esi).
2374     mov(dst, esi);
2375   }
2376
2377   // We should not have found a with context by walking the context chain
2378   // (i.e., the static scope chain and runtime context chain do not agree).
2379   // A variable occurring in such a scope should have slot type LOOKUP and
2380   // not CONTEXT.
2381   if (emit_debug_code()) {
2382     cmp(FieldOperand(dst, HeapObject::kMapOffset),
2383         isolate()->factory()->with_context_map());
2384     Check(not_equal, "Variable resolved to with context.");
2385   }
2386 }
2387
2388
2389 void MacroAssembler::LoadTransitionedArrayMapConditional(
2390     ElementsKind expected_kind,
2391     ElementsKind transitioned_kind,
2392     Register map_in_out,
2393     Register scratch,
2394     Label* no_map_match) {
2395   // Load the global or builtins object from the current context.
2396   mov(scratch, Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2397   mov(scratch, FieldOperand(scratch, GlobalObject::kNativeContextOffset));
2398
2399   // Check that the function's map is the same as the expected cached map.
2400   mov(scratch, Operand(scratch,
2401                        Context::SlotOffset(Context::JS_ARRAY_MAPS_INDEX)));
2402
2403   size_t offset = expected_kind * kPointerSize +
2404       FixedArrayBase::kHeaderSize;
2405   cmp(map_in_out, FieldOperand(scratch, offset));
2406   j(not_equal, no_map_match);
2407
2408   // Use the transitioned cached map.
2409   offset = transitioned_kind * kPointerSize +
2410       FixedArrayBase::kHeaderSize;
2411   mov(map_in_out, FieldOperand(scratch, offset));
2412 }
2413
2414
2415 void MacroAssembler::LoadInitialArrayMap(
2416     Register function_in, Register scratch,
2417     Register map_out, bool can_have_holes) {
2418   ASSERT(!function_in.is(map_out));
2419   Label done;
2420   mov(map_out, FieldOperand(function_in,
2421                             JSFunction::kPrototypeOrInitialMapOffset));
2422   if (!FLAG_smi_only_arrays) {
2423     ElementsKind kind = can_have_holes ? FAST_HOLEY_ELEMENTS : FAST_ELEMENTS;
2424     LoadTransitionedArrayMapConditional(FAST_SMI_ELEMENTS,
2425                                         kind,
2426                                         map_out,
2427                                         scratch,
2428                                         &done);
2429   } else if (can_have_holes) {
2430     LoadTransitionedArrayMapConditional(FAST_SMI_ELEMENTS,
2431                                         FAST_HOLEY_SMI_ELEMENTS,
2432                                         map_out,
2433                                         scratch,
2434                                         &done);
2435   }
2436   bind(&done);
2437 }
2438
2439
2440 void MacroAssembler::LoadGlobalContext(Register global_context) {
2441   // Load the global or builtins object from the current context.
2442   mov(global_context,
2443       Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2444   // Load the native context from the global or builtins object.
2445   mov(global_context,
2446       FieldOperand(global_context, GlobalObject::kNativeContextOffset));
2447 }
2448
2449
2450 void MacroAssembler::LoadGlobalFunction(int index, Register function) {
2451   // Load the global or builtins object from the current context.
2452   mov(function,
2453       Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2454   // Load the native context from the global or builtins object.
2455   mov(function,
2456       FieldOperand(function, GlobalObject::kNativeContextOffset));
2457   // Load the function from the native context.
2458   mov(function, Operand(function, Context::SlotOffset(index)));
2459 }
2460
2461
2462 void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
2463                                                   Register map) {
2464   // Load the initial map.  The global functions all have initial maps.
2465   mov(map, FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2466   if (emit_debug_code()) {
2467     Label ok, fail;
2468     CheckMap(map, isolate()->factory()->meta_map(), &fail, DO_SMI_CHECK);
2469     jmp(&ok);
2470     bind(&fail);
2471     Abort("Global functions must have initial map");
2472     bind(&ok);
2473   }
2474 }
2475
2476
2477 // Store the value in register src in the safepoint register stack
2478 // slot for register dst.
2479 void MacroAssembler::StoreToSafepointRegisterSlot(Register dst, Register src) {
2480   mov(SafepointRegisterSlot(dst), src);
2481 }
2482
2483
2484 void MacroAssembler::StoreToSafepointRegisterSlot(Register dst, Immediate src) {
2485   mov(SafepointRegisterSlot(dst), src);
2486 }
2487
2488
2489 void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
2490   mov(dst, SafepointRegisterSlot(src));
2491 }
2492
2493
2494 Operand MacroAssembler::SafepointRegisterSlot(Register reg) {
2495   return Operand(esp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
2496 }
2497
2498
2499 int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
2500   // The registers are pushed starting with the lowest encoding,
2501   // which means that lowest encodings are furthest away from
2502   // the stack pointer.
2503   ASSERT(reg_code >= 0 && reg_code < kNumSafepointRegisters);
2504   return kNumSafepointRegisters - reg_code - 1;
2505 }
2506
2507
2508 void MacroAssembler::LoadHeapObject(Register result,
2509                                     Handle<HeapObject> object) {
2510   ALLOW_HANDLE_DEREF(isolate(), "embedding raw address");
2511   if (isolate()->heap()->InNewSpace(*object)) {
2512     Handle<JSGlobalPropertyCell> cell =
2513         isolate()->factory()->NewJSGlobalPropertyCell(object);
2514     mov(result, Operand::Cell(cell));
2515   } else {
2516     mov(result, object);
2517   }
2518 }
2519
2520
2521 void MacroAssembler::PushHeapObject(Handle<HeapObject> object) {
2522   ALLOW_HANDLE_DEREF(isolate(), "using raw address");
2523   if (isolate()->heap()->InNewSpace(*object)) {
2524     Handle<JSGlobalPropertyCell> cell =
2525         isolate()->factory()->NewJSGlobalPropertyCell(object);
2526     push(Operand::Cell(cell));
2527   } else {
2528     Push(object);
2529   }
2530 }
2531
2532
2533 void MacroAssembler::Ret() {
2534   ret(0);
2535 }
2536
2537
2538 void MacroAssembler::Ret(int bytes_dropped, Register scratch) {
2539   if (is_uint16(bytes_dropped)) {
2540     ret(bytes_dropped);
2541   } else {
2542     pop(scratch);
2543     add(esp, Immediate(bytes_dropped));
2544     push(scratch);
2545     ret(0);
2546   }
2547 }
2548
2549
2550 void MacroAssembler::VerifyX87StackDepth(uint32_t depth) {
2551   // Make sure the floating point stack is either empty or has depth items.
2552   ASSERT(depth <= 7);
2553
2554   // The top-of-stack (tos) is 7 if there is one item pushed.
2555   int tos = (8 - depth) % 8;
2556   const int kTopMask = 0x3800;
2557   push(eax);
2558   fwait();
2559   fnstsw_ax();
2560   and_(eax, kTopMask);
2561   shr(eax, 11);
2562   cmp(eax, Immediate(tos));
2563   Check(equal, "Unexpected FPU stack depth after instruction");
2564   fnclex();
2565   pop(eax);
2566 }
2567
2568
2569 void MacroAssembler::Drop(int stack_elements) {
2570   if (stack_elements > 0) {
2571     add(esp, Immediate(stack_elements * kPointerSize));
2572   }
2573 }
2574
2575
2576 void MacroAssembler::Move(Register dst, Register src) {
2577   if (!dst.is(src)) {
2578     mov(dst, src);
2579   }
2580 }
2581
2582
2583 void MacroAssembler::SetCounter(StatsCounter* counter, int value) {
2584   if (FLAG_native_code_counters && counter->Enabled()) {
2585     mov(Operand::StaticVariable(ExternalReference(counter)), Immediate(value));
2586   }
2587 }
2588
2589
2590 void MacroAssembler::IncrementCounter(StatsCounter* counter, int value) {
2591   ASSERT(value > 0);
2592   if (FLAG_native_code_counters && counter->Enabled()) {
2593     Operand operand = Operand::StaticVariable(ExternalReference(counter));
2594     if (value == 1) {
2595       inc(operand);
2596     } else {
2597       add(operand, Immediate(value));
2598     }
2599   }
2600 }
2601
2602
2603 void MacroAssembler::DecrementCounter(StatsCounter* counter, int value) {
2604   ASSERT(value > 0);
2605   if (FLAG_native_code_counters && counter->Enabled()) {
2606     Operand operand = Operand::StaticVariable(ExternalReference(counter));
2607     if (value == 1) {
2608       dec(operand);
2609     } else {
2610       sub(operand, Immediate(value));
2611     }
2612   }
2613 }
2614
2615
2616 void MacroAssembler::IncrementCounter(Condition cc,
2617                                       StatsCounter* counter,
2618                                       int value) {
2619   ASSERT(value > 0);
2620   if (FLAG_native_code_counters && counter->Enabled()) {
2621     Label skip;
2622     j(NegateCondition(cc), &skip);
2623     pushfd();
2624     IncrementCounter(counter, value);
2625     popfd();
2626     bind(&skip);
2627   }
2628 }
2629
2630
2631 void MacroAssembler::DecrementCounter(Condition cc,
2632                                       StatsCounter* counter,
2633                                       int value) {
2634   ASSERT(value > 0);
2635   if (FLAG_native_code_counters && counter->Enabled()) {
2636     Label skip;
2637     j(NegateCondition(cc), &skip);
2638     pushfd();
2639     DecrementCounter(counter, value);
2640     popfd();
2641     bind(&skip);
2642   }
2643 }
2644
2645
2646 void MacroAssembler::Assert(Condition cc, const char* msg) {
2647   if (emit_debug_code()) Check(cc, msg);
2648 }
2649
2650
2651 void MacroAssembler::AssertFastElements(Register elements) {
2652   if (emit_debug_code()) {
2653     Factory* factory = isolate()->factory();
2654     Label ok;
2655     cmp(FieldOperand(elements, HeapObject::kMapOffset),
2656         Immediate(factory->fixed_array_map()));
2657     j(equal, &ok);
2658     cmp(FieldOperand(elements, HeapObject::kMapOffset),
2659         Immediate(factory->fixed_double_array_map()));
2660     j(equal, &ok);
2661     cmp(FieldOperand(elements, HeapObject::kMapOffset),
2662         Immediate(factory->fixed_cow_array_map()));
2663     j(equal, &ok);
2664     Abort("JSObject with fast elements map has slow elements");
2665     bind(&ok);
2666   }
2667 }
2668
2669
2670 void MacroAssembler::Check(Condition cc, const char* msg) {
2671   Label L;
2672   j(cc, &L);
2673   Abort(msg);
2674   // will not return here
2675   bind(&L);
2676 }
2677
2678
2679 void MacroAssembler::CheckStackAlignment() {
2680   int frame_alignment = OS::ActivationFrameAlignment();
2681   int frame_alignment_mask = frame_alignment - 1;
2682   if (frame_alignment > kPointerSize) {
2683     ASSERT(IsPowerOf2(frame_alignment));
2684     Label alignment_as_expected;
2685     test(esp, Immediate(frame_alignment_mask));
2686     j(zero, &alignment_as_expected);
2687     // Abort if stack is not aligned.
2688     int3();
2689     bind(&alignment_as_expected);
2690   }
2691 }
2692
2693
2694 void MacroAssembler::Abort(const char* msg) {
2695   // We want to pass the msg string like a smi to avoid GC
2696   // problems, however msg is not guaranteed to be aligned
2697   // properly. Instead, we pass an aligned pointer that is
2698   // a proper v8 smi, but also pass the alignment difference
2699   // from the real pointer as a smi.
2700   intptr_t p1 = reinterpret_cast<intptr_t>(msg);
2701   intptr_t p0 = (p1 & ~kSmiTagMask) + kSmiTag;
2702   ASSERT(reinterpret_cast<Object*>(p0)->IsSmi());
2703 #ifdef DEBUG
2704   if (msg != NULL) {
2705     RecordComment("Abort message: ");
2706     RecordComment(msg);
2707   }
2708 #endif
2709
2710   push(eax);
2711   push(Immediate(p0));
2712   push(Immediate(reinterpret_cast<intptr_t>(Smi::FromInt(p1 - p0))));
2713   // Disable stub call restrictions to always allow calls to abort.
2714   if (!has_frame_) {
2715     // We don't actually want to generate a pile of code for this, so just
2716     // claim there is a stack frame, without generating one.
2717     FrameScope scope(this, StackFrame::NONE);
2718     CallRuntime(Runtime::kAbort, 2);
2719   } else {
2720     CallRuntime(Runtime::kAbort, 2);
2721   }
2722   // will not return here
2723   int3();
2724 }
2725
2726
2727 void MacroAssembler::LoadInstanceDescriptors(Register map,
2728                                              Register descriptors) {
2729   mov(descriptors, FieldOperand(map, Map::kDescriptorsOffset));
2730 }
2731
2732
2733 void MacroAssembler::NumberOfOwnDescriptors(Register dst, Register map) {
2734   mov(dst, FieldOperand(map, Map::kBitField3Offset));
2735   DecodeField<Map::NumberOfOwnDescriptorsBits>(dst);
2736 }
2737
2738
2739 void MacroAssembler::LoadPowerOf2(XMMRegister dst,
2740                                   Register scratch,
2741                                   int power) {
2742   ASSERT(is_uintn(power + HeapNumber::kExponentBias,
2743                   HeapNumber::kExponentBits));
2744   mov(scratch, Immediate(power + HeapNumber::kExponentBias));
2745   movd(dst, scratch);
2746   psllq(dst, HeapNumber::kMantissaBits);
2747 }
2748
2749
2750 void MacroAssembler::JumpIfInstanceTypeIsNotSequentialAscii(
2751     Register instance_type,
2752     Register scratch,
2753     Label* failure) {
2754   if (!scratch.is(instance_type)) {
2755     mov(scratch, instance_type);
2756   }
2757   and_(scratch,
2758        kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
2759   cmp(scratch, kStringTag | kSeqStringTag | kOneByteStringTag);
2760   j(not_equal, failure);
2761 }
2762
2763
2764 void MacroAssembler::JumpIfNotBothSequentialAsciiStrings(Register object1,
2765                                                          Register object2,
2766                                                          Register scratch1,
2767                                                          Register scratch2,
2768                                                          Label* failure) {
2769   // Check that both objects are not smis.
2770   STATIC_ASSERT(kSmiTag == 0);
2771   mov(scratch1, object1);
2772   and_(scratch1, object2);
2773   JumpIfSmi(scratch1, failure);
2774
2775   // Load instance type for both strings.
2776   mov(scratch1, FieldOperand(object1, HeapObject::kMapOffset));
2777   mov(scratch2, FieldOperand(object2, HeapObject::kMapOffset));
2778   movzx_b(scratch1, FieldOperand(scratch1, Map::kInstanceTypeOffset));
2779   movzx_b(scratch2, FieldOperand(scratch2, Map::kInstanceTypeOffset));
2780
2781   // Check that both are flat ASCII strings.
2782   const int kFlatAsciiStringMask =
2783       kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask;
2784   const int kFlatAsciiStringTag = ASCII_STRING_TYPE;
2785   // Interleave bits from both instance types and compare them in one check.
2786   ASSERT_EQ(0, kFlatAsciiStringMask & (kFlatAsciiStringMask << 3));
2787   and_(scratch1, kFlatAsciiStringMask);
2788   and_(scratch2, kFlatAsciiStringMask);
2789   lea(scratch1, Operand(scratch1, scratch2, times_8, 0));
2790   cmp(scratch1, kFlatAsciiStringTag | (kFlatAsciiStringTag << 3));
2791   j(not_equal, failure);
2792 }
2793
2794
2795 void MacroAssembler::PrepareCallCFunction(int num_arguments, Register scratch) {
2796   int frame_alignment = OS::ActivationFrameAlignment();
2797   if (frame_alignment != 0) {
2798     // Make stack end at alignment and make room for num_arguments words
2799     // and the original value of esp.
2800     mov(scratch, esp);
2801     sub(esp, Immediate((num_arguments + 1) * kPointerSize));
2802     ASSERT(IsPowerOf2(frame_alignment));
2803     and_(esp, -frame_alignment);
2804     mov(Operand(esp, num_arguments * kPointerSize), scratch);
2805   } else {
2806     sub(esp, Immediate(num_arguments * kPointerSize));
2807   }
2808 }
2809
2810
2811 void MacroAssembler::CallCFunction(ExternalReference function,
2812                                    int num_arguments) {
2813   // Trashing eax is ok as it will be the return value.
2814   mov(eax, Immediate(function));
2815   CallCFunction(eax, num_arguments);
2816 }
2817
2818
2819 void MacroAssembler::CallCFunction(Register function,
2820                                    int num_arguments) {
2821   ASSERT(has_frame());
2822   // Check stack alignment.
2823   if (emit_debug_code()) {
2824     CheckStackAlignment();
2825   }
2826
2827   call(function);
2828   if (OS::ActivationFrameAlignment() != 0) {
2829     mov(esp, Operand(esp, num_arguments * kPointerSize));
2830   } else {
2831     add(esp, Immediate(num_arguments * kPointerSize));
2832   }
2833 }
2834
2835
2836 bool AreAliased(Register r1, Register r2, Register r3, Register r4) {
2837   if (r1.is(r2)) return true;
2838   if (r1.is(r3)) return true;
2839   if (r1.is(r4)) return true;
2840   if (r2.is(r3)) return true;
2841   if (r2.is(r4)) return true;
2842   if (r3.is(r4)) return true;
2843   return false;
2844 }
2845
2846
2847 CodePatcher::CodePatcher(byte* address, int size)
2848     : address_(address),
2849       size_(size),
2850       masm_(NULL, address, size + Assembler::kGap) {
2851   // Create a new macro assembler pointing to the address of the code to patch.
2852   // The size is adjusted with kGap on order for the assembler to generate size
2853   // bytes of instructions without failing with buffer size constraints.
2854   ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
2855 }
2856
2857
2858 CodePatcher::~CodePatcher() {
2859   // Indicate that code has changed.
2860   CPU::FlushICache(address_, size_);
2861
2862   // Check that the code was patched as expected.
2863   ASSERT(masm_.pc_ == address_ + size_);
2864   ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
2865 }
2866
2867
2868 void MacroAssembler::CheckPageFlag(
2869     Register object,
2870     Register scratch,
2871     int mask,
2872     Condition cc,
2873     Label* condition_met,
2874     Label::Distance condition_met_distance) {
2875   ASSERT(cc == zero || cc == not_zero);
2876   if (scratch.is(object)) {
2877     and_(scratch, Immediate(~Page::kPageAlignmentMask));
2878   } else {
2879     mov(scratch, Immediate(~Page::kPageAlignmentMask));
2880     and_(scratch, object);
2881   }
2882   if (mask < (1 << kBitsPerByte)) {
2883     test_b(Operand(scratch, MemoryChunk::kFlagsOffset),
2884            static_cast<uint8_t>(mask));
2885   } else {
2886     test(Operand(scratch, MemoryChunk::kFlagsOffset), Immediate(mask));
2887   }
2888   j(cc, condition_met, condition_met_distance);
2889 }
2890
2891
2892 void MacroAssembler::CheckPageFlagForMap(
2893     Handle<Map> map,
2894     int mask,
2895     Condition cc,
2896     Label* condition_met,
2897     Label::Distance condition_met_distance) {
2898   ASSERT(cc == zero || cc == not_zero);
2899   Page* page = Page::FromAddress(map->address());
2900   ExternalReference reference(ExternalReference::page_flags(page));
2901   // The inlined static address check of the page's flags relies
2902   // on maps never being compacted.
2903   ASSERT(!isolate()->heap()->mark_compact_collector()->
2904          IsOnEvacuationCandidate(*map));
2905   if (mask < (1 << kBitsPerByte)) {
2906     test_b(Operand::StaticVariable(reference), static_cast<uint8_t>(mask));
2907   } else {
2908     test(Operand::StaticVariable(reference), Immediate(mask));
2909   }
2910   j(cc, condition_met, condition_met_distance);
2911 }
2912
2913
2914 void MacroAssembler::CheckMapDeprecated(Handle<Map> map,
2915                                         Register scratch,
2916                                         Label* if_deprecated) {
2917   if (map->CanBeDeprecated()) {
2918     mov(scratch, map);
2919     mov(scratch, FieldOperand(scratch, Map::kBitField3Offset));
2920     and_(scratch, Immediate(Smi::FromInt(Map::Deprecated::kMask)));
2921     j(not_zero, if_deprecated);
2922   }
2923 }
2924
2925
2926 void MacroAssembler::JumpIfBlack(Register object,
2927                                  Register scratch0,
2928                                  Register scratch1,
2929                                  Label* on_black,
2930                                  Label::Distance on_black_near) {
2931   HasColor(object, scratch0, scratch1,
2932            on_black, on_black_near,
2933            1, 0);  // kBlackBitPattern.
2934   ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
2935 }
2936
2937
2938 void MacroAssembler::HasColor(Register object,
2939                               Register bitmap_scratch,
2940                               Register mask_scratch,
2941                               Label* has_color,
2942                               Label::Distance has_color_distance,
2943                               int first_bit,
2944                               int second_bit) {
2945   ASSERT(!AreAliased(object, bitmap_scratch, mask_scratch, ecx));
2946
2947   GetMarkBits(object, bitmap_scratch, mask_scratch);
2948
2949   Label other_color, word_boundary;
2950   test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2951   j(first_bit == 1 ? zero : not_zero, &other_color, Label::kNear);
2952   add(mask_scratch, mask_scratch);  // Shift left 1 by adding.
2953   j(zero, &word_boundary, Label::kNear);
2954   test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2955   j(second_bit == 1 ? not_zero : zero, has_color, has_color_distance);
2956   jmp(&other_color, Label::kNear);
2957
2958   bind(&word_boundary);
2959   test_b(Operand(bitmap_scratch, MemoryChunk::kHeaderSize + kPointerSize), 1);
2960
2961   j(second_bit == 1 ? not_zero : zero, has_color, has_color_distance);
2962   bind(&other_color);
2963 }
2964
2965
2966 void MacroAssembler::GetMarkBits(Register addr_reg,
2967                                  Register bitmap_reg,
2968                                  Register mask_reg) {
2969   ASSERT(!AreAliased(addr_reg, mask_reg, bitmap_reg, ecx));
2970   mov(bitmap_reg, Immediate(~Page::kPageAlignmentMask));
2971   and_(bitmap_reg, addr_reg);
2972   mov(ecx, addr_reg);
2973   int shift =
2974       Bitmap::kBitsPerCellLog2 + kPointerSizeLog2 - Bitmap::kBytesPerCellLog2;
2975   shr(ecx, shift);
2976   and_(ecx,
2977        (Page::kPageAlignmentMask >> shift) & ~(Bitmap::kBytesPerCell - 1));
2978
2979   add(bitmap_reg, ecx);
2980   mov(ecx, addr_reg);
2981   shr(ecx, kPointerSizeLog2);
2982   and_(ecx, (1 << Bitmap::kBitsPerCellLog2) - 1);
2983   mov(mask_reg, Immediate(1));
2984   shl_cl(mask_reg);
2985 }
2986
2987
2988 void MacroAssembler::EnsureNotWhite(
2989     Register value,
2990     Register bitmap_scratch,
2991     Register mask_scratch,
2992     Label* value_is_white_and_not_data,
2993     Label::Distance distance) {
2994   ASSERT(!AreAliased(value, bitmap_scratch, mask_scratch, ecx));
2995   GetMarkBits(value, bitmap_scratch, mask_scratch);
2996
2997   // If the value is black or grey we don't need to do anything.
2998   ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
2999   ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
3000   ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
3001   ASSERT(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
3002
3003   Label done;
3004
3005   // Since both black and grey have a 1 in the first position and white does
3006   // not have a 1 there we only need to check one bit.
3007   test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
3008   j(not_zero, &done, Label::kNear);
3009
3010   if (emit_debug_code()) {
3011     // Check for impossible bit pattern.
3012     Label ok;
3013     push(mask_scratch);
3014     // shl.  May overflow making the check conservative.
3015     add(mask_scratch, mask_scratch);
3016     test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
3017     j(zero, &ok, Label::kNear);
3018     int3();
3019     bind(&ok);
3020     pop(mask_scratch);
3021   }
3022
3023   // Value is white.  We check whether it is data that doesn't need scanning.
3024   // Currently only checks for HeapNumber and non-cons strings.
3025   Register map = ecx;  // Holds map while checking type.
3026   Register length = ecx;  // Holds length of object after checking type.
3027   Label not_heap_number;
3028   Label is_data_object;
3029
3030   // Check for heap-number
3031   mov(map, FieldOperand(value, HeapObject::kMapOffset));
3032   cmp(map, FACTORY->heap_number_map());
3033   j(not_equal, &not_heap_number, Label::kNear);
3034   mov(length, Immediate(HeapNumber::kSize));
3035   jmp(&is_data_object, Label::kNear);
3036
3037   bind(&not_heap_number);
3038   // Check for strings.
3039   ASSERT(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
3040   ASSERT(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
3041   // If it's a string and it's not a cons string then it's an object containing
3042   // no GC pointers.
3043   Register instance_type = ecx;
3044   movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
3045   test_b(instance_type, kIsIndirectStringMask | kIsNotStringMask);
3046   j(not_zero, value_is_white_and_not_data);
3047   // It's a non-indirect (non-cons and non-slice) string.
3048   // If it's external, the length is just ExternalString::kSize.
3049   // Otherwise it's String::kHeaderSize + string->length() * (1 or 2).
3050   Label not_external;
3051   // External strings are the only ones with the kExternalStringTag bit
3052   // set.
3053   ASSERT_EQ(0, kSeqStringTag & kExternalStringTag);
3054   ASSERT_EQ(0, kConsStringTag & kExternalStringTag);
3055   test_b(instance_type, kExternalStringTag);
3056   j(zero, &not_external, Label::kNear);
3057   mov(length, Immediate(ExternalString::kSize));
3058   jmp(&is_data_object, Label::kNear);
3059
3060   bind(&not_external);
3061   // Sequential string, either ASCII or UC16.
3062   ASSERT(kOneByteStringTag == 0x04);
3063   and_(length, Immediate(kStringEncodingMask));
3064   xor_(length, Immediate(kStringEncodingMask));
3065   add(length, Immediate(0x04));
3066   // Value now either 4 (if ASCII) or 8 (if UC16), i.e., char-size shifted
3067   // by 2. If we multiply the string length as smi by this, it still
3068   // won't overflow a 32-bit value.
3069   ASSERT_EQ(SeqOneByteString::kMaxSize, SeqTwoByteString::kMaxSize);
3070   ASSERT(SeqOneByteString::kMaxSize <=
3071          static_cast<int>(0xffffffffu >> (2 + kSmiTagSize)));
3072   imul(length, FieldOperand(value, String::kLengthOffset));
3073   shr(length, 2 + kSmiTagSize + kSmiShiftSize);
3074   add(length, Immediate(SeqString::kHeaderSize + kObjectAlignmentMask));
3075   and_(length, Immediate(~kObjectAlignmentMask));
3076
3077   bind(&is_data_object);
3078   // Value is a data object, and it is white.  Mark it black.  Since we know
3079   // that the object is white we can make it black by flipping one bit.
3080   or_(Operand(bitmap_scratch, MemoryChunk::kHeaderSize), mask_scratch);
3081
3082   and_(bitmap_scratch, Immediate(~Page::kPageAlignmentMask));
3083   add(Operand(bitmap_scratch, MemoryChunk::kLiveBytesOffset),
3084       length);
3085   if (emit_debug_code()) {
3086     mov(length, Operand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
3087     cmp(length, Operand(bitmap_scratch, MemoryChunk::kSizeOffset));
3088     Check(less_equal, "Live Bytes Count overflow chunk size");
3089   }
3090
3091   bind(&done);
3092 }
3093
3094
3095 void MacroAssembler::EnumLength(Register dst, Register map) {
3096   STATIC_ASSERT(Map::EnumLengthBits::kShift == 0);
3097   mov(dst, FieldOperand(map, Map::kBitField3Offset));
3098   and_(dst, Immediate(Smi::FromInt(Map::EnumLengthBits::kMask)));
3099 }
3100
3101
3102 void MacroAssembler::CheckEnumCache(Label* call_runtime) {
3103   Label next, start;
3104   mov(ecx, eax);
3105
3106   // Check if the enum length field is properly initialized, indicating that
3107   // there is an enum cache.
3108   mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));
3109
3110   EnumLength(edx, ebx);
3111   cmp(edx, Immediate(Smi::FromInt(Map::kInvalidEnumCache)));
3112   j(equal, call_runtime);
3113
3114   jmp(&start);
3115
3116   bind(&next);
3117   mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));
3118
3119   // For all objects but the receiver, check that the cache is empty.
3120   EnumLength(edx, ebx);
3121   cmp(edx, Immediate(Smi::FromInt(0)));
3122   j(not_equal, call_runtime);
3123
3124   bind(&start);
3125
3126   // Check that there are no elements. Register rcx contains the current JS
3127   // object we've reached through the prototype chain.
3128   mov(ecx, FieldOperand(ecx, JSObject::kElementsOffset));
3129   cmp(ecx, isolate()->factory()->empty_fixed_array());
3130   j(not_equal, call_runtime);
3131
3132   mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
3133   cmp(ecx, isolate()->factory()->null_value());
3134   j(not_equal, &next);
3135 }
3136
3137
3138 void MacroAssembler::TestJSArrayForAllocationSiteInfo(
3139     Register receiver_reg,
3140     Register scratch_reg) {
3141   Label no_info_available;
3142
3143   ExternalReference new_space_start =
3144       ExternalReference::new_space_start(isolate());
3145   ExternalReference new_space_allocation_top =
3146       ExternalReference::new_space_allocation_top_address(isolate());
3147
3148   lea(scratch_reg, Operand(receiver_reg,
3149       JSArray::kSize + AllocationSiteInfo::kSize - kHeapObjectTag));
3150   cmp(scratch_reg, Immediate(new_space_start));
3151   j(less, &no_info_available);
3152   cmp(scratch_reg, Operand::StaticVariable(new_space_allocation_top));
3153   j(greater, &no_info_available);
3154   cmp(MemOperand(scratch_reg, -AllocationSiteInfo::kSize),
3155       Immediate(Handle<Map>(isolate()->heap()->allocation_site_info_map())));
3156   bind(&no_info_available);
3157 }
3158
3159
3160 } }  // namespace v8::internal
3161
3162 #endif  // V8_TARGET_ARCH_IA32