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