Merge remote-tracking branch 'origin/v0.10'
[platform/upstream/nodejs.git] / deps / 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 sequential string. All the header fields of the string object
656   // are initialized.
657   void AllocateTwoByteString(Register result,
658                              Register length,
659                              Register scratch1,
660                              Register scratch2,
661                              Register scratch3,
662                              Label* gc_required);
663   void AllocateAsciiString(Register result,
664                            Register length,
665                            Register scratch1,
666                            Register scratch2,
667                            Register scratch3,
668                            Label* gc_required);
669   void AllocateAsciiString(Register result,
670                            int length,
671                            Register scratch1,
672                            Register scratch2,
673                            Label* gc_required);
674
675   // Allocate a raw cons string object. Only the map field of the result is
676   // initialized.
677   void AllocateTwoByteConsString(Register result,
678                           Register scratch1,
679                           Register scratch2,
680                           Label* gc_required);
681   void AllocateAsciiConsString(Register result,
682                                Register scratch1,
683                                Register scratch2,
684                                Label* gc_required);
685
686   // Allocate a raw sliced string object. Only the map field of the result is
687   // initialized.
688   void AllocateTwoByteSlicedString(Register result,
689                             Register scratch1,
690                             Register scratch2,
691                             Label* gc_required);
692   void AllocateAsciiSlicedString(Register result,
693                                  Register scratch1,
694                                  Register scratch2,
695                                  Label* gc_required);
696
697   // Copy memory, byte-by-byte, from source to destination.  Not optimized for
698   // long or aligned copies.
699   // The contents of index and scratch are destroyed.
700   void CopyBytes(Register source,
701                  Register destination,
702                  Register length,
703                  Register scratch);
704
705   // Initialize fields with filler values.  Fields starting at |start_offset|
706   // not including end_offset are overwritten with the value in |filler|.  At
707   // the end the loop, |start_offset| takes the value of |end_offset|.
708   void InitializeFieldsWithFiller(Register start_offset,
709                                   Register end_offset,
710                                   Register filler);
711
712   // ---------------------------------------------------------------------------
713   // Support functions.
714
715   // Check a boolean-bit of a Smi field.
716   void BooleanBitTest(Register object, int field_offset, int bit_index);
717
718   // Check if result is zero and op is negative.
719   void NegativeZeroTest(Register result, Register op, Label* then_label);
720
721   // Check if result is zero and any of op1 and op2 are negative.
722   // Register scratch is destroyed, and it must be different from op2.
723   void NegativeZeroTest(Register result, Register op1, Register op2,
724                         Register scratch, Label* then_label);
725
726   // Try to get function prototype of a function and puts the value in
727   // the result register. Checks that the function really is a
728   // function and jumps to the miss label if the fast checks fail. The
729   // function register will be untouched; the other registers may be
730   // clobbered.
731   void TryGetFunctionPrototype(Register function,
732                                Register result,
733                                Register scratch,
734                                Label* miss,
735                                bool miss_on_bound_function = false);
736
737   // Generates code for reporting that an illegal operation has
738   // occurred.
739   void IllegalOperation(int num_arguments);
740
741   // Picks out an array index from the hash field.
742   // Register use:
743   //   hash - holds the index's hash. Clobbered.
744   //   index - holds the overwritten index on exit.
745   void IndexFromHash(Register hash, Register index);
746
747   // ---------------------------------------------------------------------------
748   // Runtime calls
749
750   // Call a code stub.  Generate the code if necessary.
751   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
752
753   // Tail call a code stub (jump).  Generate the code if necessary.
754   void TailCallStub(CodeStub* stub);
755
756   // Return from a code stub after popping its arguments.
757   void StubReturn(int argc);
758
759   // Call a runtime routine.
760   void CallRuntime(const Runtime::Function* f,
761                    int num_arguments,
762                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
763   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
764     const Runtime::Function* function = Runtime::FunctionForId(id);
765     CallRuntime(function, function->nargs, kSaveFPRegs);
766   }
767
768   // Convenience function: Same as above, but takes the fid instead.
769   void CallRuntime(Runtime::FunctionId id,
770                    int num_arguments,
771                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
772     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
773   }
774
775   // Convenience function: call an external reference.
776   void CallExternalReference(ExternalReference ref, int num_arguments);
777
778   // Tail call of a runtime routine (jump).
779   // Like JumpToExternalReference, but also takes care of passing the number
780   // of parameters.
781   void TailCallExternalReference(const ExternalReference& ext,
782                                  int num_arguments,
783                                  int result_size);
784
785   // Convenience function: tail call a runtime routine (jump).
786   void TailCallRuntime(Runtime::FunctionId fid,
787                        int num_arguments,
788                        int result_size);
789
790   // Before calling a C-function from generated code, align arguments on stack.
791   // After aligning the frame, arguments must be stored in esp[0], esp[4],
792   // etc., not pushed. The argument count assumes all arguments are word sized.
793   // Some compilers/platforms require the stack to be aligned when calling
794   // C++ code.
795   // Needs a scratch register to do some arithmetic. This register will be
796   // trashed.
797   void PrepareCallCFunction(int num_arguments, Register scratch);
798
799   // Calls a C function and cleans up the space for arguments allocated
800   // by PrepareCallCFunction. The called function is not allowed to trigger a
801   // garbage collection, since that might move the code and invalidate the
802   // return address (unless this is somehow accounted for by the called
803   // function).
804   void CallCFunction(ExternalReference function, int num_arguments);
805   void CallCFunction(Register function, int num_arguments);
806
807   // Prepares stack to put arguments (aligns and so on). Reserves
808   // space for return value if needed (assumes the return value is a handle).
809   // Arguments must be stored in ApiParameterOperand(0), ApiParameterOperand(1)
810   // etc. Saves context (esi). If space was reserved for return value then
811   // stores the pointer to the reserved slot into esi.
812   void PrepareCallApiFunction(int argc);
813
814   // Calls an API function.  Allocates HandleScope, extracts returned value
815   // from handle and propagates exceptions.  Clobbers ebx, edi and
816   // caller-save registers.  Restores context.  On return removes
817   // stack_space * kPointerSize (GCed).
818   void CallApiFunctionAndReturn(Register function_address,
819                                 Address thunk_address,
820                                 Operand thunk_last_arg,
821                                 int stack_space,
822                                 Operand return_value_operand,
823                                 Operand* context_restore_operand);
824
825   // Jump to a runtime routine.
826   void JumpToExternalReference(const ExternalReference& ext);
827
828   // ---------------------------------------------------------------------------
829   // Utilities
830
831   void Ret();
832
833   // Return and drop arguments from stack, where the number of arguments
834   // may be bigger than 2^16 - 1.  Requires a scratch register.
835   void Ret(int bytes_dropped, Register scratch);
836
837   // Emit code to discard a non-negative number of pointer-sized elements
838   // from the stack, clobbering only the esp register.
839   void Drop(int element_count);
840
841   void Call(Label* target) { call(target); }
842   void Push(Register src) { push(src); }
843   void Pop(Register dst) { pop(dst); }
844
845   // Emit call to the code we are currently generating.
846   void CallSelf() {
847     Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
848     call(self, RelocInfo::CODE_TARGET);
849   }
850
851   // Move if the registers are not identical.
852   void Move(Register target, Register source);
853
854   // Push a handle value.
855   void Push(Handle<Object> handle) { push(Immediate(handle)); }
856   void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
857
858   Handle<Object> CodeObject() {
859     ASSERT(!code_object_.is_null());
860     return code_object_;
861   }
862
863   // Insert code to verify that the x87 stack has the specified depth (0-7)
864   void VerifyX87StackDepth(uint32_t depth);
865
866   // ---------------------------------------------------------------------------
867   // StatsCounter support
868
869   void SetCounter(StatsCounter* counter, int value);
870   void IncrementCounter(StatsCounter* counter, int value);
871   void DecrementCounter(StatsCounter* counter, int value);
872   void IncrementCounter(Condition cc, StatsCounter* counter, int value);
873   void DecrementCounter(Condition cc, StatsCounter* counter, int value);
874
875
876   // ---------------------------------------------------------------------------
877   // Debugging
878
879   // Calls Abort(msg) if the condition cc is not satisfied.
880   // Use --debug_code to enable.
881   void Assert(Condition cc, BailoutReason reason);
882
883   void AssertFastElements(Register elements);
884
885   // Like Assert(), but always enabled.
886   void Check(Condition cc, BailoutReason reason);
887
888   // Print a message to stdout and abort execution.
889   void Abort(BailoutReason reason);
890
891   // Check that the stack is aligned.
892   void CheckStackAlignment();
893
894   // Verify restrictions about code generated in stubs.
895   void set_generating_stub(bool value) { generating_stub_ = value; }
896   bool generating_stub() { return generating_stub_; }
897   void set_has_frame(bool value) { has_frame_ = value; }
898   bool has_frame() { return has_frame_; }
899   inline bool AllowThisStubCall(CodeStub* stub);
900
901   // ---------------------------------------------------------------------------
902   // String utilities.
903
904   // Generate code to do a lookup in the number string cache. If the number in
905   // the register object is found in the cache the generated code falls through
906   // with the result in the result register. The object and the result register
907   // can be the same. If the number is not found in the cache the code jumps to
908   // the label not_found with only the content of register object unchanged.
909   void LookupNumberStringCache(Register object,
910                                Register result,
911                                Register scratch1,
912                                Register scratch2,
913                                Label* not_found);
914
915   // Check whether the instance type represents a flat ASCII string. Jump to the
916   // label if not. If the instance type can be scratched specify same register
917   // for both instance type and scratch.
918   void JumpIfInstanceTypeIsNotSequentialAscii(Register instance_type,
919                                               Register scratch,
920                                               Label* on_not_flat_ascii_string);
921
922   // Checks if both objects are sequential ASCII strings, and jumps to label
923   // if either is not.
924   void JumpIfNotBothSequentialAsciiStrings(Register object1,
925                                            Register object2,
926                                            Register scratch1,
927                                            Register scratch2,
928                                            Label* on_not_flat_ascii_strings);
929
930   // Checks if the given register or operand is a unique name
931   void JumpIfNotUniqueName(Register reg, Label* not_unique_name,
932                            Label::Distance distance = Label::kFar) {
933     JumpIfNotUniqueName(Operand(reg), not_unique_name, distance);
934   }
935
936   void JumpIfNotUniqueName(Operand operand, Label* not_unique_name,
937                            Label::Distance distance = Label::kFar);
938
939   void EmitSeqStringSetCharCheck(Register string,
940                                  Register index,
941                                  Register value,
942                                  uint32_t encoding_mask);
943
944   static int SafepointRegisterStackIndex(Register reg) {
945     return SafepointRegisterStackIndex(reg.code());
946   }
947
948   // Activation support.
949   void EnterFrame(StackFrame::Type type);
950   void LeaveFrame(StackFrame::Type type);
951
952   // Expects object in eax and returns map with validated enum cache
953   // in eax.  Assumes that any other register can be used as a scratch.
954   void CheckEnumCache(Label* call_runtime);
955
956   // AllocationMemento support. Arrays may have an associated
957   // AllocationMemento object that can be checked for in order to pretransition
958   // to another type.
959   // On entry, receiver_reg should point to the array object.
960   // scratch_reg gets clobbered.
961   // If allocation info is present, conditional code is set to equal.
962   void TestJSArrayForAllocationMemento(Register receiver_reg,
963                                        Register scratch_reg,
964                                        Label* no_memento_found);
965
966   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
967                                          Register scratch_reg,
968                                          Label* memento_found) {
969     Label no_memento_found;
970     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
971                                     &no_memento_found);
972     j(equal, memento_found);
973     bind(&no_memento_found);
974   }
975
976   // Jumps to found label if a prototype map has dictionary elements.
977   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
978                                         Register scratch1, Label* found);
979
980  private:
981   bool generating_stub_;
982   bool has_frame_;
983   // This handle will be patched with the code object on installation.
984   Handle<Object> code_object_;
985
986   // Helper functions for generating invokes.
987   void InvokePrologue(const ParameterCount& expected,
988                       const ParameterCount& actual,
989                       Handle<Code> code_constant,
990                       const Operand& code_operand,
991                       Label* done,
992                       bool* definitely_mismatches,
993                       InvokeFlag flag,
994                       Label::Distance done_distance,
995                       const CallWrapper& call_wrapper = NullCallWrapper());
996
997   void EnterExitFramePrologue();
998   void EnterExitFrameEpilogue(int argc, bool save_doubles);
999
1000   void LeaveExitFrameEpilogue(bool restore_context);
1001
1002   // Allocation support helpers.
1003   void LoadAllocationTopHelper(Register result,
1004                                Register scratch,
1005                                AllocationFlags flags);
1006
1007   void UpdateAllocationTopHelper(Register result_end,
1008                                  Register scratch,
1009                                  AllocationFlags flags);
1010
1011   // Helper for PopHandleScope.  Allowed to perform a GC and returns
1012   // NULL if gc_allowed.  Does not perform a GC if !gc_allowed, and
1013   // possibly returns a failure object indicating an allocation failure.
1014   MUST_USE_RESULT MaybeObject* PopHandleScopeHelper(Register saved,
1015                                                     Register scratch,
1016                                                     bool gc_allowed);
1017
1018   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
1019   void InNewSpace(Register object,
1020                   Register scratch,
1021                   Condition cc,
1022                   Label* condition_met,
1023                   Label::Distance condition_met_distance = Label::kFar);
1024
1025   // Helper for finding the mark bits for an address.  Afterwards, the
1026   // bitmap register points at the word with the mark bits and the mask
1027   // the position of the first bit.  Uses ecx as scratch and leaves addr_reg
1028   // unchanged.
1029   inline void GetMarkBits(Register addr_reg,
1030                           Register bitmap_reg,
1031                           Register mask_reg);
1032
1033   // Helper for throwing exceptions.  Compute a handler address and jump to
1034   // it.  See the implementation for register usage.
1035   void JumpToHandlerEntry();
1036
1037   // Compute memory operands for safepoint stack slots.
1038   Operand SafepointRegisterSlot(Register reg);
1039   static int SafepointRegisterStackIndex(int reg_code);
1040
1041   // Needs access to SafepointRegisterStackIndex for compiled frame
1042   // traversal.
1043   friend class StandardFrame;
1044 };
1045
1046
1047 // The code patcher is used to patch (typically) small parts of code e.g. for
1048 // debugging and other types of instrumentation. When using the code patcher
1049 // the exact number of bytes specified must be emitted. Is not legal to emit
1050 // relocation information. If any of these constraints are violated it causes
1051 // an assertion.
1052 class CodePatcher {
1053  public:
1054   CodePatcher(byte* address, int size);
1055   virtual ~CodePatcher();
1056
1057   // Macro assembler to emit code.
1058   MacroAssembler* masm() { return &masm_; }
1059
1060  private:
1061   byte* address_;  // The address of the code being patched.
1062   int size_;  // Number of bytes of the expected patch size.
1063   MacroAssembler masm_;  // Macro assembler used to generate the code.
1064 };
1065
1066
1067 // -----------------------------------------------------------------------------
1068 // Static helper functions.
1069
1070 // Generate an Operand for loading a field from an object.
1071 inline Operand FieldOperand(Register object, int offset) {
1072   return Operand(object, offset - kHeapObjectTag);
1073 }
1074
1075
1076 // Generate an Operand for loading an indexed field from an object.
1077 inline Operand FieldOperand(Register object,
1078                             Register index,
1079                             ScaleFactor scale,
1080                             int offset) {
1081   return Operand(object, index, scale, offset - kHeapObjectTag);
1082 }
1083
1084
1085 inline Operand FixedArrayElementOperand(Register array,
1086                                         Register index_as_smi,
1087                                         int additional_offset = 0) {
1088   int offset = FixedArray::kHeaderSize + additional_offset * kPointerSize;
1089   return FieldOperand(array, index_as_smi, times_half_pointer_size, offset);
1090 }
1091
1092
1093 inline Operand ContextOperand(Register context, int index) {
1094   return Operand(context, Context::SlotOffset(index));
1095 }
1096
1097
1098 inline Operand GlobalObjectOperand() {
1099   return ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX);
1100 }
1101
1102
1103 // Generates an Operand for saving parameters after PrepareCallApiFunction.
1104 Operand ApiParameterOperand(int index);
1105
1106
1107 #ifdef GENERATED_CODE_COVERAGE
1108 extern void LogGeneratedCodeCoverage(const char* file_line);
1109 #define CODE_COVERAGE_STRINGIFY(x) #x
1110 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1111 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1112 #define ACCESS_MASM(masm) {                                               \
1113     byte* ia32_coverage_function =                                        \
1114         reinterpret_cast<byte*>(FUNCTION_ADDR(LogGeneratedCodeCoverage)); \
1115     masm->pushfd();                                                       \
1116     masm->pushad();                                                       \
1117     masm->push(Immediate(reinterpret_cast<int>(&__FILE_LINE__)));         \
1118     masm->call(ia32_coverage_function, RelocInfo::RUNTIME_ENTRY);         \
1119     masm->pop(eax);                                                       \
1120     masm->popad();                                                        \
1121     masm->popfd();                                                        \
1122   }                                                                       \
1123   masm->
1124 #else
1125 #define ACCESS_MASM(masm) masm->
1126 #endif
1127
1128
1129 } }  // namespace v8::internal
1130
1131 #endif  // V8_IA32_MACRO_ASSEMBLER_IA32_H_