3c1c4592dcbcadb5786ad6247cd1ce005def139e
[oota-llvm.git] / lib / Target / X86 / X86AsmBackend.cpp
1 //===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Target/TargetAsmBackend.h"
11 #include "X86.h"
12 #include "X86FixupKinds.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCFixupKindInfo.h"
17 #include "llvm/MC/MCMachObjectWriter.h"
18 #include "llvm/MC/MCObjectFormat.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSectionCOFF.h"
21 #include "llvm/MC/MCSectionELF.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/Object/MachOFormat.h"
24 #include "llvm/Support/ELF.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Target/TargetAsmBackend.h"
29 using namespace llvm;
30
31 static unsigned getFixupKindLog2Size(unsigned Kind) {
32   switch (Kind) {
33   default: assert(0 && "invalid fixup kind!");
34   case FK_PCRel_1:
35   case FK_Data_1: return 0;
36   case FK_PCRel_2:
37   case FK_Data_2: return 1;
38   case FK_PCRel_4:
39   case X86::reloc_riprel_4byte:
40   case X86::reloc_riprel_4byte_movq_load:
41   case X86::reloc_signed_4byte:
42   case X86::reloc_global_offset_table:
43   case FK_Data_4: return 2;
44   case FK_Data_8: return 3;
45   }
46 }
47
48 namespace {
49 class X86MachObjectWriter : public MCMachObjectTargetWriter {
50 };
51
52 class X86AsmBackend : public TargetAsmBackend {
53 public:
54   X86AsmBackend(const Target &T)
55     : TargetAsmBackend() {}
56
57   unsigned getNumFixupKinds() const {
58     return X86::NumTargetFixupKinds;
59   }
60
61   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
62     const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
63       { "reloc_riprel_4byte", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel },
64       { "reloc_riprel_4byte_movq_load", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel},
65       { "reloc_signed_4byte", 0, 4 * 8, 0},
66       { "reloc_global_offset_table", 0, 4 * 8, 0}
67     };
68
69     if (Kind < FirstTargetFixupKind)
70       return TargetAsmBackend::getFixupKindInfo(Kind);
71
72     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
73            "Invalid kind!");
74     return Infos[Kind - FirstTargetFixupKind];
75   }
76
77   void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
78                   uint64_t Value) const {
79     unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
80
81     assert(Fixup.getOffset() + Size <= DataSize &&
82            "Invalid fixup offset!");
83     for (unsigned i = 0; i != Size; ++i)
84       Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
85   }
86
87   bool MayNeedRelaxation(const MCInst &Inst) const;
88
89   void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
90
91   bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
92 };
93 } // end anonymous namespace
94
95 static unsigned getRelaxedOpcodeBranch(unsigned Op) {
96   switch (Op) {
97   default:
98     return Op;
99
100   case X86::JAE_1: return X86::JAE_4;
101   case X86::JA_1:  return X86::JA_4;
102   case X86::JBE_1: return X86::JBE_4;
103   case X86::JB_1:  return X86::JB_4;
104   case X86::JE_1:  return X86::JE_4;
105   case X86::JGE_1: return X86::JGE_4;
106   case X86::JG_1:  return X86::JG_4;
107   case X86::JLE_1: return X86::JLE_4;
108   case X86::JL_1:  return X86::JL_4;
109   case X86::JMP_1: return X86::JMP_4;
110   case X86::JNE_1: return X86::JNE_4;
111   case X86::JNO_1: return X86::JNO_4;
112   case X86::JNP_1: return X86::JNP_4;
113   case X86::JNS_1: return X86::JNS_4;
114   case X86::JO_1:  return X86::JO_4;
115   case X86::JP_1:  return X86::JP_4;
116   case X86::JS_1:  return X86::JS_4;
117   }
118 }
119
120 static unsigned getRelaxedOpcodeArith(unsigned Op) {
121   switch (Op) {
122   default:
123     return Op;
124
125     // IMUL
126   case X86::IMUL16rri8: return X86::IMUL16rri;
127   case X86::IMUL16rmi8: return X86::IMUL16rmi;
128   case X86::IMUL32rri8: return X86::IMUL32rri;
129   case X86::IMUL32rmi8: return X86::IMUL32rmi;
130   case X86::IMUL64rri8: return X86::IMUL64rri32;
131   case X86::IMUL64rmi8: return X86::IMUL64rmi32;
132
133     // AND
134   case X86::AND16ri8: return X86::AND16ri;
135   case X86::AND16mi8: return X86::AND16mi;
136   case X86::AND32ri8: return X86::AND32ri;
137   case X86::AND32mi8: return X86::AND32mi;
138   case X86::AND64ri8: return X86::AND64ri32;
139   case X86::AND64mi8: return X86::AND64mi32;
140
141     // OR
142   case X86::OR16ri8: return X86::OR16ri;
143   case X86::OR16mi8: return X86::OR16mi;
144   case X86::OR32ri8: return X86::OR32ri;
145   case X86::OR32mi8: return X86::OR32mi;
146   case X86::OR64ri8: return X86::OR64ri32;
147   case X86::OR64mi8: return X86::OR64mi32;
148
149     // XOR
150   case X86::XOR16ri8: return X86::XOR16ri;
151   case X86::XOR16mi8: return X86::XOR16mi;
152   case X86::XOR32ri8: return X86::XOR32ri;
153   case X86::XOR32mi8: return X86::XOR32mi;
154   case X86::XOR64ri8: return X86::XOR64ri32;
155   case X86::XOR64mi8: return X86::XOR64mi32;
156
157     // ADD
158   case X86::ADD16ri8: return X86::ADD16ri;
159   case X86::ADD16mi8: return X86::ADD16mi;
160   case X86::ADD32ri8: return X86::ADD32ri;
161   case X86::ADD32mi8: return X86::ADD32mi;
162   case X86::ADD64ri8: return X86::ADD64ri32;
163   case X86::ADD64mi8: return X86::ADD64mi32;
164
165     // SUB
166   case X86::SUB16ri8: return X86::SUB16ri;
167   case X86::SUB16mi8: return X86::SUB16mi;
168   case X86::SUB32ri8: return X86::SUB32ri;
169   case X86::SUB32mi8: return X86::SUB32mi;
170   case X86::SUB64ri8: return X86::SUB64ri32;
171   case X86::SUB64mi8: return X86::SUB64mi32;
172
173     // CMP
174   case X86::CMP16ri8: return X86::CMP16ri;
175   case X86::CMP16mi8: return X86::CMP16mi;
176   case X86::CMP32ri8: return X86::CMP32ri;
177   case X86::CMP32mi8: return X86::CMP32mi;
178   case X86::CMP64ri8: return X86::CMP64ri32;
179   case X86::CMP64mi8: return X86::CMP64mi32;
180   }
181 }
182
183 static unsigned getRelaxedOpcode(unsigned Op) {
184   unsigned R = getRelaxedOpcodeArith(Op);
185   if (R != Op)
186     return R;
187   return getRelaxedOpcodeBranch(Op);
188 }
189
190 bool X86AsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
191   // Branches can always be relaxed.
192   if (getRelaxedOpcodeBranch(Inst.getOpcode()) != Inst.getOpcode())
193     return true;
194
195   // Check if this instruction is ever relaxable.
196   if (getRelaxedOpcodeArith(Inst.getOpcode()) == Inst.getOpcode())
197     return false;
198
199
200   // Check if it has an expression and is not RIP relative.
201   bool hasExp = false;
202   bool hasRIP = false;
203   for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
204     const MCOperand &Op = Inst.getOperand(i);
205     if (Op.isExpr())
206       hasExp = true;
207
208     if (Op.isReg() && Op.getReg() == X86::RIP)
209       hasRIP = true;
210   }
211
212   // FIXME: Why exactly do we need the !hasRIP? Is it just a limitation on
213   // how we do relaxations?
214   return hasExp && !hasRIP;
215 }
216
217 // FIXME: Can tblgen help at all here to verify there aren't other instructions
218 // we can relax?
219 void X86AsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
220   // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
221   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
222
223   if (RelaxedOp == Inst.getOpcode()) {
224     SmallString<256> Tmp;
225     raw_svector_ostream OS(Tmp);
226     Inst.dump_pretty(OS);
227     OS << "\n";
228     report_fatal_error("unexpected instruction to relax: " + OS.str());
229   }
230
231   Res = Inst;
232   Res.setOpcode(RelaxedOp);
233 }
234
235 /// WriteNopData - Write optimal nops to the output file for the \arg Count
236 /// bytes.  This returns the number of bytes written.  It may return 0 if
237 /// the \arg Count is more than the maximum optimal nops.
238 bool X86AsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
239   static const uint8_t Nops[10][10] = {
240     // nop
241     {0x90},
242     // xchg %ax,%ax
243     {0x66, 0x90},
244     // nopl (%[re]ax)
245     {0x0f, 0x1f, 0x00},
246     // nopl 0(%[re]ax)
247     {0x0f, 0x1f, 0x40, 0x00},
248     // nopl 0(%[re]ax,%[re]ax,1)
249     {0x0f, 0x1f, 0x44, 0x00, 0x00},
250     // nopw 0(%[re]ax,%[re]ax,1)
251     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
252     // nopl 0L(%[re]ax)
253     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
254     // nopl 0L(%[re]ax,%[re]ax,1)
255     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
256     // nopw 0L(%[re]ax,%[re]ax,1)
257     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
258     // nopw %cs:0L(%[re]ax,%[re]ax,1)
259     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
260   };
261
262   // Write an optimal sequence for the first 15 bytes.
263   const uint64_t OptimalCount = (Count < 16) ? Count : 15;
264   const uint64_t Prefixes = OptimalCount <= 10 ? 0 : OptimalCount - 10;
265   for (uint64_t i = 0, e = Prefixes; i != e; i++)
266     OW->Write8(0x66);
267   const uint64_t Rest = OptimalCount - Prefixes;
268   for (uint64_t i = 0, e = Rest; i != e; i++)
269     OW->Write8(Nops[Rest - 1][i]);
270
271   // Finish with single byte nops.
272   for (uint64_t i = OptimalCount, e = Count; i != e; ++i)
273    OW->Write8(0x90);
274
275   return true;
276 }
277
278 /* *** */
279
280 namespace {
281 class ELFX86AsmBackend : public X86AsmBackend {
282   MCELFObjectFormat Format;
283
284 public:
285   Triple::OSType OSType;
286   ELFX86AsmBackend(const Target &T, Triple::OSType _OSType)
287     : X86AsmBackend(T), OSType(_OSType) {
288     HasScatteredSymbols = true;
289     HasReliableSymbolDifference = true;
290   }
291
292   virtual const MCObjectFormat &getObjectFormat() const {
293     return Format;
294   }
295
296   virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
297     const MCSectionELF &ES = static_cast<const MCSectionELF&>(Section);
298     return ES.getFlags() & MCSectionELF::SHF_MERGE;
299   }
300 };
301
302 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
303 public:
304   ELFX86_32AsmBackend(const Target &T, Triple::OSType OSType)
305     : ELFX86AsmBackend(T, OSType) {}
306
307   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
308     return createELFObjectWriter(OS, /*Is64Bit=*/false,
309                                  OSType, ELF::EM_386,
310                                  /*IsLittleEndian=*/true,
311                                  /*HasRelocationAddend=*/false);
312   }
313 };
314
315 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
316 public:
317   ELFX86_64AsmBackend(const Target &T, Triple::OSType OSType)
318     : ELFX86AsmBackend(T, OSType) {}
319
320   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
321     return createELFObjectWriter(OS, /*Is64Bit=*/true,
322                                  OSType, ELF::EM_X86_64,
323                                  /*IsLittleEndian=*/true,
324                                  /*HasRelocationAddend=*/true);
325   }
326 };
327
328 class WindowsX86AsmBackend : public X86AsmBackend {
329   bool Is64Bit;
330   MCCOFFObjectFormat Format;
331
332 public:
333   WindowsX86AsmBackend(const Target &T, bool is64Bit)
334     : X86AsmBackend(T)
335     , Is64Bit(is64Bit) {
336     HasScatteredSymbols = true;
337   }
338
339   virtual const MCObjectFormat &getObjectFormat() const {
340     return Format;
341   }
342
343   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
344     return createWinCOFFObjectWriter(OS, Is64Bit);
345   }
346 };
347
348 class DarwinX86AsmBackend : public X86AsmBackend {
349   MCMachOObjectFormat Format;
350
351 public:
352   DarwinX86AsmBackend(const Target &T)
353     : X86AsmBackend(T) {
354     HasScatteredSymbols = true;
355   }
356
357   virtual const MCObjectFormat &getObjectFormat() const {
358     return Format;
359   }
360 };
361
362 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
363 public:
364   DarwinX86_32AsmBackend(const Target &T)
365     : DarwinX86AsmBackend(T) {}
366
367   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
368     return createMachObjectWriter(new X86MachObjectWriter,
369                                   OS, /*Is64Bit=*/false,
370                                   object::mach::CTM_i386,
371                                   object::mach::CSX86_ALL,
372                                   /*IsLittleEndian=*/true);
373   }
374 };
375
376 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
377 public:
378   DarwinX86_64AsmBackend(const Target &T)
379     : DarwinX86AsmBackend(T) {
380     HasReliableSymbolDifference = true;
381   }
382
383   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
384     return createMachObjectWriter(new X86MachObjectWriter,
385                                   OS, /*Is64Bit=*/true,
386                                   object::mach::CTM_x86_64,
387                                   object::mach::CSX86_ALL,
388                                   /*IsLittleEndian=*/true);
389   }
390
391   virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
392     // Temporary labels in the string literals sections require symbols. The
393     // issue is that the x86_64 relocation format does not allow symbol +
394     // offset, and so the linker does not have enough information to resolve the
395     // access to the appropriate atom unless an external relocation is used. For
396     // non-cstring sections, we expect the compiler to use a non-temporary label
397     // for anything that could have an addend pointing outside the symbol.
398     //
399     // See <rdar://problem/4765733>.
400     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
401     return SMO.getType() == MCSectionMachO::S_CSTRING_LITERALS;
402   }
403
404   virtual bool isSectionAtomizable(const MCSection &Section) const {
405     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
406     // Fixed sized data sections are uniqued, they cannot be diced into atoms.
407     switch (SMO.getType()) {
408     default:
409       return true;
410
411     case MCSectionMachO::S_4BYTE_LITERALS:
412     case MCSectionMachO::S_8BYTE_LITERALS:
413     case MCSectionMachO::S_16BYTE_LITERALS:
414     case MCSectionMachO::S_LITERAL_POINTERS:
415     case MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS:
416     case MCSectionMachO::S_LAZY_SYMBOL_POINTERS:
417     case MCSectionMachO::S_MOD_INIT_FUNC_POINTERS:
418     case MCSectionMachO::S_MOD_TERM_FUNC_POINTERS:
419     case MCSectionMachO::S_INTERPOSING:
420       return false;
421     }
422   }
423 };
424
425 } // end anonymous namespace
426
427 TargetAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
428                                                const std::string &TT) {
429   switch (Triple(TT).getOS()) {
430   case Triple::Darwin:
431     return new DarwinX86_32AsmBackend(T);
432   case Triple::MinGW32:
433   case Triple::Cygwin:
434   case Triple::Win32:
435     return new WindowsX86AsmBackend(T, false);
436   default:
437     return new ELFX86_32AsmBackend(T, Triple(TT).getOS());
438   }
439 }
440
441 TargetAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
442                                                const std::string &TT) {
443   switch (Triple(TT).getOS()) {
444   case Triple::Darwin:
445     return new DarwinX86_64AsmBackend(T);
446   case Triple::MinGW64:
447   case Triple::Cygwin:
448   case Triple::Win32:
449     return new WindowsX86AsmBackend(T, true);
450   default:
451     return new ELFX86_64AsmBackend(T, Triple(TT).getOS());
452   }
453 }