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