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