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