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