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