deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / x87 / assembler-x87.h
1 // Copyright (c) 1994-2006 Sun Microsystems Inc.
2 // All Rights Reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // - Redistributions of source code must retain the above copyright notice,
9 // this list of conditions and the following disclaimer.
10 //
11 // - Redistribution in binary form must reproduce the above copyright
12 // notice, this list of conditions and the following disclaimer in the
13 // documentation and/or other materials provided with the distribution.
14 //
15 // - Neither the name of Sun Microsystems or the names of contributors may
16 // be used to endorse or promote products derived from this software without
17 // specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // The original source code covered by the above license above has been
32 // modified significantly by Google Inc.
33 // Copyright 2011 the V8 project authors. All rights reserved.
34
35 // A light-weight IA32 Assembler.
36
37 #ifndef V8_X87_ASSEMBLER_X87_H_
38 #define V8_X87_ASSEMBLER_X87_H_
39
40 #include <deque>
41
42 #include "src/assembler.h"
43 #include "src/compiler.h"
44 #include "src/isolate.h"
45
46 namespace v8 {
47 namespace internal {
48
49 // CPU Registers.
50 //
51 // 1) We would prefer to use an enum, but enum values are assignment-
52 // compatible with int, which has caused code-generation bugs.
53 //
54 // 2) We would prefer to use a class instead of a struct but we don't like
55 // the register initialization to depend on the particular initialization
56 // order (which appears to be different on OS X, Linux, and Windows for the
57 // installed versions of C++ we tried). Using a struct permits C-style
58 // "initialization". Also, the Register objects cannot be const as this
59 // forces initialization stubs in MSVC, making us dependent on initialization
60 // order.
61 //
62 // 3) By not using an enum, we are possibly preventing the compiler from
63 // doing certain constant folds, which may significantly reduce the
64 // code generated for some assembly instructions (because they boil down
65 // to a few constants). If this is a problem, we could change the code
66 // such that we use an enum in optimized mode, and the struct in debug
67 // mode. This way we get the compile-time error checking in debug mode
68 // and best performance in optimized code.
69 //
70 struct Register {
71   static const int kMaxNumAllocatableRegisters = 6;
72   static int NumAllocatableRegisters() {
73     return kMaxNumAllocatableRegisters;
74   }
75   static const int kNumRegisters = 8;
76
77   static inline const char* AllocationIndexToString(int index);
78
79   static inline int ToAllocationIndex(Register reg);
80
81   static inline Register FromAllocationIndex(int index);
82
83   static Register from_code(int code) {
84     DCHECK(code >= 0);
85     DCHECK(code < kNumRegisters);
86     Register r = { code };
87     return r;
88   }
89   bool is_valid() const { return 0 <= code_ && code_ < kNumRegisters; }
90   bool is(Register reg) const { return code_ == reg.code_; }
91   // eax, ebx, ecx and edx are byte registers, the rest are not.
92   bool is_byte_register() const { return code_ <= 3; }
93   int code() const {
94     DCHECK(is_valid());
95     return code_;
96   }
97   int bit() const {
98     DCHECK(is_valid());
99     return 1 << code_;
100   }
101
102   // Unfortunately we can't make this private in a struct.
103   int code_;
104 };
105
106 const int kRegister_eax_Code = 0;
107 const int kRegister_ecx_Code = 1;
108 const int kRegister_edx_Code = 2;
109 const int kRegister_ebx_Code = 3;
110 const int kRegister_esp_Code = 4;
111 const int kRegister_ebp_Code = 5;
112 const int kRegister_esi_Code = 6;
113 const int kRegister_edi_Code = 7;
114 const int kRegister_no_reg_Code = -1;
115
116 const Register eax = { kRegister_eax_Code };
117 const Register ecx = { kRegister_ecx_Code };
118 const Register edx = { kRegister_edx_Code };
119 const Register ebx = { kRegister_ebx_Code };
120 const Register esp = { kRegister_esp_Code };
121 const Register ebp = { kRegister_ebp_Code };
122 const Register esi = { kRegister_esi_Code };
123 const Register edi = { kRegister_edi_Code };
124 const Register no_reg = { kRegister_no_reg_Code };
125
126
127 inline const char* Register::AllocationIndexToString(int index) {
128   DCHECK(index >= 0 && index < kMaxNumAllocatableRegisters);
129   // This is the mapping of allocation indices to registers.
130   const char* const kNames[] = { "eax", "ecx", "edx", "ebx", "esi", "edi" };
131   return kNames[index];
132 }
133
134
135 inline int Register::ToAllocationIndex(Register reg) {
136   DCHECK(reg.is_valid() && !reg.is(esp) && !reg.is(ebp));
137   return (reg.code() >= 6) ? reg.code() - 2 : reg.code();
138 }
139
140
141 inline Register Register::FromAllocationIndex(int index)  {
142   DCHECK(index >= 0 && index < kMaxNumAllocatableRegisters);
143   return (index >= 4) ? from_code(index + 2) : from_code(index);
144 }
145
146
147 struct X87Register {
148   static const int kMaxNumAllocatableRegisters = 6;
149   static const int kMaxNumRegisters = 8;
150   static int NumAllocatableRegisters() {
151     return kMaxNumAllocatableRegisters;
152   }
153
154
155   // TODO(turbofan): Proper support for float32.
156   static int NumAllocatableAliasedRegisters() {
157     return NumAllocatableRegisters();
158   }
159
160
161   static int ToAllocationIndex(X87Register reg) {
162     return reg.code_;
163   }
164
165   static const char* AllocationIndexToString(int index) {
166     DCHECK(index >= 0 && index < kMaxNumAllocatableRegisters);
167     const char* const names[] = {
168       "stX_0", "stX_1", "stX_2", "stX_3", "stX_4",
169       "stX_5", "stX_6", "stX_7"
170     };
171     return names[index];
172   }
173
174   static X87Register FromAllocationIndex(int index) {
175     DCHECK(index >= 0 && index < kMaxNumAllocatableRegisters);
176     X87Register result;
177     result.code_ = index;
178     return result;
179   }
180
181   bool is_valid() const {
182     return 0 <= code_ && code_ < kMaxNumRegisters;
183   }
184
185   int code() const {
186     DCHECK(is_valid());
187     return code_;
188   }
189
190   bool is(X87Register reg) const {
191     return code_ == reg.code_;
192   }
193
194   int code_;
195 };
196
197
198 typedef X87Register DoubleRegister;
199
200
201 const X87Register stX_0 = { 0 };
202 const X87Register stX_1 = { 1 };
203 const X87Register stX_2 = { 2 };
204 const X87Register stX_3 = { 3 };
205 const X87Register stX_4 = { 4 };
206 const X87Register stX_5 = { 5 };
207 const X87Register stX_6 = { 6 };
208 const X87Register stX_7 = { 7 };
209
210
211 enum Condition {
212   // any value < 0 is considered no_condition
213   no_condition  = -1,
214
215   overflow      =  0,
216   no_overflow   =  1,
217   below         =  2,
218   above_equal   =  3,
219   equal         =  4,
220   not_equal     =  5,
221   below_equal   =  6,
222   above         =  7,
223   negative      =  8,
224   positive      =  9,
225   parity_even   = 10,
226   parity_odd    = 11,
227   less          = 12,
228   greater_equal = 13,
229   less_equal    = 14,
230   greater       = 15,
231
232   // aliases
233   carry         = below,
234   not_carry     = above_equal,
235   zero          = equal,
236   not_zero      = not_equal,
237   sign          = negative,
238   not_sign      = positive
239 };
240
241
242 // Returns the equivalent of !cc.
243 // Negation of the default no_condition (-1) results in a non-default
244 // no_condition value (-2). As long as tests for no_condition check
245 // for condition < 0, this will work as expected.
246 inline Condition NegateCondition(Condition cc) {
247   return static_cast<Condition>(cc ^ 1);
248 }
249
250
251 // Commute a condition such that {a cond b == b cond' a}.
252 inline Condition CommuteCondition(Condition cc) {
253   switch (cc) {
254     case below:
255       return above;
256     case above:
257       return below;
258     case above_equal:
259       return below_equal;
260     case below_equal:
261       return above_equal;
262     case less:
263       return greater;
264     case greater:
265       return less;
266     case greater_equal:
267       return less_equal;
268     case less_equal:
269       return greater_equal;
270     default:
271       return cc;
272   }
273 }
274
275
276 // -----------------------------------------------------------------------------
277 // Machine instruction Immediates
278
279 class Immediate BASE_EMBEDDED {
280  public:
281   inline explicit Immediate(int x);
282   inline explicit Immediate(const ExternalReference& ext);
283   inline explicit Immediate(Handle<Object> handle);
284   inline explicit Immediate(Smi* value);
285   inline explicit Immediate(Address addr);
286
287   static Immediate CodeRelativeOffset(Label* label) {
288     return Immediate(label);
289   }
290
291   bool is_zero() const { return x_ == 0 && RelocInfo::IsNone(rmode_); }
292   bool is_int8() const {
293     return -128 <= x_ && x_ < 128 && RelocInfo::IsNone(rmode_);
294   }
295   bool is_int16() const {
296     return -32768 <= x_ && x_ < 32768 && RelocInfo::IsNone(rmode_);
297   }
298
299  private:
300   inline explicit Immediate(Label* value);
301
302   int x_;
303   RelocInfo::Mode rmode_;
304
305   friend class Operand;
306   friend class Assembler;
307   friend class MacroAssembler;
308 };
309
310
311 // -----------------------------------------------------------------------------
312 // Machine instruction Operands
313
314 enum ScaleFactor {
315   times_1 = 0,
316   times_2 = 1,
317   times_4 = 2,
318   times_8 = 3,
319   times_int_size = times_4,
320   times_half_pointer_size = times_2,
321   times_pointer_size = times_4,
322   times_twice_pointer_size = times_8
323 };
324
325
326 class Operand BASE_EMBEDDED {
327  public:
328   // reg
329   INLINE(explicit Operand(Register reg));
330
331   // [disp/r]
332   INLINE(explicit Operand(int32_t disp, RelocInfo::Mode rmode));
333
334   // [disp/r]
335   INLINE(explicit Operand(Immediate imm));
336
337   // [base + disp/r]
338   explicit Operand(Register base, int32_t disp,
339                    RelocInfo::Mode rmode = RelocInfo::NONE32);
340
341   // [base + index*scale + disp/r]
342   explicit Operand(Register base,
343                    Register index,
344                    ScaleFactor scale,
345                    int32_t disp,
346                    RelocInfo::Mode rmode = RelocInfo::NONE32);
347
348   // [index*scale + disp/r]
349   explicit Operand(Register index,
350                    ScaleFactor scale,
351                    int32_t disp,
352                    RelocInfo::Mode rmode = RelocInfo::NONE32);
353
354   static Operand JumpTable(Register index, ScaleFactor scale, Label* table) {
355     return Operand(index, scale, reinterpret_cast<int32_t>(table),
356                    RelocInfo::INTERNAL_REFERENCE);
357   }
358
359   static Operand StaticVariable(const ExternalReference& ext) {
360     return Operand(reinterpret_cast<int32_t>(ext.address()),
361                    RelocInfo::EXTERNAL_REFERENCE);
362   }
363
364   static Operand StaticArray(Register index,
365                              ScaleFactor scale,
366                              const ExternalReference& arr) {
367     return Operand(index, scale, reinterpret_cast<int32_t>(arr.address()),
368                    RelocInfo::EXTERNAL_REFERENCE);
369   }
370
371   static Operand ForCell(Handle<Cell> cell) {
372     AllowDeferredHandleDereference embedding_raw_address;
373     return Operand(reinterpret_cast<int32_t>(cell.location()),
374                    RelocInfo::CELL);
375   }
376
377   static Operand ForRegisterPlusImmediate(Register base, Immediate imm) {
378     return Operand(base, imm.x_, imm.rmode_);
379   }
380
381   // Returns true if this Operand is a wrapper for the specified register.
382   bool is_reg(Register reg) const;
383
384   // Returns true if this Operand is a wrapper for one register.
385   bool is_reg_only() const;
386
387   // Asserts that this Operand is a wrapper for one register and returns the
388   // register.
389   Register reg() const;
390
391  private:
392   // Set the ModRM byte without an encoded 'reg' register. The
393   // register is encoded later as part of the emit_operand operation.
394   inline void set_modrm(int mod, Register rm);
395
396   inline void set_sib(ScaleFactor scale, Register index, Register base);
397   inline void set_disp8(int8_t disp);
398   inline void set_dispr(int32_t disp, RelocInfo::Mode rmode);
399
400   byte buf_[6];
401   // The number of bytes in buf_.
402   unsigned int len_;
403   // Only valid if len_ > 4.
404   RelocInfo::Mode rmode_;
405
406   friend class Assembler;
407   friend class MacroAssembler;
408 };
409
410
411 // -----------------------------------------------------------------------------
412 // A Displacement describes the 32bit immediate field of an instruction which
413 // may be used together with a Label in order to refer to a yet unknown code
414 // position. Displacements stored in the instruction stream are used to describe
415 // the instruction and to chain a list of instructions using the same Label.
416 // A Displacement contains 2 different fields:
417 //
418 // next field: position of next displacement in the chain (0 = end of list)
419 // type field: instruction type
420 //
421 // A next value of null (0) indicates the end of a chain (note that there can
422 // be no displacement at position zero, because there is always at least one
423 // instruction byte before the displacement).
424 //
425 // Displacement _data field layout
426 //
427 // |31.....2|1......0|
428 // [  next  |  type  |
429
430 class Displacement BASE_EMBEDDED {
431  public:
432   enum Type { UNCONDITIONAL_JUMP, CODE_RELATIVE, OTHER, CODE_ABSOLUTE };
433
434   int data() const { return data_; }
435   Type type() const { return TypeField::decode(data_); }
436   void next(Label* L) const {
437     int n = NextField::decode(data_);
438     n > 0 ? L->link_to(n) : L->Unuse();
439   }
440   void link_to(Label* L) { init(L, type()); }
441
442   explicit Displacement(int data) { data_ = data; }
443
444   Displacement(Label* L, Type type) { init(L, type); }
445
446   void print() {
447     PrintF("%s (%x) ", (type() == UNCONDITIONAL_JUMP ? "jmp" : "[other]"),
448                        NextField::decode(data_));
449   }
450
451  private:
452   int data_;
453
454   class TypeField: public BitField<Type, 0, 2> {};
455   class NextField: public BitField<int,  2, 32-2> {};
456
457   void init(Label* L, Type type);
458 };
459
460
461 class Assembler : public AssemblerBase {
462  private:
463   // We check before assembling an instruction that there is sufficient
464   // space to write an instruction and its relocation information.
465   // The relocation writer's position must be kGap bytes above the end of
466   // the generated instructions. This leaves enough space for the
467   // longest possible ia32 instruction, 15 bytes, and the longest possible
468   // relocation information encoding, RelocInfoWriter::kMaxLength == 16.
469   // (There is a 15 byte limit on ia32 instruction length that rules out some
470   // otherwise valid instructions.)
471   // This allows for a single, fast space check per instruction.
472   static const int kGap = 32;
473
474  public:
475   // Create an assembler. Instructions and relocation information are emitted
476   // into a buffer, with the instructions starting from the beginning and the
477   // relocation information starting from the end of the buffer. See CodeDesc
478   // for a detailed comment on the layout (globals.h).
479   //
480   // If the provided buffer is NULL, the assembler allocates and grows its own
481   // buffer, and buffer_size determines the initial buffer size. The buffer is
482   // owned by the assembler and deallocated upon destruction of the assembler.
483   //
484   // If the provided buffer is not NULL, the assembler uses the provided buffer
485   // for code generation and assumes its size to be buffer_size. If the buffer
486   // is too small, a fatal error occurs. No deallocation of the buffer is done
487   // upon destruction of the assembler.
488   // TODO(vitalyr): the assembler does not need an isolate.
489   Assembler(Isolate* isolate, void* buffer, int buffer_size);
490   virtual ~Assembler() { }
491
492   // GetCode emits any pending (non-emitted) code and fills the descriptor
493   // desc. GetCode() is idempotent; it returns the same result if no other
494   // Assembler functions are invoked in between GetCode() calls.
495   void GetCode(CodeDesc* desc);
496
497   // Read/Modify the code target in the branch/call instruction at pc.
498   inline static Address target_address_at(Address pc,
499                                           ConstantPoolArray* constant_pool);
500   inline static void set_target_address_at(Address pc,
501                                            ConstantPoolArray* constant_pool,
502                                            Address target,
503                                            ICacheFlushMode icache_flush_mode =
504                                                FLUSH_ICACHE_IF_NEEDED);
505   static inline Address target_address_at(Address pc, Code* code) {
506     ConstantPoolArray* constant_pool = code ? code->constant_pool() : NULL;
507     return target_address_at(pc, constant_pool);
508   }
509   static inline void set_target_address_at(Address pc,
510                                            Code* code,
511                                            Address target,
512                                            ICacheFlushMode icache_flush_mode =
513                                                FLUSH_ICACHE_IF_NEEDED) {
514     ConstantPoolArray* constant_pool = code ? code->constant_pool() : NULL;
515     set_target_address_at(pc, constant_pool, target);
516   }
517
518   // Return the code target address at a call site from the return address
519   // of that call in the instruction stream.
520   inline static Address target_address_from_return_address(Address pc);
521
522   // Return the code target address of the patch debug break slot
523   inline static Address break_address_from_return_address(Address pc);
524
525   // This sets the branch destination (which is in the instruction on x86).
526   // This is for calls and branches within generated code.
527   inline static void deserialization_set_special_target_at(
528       Address instruction_payload, Code* code, Address target) {
529     set_target_address_at(instruction_payload, code, target);
530   }
531
532   // This sets the internal reference at the pc.
533   inline static void deserialization_set_target_internal_reference_at(
534       Address pc, Address target,
535       RelocInfo::Mode mode = RelocInfo::INTERNAL_REFERENCE);
536
537   static const int kSpecialTargetSize = kPointerSize;
538
539   // Distance between the address of the code target in the call instruction
540   // and the return address
541   static const int kCallTargetAddressOffset = kPointerSize;
542   // Distance between start of patched return sequence and the emitted address
543   // to jump to.
544   static const int kPatchReturnSequenceAddressOffset = 1;  // JMP imm32.
545
546   // Distance between start of patched debug break slot and the emitted address
547   // to jump to.
548   static const int kPatchDebugBreakSlotAddressOffset = 1;  // JMP imm32.
549
550   static const int kCallInstructionLength = 5;
551   static const int kPatchDebugBreakSlotReturnOffset = kPointerSize;
552   static const int kJSReturnSequenceLength = 6;
553
554   // The debug break slot must be able to contain a call instruction.
555   static const int kDebugBreakSlotLength = kCallInstructionLength;
556
557   // One byte opcode for test al, 0xXX.
558   static const byte kTestAlByte = 0xA8;
559   // One byte opcode for nop.
560   static const byte kNopByte = 0x90;
561
562   // One byte opcode for a short unconditional jump.
563   static const byte kJmpShortOpcode = 0xEB;
564   // One byte prefix for a short conditional jump.
565   static const byte kJccShortPrefix = 0x70;
566   static const byte kJncShortOpcode = kJccShortPrefix | not_carry;
567   static const byte kJcShortOpcode = kJccShortPrefix | carry;
568   static const byte kJnzShortOpcode = kJccShortPrefix | not_zero;
569   static const byte kJzShortOpcode = kJccShortPrefix | zero;
570
571
572   // ---------------------------------------------------------------------------
573   // Code generation
574   //
575   // - function names correspond one-to-one to ia32 instruction mnemonics
576   // - unless specified otherwise, instructions operate on 32bit operands
577   // - instructions on 8bit (byte) operands/registers have a trailing '_b'
578   // - instructions on 16bit (word) operands/registers have a trailing '_w'
579   // - naming conflicts with C++ keywords are resolved via a trailing '_'
580
581   // NOTE ON INTERFACE: Currently, the interface is not very consistent
582   // in the sense that some operations (e.g. mov()) can be called in more
583   // the one way to generate the same instruction: The Register argument
584   // can in some cases be replaced with an Operand(Register) argument.
585   // This should be cleaned up and made more orthogonal. The questions
586   // is: should we always use Operands instead of Registers where an
587   // Operand is possible, or should we have a Register (overloaded) form
588   // instead? We must be careful to make sure that the selected instruction
589   // is obvious from the parameters to avoid hard-to-find code generation
590   // bugs.
591
592   // Insert the smallest number of nop instructions
593   // possible to align the pc offset to a multiple
594   // of m. m must be a power of 2.
595   void Align(int m);
596   void Nop(int bytes = 1);
597   // Aligns code to something that's optimal for a jump target for the platform.
598   void CodeTargetAlign();
599
600   // Stack
601   void pushad();
602   void popad();
603
604   void pushfd();
605   void popfd();
606
607   void push(const Immediate& x);
608   void push_imm32(int32_t imm32);
609   void push(Register src);
610   void push(const Operand& src);
611
612   void pop(Register dst);
613   void pop(const Operand& dst);
614
615   void enter(const Immediate& size);
616   void leave();
617
618   // Moves
619   void mov_b(Register dst, Register src) { mov_b(dst, Operand(src)); }
620   void mov_b(Register dst, const Operand& src);
621   void mov_b(Register dst, int8_t imm8) { mov_b(Operand(dst), imm8); }
622   void mov_b(const Operand& dst, int8_t imm8);
623   void mov_b(const Operand& dst, Register src);
624
625   void mov_w(Register dst, const Operand& src);
626   void mov_w(const Operand& dst, Register src);
627   void mov_w(const Operand& dst, int16_t imm16);
628
629   void mov(Register dst, int32_t imm32);
630   void mov(Register dst, const Immediate& x);
631   void mov(Register dst, Handle<Object> handle);
632   void mov(Register dst, const Operand& src);
633   void mov(Register dst, Register src);
634   void mov(const Operand& dst, const Immediate& x);
635   void mov(const Operand& dst, Handle<Object> handle);
636   void mov(const Operand& dst, Register src);
637
638   void movsx_b(Register dst, Register src) { movsx_b(dst, Operand(src)); }
639   void movsx_b(Register dst, const Operand& src);
640
641   void movsx_w(Register dst, Register src) { movsx_w(dst, Operand(src)); }
642   void movsx_w(Register dst, const Operand& src);
643
644   void movzx_b(Register dst, Register src) { movzx_b(dst, Operand(src)); }
645   void movzx_b(Register dst, const Operand& src);
646
647   void movzx_w(Register dst, Register src) { movzx_w(dst, Operand(src)); }
648   void movzx_w(Register dst, const Operand& src);
649
650   // Flag management.
651   void cld();
652
653   // Repetitive string instructions.
654   void rep_movs();
655   void rep_stos();
656   void stos();
657
658   // Exchange
659   void xchg(Register dst, Register src);
660   void xchg(Register dst, const Operand& src);
661
662   // Arithmetics
663   void adc(Register dst, int32_t imm32);
664   void adc(Register dst, const Operand& src);
665
666   void add(Register dst, Register src) { add(dst, Operand(src)); }
667   void add(Register dst, const Operand& src);
668   void add(const Operand& dst, Register src);
669   void add(Register dst, const Immediate& imm) { add(Operand(dst), imm); }
670   void add(const Operand& dst, const Immediate& x);
671
672   void and_(Register dst, int32_t imm32);
673   void and_(Register dst, const Immediate& x);
674   void and_(Register dst, Register src) { and_(dst, Operand(src)); }
675   void and_(Register dst, const Operand& src);
676   void and_(const Operand& dst, Register src);
677   void and_(const Operand& dst, const Immediate& x);
678
679   void cmpb(Register reg, int8_t imm8) { cmpb(Operand(reg), imm8); }
680   void cmpb(const Operand& op, int8_t imm8);
681   void cmpb(Register reg, const Operand& op);
682   void cmpb(const Operand& op, Register reg);
683   void cmpb_al(const Operand& op);
684   void cmpw_ax(const Operand& op);
685   void cmpw(const Operand& op, Immediate imm16);
686   void cmp(Register reg, int32_t imm32);
687   void cmp(Register reg, Handle<Object> handle);
688   void cmp(Register reg0, Register reg1) { cmp(reg0, Operand(reg1)); }
689   void cmp(Register reg, const Operand& op);
690   void cmp(Register reg, const Immediate& imm) { cmp(Operand(reg), imm); }
691   void cmp(const Operand& op, const Immediate& imm);
692   void cmp(const Operand& op, Handle<Object> handle);
693
694   void dec_b(Register dst);
695   void dec_b(const Operand& dst);
696
697   void dec(Register dst);
698   void dec(const Operand& dst);
699
700   void cdq();
701
702   void idiv(Register src) { idiv(Operand(src)); }
703   void idiv(const Operand& src);
704   void div(Register src) { div(Operand(src)); }
705   void div(const Operand& src);
706
707   // Signed multiply instructions.
708   void imul(Register src);                               // edx:eax = eax * src.
709   void imul(Register dst, Register src) { imul(dst, Operand(src)); }
710   void imul(Register dst, const Operand& src);           // dst = dst * src.
711   void imul(Register dst, Register src, int32_t imm32);  // dst = src * imm32.
712   void imul(Register dst, const Operand& src, int32_t imm32);
713
714   void inc(Register dst);
715   void inc(const Operand& dst);
716
717   void lea(Register dst, const Operand& src);
718
719   // Unsigned multiply instruction.
720   void mul(Register src);                                // edx:eax = eax * reg.
721
722   void neg(Register dst);
723   void neg(const Operand& dst);
724
725   void not_(Register dst);
726   void not_(const Operand& dst);
727
728   void or_(Register dst, int32_t imm32);
729   void or_(Register dst, Register src) { or_(dst, Operand(src)); }
730   void or_(Register dst, const Operand& src);
731   void or_(const Operand& dst, Register src);
732   void or_(Register dst, const Immediate& imm) { or_(Operand(dst), imm); }
733   void or_(const Operand& dst, const Immediate& x);
734
735   void rcl(Register dst, uint8_t imm8);
736   void rcr(Register dst, uint8_t imm8);
737
738   void ror(Register dst, uint8_t imm8) { ror(Operand(dst), imm8); }
739   void ror(const Operand& dst, uint8_t imm8);
740   void ror_cl(Register dst) { ror_cl(Operand(dst)); }
741   void ror_cl(const Operand& dst);
742
743   void sar(Register dst, uint8_t imm8) { sar(Operand(dst), imm8); }
744   void sar(const Operand& dst, uint8_t imm8);
745   void sar_cl(Register dst) { sar_cl(Operand(dst)); }
746   void sar_cl(const Operand& dst);
747
748   void sbb(Register dst, const Operand& src);
749
750   void shld(Register dst, Register src) { shld(dst, Operand(src)); }
751   void shld(Register dst, const Operand& src);
752
753   void shl(Register dst, uint8_t imm8) { shl(Operand(dst), imm8); }
754   void shl(const Operand& dst, uint8_t imm8);
755   void shl_cl(Register dst) { shl_cl(Operand(dst)); }
756   void shl_cl(const Operand& dst);
757
758   void shrd(Register dst, Register src) { shrd(dst, Operand(src)); }
759   void shrd(Register dst, const Operand& src);
760
761   void shr(Register dst, uint8_t imm8) { shr(Operand(dst), imm8); }
762   void shr(const Operand& dst, uint8_t imm8);
763   void shr_cl(Register dst) { shr_cl(Operand(dst)); }
764   void shr_cl(const Operand& dst);
765
766   void sub(Register dst, const Immediate& imm) { sub(Operand(dst), imm); }
767   void sub(const Operand& dst, const Immediate& x);
768   void sub(Register dst, Register src) { sub(dst, Operand(src)); }
769   void sub(Register dst, const Operand& src);
770   void sub(const Operand& dst, Register src);
771
772   void test(Register reg, const Immediate& imm);
773   void test(Register reg0, Register reg1) { test(reg0, Operand(reg1)); }
774   void test(Register reg, const Operand& op);
775   void test_b(Register reg, const Operand& op);
776   void test(const Operand& op, const Immediate& imm);
777   void test_b(Register reg, uint8_t imm8);
778   void test_b(const Operand& op, uint8_t imm8);
779
780   void xor_(Register dst, int32_t imm32);
781   void xor_(Register dst, Register src) { xor_(dst, Operand(src)); }
782   void xor_(Register dst, const Operand& src);
783   void xor_(const Operand& dst, Register src);
784   void xor_(Register dst, const Immediate& imm) { xor_(Operand(dst), imm); }
785   void xor_(const Operand& dst, const Immediate& x);
786
787   // Bit operations.
788   void bt(const Operand& dst, Register src);
789   void bts(Register dst, Register src) { bts(Operand(dst), src); }
790   void bts(const Operand& dst, Register src);
791   void bsr(Register dst, Register src) { bsr(dst, Operand(src)); }
792   void bsr(Register dst, const Operand& src);
793
794   // Miscellaneous
795   void hlt();
796   void int3();
797   void nop();
798   void ret(int imm16);
799   void ud2();
800
801   // Label operations & relative jumps (PPUM Appendix D)
802   //
803   // Takes a branch opcode (cc) and a label (L) and generates
804   // either a backward branch or a forward branch and links it
805   // to the label fixup chain. Usage:
806   //
807   // Label L;    // unbound label
808   // j(cc, &L);  // forward branch to unbound label
809   // bind(&L);   // bind label to the current pc
810   // j(cc, &L);  // backward branch to bound label
811   // bind(&L);   // illegal: a label may be bound only once
812   //
813   // Note: The same Label can be used for forward and backward branches
814   // but it may be bound only once.
815
816   void bind(Label* L);  // binds an unbound label L to the current code position
817
818   // Calls
819   void call(Label* L);
820   void call(byte* entry, RelocInfo::Mode rmode);
821   int CallSize(const Operand& adr);
822   void call(Register reg) { call(Operand(reg)); }
823   void call(const Operand& adr);
824   int CallSize(Handle<Code> code, RelocInfo::Mode mode);
825   void call(Handle<Code> code,
826             RelocInfo::Mode rmode,
827             TypeFeedbackId id = TypeFeedbackId::None());
828
829   // Jumps
830   // unconditional jump to L
831   void jmp(Label* L, Label::Distance distance = Label::kFar);
832   void jmp(byte* entry, RelocInfo::Mode rmode);
833   void jmp(Register reg) { jmp(Operand(reg)); }
834   void jmp(const Operand& adr);
835   void jmp(Handle<Code> code, RelocInfo::Mode rmode);
836
837   // Conditional jumps
838   void j(Condition cc,
839          Label* L,
840          Label::Distance distance = Label::kFar);
841   void j(Condition cc, byte* entry, RelocInfo::Mode rmode);
842   void j(Condition cc, Handle<Code> code);
843
844   // Floating-point operations
845   void fld(int i);
846   void fstp(int i);
847
848   void fld1();
849   void fldz();
850   void fldpi();
851   void fldln2();
852
853   void fld_s(const Operand& adr);
854   void fld_d(const Operand& adr);
855
856   void fstp_s(const Operand& adr);
857   void fst_s(const Operand& adr);
858   void fstp_d(const Operand& adr);
859   void fst_d(const Operand& adr);
860
861   void fild_s(const Operand& adr);
862   void fild_d(const Operand& adr);
863
864   void fist_s(const Operand& adr);
865
866   void fistp_s(const Operand& adr);
867   void fistp_d(const Operand& adr);
868
869   // The fisttp instructions require SSE3.
870   void fisttp_s(const Operand& adr);
871   void fisttp_d(const Operand& adr);
872
873   void fabs();
874   void fchs();
875   void fsqrt();
876   void fcos();
877   void fsin();
878   void fptan();
879   void fyl2x();
880   void f2xm1();
881   void fscale();
882   void fninit();
883
884   void fadd(int i);
885   void fadd_i(int i);
886   void fadd_d(const Operand& adr);
887   void fsub(int i);
888   void fsub_i(int i);
889   void fmul(int i);
890   void fmul_i(int i);
891   void fdiv(int i);
892   void fdiv_i(int i);
893
894   void fisub_s(const Operand& adr);
895
896   void faddp(int i = 1);
897   void fsubp(int i = 1);
898   void fsubrp(int i = 1);
899   void fmulp(int i = 1);
900   void fdivp(int i = 1);
901   void fprem();
902   void fprem1();
903
904   void fxch(int i = 1);
905   void fincstp();
906   void ffree(int i = 0);
907
908   void ftst();
909   void fxam();
910   void fucomp(int i);
911   void fucompp();
912   void fucomi(int i);
913   void fucomip();
914   void fcompp();
915   void fnstsw_ax();
916   void fldcw(const Operand& adr);
917   void fnstcw(const Operand& adr);
918   void fwait();
919   void fnclex();
920   void fnsave(const Operand& adr);
921   void frstor(const Operand& adr);
922
923   void frndint();
924
925   void sahf();
926   void setcc(Condition cc, Register reg);
927
928   void cpuid();
929
930   // TODO(lrn): Need SFENCE for movnt?
931
932   // Check the code size generated from label to here.
933   int SizeOfCodeGeneratedSince(Label* label) {
934     return pc_offset() - label->pos();
935   }
936
937   // Mark address of the ExitJSFrame code.
938   void RecordJSReturn();
939
940   // Mark address of a debug break slot.
941   void RecordDebugBreakSlot();
942
943   // Record a comment relocation entry that can be used by a disassembler.
944   // Use --code-comments to enable.
945   void RecordComment(const char* msg);
946
947   // Record a deoptimization reason that can be used by a log or cpu profiler.
948   // Use --trace-deopt to enable.
949   void RecordDeoptReason(const int reason, const SourcePosition position);
950
951   // Writes a single byte or word of data in the code stream.  Used for
952   // inline tables, e.g., jump-tables.
953   void db(uint8_t data);
954   void dd(uint32_t data);
955   void dd(Label* label);
956
957   // Check if there is less than kGap bytes available in the buffer.
958   // If this is the case, we need to grow the buffer before emitting
959   // an instruction or relocation information.
960   inline bool buffer_overflow() const {
961     return pc_ >= reloc_info_writer.pos() - kGap;
962   }
963
964   // Get the number of bytes available in the buffer.
965   inline int available_space() const { return reloc_info_writer.pos() - pc_; }
966
967   static bool IsNop(Address addr);
968
969   PositionsRecorder* positions_recorder() { return &positions_recorder_; }
970
971   int relocation_writer_size() {
972     return (buffer_ + buffer_size_) - reloc_info_writer.pos();
973   }
974
975   // Avoid overflows for displacements etc.
976   static const int kMaximalBufferSize = 512*MB;
977
978   byte byte_at(int pos) { return buffer_[pos]; }
979   void set_byte_at(int pos, byte value) { buffer_[pos] = value; }
980
981   // Allocate a constant pool of the correct size for the generated code.
982   Handle<ConstantPoolArray> NewConstantPool(Isolate* isolate);
983
984   // Generate the constant pool for the generated code.
985   void PopulateConstantPool(ConstantPoolArray* constant_pool);
986
987  protected:
988   byte* addr_at(int pos) { return buffer_ + pos; }
989
990
991  private:
992   uint32_t long_at(int pos)  {
993     return *reinterpret_cast<uint32_t*>(addr_at(pos));
994   }
995   void long_at_put(int pos, uint32_t x)  {
996     *reinterpret_cast<uint32_t*>(addr_at(pos)) = x;
997   }
998
999   // code emission
1000   void GrowBuffer();
1001   inline void emit(uint32_t x);
1002   inline void emit(Handle<Object> handle);
1003   inline void emit(uint32_t x,
1004                    RelocInfo::Mode rmode,
1005                    TypeFeedbackId id = TypeFeedbackId::None());
1006   inline void emit(Handle<Code> code,
1007                    RelocInfo::Mode rmode,
1008                    TypeFeedbackId id = TypeFeedbackId::None());
1009   inline void emit(const Immediate& x);
1010   inline void emit_w(const Immediate& x);
1011
1012   // Emit the code-object-relative offset of the label's position
1013   inline void emit_code_relative_offset(Label* label);
1014
1015   // instruction generation
1016   void emit_arith_b(int op1, int op2, Register dst, int imm8);
1017
1018   // Emit a basic arithmetic instruction (i.e. first byte of the family is 0x81)
1019   // with a given destination expression and an immediate operand.  It attempts
1020   // to use the shortest encoding possible.
1021   // sel specifies the /n in the modrm byte (see the Intel PRM).
1022   void emit_arith(int sel, Operand dst, const Immediate& x);
1023
1024   void emit_operand(Register reg, const Operand& adr);
1025
1026   void emit_label(Label* label);
1027
1028   void emit_farith(int b1, int b2, int i);
1029
1030   // labels
1031   void print(Label* L);
1032   void bind_to(Label* L, int pos);
1033
1034   // displacements
1035   inline Displacement disp_at(Label* L);
1036   inline void disp_at_put(Label* L, Displacement disp);
1037   inline void emit_disp(Label* L, Displacement::Type type);
1038   inline void emit_near_disp(Label* L);
1039
1040   // record reloc info for current pc_
1041   void RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data = 0);
1042
1043   friend class CodePatcher;
1044   friend class EnsureSpace;
1045
1046   // Internal reference positions, required for (potential) patching in
1047   // GrowBuffer(); contains only those internal references whose labels
1048   // are already bound.
1049   std::deque<int> internal_reference_positions_;
1050
1051   // code generation
1052   RelocInfoWriter reloc_info_writer;
1053
1054   PositionsRecorder positions_recorder_;
1055   friend class PositionsRecorder;
1056 };
1057
1058
1059 // Helper class that ensures that there is enough space for generating
1060 // instructions and relocation information.  The constructor makes
1061 // sure that there is enough space and (in debug mode) the destructor
1062 // checks that we did not generate too much.
1063 class EnsureSpace BASE_EMBEDDED {
1064  public:
1065   explicit EnsureSpace(Assembler* assembler) : assembler_(assembler) {
1066     if (assembler_->buffer_overflow()) assembler_->GrowBuffer();
1067 #ifdef DEBUG
1068     space_before_ = assembler_->available_space();
1069 #endif
1070   }
1071
1072 #ifdef DEBUG
1073   ~EnsureSpace() {
1074     int bytes_generated = space_before_ - assembler_->available_space();
1075     DCHECK(bytes_generated < assembler_->kGap);
1076   }
1077 #endif
1078
1079  private:
1080   Assembler* assembler_;
1081 #ifdef DEBUG
1082   int space_before_;
1083 #endif
1084 };
1085
1086 } }  // namespace v8::internal
1087
1088 #endif  // V8_X87_ASSEMBLER_X87_H_