Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / 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 float32x4 or int32x4 object in new space with undefined value.
624   // Returns tagged pointer in result register, or jumps to gc_required if new
625   // space is full.
626   void AllocateSIMDHeapObject(int size,
627                               Register result,
628                               Register scratch,
629                               Label* gc_required,
630                               Heap::RootListIndex map_index);
631
632   // Allocate a sequential string. All the header fields of the string object
633   // are initialized.
634   void AllocateTwoByteString(Register result,
635                              Register length,
636                              Register scratch1,
637                              Register scratch2,
638                              Register scratch3,
639                              Label* gc_required);
640   void AllocateAsciiString(Register result,
641                            Register length,
642                            Register scratch1,
643                            Register scratch2,
644                            Register scratch3,
645                            Label* gc_required);
646   void AllocateAsciiString(Register result,
647                            int length,
648                            Register scratch1,
649                            Register scratch2,
650                            Label* gc_required);
651
652   // Allocate a raw cons string object. Only the map field of the result is
653   // initialized.
654   void AllocateTwoByteConsString(Register result,
655                           Register scratch1,
656                           Register scratch2,
657                           Label* gc_required);
658   void AllocateAsciiConsString(Register result,
659                                Register scratch1,
660                                Register scratch2,
661                                Label* gc_required);
662
663   // Allocate a raw sliced string object. Only the map field of the result is
664   // initialized.
665   void AllocateTwoByteSlicedString(Register result,
666                             Register scratch1,
667                             Register scratch2,
668                             Label* gc_required);
669   void AllocateAsciiSlicedString(Register result,
670                                  Register scratch1,
671                                  Register scratch2,
672                                  Label* gc_required);
673
674   // Copy memory, byte-by-byte, from source to destination.  Not optimized for
675   // long or aligned copies.
676   // The contents of index and scratch are destroyed.
677   void CopyBytes(Register source,
678                  Register destination,
679                  Register length,
680                  Register scratch);
681
682   // Initialize fields with filler values.  Fields starting at |start_offset|
683   // not including end_offset are overwritten with the value in |filler|.  At
684   // the end the loop, |start_offset| takes the value of |end_offset|.
685   void InitializeFieldsWithFiller(Register start_offset,
686                                   Register end_offset,
687                                   Register filler);
688
689   // ---------------------------------------------------------------------------
690   // Support functions.
691
692   // Check a boolean-bit of a Smi field.
693   void BooleanBitTest(Register object, int field_offset, int bit_index);
694
695   // Check if result is zero and op is negative.
696   void NegativeZeroTest(Register result, Register op, Label* then_label);
697
698   // Check if result is zero and any of op1 and op2 are negative.
699   // Register scratch is destroyed, and it must be different from op2.
700   void NegativeZeroTest(Register result, Register op1, Register op2,
701                         Register scratch, Label* then_label);
702
703   // Try to get function prototype of a function and puts the value in
704   // the result register. Checks that the function really is a
705   // function and jumps to the miss label if the fast checks fail. The
706   // function register will be untouched; the other registers may be
707   // clobbered.
708   void TryGetFunctionPrototype(Register function,
709                                Register result,
710                                Register scratch,
711                                Label* miss,
712                                bool miss_on_bound_function = false);
713
714   // Generates code for reporting that an illegal operation has
715   // occurred.
716   void IllegalOperation(int num_arguments);
717
718   // Picks out an array index from the hash field.
719   // Register use:
720   //   hash - holds the index's hash. Clobbered.
721   //   index - holds the overwritten index on exit.
722   void IndexFromHash(Register hash, Register index);
723
724   // ---------------------------------------------------------------------------
725   // Runtime calls
726
727   // Call a code stub.  Generate the code if necessary.
728   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
729
730   // Tail call a code stub (jump).  Generate the code if necessary.
731   void TailCallStub(CodeStub* stub);
732
733   // Return from a code stub after popping its arguments.
734   void StubReturn(int argc);
735
736   // Call a runtime routine.
737   void CallRuntime(const Runtime::Function* f,
738                    int num_arguments,
739                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
740   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
741     const Runtime::Function* function = Runtime::FunctionForId(id);
742     CallRuntime(function, function->nargs, kSaveFPRegs);
743   }
744
745   // Convenience function: Same as above, but takes the fid instead.
746   void CallRuntime(Runtime::FunctionId id,
747                    int num_arguments,
748                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
749     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
750   }
751
752   // Convenience function: call an external reference.
753   void CallExternalReference(ExternalReference ref, int num_arguments);
754
755   // Tail call of a runtime routine (jump).
756   // Like JumpToExternalReference, but also takes care of passing the number
757   // of parameters.
758   void TailCallExternalReference(const ExternalReference& ext,
759                                  int num_arguments,
760                                  int result_size);
761
762   // Convenience function: tail call a runtime routine (jump).
763   void TailCallRuntime(Runtime::FunctionId fid,
764                        int num_arguments,
765                        int result_size);
766
767   // Before calling a C-function from generated code, align arguments on stack.
768   // After aligning the frame, arguments must be stored in esp[0], esp[4],
769   // etc., not pushed. The argument count assumes all arguments are word sized.
770   // Some compilers/platforms require the stack to be aligned when calling
771   // C++ code.
772   // Needs a scratch register to do some arithmetic. This register will be
773   // trashed.
774   void PrepareCallCFunction(int num_arguments, Register scratch);
775
776   // Calls a C function and cleans up the space for arguments allocated
777   // by PrepareCallCFunction. The called function is not allowed to trigger a
778   // garbage collection, since that might move the code and invalidate the
779   // return address (unless this is somehow accounted for by the called
780   // function).
781   void CallCFunction(ExternalReference function, int num_arguments);
782   void CallCFunction(Register function, int num_arguments);
783
784   // Prepares stack to put arguments (aligns and so on). Reserves
785   // space for return value if needed (assumes the return value is a handle).
786   // Arguments must be stored in ApiParameterOperand(0), ApiParameterOperand(1)
787   // etc. Saves context (esi). If space was reserved for return value then
788   // stores the pointer to the reserved slot into esi.
789   void PrepareCallApiFunction(int argc);
790
791   // Calls an API function.  Allocates HandleScope, extracts returned value
792   // from handle and propagates exceptions.  Clobbers ebx, edi and
793   // caller-save registers.  Restores context.  On return removes
794   // stack_space * kPointerSize (GCed).
795   void CallApiFunctionAndReturn(Register function_address,
796                                 ExternalReference thunk_ref,
797                                 Operand thunk_last_arg,
798                                 int stack_space,
799                                 Operand return_value_operand,
800                                 Operand* context_restore_operand);
801
802   // Jump to a runtime routine.
803   void JumpToExternalReference(const ExternalReference& ext);
804
805   // ---------------------------------------------------------------------------
806   // Utilities
807
808   void Ret();
809
810   // Return and drop arguments from stack, where the number of arguments
811   // may be bigger than 2^16 - 1.  Requires a scratch register.
812   void Ret(int bytes_dropped, Register scratch);
813
814   // Emit code to discard a non-negative number of pointer-sized elements
815   // from the stack, clobbering only the esp register.
816   void Drop(int element_count);
817
818   void Call(Label* target) { call(target); }
819   void Push(Register src) { push(src); }
820   void Pop(Register dst) { pop(dst); }
821
822   // Emit call to the code we are currently generating.
823   void CallSelf() {
824     Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
825     call(self, RelocInfo::CODE_TARGET);
826   }
827
828   // Move if the registers are not identical.
829   void Move(Register target, Register source);
830
831   // Move a constant into a destination using the most efficient encoding.
832   void Move(Register dst, const Immediate& x);
833   void Move(const Operand& dst, const Immediate& x);
834
835   // Move an immediate into an XMM register.
836   void Move(XMMRegister dst, double val);
837
838   // Push a handle value.
839   void Push(Handle<Object> handle) { push(Immediate(handle)); }
840   void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
841
842   Handle<Object> CodeObject() {
843     ASSERT(!code_object_.is_null());
844     return code_object_;
845   }
846
847   // Insert code to verify that the x87 stack has the specified depth (0-7)
848   void VerifyX87StackDepth(uint32_t depth);
849
850   // Emit code for a truncating division by a constant. The dividend register is
851   // unchanged, the result is in edx, and eax gets clobbered.
852   void TruncatingDiv(Register dividend, int32_t divisor);
853
854   // ---------------------------------------------------------------------------
855   // StatsCounter support
856
857   void SetCounter(StatsCounter* counter, int value);
858   void IncrementCounter(StatsCounter* counter, int value);
859   void DecrementCounter(StatsCounter* counter, int value);
860   void IncrementCounter(Condition cc, StatsCounter* counter, int value);
861   void DecrementCounter(Condition cc, StatsCounter* counter, int value);
862
863
864   // ---------------------------------------------------------------------------
865   // Debugging
866
867   // Calls Abort(msg) if the condition cc is not satisfied.
868   // Use --debug_code to enable.
869   void Assert(Condition cc, BailoutReason reason);
870
871   void AssertFastElements(Register elements);
872
873   // Like Assert(), but always enabled.
874   void Check(Condition cc, BailoutReason reason);
875
876   // Print a message to stdout and abort execution.
877   void Abort(BailoutReason reason);
878
879   // Check that the stack is aligned.
880   void CheckStackAlignment();
881
882   // Verify restrictions about code generated in stubs.
883   void set_generating_stub(bool value) { generating_stub_ = value; }
884   bool generating_stub() { return generating_stub_; }
885   void set_has_frame(bool value) { has_frame_ = value; }
886   bool has_frame() { return has_frame_; }
887   inline bool AllowThisStubCall(CodeStub* stub);
888
889   // ---------------------------------------------------------------------------
890   // SIMD macros.
891   void absps(XMMRegister dst);
892   void abspd(XMMRegister dst);
893   void negateps(XMMRegister dst);
894   void negatepd(XMMRegister dst);
895   void notps(XMMRegister dst);
896   void pnegd(XMMRegister dst);
897
898   // ---------------------------------------------------------------------------
899   // String utilities.
900
901   // Generate code to do a lookup in the number string cache. If the number in
902   // the register object is found in the cache the generated code falls through
903   // with the result in the result register. The object and the result register
904   // can be the same. If the number is not found in the cache the code jumps to
905   // the label not_found with only the content of register object unchanged.
906   void LookupNumberStringCache(Register object,
907                                Register result,
908                                Register scratch1,
909                                Register scratch2,
910                                Label* not_found);
911
912   // Check whether the instance type represents a flat ASCII string. Jump to the
913   // label if not. If the instance type can be scratched specify same register
914   // for both instance type and scratch.
915   void JumpIfInstanceTypeIsNotSequentialAscii(Register instance_type,
916                                               Register scratch,
917                                               Label* on_not_flat_ascii_string);
918
919   // Checks if both objects are sequential ASCII strings, and jumps to label
920   // if either is not.
921   void JumpIfNotBothSequentialAsciiStrings(Register object1,
922                                            Register object2,
923                                            Register scratch1,
924                                            Register scratch2,
925                                            Label* on_not_flat_ascii_strings);
926
927   // Checks if the given register or operand is a unique name
928   void JumpIfNotUniqueName(Register reg, Label* not_unique_name,
929                            Label::Distance distance = Label::kFar) {
930     JumpIfNotUniqueName(Operand(reg), not_unique_name, distance);
931   }
932
933   void JumpIfNotUniqueName(Operand operand, Label* not_unique_name,
934                            Label::Distance distance = Label::kFar);
935
936   void EmitSeqStringSetCharCheck(Register string,
937                                  Register index,
938                                  Register value,
939                                  uint32_t encoding_mask);
940
941   static int SafepointRegisterStackIndex(Register reg) {
942     return SafepointRegisterStackIndex(reg.code());
943   }
944
945   // Activation support.
946   void EnterFrame(StackFrame::Type type);
947   void LeaveFrame(StackFrame::Type type);
948
949   // Expects object in eax and returns map with validated enum cache
950   // in eax.  Assumes that any other register can be used as a scratch.
951   void CheckEnumCache(Label* call_runtime);
952
953   // AllocationMemento support. Arrays may have an associated
954   // AllocationMemento object that can be checked for in order to pretransition
955   // to another type.
956   // On entry, receiver_reg should point to the array object.
957   // scratch_reg gets clobbered.
958   // If allocation info is present, conditional code is set to equal.
959   void TestJSArrayForAllocationMemento(Register receiver_reg,
960                                        Register scratch_reg,
961                                        Label* no_memento_found);
962
963   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
964                                          Register scratch_reg,
965                                          Label* memento_found) {
966     Label no_memento_found;
967     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
968                                     &no_memento_found);
969     j(equal, memento_found);
970     bind(&no_memento_found);
971   }
972
973   // Jumps to found label if a prototype map has dictionary elements.
974   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
975                                         Register scratch1, Label* found);
976
977  private:
978   bool generating_stub_;
979   bool has_frame_;
980   // This handle will be patched with the code object on installation.
981   Handle<Object> code_object_;
982
983   // Helper functions for generating invokes.
984   void InvokePrologue(const ParameterCount& expected,
985                       const ParameterCount& actual,
986                       Handle<Code> code_constant,
987                       const Operand& code_operand,
988                       Label* done,
989                       bool* definitely_mismatches,
990                       InvokeFlag flag,
991                       Label::Distance done_distance,
992                       const CallWrapper& call_wrapper = NullCallWrapper());
993
994   void EnterExitFramePrologue();
995   void EnterExitFrameEpilogue(int argc, bool save_doubles);
996
997   void LeaveExitFrameEpilogue(bool restore_context);
998
999   // Allocation support helpers.
1000   void LoadAllocationTopHelper(Register result,
1001                                Register scratch,
1002                                AllocationFlags flags);
1003
1004   void UpdateAllocationTopHelper(Register result_end,
1005                                  Register scratch,
1006                                  AllocationFlags flags);
1007
1008   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
1009   void InNewSpace(Register object,
1010                   Register scratch,
1011                   Condition cc,
1012                   Label* condition_met,
1013                   Label::Distance condition_met_distance = Label::kFar);
1014
1015   // Helper for finding the mark bits for an address.  Afterwards, the
1016   // bitmap register points at the word with the mark bits and the mask
1017   // the position of the first bit.  Uses ecx as scratch and leaves addr_reg
1018   // unchanged.
1019   inline void GetMarkBits(Register addr_reg,
1020                           Register bitmap_reg,
1021                           Register mask_reg);
1022
1023   // Helper for throwing exceptions.  Compute a handler address and jump to
1024   // it.  See the implementation for register usage.
1025   void JumpToHandlerEntry();
1026
1027   // Compute memory operands for safepoint stack slots.
1028   Operand SafepointRegisterSlot(Register reg);
1029   static int SafepointRegisterStackIndex(int reg_code);
1030
1031   // Needs access to SafepointRegisterStackIndex for compiled frame
1032   // traversal.
1033   friend class StandardFrame;
1034 };
1035
1036
1037 // The code patcher is used to patch (typically) small parts of code e.g. for
1038 // debugging and other types of instrumentation. When using the code patcher
1039 // the exact number of bytes specified must be emitted. Is not legal to emit
1040 // relocation information. If any of these constraints are violated it causes
1041 // an assertion.
1042 class CodePatcher {
1043  public:
1044   CodePatcher(byte* address, int size);
1045   virtual ~CodePatcher();
1046
1047   // Macro assembler to emit code.
1048   MacroAssembler* masm() { return &masm_; }
1049
1050  private:
1051   byte* address_;  // The address of the code being patched.
1052   int size_;  // Number of bytes of the expected patch size.
1053   MacroAssembler masm_;  // Macro assembler used to generate the code.
1054 };
1055
1056
1057 // -----------------------------------------------------------------------------
1058 // Static helper functions.
1059
1060 // Generate an Operand for loading a field from an object.
1061 inline Operand FieldOperand(Register object, int offset) {
1062   return Operand(object, offset - kHeapObjectTag);
1063 }
1064
1065
1066 // Generate an Operand for loading an indexed field from an object.
1067 inline Operand FieldOperand(Register object,
1068                             Register index,
1069                             ScaleFactor scale,
1070                             int offset) {
1071   return Operand(object, index, scale, offset - kHeapObjectTag);
1072 }
1073
1074
1075 inline Operand FixedArrayElementOperand(Register array,
1076                                         Register index_as_smi,
1077                                         int additional_offset = 0) {
1078   int offset = FixedArray::kHeaderSize + additional_offset * kPointerSize;
1079   return FieldOperand(array, index_as_smi, times_half_pointer_size, offset);
1080 }
1081
1082
1083 inline Operand ContextOperand(Register context, int index) {
1084   return Operand(context, Context::SlotOffset(index));
1085 }
1086
1087
1088 inline Operand GlobalObjectOperand() {
1089   return ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX);
1090 }
1091
1092
1093 // Generates an Operand for saving parameters after PrepareCallApiFunction.
1094 Operand ApiParameterOperand(int index);
1095
1096
1097 #ifdef GENERATED_CODE_COVERAGE
1098 extern void LogGeneratedCodeCoverage(const char* file_line);
1099 #define CODE_COVERAGE_STRINGIFY(x) #x
1100 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1101 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1102 #define ACCESS_MASM(masm) {                                               \
1103     byte* ia32_coverage_function =                                        \
1104         reinterpret_cast<byte*>(FUNCTION_ADDR(LogGeneratedCodeCoverage)); \
1105     masm->pushfd();                                                       \
1106     masm->pushad();                                                       \
1107     masm->push(Immediate(reinterpret_cast<int>(&__FILE_LINE__)));         \
1108     masm->call(ia32_coverage_function, RelocInfo::RUNTIME_ENTRY);         \
1109     masm->pop(eax);                                                       \
1110     masm->popad();                                                        \
1111     masm->popfd();                                                        \
1112   }                                                                       \
1113   masm->
1114 #else
1115 #define ACCESS_MASM(masm) masm->
1116 #endif
1117
1118
1119 } }  // namespace v8::internal
1120
1121 #endif  // V8_IA32_MACRO_ASSEMBLER_IA32_H_