e9fed979cf71a078e4a8911d8bc42a448ed76f77
[oota-llvm.git] / lib / Target / ARM / ARMAsmBackend.cpp
1 //===-- ARMAsmBackend.cpp - ARM 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 "ARM.h"
11 #include "ARMAddressingModes.h"
12 #include "ARMFixupKinds.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCMachObjectWriter.h"
19 #include "llvm/MC/MCObjectFormat.h"
20 #include "llvm/MC/MCObjectWriter.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/TargetAsmBackend.h"
28 #include "llvm/Target/TargetRegistry.h"
29 using namespace llvm;
30
31 namespace {
32 class ARMMachObjectWriter : public MCMachObjectTargetWriter {
33 public:
34   ARMMachObjectWriter(bool Is64Bit, uint32_t CPUType,
35                       uint32_t CPUSubtype)
36     : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype,
37                                /*UseAggressiveSymbolFolding=*/true) {}
38 };
39
40 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
41 public:
42   ARMELFObjectWriter() : MCELFObjectTargetWriter() {}
43 };
44
45 class ARMAsmBackend : public TargetAsmBackend {
46   bool isThumbMode;  // Currently emitting Thumb code.
47 public:
48   ARMAsmBackend(const Target &T) : TargetAsmBackend(), isThumbMode(false) {}
49
50   unsigned getNumFixupKinds() const { return ARM::NumTargetFixupKinds; }
51
52   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
53     const static MCFixupKindInfo Infos[ARM::NumTargetFixupKinds] = {
54 // This table *must* be in the order that the fixup_* kinds are defined in
55 // ARMFixupKinds.h.
56 //
57 // Name                      Offset (bits) Size (bits)     Flags
58 { "fixup_arm_ldst_pcrel_12", 1,            24,  MCFixupKindInfo::FKF_IsPCRel },
59 { "fixup_t2_ldst_pcrel_12",  0,            32,  MCFixupKindInfo::FKF_IsPCRel |
60                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
61 { "fixup_arm_pcrel_10",      1,            24,  MCFixupKindInfo::FKF_IsPCRel },
62 { "fixup_t2_pcrel_10",       0,            32,  MCFixupKindInfo::FKF_IsPCRel |
63                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
64 { "fixup_thumb_adr_pcrel_10",0,            8,   MCFixupKindInfo::FKF_IsPCRel |
65                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
66 { "fixup_arm_adr_pcrel_12",  1,            24,  MCFixupKindInfo::FKF_IsPCRel },
67 { "fixup_t2_adr_pcrel_12",   0,            32,  MCFixupKindInfo::FKF_IsPCRel |
68                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
69 { "fixup_arm_branch",        0,            24,  MCFixupKindInfo::FKF_IsPCRel },
70 { "fixup_t2_condbranch",     0,            32,  MCFixupKindInfo::FKF_IsPCRel },
71 { "fixup_t2_uncondbranch",   0,            32,  MCFixupKindInfo::FKF_IsPCRel },
72 { "fixup_arm_thumb_br",      0,            16,  MCFixupKindInfo::FKF_IsPCRel },
73 { "fixup_arm_thumb_bl",      0,            32,  MCFixupKindInfo::FKF_IsPCRel },
74 { "fixup_arm_thumb_blx",     7,            21,  MCFixupKindInfo::FKF_IsPCRel },
75 { "fixup_arm_thumb_cb",      0,            16,  MCFixupKindInfo::FKF_IsPCRel },
76 { "fixup_arm_thumb_cp",      1,             8,  MCFixupKindInfo::FKF_IsPCRel },
77 { "fixup_arm_thumb_bcc",     1,             8,  MCFixupKindInfo::FKF_IsPCRel },
78 { "fixup_arm_movt_hi16",     0,            16,  0 },
79 { "fixup_arm_movw_lo16",     0,            16,  0 },
80     };
81
82     if (Kind < FirstTargetFixupKind)
83       return TargetAsmBackend::getFixupKindInfo(Kind);
84
85     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
86            "Invalid kind!");
87     return Infos[Kind - FirstTargetFixupKind];
88   }
89
90   bool MayNeedRelaxation(const MCInst &Inst) const;
91
92   void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
93
94   bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
95
96   void HandleAssemblerFlag(MCAssemblerFlag Flag) {
97     switch (Flag) {
98     default: break;
99     case MCAF_Code16:
100       setIsThumb(true);
101       break;
102     case MCAF_Code32:
103       setIsThumb(false);
104       break;
105     }
106   }
107
108   unsigned getPointerSize() const { return 4; }
109   bool isThumb() const { return isThumbMode; }
110   void setIsThumb(bool it) { isThumbMode = it; }
111 };
112 } // end anonymous namespace
113
114 bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
115   // FIXME: Thumb targets, different move constant targets..
116   return false;
117 }
118
119 void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
120   assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented");
121   return;
122 }
123
124 bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
125   if (isThumb()) {
126     // FIXME: 0xbf00 is the ARMv7 value. For v6 and before, we'll need to
127     // use 0x46c0 (which is a 'mov r8, r8' insn).
128     uint64_t NumNops = Count / 2;
129     for (uint64_t i = 0; i != NumNops; ++i)
130       OW->Write16(0xbf00);
131     if (Count & 1)
132       OW->Write8(0);
133     return true;
134   }
135   // ARM mode
136   uint64_t NumNops = Count / 4;
137   for (uint64_t i = 0; i != NumNops; ++i)
138     OW->Write32(0xe1a00000);
139   switch (Count % 4) {
140   default: break; // No leftover bytes to write
141   case 1: OW->Write8(0); break;
142   case 2: OW->Write16(0); break;
143   case 3: OW->Write16(0); OW->Write8(0xa0); break;
144   }
145
146   return true;
147 }
148
149 static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
150   switch (Kind) {
151   default:
152     llvm_unreachable("Unknown fixup kind!");
153   case FK_Data_1:
154   case FK_Data_2:
155   case FK_Data_4:
156     return Value;
157   case ARM::fixup_arm_movt_hi16:
158   case ARM::fixup_arm_movw_lo16: {
159     unsigned Hi4 = (Value & 0xF000) >> 12;
160     unsigned Lo12 = Value & 0x0FFF;
161     // inst{19-16} = Hi4;
162     // inst{11-0} = Lo12;
163     Value = (Hi4 << 16) | (Lo12);
164     return Value;
165   }
166   case ARM::fixup_arm_ldst_pcrel_12:
167     // ARM PC-relative values are offset by 8.
168     Value -= 4;
169     // FALLTHROUGH
170   case ARM::fixup_t2_ldst_pcrel_12: {
171     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
172     Value -= 4;
173     bool isAdd = true;
174     if ((int64_t)Value < 0) {
175       Value = -Value;
176       isAdd = false;
177     }
178     assert ((Value < 4096) && "Out of range pc-relative fixup value!");
179     Value |= isAdd << 23;
180
181     // Same addressing mode as fixup_arm_pcrel_10,
182     // but with 16-bit halfwords swapped.
183     if (Kind == ARM::fixup_t2_ldst_pcrel_12) {
184       uint64_t swapped = (Value & 0xFFFF0000) >> 16;
185       swapped |= (Value & 0x0000FFFF) << 16;
186       return swapped;
187     }
188
189     return Value;
190   }
191   case ARM::fixup_thumb_adr_pcrel_10:
192     return ((Value - 4) >> 2) & 0xff;
193   case ARM::fixup_arm_adr_pcrel_12: {
194     // ARM PC-relative values are offset by 8.
195     Value -= 8;
196     unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
197     if ((int64_t)Value < 0) {
198       Value = -Value;
199       opc = 2; // 0b0010
200     }
201     assert(ARM_AM::getSOImmVal(Value) != -1 &&
202            "Out of range pc-relative fixup value!");
203     // Encode the immediate and shift the opcode into place.
204     return ARM_AM::getSOImmVal(Value) | (opc << 21);
205   }
206
207   case ARM::fixup_t2_adr_pcrel_12: {
208     Value -= 4;
209     unsigned opc = 0;
210     if ((int64_t)Value < 0) {
211       Value = -Value;
212       opc = 5;
213     }
214
215     uint32_t out = (opc << 21);
216     out |= (Value & 0x800) << 14;
217     out |= (Value & 0x700) << 4;
218     out |= (Value & 0x0FF);
219
220     uint64_t swapped = (out & 0xFFFF0000) >> 16;
221     swapped |= (out & 0x0000FFFF) << 16;
222     return swapped;
223   }
224
225   case ARM::fixup_arm_branch:
226     // These values don't encode the low two bits since they're always zero.
227     // Offset by 8 just as above.
228     return 0xffffff & ((Value - 8) >> 2);
229   case ARM::fixup_t2_uncondbranch: {
230     Value = Value - 4;
231     Value >>= 1; // Low bit is not encoded.
232
233     uint32_t out = 0;
234     bool I =  Value & 0x800000;
235     bool J1 = Value & 0x400000;
236     bool J2 = Value & 0x200000;
237     J1 ^= I;
238     J2 ^= I;
239
240     out |= I  << 26; // S bit
241     out |= !J1 << 13; // J1 bit
242     out |= !J2 << 11; // J2 bit
243     out |= (Value & 0x1FF800)  << 5; // imm6 field
244     out |= (Value & 0x0007FF);        // imm11 field
245
246     uint64_t swapped = (out & 0xFFFF0000) >> 16;
247     swapped |= (out & 0x0000FFFF) << 16;
248     return swapped;
249   }
250   case ARM::fixup_t2_condbranch: {
251     Value = Value - 4;
252     Value >>= 1; // Low bit is not encoded.
253
254     uint64_t out = 0;
255     out |= (Value & 0x80000) << 7; // S bit
256     out |= (Value & 0x40000) >> 7; // J2 bit
257     out |= (Value & 0x20000) >> 4; // J1 bit
258     out |= (Value & 0x1F800) << 5; // imm6 field
259     out |= (Value & 0x007FF);      // imm11 field
260
261     uint32_t swapped = (out & 0xFFFF0000) >> 16;
262     swapped |= (out & 0x0000FFFF) << 16;
263     return swapped;
264   }
265   case ARM::fixup_arm_thumb_bl: {
266     // The value doesn't encode the low bit (always zero) and is offset by
267     // four. The value is encoded into disjoint bit positions in the destination
268     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit
269     //
270     //   BL:  xxxxxSIIIIIIIIII xxxxxIIIIIIIIIII
271     //
272     // Note that the halfwords are stored high first, low second; so we need
273     // to transpose the fixup value here to map properly.
274     unsigned isNeg = (int64_t(Value) < 0) ? 1 : 0;
275     uint32_t Binary = 0;
276     Value = 0x3fffff & ((Value - 4) >> 1);
277     Binary  = (Value & 0x7ff) << 16;    // Low imm11 value.
278     Binary |= (Value & 0x1ffc00) >> 11; // High imm10 value.
279     Binary |= isNeg << 10;              // Sign bit.
280     return Binary;
281   }
282   case ARM::fixup_arm_thumb_blx: {
283     // The value doesn't encode the low two bits (always zero) and is offset by
284     // four (see fixup_arm_thumb_cp). The value is encoded into disjoint bit
285     // positions in the destination opcode. x = unchanged, I = immediate value
286     // bit, S = sign extension bit, 0 = zero.
287     //
288     //   BLX: xxxxxSIIIIIIIIII xxxxxIIIIIIIIII0
289     //
290     // Note that the halfwords are stored high first, low second; so we need
291     // to transpose the fixup value here to map properly.
292     unsigned isNeg = (int64_t(Value) < 0) ? 1 : 0;
293     uint32_t Binary = 0;
294     Value = 0xfffff & ((Value - 2) >> 2);
295     Binary  = (Value & 0x3ff) << 17;    // Low imm10L value.
296     Binary |= (Value & 0xffc00) >> 10;  // High imm10H value.
297     Binary |= isNeg << 10;              // Sign bit.
298     return Binary;
299   }
300   case ARM::fixup_arm_thumb_cp:
301     // Offset by 4, and don't encode the low two bits. Two bytes of that
302     // 'off by 4' is implicitly handled by the half-word ordering of the
303     // Thumb encoding, so we only need to adjust by 2 here.
304     return ((Value - 2) >> 2) & 0xff;
305   case ARM::fixup_arm_thumb_cb: {
306     // Offset by 4 and don't encode the lower bit, which is always 0.
307     uint32_t Binary = (Value - 4) >> 1;
308     return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
309   }
310   case ARM::fixup_arm_thumb_br:
311     // Offset by 4 and don't encode the lower bit, which is always 0.
312     return ((Value - 4) >> 1) & 0x7ff;
313   case ARM::fixup_arm_thumb_bcc:
314     // Offset by 4 and don't encode the lower bit, which is always 0.
315     return ((Value - 4) >> 1) & 0xff;
316   case ARM::fixup_arm_pcrel_10:
317     Value = Value - 4; // ARM fixups offset by an additional word and don't
318                        // need to adjust for the half-word ordering.
319     // Fall through.
320   case ARM::fixup_t2_pcrel_10: {
321     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
322     Value = Value - 4;
323     bool isAdd = true;
324     if ((int64_t)Value < 0) {
325       Value = -Value;
326       isAdd = false;
327     }
328     // These values don't encode the low two bits since they're always zero.
329     Value >>= 2;
330     assert ((Value < 256) && "Out of range pc-relative fixup value!");
331     Value |= isAdd << 23;
332
333     // Same addressing mode as fixup_arm_pcrel_10,
334     // but with 16-bit halfwords swapped.
335     if (Kind == ARM::fixup_t2_pcrel_10) {
336       uint32_t swapped = (Value & 0xFFFF0000) >> 16;
337       swapped |= (Value & 0x0000FFFF) << 16;
338       return swapped;
339     }
340
341     return Value;
342   }
343   }
344 }
345
346 namespace {
347
348 // FIXME: This should be in a separate file.
349 // ELF is an ELF of course...
350 class ELFARMAsmBackend : public ARMAsmBackend {
351   MCELFObjectFormat Format;
352
353 public:
354   Triple::OSType OSType;
355   ELFARMAsmBackend(const Target &T, Triple::OSType _OSType)
356     : ARMAsmBackend(T), OSType(_OSType) { }
357
358   virtual const MCObjectFormat &getObjectFormat() const {
359     return Format;
360   }
361
362   void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
363                   uint64_t Value) const;
364
365   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
366     return createELFObjectWriter(new ARMELFObjectWriter(), OS,
367                                  /*Is64Bit=*/false,
368                                  OSType, ELF::EM_ARM,
369                                  /*IsLittleEndian=*/true,
370                                  /*HasRelocationAddend=*/false);
371   }
372 };
373
374 // FIXME: Raise this to share code between Darwin and ELF.
375 void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
376                                   unsigned DataSize, uint64_t Value) const {
377   unsigned NumBytes = 4;        // FIXME: 2 for Thumb
378   Value = adjustFixupValue(Fixup.getKind(), Value);
379   if (!Value) return;           // Doesn't change encoding.
380
381   unsigned Offset = Fixup.getOffset();
382   assert(Offset % NumBytes == 0 && "Offset mod NumBytes is nonzero!");
383
384   // For each byte of the fragment that the fixup touches, mask in the bits from
385   // the fixup value. The Value has been "split up" into the appropriate
386   // bitfields above.
387   for (unsigned i = 0; i != NumBytes; ++i)
388     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
389 }
390
391 // FIXME: This should be in a separate file.
392 class DarwinARMAsmBackend : public ARMAsmBackend {
393   MCMachOObjectFormat Format;
394 public:
395   DarwinARMAsmBackend(const Target &T) : ARMAsmBackend(T) { }
396
397   virtual const MCObjectFormat &getObjectFormat() const {
398     return Format;
399   }
400
401   void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
402                   uint64_t Value) const;
403
404   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
405     // FIXME: Subtarget info should be derived. Force v7 for now.
406     return createMachObjectWriter(new ARMMachObjectWriter(
407                                     /*Is64Bit=*/false,
408                                     object::mach::CTM_ARM,
409                                     object::mach::CSARM_V7),
410                                   OS,
411                                   /*IsLittleEndian=*/true);
412   }
413
414   virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
415     return false;
416   }
417 };
418
419 /// getFixupKindNumBytes - The number of bytes the fixup may change.
420 static unsigned getFixupKindNumBytes(unsigned Kind) {
421   switch (Kind) {
422   default:
423     llvm_unreachable("Unknown fixup kind!");
424
425   case FK_Data_1:
426   case ARM::fixup_arm_thumb_bcc:
427   case ARM::fixup_arm_thumb_cp:
428   case ARM::fixup_thumb_adr_pcrel_10:
429     return 1;
430
431   case FK_Data_2:
432   case ARM::fixup_arm_thumb_br:
433   case ARM::fixup_arm_thumb_cb:
434     return 2;
435
436   case ARM::fixup_arm_ldst_pcrel_12:
437   case ARM::fixup_arm_pcrel_10:
438   case ARM::fixup_arm_adr_pcrel_12:
439   case ARM::fixup_arm_branch:
440     return 3;
441
442   case FK_Data_4:
443   case ARM::fixup_t2_ldst_pcrel_12:
444   case ARM::fixup_t2_condbranch:
445   case ARM::fixup_t2_uncondbranch:
446   case ARM::fixup_t2_pcrel_10:
447   case ARM::fixup_t2_adr_pcrel_12:
448   case ARM::fixup_arm_thumb_bl:
449   case ARM::fixup_arm_thumb_blx:
450     return 4;
451   }
452 }
453
454 void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
455                                      unsigned DataSize, uint64_t Value) const {
456   unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
457   Value = adjustFixupValue(Fixup.getKind(), Value);
458   if (!Value) return;           // Doesn't change encoding.
459
460   unsigned Offset = Fixup.getOffset();
461   assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
462
463   // For each byte of the fragment that the fixup touches, mask in the
464   // bits from the fixup value.
465   for (unsigned i = 0; i != NumBytes; ++i)
466     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
467 }
468
469 } // end anonymous namespace
470
471 TargetAsmBackend *llvm::createARMAsmBackend(const Target &T,
472                                             const std::string &TT) {
473   switch (Triple(TT).getOS()) {
474   case Triple::Darwin:
475     return new DarwinARMAsmBackend(T);
476   case Triple::MinGW32:
477   case Triple::Cygwin:
478   case Triple::Win32:
479     assert(0 && "Windows not supported on ARM");
480   default:
481     return new ELFARMAsmBackend(T, Triple(TT).getOS());
482   }
483 }