Merge remote-tracking branch 'upstream/v0.10' into v0.12
[platform/upstream/nodejs.git] / deps / v8 / src / ia32 / macro-assembler-ia32.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_IA32_MACRO_ASSEMBLER_IA32_H_
6 #define V8_IA32_MACRO_ASSEMBLER_IA32_H_
7
8 #include "assembler.h"
9 #include "frames.h"
10 #include "v8globals.h"
11
12 namespace v8 {
13 namespace internal {
14
15 // Convenience for platform-independent signatures.  We do not normally
16 // distinguish memory operands from other operands on ia32.
17 typedef Operand MemOperand;
18
19 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
20 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
21
22
23 enum RegisterValueType {
24   REGISTER_VALUE_IS_SMI,
25   REGISTER_VALUE_IS_INT32
26 };
27
28
29 bool AreAliased(Register r1, Register r2, Register r3, Register r4);
30
31
32 // MacroAssembler implements a collection of frequently used macros.
33 class MacroAssembler: public Assembler {
34  public:
35   // The isolate parameter can be NULL if the macro assembler should
36   // not use isolate-dependent functionality. In this case, it's the
37   // responsibility of the caller to never invoke such function on the
38   // macro assembler.
39   MacroAssembler(Isolate* isolate, void* buffer, int size);
40
41   void Load(Register dst, const Operand& src, Representation r);
42   void Store(Register src, const Operand& dst, Representation r);
43
44   // Operations on roots in the root-array.
45   void LoadRoot(Register destination, Heap::RootListIndex index);
46   void StoreRoot(Register source, Register scratch, Heap::RootListIndex index);
47   void CompareRoot(Register with, Register scratch, Heap::RootListIndex index);
48   // These methods can only be used with constant roots (i.e. non-writable
49   // and not in new space).
50   void CompareRoot(Register with, Heap::RootListIndex index);
51   void CompareRoot(const Operand& with, Heap::RootListIndex index);
52
53   // ---------------------------------------------------------------------------
54   // GC Support
55   enum RememberedSetFinalAction {
56     kReturnAtEnd,
57     kFallThroughAtEnd
58   };
59
60   // Record in the remembered set the fact that we have a pointer to new space
61   // at the address pointed to by the addr register.  Only works if addr is not
62   // in new space.
63   void RememberedSetHelper(Register object,  // Used for debug code.
64                            Register addr,
65                            Register scratch,
66                            SaveFPRegsMode save_fp,
67                            RememberedSetFinalAction and_then);
68
69   void CheckPageFlag(Register object,
70                      Register scratch,
71                      int mask,
72                      Condition cc,
73                      Label* condition_met,
74                      Label::Distance condition_met_distance = Label::kFar);
75
76   void CheckPageFlagForMap(
77       Handle<Map> map,
78       int mask,
79       Condition cc,
80       Label* condition_met,
81       Label::Distance condition_met_distance = Label::kFar);
82
83   void CheckMapDeprecated(Handle<Map> map,
84                           Register scratch,
85                           Label* if_deprecated);
86
87   // Check if object is in new space.  Jumps if the object is not in new space.
88   // The register scratch can be object itself, but scratch will be clobbered.
89   void JumpIfNotInNewSpace(Register object,
90                            Register scratch,
91                            Label* branch,
92                            Label::Distance distance = Label::kFar) {
93     InNewSpace(object, scratch, zero, branch, distance);
94   }
95
96   // Check if object is in new space.  Jumps if the object is in new space.
97   // The register scratch can be object itself, but it will be clobbered.
98   void JumpIfInNewSpace(Register object,
99                         Register scratch,
100                         Label* branch,
101                         Label::Distance distance = Label::kFar) {
102     InNewSpace(object, scratch, not_zero, branch, distance);
103   }
104
105   // Check if an object has a given incremental marking color.  Also uses ecx!
106   void HasColor(Register object,
107                 Register scratch0,
108                 Register scratch1,
109                 Label* has_color,
110                 Label::Distance has_color_distance,
111                 int first_bit,
112                 int second_bit);
113
114   void JumpIfBlack(Register object,
115                    Register scratch0,
116                    Register scratch1,
117                    Label* on_black,
118                    Label::Distance on_black_distance = Label::kFar);
119
120   // Checks the color of an object.  If the object is already grey or black
121   // then we just fall through, since it is already live.  If it is white and
122   // we can determine that it doesn't need to be scanned, then we just mark it
123   // black and fall through.  For the rest we jump to the label so the
124   // incremental marker can fix its assumptions.
125   void EnsureNotWhite(Register object,
126                       Register scratch1,
127                       Register scratch2,
128                       Label* object_is_white_and_not_data,
129                       Label::Distance distance);
130
131   // Notify the garbage collector that we wrote a pointer into an object.
132   // |object| is the object being stored into, |value| is the object being
133   // stored.  value and scratch registers are clobbered by the operation.
134   // The offset is the offset from the start of the object, not the offset from
135   // the tagged HeapObject pointer.  For use with FieldOperand(reg, off).
136   void RecordWriteField(
137       Register object,
138       int offset,
139       Register value,
140       Register scratch,
141       SaveFPRegsMode save_fp,
142       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
143       SmiCheck smi_check = INLINE_SMI_CHECK);
144
145   // As above, but the offset has the tag presubtracted.  For use with
146   // Operand(reg, off).
147   void RecordWriteContextSlot(
148       Register context,
149       int offset,
150       Register value,
151       Register scratch,
152       SaveFPRegsMode save_fp,
153       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
154       SmiCheck smi_check = INLINE_SMI_CHECK) {
155     RecordWriteField(context,
156                      offset + kHeapObjectTag,
157                      value,
158                      scratch,
159                      save_fp,
160                      remembered_set_action,
161                      smi_check);
162   }
163
164   // Notify the garbage collector that we wrote a pointer into a fixed array.
165   // |array| is the array being stored into, |value| is the
166   // object being stored.  |index| is the array index represented as a
167   // Smi. All registers are clobbered by the operation RecordWriteArray
168   // filters out smis so it does not update the write barrier if the
169   // value is a smi.
170   void RecordWriteArray(
171       Register array,
172       Register value,
173       Register index,
174       SaveFPRegsMode save_fp,
175       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
176       SmiCheck smi_check = INLINE_SMI_CHECK);
177
178   // For page containing |object| mark region covering |address|
179   // dirty. |object| is the object being stored into, |value| is the
180   // object being stored. The address and value registers are clobbered by the
181   // operation. RecordWrite filters out smis so it does not update the
182   // write barrier if the value is a smi.
183   void RecordWrite(
184       Register object,
185       Register address,
186       Register value,
187       SaveFPRegsMode save_fp,
188       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
189       SmiCheck smi_check = INLINE_SMI_CHECK);
190
191   // For page containing |object| mark the region covering the object's map
192   // dirty. |object| is the object being stored into, |map| is the Map object
193   // that was stored.
194   void RecordWriteForMap(
195       Register object,
196       Handle<Map> map,
197       Register scratch1,
198       Register scratch2,
199       SaveFPRegsMode save_fp);
200
201   // ---------------------------------------------------------------------------
202   // Debugger Support
203
204   void DebugBreak();
205
206   // Generates function and stub prologue code.
207   void Prologue(PrologueFrameMode frame_mode);
208
209   // Enter specific kind of exit frame. Expects the number of
210   // arguments in register eax and sets up the number of arguments in
211   // register edi and the pointer to the first argument in register
212   // esi.
213   void EnterExitFrame(bool save_doubles);
214
215   void EnterApiExitFrame(int argc);
216
217   // Leave the current exit frame. Expects the return value in
218   // register eax:edx (untouched) and the pointer to the first
219   // argument in register esi.
220   void LeaveExitFrame(bool save_doubles);
221
222   // Leave the current exit frame. Expects the return value in
223   // register eax (untouched).
224   void LeaveApiExitFrame(bool restore_context);
225
226   // Find the function context up the context chain.
227   void LoadContext(Register dst, int context_chain_length);
228
229   // Conditionally load the cached Array transitioned map of type
230   // transitioned_kind from the native context if the map in register
231   // map_in_out is the cached Array map in the native context of
232   // expected_kind.
233   void LoadTransitionedArrayMapConditional(
234       ElementsKind expected_kind,
235       ElementsKind transitioned_kind,
236       Register map_in_out,
237       Register scratch,
238       Label* no_map_match);
239
240   // Load the global function with the given index.
241   void LoadGlobalFunction(int index, Register function);
242
243   // Load the initial map from the global function. The registers
244   // function and map can be the same.
245   void LoadGlobalFunctionInitialMap(Register function, Register map);
246
247   // Push and pop the registers that can hold pointers.
248   void PushSafepointRegisters() { pushad(); }
249   void PopSafepointRegisters() { popad(); }
250   // Store the value in register/immediate src in the safepoint
251   // register stack slot for register dst.
252   void StoreToSafepointRegisterSlot(Register dst, Register src);
253   void StoreToSafepointRegisterSlot(Register dst, Immediate src);
254   void LoadFromSafepointRegisterSlot(Register dst, Register src);
255
256   void LoadHeapObject(Register result, Handle<HeapObject> object);
257   void CmpHeapObject(Register reg, Handle<HeapObject> object);
258   void PushHeapObject(Handle<HeapObject> object);
259
260   void LoadObject(Register result, Handle<Object> object) {
261     AllowDeferredHandleDereference heap_object_check;
262     if (object->IsHeapObject()) {
263       LoadHeapObject(result, Handle<HeapObject>::cast(object));
264     } else {
265       Move(result, Immediate(object));
266     }
267   }
268
269   void CmpObject(Register reg, Handle<Object> object) {
270     AllowDeferredHandleDereference heap_object_check;
271     if (object->IsHeapObject()) {
272       CmpHeapObject(reg, Handle<HeapObject>::cast(object));
273     } else {
274       cmp(reg, Immediate(object));
275     }
276   }
277
278   // ---------------------------------------------------------------------------
279   // JavaScript invokes
280
281   // Invoke the JavaScript function code by either calling or jumping.
282   void InvokeCode(Register code,
283                   const ParameterCount& expected,
284                   const ParameterCount& actual,
285                   InvokeFlag flag,
286                   const CallWrapper& call_wrapper) {
287     InvokeCode(Operand(code), expected, actual, flag, call_wrapper);
288   }
289
290   void InvokeCode(const Operand& code,
291                   const ParameterCount& expected,
292                   const ParameterCount& actual,
293                   InvokeFlag flag,
294                   const CallWrapper& call_wrapper);
295
296   // Invoke the JavaScript function in the given register. Changes the
297   // current context to the context in the function before invoking.
298   void InvokeFunction(Register function,
299                       const ParameterCount& actual,
300                       InvokeFlag flag,
301                       const CallWrapper& call_wrapper);
302
303   void InvokeFunction(Register function,
304                       const ParameterCount& expected,
305                       const ParameterCount& actual,
306                       InvokeFlag flag,
307                       const CallWrapper& call_wrapper);
308
309   void InvokeFunction(Handle<JSFunction> function,
310                       const ParameterCount& expected,
311                       const ParameterCount& actual,
312                       InvokeFlag flag,
313                       const CallWrapper& call_wrapper);
314
315   // Invoke specified builtin JavaScript function. Adds an entry to
316   // the unresolved list if the name does not resolve.
317   void InvokeBuiltin(Builtins::JavaScript id,
318                      InvokeFlag flag,
319                      const CallWrapper& call_wrapper = NullCallWrapper());
320
321   // Store the function for the given builtin in the target register.
322   void GetBuiltinFunction(Register target, Builtins::JavaScript id);
323
324   // Store the code object for the given builtin in the target register.
325   void GetBuiltinEntry(Register target, Builtins::JavaScript id);
326
327   // Expression support
328   // cvtsi2sd instruction only writes to the low 64-bit of dst register, which
329   // hinders register renaming and makes dependence chains longer. So we use
330   // xorps to clear the dst register before cvtsi2sd to solve this issue.
331   void Cvtsi2sd(XMMRegister dst, Register src) { Cvtsi2sd(dst, Operand(src)); }
332   void Cvtsi2sd(XMMRegister dst, const Operand& src);
333
334   // Support for constant splitting.
335   bool IsUnsafeImmediate(const Immediate& x);
336   void SafeMove(Register dst, const Immediate& x);
337   void SafePush(const Immediate& x);
338
339   // Compare object type for heap object.
340   // Incoming register is heap_object and outgoing register is map.
341   void CmpObjectType(Register heap_object, InstanceType type, Register map);
342
343   // Compare instance type for map.
344   void CmpInstanceType(Register map, InstanceType type);
345
346   // Check if a map for a JSObject indicates that the object has fast elements.
347   // Jump to the specified label if it does not.
348   void CheckFastElements(Register map,
349                          Label* fail,
350                          Label::Distance distance = Label::kFar);
351
352   // Check if a map for a JSObject indicates that the object can have both smi
353   // and HeapObject elements.  Jump to the specified label if it does not.
354   void CheckFastObjectElements(Register map,
355                                Label* fail,
356                                Label::Distance distance = Label::kFar);
357
358   // Check if a map for a JSObject indicates that the object has fast smi only
359   // elements.  Jump to the specified label if it does not.
360   void CheckFastSmiElements(Register map,
361                             Label* fail,
362                             Label::Distance distance = Label::kFar);
363
364   // Check to see if maybe_number can be stored as a double in
365   // FastDoubleElements. If it can, store it at the index specified by key in
366   // the FastDoubleElements array elements, otherwise jump to fail.
367   void StoreNumberToDoubleElements(Register maybe_number,
368                                    Register elements,
369                                    Register key,
370                                    Register scratch1,
371                                    XMMRegister scratch2,
372                                    Label* fail,
373                                    bool specialize_for_processor,
374                                    int offset = 0);
375
376   // Compare an object's map with the specified map.
377   void CompareMap(Register obj, Handle<Map> map);
378
379   // Check if the map of an object is equal to a specified map and branch to
380   // label if not. Skip the smi check if not required (object is known to be a
381   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
382   // against maps that are ElementsKind transition maps of the specified map.
383   void CheckMap(Register obj,
384                 Handle<Map> map,
385                 Label* fail,
386                 SmiCheckType smi_check_type);
387
388   // Check if the map of an object is equal to a specified map and branch to a
389   // specified target if equal. Skip the smi check if not required (object is
390   // known to be a heap object)
391   void DispatchMap(Register obj,
392                    Register unused,
393                    Handle<Map> map,
394                    Handle<Code> success,
395                    SmiCheckType smi_check_type);
396
397   // Check if the object in register heap_object is a string. Afterwards the
398   // register map contains the object map and the register instance_type
399   // contains the instance_type. The registers map and instance_type can be the
400   // same in which case it contains the instance type afterwards. Either of the
401   // registers map and instance_type can be the same as heap_object.
402   Condition IsObjectStringType(Register heap_object,
403                                Register map,
404                                Register instance_type);
405
406   // Check if the object in register heap_object is a name. Afterwards the
407   // register map contains the object map and the register instance_type
408   // contains the instance_type. The registers map and instance_type can be the
409   // same in which case it contains the instance type afterwards. Either of the
410   // registers map and instance_type can be the same as heap_object.
411   Condition IsObjectNameType(Register heap_object,
412                              Register map,
413                              Register instance_type);
414
415   // Check if a heap object's type is in the JSObject range, not including
416   // JSFunction.  The object's map will be loaded in the map register.
417   // Any or all of the three registers may be the same.
418   // The contents of the scratch register will always be overwritten.
419   void IsObjectJSObjectType(Register heap_object,
420                             Register map,
421                             Register scratch,
422                             Label* fail);
423
424   // The contents of the scratch register will be overwritten.
425   void IsInstanceJSObjectType(Register map, Register scratch, Label* fail);
426
427   // FCmp is similar to integer cmp, but requires unsigned
428   // jcc instructions (je, ja, jae, jb, jbe, je, and jz).
429   void FCmp();
430
431   void ClampUint8(Register reg);
432
433   void ClampDoubleToUint8(XMMRegister input_reg,
434                           XMMRegister scratch_reg,
435                           Register result_reg);
436
437   void SlowTruncateToI(Register result_reg, Register input_reg,
438       int offset = HeapNumber::kValueOffset - kHeapObjectTag);
439
440   void TruncateHeapNumberToI(Register result_reg, Register input_reg);
441   void TruncateDoubleToI(Register result_reg, XMMRegister input_reg);
442   void TruncateX87TOSToI(Register result_reg);
443
444   void DoubleToI(Register result_reg, XMMRegister input_reg,
445       XMMRegister scratch, MinusZeroMode minus_zero_mode,
446       Label* conversion_failed, Label::Distance dst = Label::kFar);
447   void X87TOSToI(Register result_reg, MinusZeroMode minus_zero_mode,
448       Label* conversion_failed, Label::Distance dst = Label::kFar);
449
450   void TaggedToI(Register result_reg, Register input_reg, XMMRegister temp,
451       MinusZeroMode minus_zero_mode, Label* lost_precision);
452
453   // Smi tagging support.
454   void SmiTag(Register reg) {
455     STATIC_ASSERT(kSmiTag == 0);
456     STATIC_ASSERT(kSmiTagSize == 1);
457     add(reg, reg);
458   }
459   void SmiUntag(Register reg) {
460     sar(reg, kSmiTagSize);
461   }
462
463   // Modifies the register even if it does not contain a Smi!
464   void SmiUntag(Register reg, Label* is_smi) {
465     STATIC_ASSERT(kSmiTagSize == 1);
466     sar(reg, kSmiTagSize);
467     STATIC_ASSERT(kSmiTag == 0);
468     j(not_carry, is_smi);
469   }
470
471   void LoadUint32(XMMRegister dst, Register src, XMMRegister scratch);
472   void LoadUint32NoSSE2(Register src);
473
474   // Jump the register contains a smi.
475   inline void JumpIfSmi(Register value,
476                         Label* smi_label,
477                         Label::Distance distance = Label::kFar) {
478     test(value, Immediate(kSmiTagMask));
479     j(zero, smi_label, distance);
480   }
481   // Jump if the operand is a smi.
482   inline void JumpIfSmi(Operand value,
483                         Label* smi_label,
484                         Label::Distance distance = Label::kFar) {
485     test(value, Immediate(kSmiTagMask));
486     j(zero, smi_label, distance);
487   }
488   // Jump if register contain a non-smi.
489   inline void JumpIfNotSmi(Register value,
490                            Label* not_smi_label,
491                            Label::Distance distance = Label::kFar) {
492     test(value, Immediate(kSmiTagMask));
493     j(not_zero, not_smi_label, distance);
494   }
495
496   void LoadInstanceDescriptors(Register map, Register descriptors);
497   void EnumLength(Register dst, Register map);
498   void NumberOfOwnDescriptors(Register dst, Register map);
499
500   template<typename Field>
501   void DecodeField(Register reg) {
502     static const int shift = Field::kShift;
503     static const int mask = (Field::kMask >> Field::kShift) << kSmiTagSize;
504     sar(reg, shift);
505     and_(reg, Immediate(mask));
506   }
507   void LoadPowerOf2(XMMRegister dst, Register scratch, int power);
508
509   // Abort execution if argument is not a number, enabled via --debug-code.
510   void AssertNumber(Register object);
511
512   // Abort execution if argument is not a smi, enabled via --debug-code.
513   void AssertSmi(Register object);
514
515   // Abort execution if argument is a smi, enabled via --debug-code.
516   void AssertNotSmi(Register object);
517
518   // Abort execution if argument is not a string, enabled via --debug-code.
519   void AssertString(Register object);
520
521   // Abort execution if argument is not a name, enabled via --debug-code.
522   void AssertName(Register object);
523
524   // Abort execution if argument is not undefined or an AllocationSite, enabled
525   // via --debug-code.
526   void AssertUndefinedOrAllocationSite(Register object);
527
528   // ---------------------------------------------------------------------------
529   // Exception handling
530
531   // Push a new try handler and link it into try handler chain.
532   void PushTryHandler(StackHandler::Kind kind, int handler_index);
533
534   // Unlink the stack handler on top of the stack from the try handler chain.
535   void PopTryHandler();
536
537   // Throw to the top handler in the try hander chain.
538   void Throw(Register value);
539
540   // Throw past all JS frames to the top JS entry frame.
541   void ThrowUncatchable(Register value);
542
543   // Throw a message string as an exception.
544   void Throw(BailoutReason reason);
545
546   // Throw a message string as an exception if a condition is not true.
547   void ThrowIf(Condition cc, BailoutReason reason);
548
549   // ---------------------------------------------------------------------------
550   // Inline caching support
551
552   // Generate code for checking access rights - used for security checks
553   // on access to global objects across environments. The holder register
554   // is left untouched, but the scratch register is clobbered.
555   void CheckAccessGlobalProxy(Register holder_reg,
556                               Register scratch1,
557                               Register scratch2,
558                               Label* miss);
559
560   void GetNumberHash(Register r0, Register scratch);
561
562   void LoadFromNumberDictionary(Label* miss,
563                                 Register elements,
564                                 Register key,
565                                 Register r0,
566                                 Register r1,
567                                 Register r2,
568                                 Register result);
569
570
571   // ---------------------------------------------------------------------------
572   // Allocation support
573
574   // Allocate an object in new space or old pointer space. If the given space
575   // is exhausted control continues at the gc_required label. The allocated
576   // object is returned in result and end of the new object is returned in
577   // result_end. The register scratch can be passed as no_reg in which case
578   // an additional object reference will be added to the reloc info. The
579   // returned pointers in result and result_end have not yet been tagged as
580   // heap objects. If result_contains_top_on_entry is true the content of
581   // result is known to be the allocation top on entry (could be result_end
582   // from a previous call). If result_contains_top_on_entry is true scratch
583   // should be no_reg as it is never used.
584   void Allocate(int object_size,
585                 Register result,
586                 Register result_end,
587                 Register scratch,
588                 Label* gc_required,
589                 AllocationFlags flags);
590
591   void Allocate(int header_size,
592                 ScaleFactor element_size,
593                 Register element_count,
594                 RegisterValueType element_count_type,
595                 Register result,
596                 Register result_end,
597                 Register scratch,
598                 Label* gc_required,
599                 AllocationFlags flags);
600
601   void Allocate(Register object_size,
602                 Register result,
603                 Register result_end,
604                 Register scratch,
605                 Label* gc_required,
606                 AllocationFlags flags);
607
608   // Undo allocation in new space. The object passed and objects allocated after
609   // it will no longer be allocated. Make sure that no pointers are left to the
610   // object(s) no longer allocated as they would be invalid when allocation is
611   // un-done.
612   void UndoAllocationInNewSpace(Register object);
613
614   // Allocate a heap number in new space with undefined value. The
615   // register scratch2 can be passed as no_reg; the others must be
616   // valid registers. Returns tagged pointer in result register, or
617   // jumps to gc_required if new space is full.
618   void AllocateHeapNumber(Register result,
619                           Register scratch1,
620                           Register scratch2,
621                           Label* gc_required);
622
623   // Allocate a sequential string. All the header fields of the string object
624   // are initialized.
625   void AllocateTwoByteString(Register result,
626                              Register length,
627                              Register scratch1,
628                              Register scratch2,
629                              Register scratch3,
630                              Label* gc_required);
631   void AllocateAsciiString(Register result,
632                            Register length,
633                            Register scratch1,
634                            Register scratch2,
635                            Register scratch3,
636                            Label* gc_required);
637   void AllocateAsciiString(Register result,
638                            int length,
639                            Register scratch1,
640                            Register scratch2,
641                            Label* gc_required);
642
643   // Allocate a raw cons string object. Only the map field of the result is
644   // initialized.
645   void AllocateTwoByteConsString(Register result,
646                           Register scratch1,
647                           Register scratch2,
648                           Label* gc_required);
649   void AllocateAsciiConsString(Register result,
650                                Register scratch1,
651                                Register scratch2,
652                                Label* gc_required);
653
654   // Allocate a raw sliced string object. Only the map field of the result is
655   // initialized.
656   void AllocateTwoByteSlicedString(Register result,
657                             Register scratch1,
658                             Register scratch2,
659                             Label* gc_required);
660   void AllocateAsciiSlicedString(Register result,
661                                  Register scratch1,
662                                  Register scratch2,
663                                  Label* gc_required);
664
665   // Copy memory, byte-by-byte, from source to destination.  Not optimized for
666   // long or aligned copies.
667   // The contents of index and scratch are destroyed.
668   void CopyBytes(Register source,
669                  Register destination,
670                  Register length,
671                  Register scratch);
672
673   // Initialize fields with filler values.  Fields starting at |start_offset|
674   // not including end_offset are overwritten with the value in |filler|.  At
675   // the end the loop, |start_offset| takes the value of |end_offset|.
676   void InitializeFieldsWithFiller(Register start_offset,
677                                   Register end_offset,
678                                   Register filler);
679
680   // ---------------------------------------------------------------------------
681   // Support functions.
682
683   // Check a boolean-bit of a Smi field.
684   void BooleanBitTest(Register object, int field_offset, int bit_index);
685
686   // Check if result is zero and op is negative.
687   void NegativeZeroTest(Register result, Register op, Label* then_label);
688
689   // Check if result is zero and any of op1 and op2 are negative.
690   // Register scratch is destroyed, and it must be different from op2.
691   void NegativeZeroTest(Register result, Register op1, Register op2,
692                         Register scratch, Label* then_label);
693
694   // Try to get function prototype of a function and puts the value in
695   // the result register. Checks that the function really is a
696   // function and jumps to the miss label if the fast checks fail. The
697   // function register will be untouched; the other registers may be
698   // clobbered.
699   void TryGetFunctionPrototype(Register function,
700                                Register result,
701                                Register scratch,
702                                Label* miss,
703                                bool miss_on_bound_function = false);
704
705   // Picks out an array index from the hash field.
706   // Register use:
707   //   hash - holds the index's hash. Clobbered.
708   //   index - holds the overwritten index on exit.
709   void IndexFromHash(Register hash, Register index);
710
711   // ---------------------------------------------------------------------------
712   // Runtime calls
713
714   // Call a code stub.  Generate the code if necessary.
715   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
716
717   // Tail call a code stub (jump).  Generate the code if necessary.
718   void TailCallStub(CodeStub* stub);
719
720   // Return from a code stub after popping its arguments.
721   void StubReturn(int argc);
722
723   // Call a runtime routine.
724   void CallRuntime(const Runtime::Function* f,
725                    int num_arguments,
726                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
727   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
728     const Runtime::Function* function = Runtime::FunctionForId(id);
729     CallRuntime(function, function->nargs, kSaveFPRegs);
730   }
731
732   // Convenience function: Same as above, but takes the fid instead.
733   void CallRuntime(Runtime::FunctionId id,
734                    int num_arguments,
735                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
736     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
737   }
738
739   // Convenience function: call an external reference.
740   void CallExternalReference(ExternalReference ref, int num_arguments);
741
742   // Tail call of a runtime routine (jump).
743   // Like JumpToExternalReference, but also takes care of passing the number
744   // of parameters.
745   void TailCallExternalReference(const ExternalReference& ext,
746                                  int num_arguments,
747                                  int result_size);
748
749   // Convenience function: tail call a runtime routine (jump).
750   void TailCallRuntime(Runtime::FunctionId fid,
751                        int num_arguments,
752                        int result_size);
753
754   // Before calling a C-function from generated code, align arguments on stack.
755   // After aligning the frame, arguments must be stored in esp[0], esp[4],
756   // etc., not pushed. The argument count assumes all arguments are word sized.
757   // Some compilers/platforms require the stack to be aligned when calling
758   // C++ code.
759   // Needs a scratch register to do some arithmetic. This register will be
760   // trashed.
761   void PrepareCallCFunction(int num_arguments, Register scratch);
762
763   // Calls a C function and cleans up the space for arguments allocated
764   // by PrepareCallCFunction. The called function is not allowed to trigger a
765   // garbage collection, since that might move the code and invalidate the
766   // return address (unless this is somehow accounted for by the called
767   // function).
768   void CallCFunction(ExternalReference function, int num_arguments);
769   void CallCFunction(Register function, int num_arguments);
770
771   // Prepares stack to put arguments (aligns and so on). Reserves
772   // space for return value if needed (assumes the return value is a handle).
773   // Arguments must be stored in ApiParameterOperand(0), ApiParameterOperand(1)
774   // etc. Saves context (esi). If space was reserved for return value then
775   // stores the pointer to the reserved slot into esi.
776   void PrepareCallApiFunction(int argc);
777
778   // Calls an API function.  Allocates HandleScope, extracts returned value
779   // from handle and propagates exceptions.  Clobbers ebx, edi and
780   // caller-save registers.  Restores context.  On return removes
781   // stack_space * kPointerSize (GCed).
782   void CallApiFunctionAndReturn(Register function_address,
783                                 ExternalReference thunk_ref,
784                                 Operand thunk_last_arg,
785                                 int stack_space,
786                                 Operand return_value_operand,
787                                 Operand* context_restore_operand);
788
789   // Jump to a runtime routine.
790   void JumpToExternalReference(const ExternalReference& ext);
791
792   // ---------------------------------------------------------------------------
793   // Utilities
794
795   void Ret();
796
797   // Return and drop arguments from stack, where the number of arguments
798   // may be bigger than 2^16 - 1.  Requires a scratch register.
799   void Ret(int bytes_dropped, Register scratch);
800
801   // Emit code to discard a non-negative number of pointer-sized elements
802   // from the stack, clobbering only the esp register.
803   void Drop(int element_count);
804
805   void Call(Label* target) { call(target); }
806   void Push(Register src) { push(src); }
807   void Pop(Register dst) { pop(dst); }
808
809   // Emit call to the code we are currently generating.
810   void CallSelf() {
811     Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
812     call(self, RelocInfo::CODE_TARGET);
813   }
814
815   // Move if the registers are not identical.
816   void Move(Register target, Register source);
817
818   // Move a constant into a destination using the most efficient encoding.
819   void Move(Register dst, const Immediate& x);
820   void Move(const Operand& dst, const Immediate& x);
821
822   // Move an immediate into an XMM register.
823   void Move(XMMRegister dst, double val);
824
825   // Push a handle value.
826   void Push(Handle<Object> handle) { push(Immediate(handle)); }
827   void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
828
829   Handle<Object> CodeObject() {
830     ASSERT(!code_object_.is_null());
831     return code_object_;
832   }
833
834   // Insert code to verify that the x87 stack has the specified depth (0-7)
835   void VerifyX87StackDepth(uint32_t depth);
836
837   // Emit code for a truncating division by a constant. The dividend register is
838   // unchanged, the result is in edx, and eax gets clobbered.
839   void TruncatingDiv(Register dividend, int32_t divisor);
840
841   // ---------------------------------------------------------------------------
842   // StatsCounter support
843
844   void SetCounter(StatsCounter* counter, int value);
845   void IncrementCounter(StatsCounter* counter, int value);
846   void DecrementCounter(StatsCounter* counter, int value);
847   void IncrementCounter(Condition cc, StatsCounter* counter, int value);
848   void DecrementCounter(Condition cc, StatsCounter* counter, int value);
849
850
851   // ---------------------------------------------------------------------------
852   // Debugging
853
854   // Calls Abort(msg) if the condition cc is not satisfied.
855   // Use --debug_code to enable.
856   void Assert(Condition cc, BailoutReason reason);
857
858   void AssertFastElements(Register elements);
859
860   // Like Assert(), but always enabled.
861   void Check(Condition cc, BailoutReason reason);
862
863   // Print a message to stdout and abort execution.
864   void Abort(BailoutReason reason);
865
866   // Check that the stack is aligned.
867   void CheckStackAlignment();
868
869   // Verify restrictions about code generated in stubs.
870   void set_generating_stub(bool value) { generating_stub_ = value; }
871   bool generating_stub() { return generating_stub_; }
872   void set_has_frame(bool value) { has_frame_ = value; }
873   bool has_frame() { return has_frame_; }
874   inline bool AllowThisStubCall(CodeStub* stub);
875
876   // ---------------------------------------------------------------------------
877   // String utilities.
878
879   // Generate code to do a lookup in the number string cache. If the number in
880   // the register object is found in the cache the generated code falls through
881   // with the result in the result register. The object and the result register
882   // can be the same. If the number is not found in the cache the code jumps to
883   // the label not_found with only the content of register object unchanged.
884   void LookupNumberStringCache(Register object,
885                                Register result,
886                                Register scratch1,
887                                Register scratch2,
888                                Label* not_found);
889
890   // Check whether the instance type represents a flat ASCII string. Jump to the
891   // label if not. If the instance type can be scratched specify same register
892   // for both instance type and scratch.
893   void JumpIfInstanceTypeIsNotSequentialAscii(Register instance_type,
894                                               Register scratch,
895                                               Label* on_not_flat_ascii_string);
896
897   // Checks if both objects are sequential ASCII strings, and jumps to label
898   // if either is not.
899   void JumpIfNotBothSequentialAsciiStrings(Register object1,
900                                            Register object2,
901                                            Register scratch1,
902                                            Register scratch2,
903                                            Label* on_not_flat_ascii_strings);
904
905   // Checks if the given register or operand is a unique name
906   void JumpIfNotUniqueName(Register reg, Label* not_unique_name,
907                            Label::Distance distance = Label::kFar) {
908     JumpIfNotUniqueName(Operand(reg), not_unique_name, distance);
909   }
910
911   void JumpIfNotUniqueName(Operand operand, Label* not_unique_name,
912                            Label::Distance distance = Label::kFar);
913
914   void EmitSeqStringSetCharCheck(Register string,
915                                  Register index,
916                                  Register value,
917                                  uint32_t encoding_mask);
918
919   static int SafepointRegisterStackIndex(Register reg) {
920     return SafepointRegisterStackIndex(reg.code());
921   }
922
923   // Activation support.
924   void EnterFrame(StackFrame::Type type);
925   void LeaveFrame(StackFrame::Type type);
926
927   // Expects object in eax and returns map with validated enum cache
928   // in eax.  Assumes that any other register can be used as a scratch.
929   void CheckEnumCache(Label* call_runtime);
930
931   // AllocationMemento support. Arrays may have an associated
932   // AllocationMemento object that can be checked for in order to pretransition
933   // to another type.
934   // On entry, receiver_reg should point to the array object.
935   // scratch_reg gets clobbered.
936   // If allocation info is present, conditional code is set to equal.
937   void TestJSArrayForAllocationMemento(Register receiver_reg,
938                                        Register scratch_reg,
939                                        Label* no_memento_found);
940
941   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
942                                          Register scratch_reg,
943                                          Label* memento_found) {
944     Label no_memento_found;
945     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
946                                     &no_memento_found);
947     j(equal, memento_found);
948     bind(&no_memento_found);
949   }
950
951   // Jumps to found label if a prototype map has dictionary elements.
952   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
953                                         Register scratch1, Label* found);
954
955  private:
956   bool generating_stub_;
957   bool has_frame_;
958   // This handle will be patched with the code object on installation.
959   Handle<Object> code_object_;
960
961   // Helper functions for generating invokes.
962   void InvokePrologue(const ParameterCount& expected,
963                       const ParameterCount& actual,
964                       Handle<Code> code_constant,
965                       const Operand& code_operand,
966                       Label* done,
967                       bool* definitely_mismatches,
968                       InvokeFlag flag,
969                       Label::Distance done_distance,
970                       const CallWrapper& call_wrapper = NullCallWrapper());
971
972   void EnterExitFramePrologue();
973   void EnterExitFrameEpilogue(int argc, bool save_doubles);
974
975   void LeaveExitFrameEpilogue(bool restore_context);
976
977   // Allocation support helpers.
978   void LoadAllocationTopHelper(Register result,
979                                Register scratch,
980                                AllocationFlags flags);
981
982   void UpdateAllocationTopHelper(Register result_end,
983                                  Register scratch,
984                                  AllocationFlags flags);
985
986   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
987   void InNewSpace(Register object,
988                   Register scratch,
989                   Condition cc,
990                   Label* condition_met,
991                   Label::Distance condition_met_distance = Label::kFar);
992
993   // Helper for finding the mark bits for an address.  Afterwards, the
994   // bitmap register points at the word with the mark bits and the mask
995   // the position of the first bit.  Uses ecx as scratch and leaves addr_reg
996   // unchanged.
997   inline void GetMarkBits(Register addr_reg,
998                           Register bitmap_reg,
999                           Register mask_reg);
1000
1001   // Helper for throwing exceptions.  Compute a handler address and jump to
1002   // it.  See the implementation for register usage.
1003   void JumpToHandlerEntry();
1004
1005   // Compute memory operands for safepoint stack slots.
1006   Operand SafepointRegisterSlot(Register reg);
1007   static int SafepointRegisterStackIndex(int reg_code);
1008
1009   // Needs access to SafepointRegisterStackIndex for compiled frame
1010   // traversal.
1011   friend class StandardFrame;
1012 };
1013
1014
1015 // The code patcher is used to patch (typically) small parts of code e.g. for
1016 // debugging and other types of instrumentation. When using the code patcher
1017 // the exact number of bytes specified must be emitted. Is not legal to emit
1018 // relocation information. If any of these constraints are violated it causes
1019 // an assertion.
1020 class CodePatcher {
1021  public:
1022   CodePatcher(byte* address, int size);
1023   virtual ~CodePatcher();
1024
1025   // Macro assembler to emit code.
1026   MacroAssembler* masm() { return &masm_; }
1027
1028  private:
1029   byte* address_;  // The address of the code being patched.
1030   int size_;  // Number of bytes of the expected patch size.
1031   MacroAssembler masm_;  // Macro assembler used to generate the code.
1032 };
1033
1034
1035 // -----------------------------------------------------------------------------
1036 // Static helper functions.
1037
1038 // Generate an Operand for loading a field from an object.
1039 inline Operand FieldOperand(Register object, int offset) {
1040   return Operand(object, offset - kHeapObjectTag);
1041 }
1042
1043
1044 // Generate an Operand for loading an indexed field from an object.
1045 inline Operand FieldOperand(Register object,
1046                             Register index,
1047                             ScaleFactor scale,
1048                             int offset) {
1049   return Operand(object, index, scale, offset - kHeapObjectTag);
1050 }
1051
1052
1053 inline Operand FixedArrayElementOperand(Register array,
1054                                         Register index_as_smi,
1055                                         int additional_offset = 0) {
1056   int offset = FixedArray::kHeaderSize + additional_offset * kPointerSize;
1057   return FieldOperand(array, index_as_smi, times_half_pointer_size, offset);
1058 }
1059
1060
1061 inline Operand ContextOperand(Register context, int index) {
1062   return Operand(context, Context::SlotOffset(index));
1063 }
1064
1065
1066 inline Operand GlobalObjectOperand() {
1067   return ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX);
1068 }
1069
1070
1071 // Generates an Operand for saving parameters after PrepareCallApiFunction.
1072 Operand ApiParameterOperand(int index);
1073
1074
1075 #ifdef GENERATED_CODE_COVERAGE
1076 extern void LogGeneratedCodeCoverage(const char* file_line);
1077 #define CODE_COVERAGE_STRINGIFY(x) #x
1078 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1079 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1080 #define ACCESS_MASM(masm) {                                               \
1081     byte* ia32_coverage_function =                                        \
1082         reinterpret_cast<byte*>(FUNCTION_ADDR(LogGeneratedCodeCoverage)); \
1083     masm->pushfd();                                                       \
1084     masm->pushad();                                                       \
1085     masm->push(Immediate(reinterpret_cast<int>(&__FILE_LINE__)));         \
1086     masm->call(ia32_coverage_function, RelocInfo::RUNTIME_ENTRY);         \
1087     masm->pop(eax);                                                       \
1088     masm->popad();                                                        \
1089     masm->popfd();                                                        \
1090   }                                                                       \
1091   masm->
1092 #else
1093 #define ACCESS_MASM(masm) masm->
1094 #endif
1095
1096
1097 } }  // namespace v8::internal
1098
1099 #endif  // V8_IA32_MACRO_ASSEMBLER_IA32_H_