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