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