aaa8f362e20461ee8176c4124ca67eee5fe59d87
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / 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 "MCTargetDesc/ARMMCTargetDesc.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMFixupKinds.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCDirectives.h"
19 #include "llvm/MC/MCELFObjectWriter.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCMachObjectWriter.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/ELF.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MachO.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 namespace {
35 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
36 public:
37   ARMELFObjectWriter(uint8_t OSABI)
38     : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
39                               /*HasRelocationAddend*/ false) {}
40 };
41
42 class ARMAsmBackend : public MCAsmBackend {
43   const MCSubtargetInfo* STI;
44   bool isThumbMode;  // Currently emitting Thumb code.
45 public:
46   ARMAsmBackend(const Target &T, const StringRef TT)
47     : MCAsmBackend(), STI(ARM_MC::createARMMCSubtargetInfo(TT, "", "")),
48       isThumbMode(TT.startswith("thumb")) {}
49
50   ~ARMAsmBackend() {
51     delete STI;
52   }
53
54   unsigned getNumFixupKinds() const override {
55     return ARM::NumTargetFixupKinds;
56   }
57
58   bool hasNOP() const {
59     return (STI->getFeatureBits() & ARM::HasV6T2Ops) != 0;
60   }
61
62   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
63     const static MCFixupKindInfo Infos[ARM::NumTargetFixupKinds] = {
64 // This table *must* be in the order that the fixup_* kinds are defined in
65 // ARMFixupKinds.h.
66 //
67 // Name                      Offset (bits) Size (bits)     Flags
68 { "fixup_arm_ldst_pcrel_12", 0,            32,  MCFixupKindInfo::FKF_IsPCRel },
69 { "fixup_t2_ldst_pcrel_12",  0,            32,  MCFixupKindInfo::FKF_IsPCRel |
70                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
71 { "fixup_arm_pcrel_10_unscaled", 0,        32,  MCFixupKindInfo::FKF_IsPCRel },
72 { "fixup_arm_pcrel_10",      0,            32,  MCFixupKindInfo::FKF_IsPCRel },
73 { "fixup_t2_pcrel_10",       0,            32,  MCFixupKindInfo::FKF_IsPCRel |
74                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
75 { "fixup_thumb_adr_pcrel_10",0,            8,   MCFixupKindInfo::FKF_IsPCRel |
76                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
77 { "fixup_arm_adr_pcrel_12",  0,            32,  MCFixupKindInfo::FKF_IsPCRel },
78 { "fixup_t2_adr_pcrel_12",   0,            32,  MCFixupKindInfo::FKF_IsPCRel |
79                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
80 { "fixup_arm_condbranch",    0,            24,  MCFixupKindInfo::FKF_IsPCRel },
81 { "fixup_arm_uncondbranch",  0,            24,  MCFixupKindInfo::FKF_IsPCRel },
82 { "fixup_t2_condbranch",     0,            32,  MCFixupKindInfo::FKF_IsPCRel },
83 { "fixup_t2_uncondbranch",   0,            32,  MCFixupKindInfo::FKF_IsPCRel },
84 { "fixup_arm_thumb_br",      0,            16,  MCFixupKindInfo::FKF_IsPCRel },
85 { "fixup_arm_uncondbl",      0,            24,  MCFixupKindInfo::FKF_IsPCRel },
86 { "fixup_arm_condbl",        0,            24,  MCFixupKindInfo::FKF_IsPCRel },
87 { "fixup_arm_blx",           0,            24,  MCFixupKindInfo::FKF_IsPCRel },
88 { "fixup_arm_thumb_bl",      0,            32,  MCFixupKindInfo::FKF_IsPCRel },
89 { "fixup_arm_thumb_blx",     0,            32,  MCFixupKindInfo::FKF_IsPCRel },
90 { "fixup_arm_thumb_cb",      0,            16,  MCFixupKindInfo::FKF_IsPCRel },
91 { "fixup_arm_thumb_cp",      0,             8,  MCFixupKindInfo::FKF_IsPCRel |
92                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
93 { "fixup_arm_thumb_bcc",     0,             8,  MCFixupKindInfo::FKF_IsPCRel },
94 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16 - 19.
95 { "fixup_arm_movt_hi16",     0,            20,  0 },
96 { "fixup_arm_movw_lo16",     0,            20,  0 },
97 { "fixup_t2_movt_hi16",      0,            20,  0 },
98 { "fixup_t2_movw_lo16",      0,            20,  0 },
99 { "fixup_arm_movt_hi16_pcrel", 0,          20,  MCFixupKindInfo::FKF_IsPCRel },
100 { "fixup_arm_movw_lo16_pcrel", 0,          20,  MCFixupKindInfo::FKF_IsPCRel },
101 { "fixup_t2_movt_hi16_pcrel", 0,           20,  MCFixupKindInfo::FKF_IsPCRel },
102 { "fixup_t2_movw_lo16_pcrel", 0,           20,  MCFixupKindInfo::FKF_IsPCRel },
103     };
104
105     if (Kind < FirstTargetFixupKind)
106       return MCAsmBackend::getFixupKindInfo(Kind);
107
108     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
109            "Invalid kind!");
110     return Infos[Kind - FirstTargetFixupKind];
111   }
112
113   /// processFixupValue - Target hook to process the literal value of a fixup
114   /// if necessary.
115   void processFixupValue(const MCAssembler &Asm, const MCAsmLayout &Layout,
116                          const MCFixup &Fixup, const MCFragment *DF,
117                          MCValue &Target, uint64_t &Value,
118                          bool &IsResolved) override;
119
120
121   void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
122                   uint64_t Value) const override;
123
124   bool mayNeedRelaxation(const MCInst &Inst) const override;
125
126   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
127                             const MCRelaxableFragment *DF,
128                             const MCAsmLayout &Layout) const override;
129
130   void relaxInstruction(const MCInst &Inst, MCInst &Res) const override;
131
132   bool writeNopData(uint64_t Count, MCObjectWriter *OW) const override;
133
134   void handleAssemblerFlag(MCAssemblerFlag Flag) override {
135     switch (Flag) {
136     default: break;
137     case MCAF_Code16:
138       setIsThumb(true);
139       break;
140     case MCAF_Code32:
141       setIsThumb(false);
142       break;
143     }
144   }
145
146   unsigned getPointerSize() const { return 4; }
147   bool isThumb() const { return isThumbMode; }
148   void setIsThumb(bool it) { isThumbMode = it; }
149 };
150 } // end anonymous namespace
151
152 static unsigned getRelaxedOpcode(unsigned Op) {
153   switch (Op) {
154   default: return Op;
155   case ARM::tBcc:       return ARM::t2Bcc;
156   case ARM::tLDRpci:    return ARM::t2LDRpci;
157   case ARM::tADR:       return ARM::t2ADR;
158   case ARM::tB:         return ARM::t2B;
159   case ARM::tCBZ:       return ARM::tHINT;
160   case ARM::tCBNZ:      return ARM::tHINT;
161   }
162 }
163
164 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
165   if (getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode())
166     return true;
167   return false;
168 }
169
170 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
171                                          uint64_t Value,
172                                          const MCRelaxableFragment *DF,
173                                          const MCAsmLayout &Layout) const {
174   switch ((unsigned)Fixup.getKind()) {
175   case ARM::fixup_arm_thumb_br: {
176     // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
177     // low bit being an implied zero. There's an implied +4 offset for the
178     // branch, so we adjust the other way here to determine what's
179     // encodable.
180     //
181     // Relax if the value is too big for a (signed) i8.
182     int64_t Offset = int64_t(Value) - 4;
183     return Offset > 2046 || Offset < -2048;
184   }
185   case ARM::fixup_arm_thumb_bcc: {
186     // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with the
187     // low bit being an implied zero. There's an implied +4 offset for the
188     // branch, so we adjust the other way here to determine what's
189     // encodable.
190     //
191     // Relax if the value is too big for a (signed) i8.
192     int64_t Offset = int64_t(Value) - 4;
193     return Offset > 254 || Offset < -256;
194   }
195   case ARM::fixup_thumb_adr_pcrel_10:
196   case ARM::fixup_arm_thumb_cp: {
197     // If the immediate is negative, greater than 1020, or not a multiple
198     // of four, the wide version of the instruction must be used.
199     int64_t Offset = int64_t(Value) - 4;
200     return Offset > 1020 || Offset < 0 || Offset & 3;
201   }
202   case ARM::fixup_arm_thumb_cb:
203     // If we have a Thumb CBZ or CBNZ instruction and its target is the next
204     // instruction it is is actually out of range for the instruction.
205     // It will be changed to a NOP.
206     int64_t Offset = (Value & ~1);
207     return Offset == 2;
208   }
209   llvm_unreachable("Unexpected fixup kind in fixupNeedsRelaxation()!");
210 }
211
212 void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
213   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
214
215   // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
216   if (RelaxedOp == Inst.getOpcode()) {
217     SmallString<256> Tmp;
218     raw_svector_ostream OS(Tmp);
219     Inst.dump_pretty(OS);
220     OS << "\n";
221     report_fatal_error("unexpected instruction to relax: " + OS.str());
222   }
223
224   // If we are changing Thumb CBZ or CBNZ instruction to a NOP, aka tHINT, we
225   // have to change the operands too.
226   if ((Inst.getOpcode() == ARM::tCBZ || Inst.getOpcode() == ARM::tCBNZ) &&
227       RelaxedOp == ARM::tHINT) {
228     Res.setOpcode(RelaxedOp);
229     Res.addOperand(MCOperand::CreateImm(0));
230     Res.addOperand(MCOperand::CreateImm(14));
231     Res.addOperand(MCOperand::CreateReg(0));
232     return;
233   } 
234
235   // The rest of instructions we're relaxing have the same operands.
236   // We just need to update to the proper opcode.
237   Res = Inst;
238   Res.setOpcode(RelaxedOp);
239 }
240
241 bool ARMAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
242   const uint16_t Thumb1_16bitNopEncoding = 0x46c0; // using MOV r8,r8
243   const uint16_t Thumb2_16bitNopEncoding = 0xbf00; // NOP
244   const uint32_t ARMv4_NopEncoding = 0xe1a00000; // using MOV r0,r0
245   const uint32_t ARMv6T2_NopEncoding = 0xe320f000; // NOP
246   if (isThumb()) {
247     const uint16_t nopEncoding = hasNOP() ? Thumb2_16bitNopEncoding
248                                           : Thumb1_16bitNopEncoding;
249     uint64_t NumNops = Count / 2;
250     for (uint64_t i = 0; i != NumNops; ++i)
251       OW->Write16(nopEncoding);
252     if (Count & 1)
253       OW->Write8(0);
254     return true;
255   }
256   // ARM mode
257   const uint32_t nopEncoding = hasNOP() ? ARMv6T2_NopEncoding
258                                         : ARMv4_NopEncoding;
259   uint64_t NumNops = Count / 4;
260   for (uint64_t i = 0; i != NumNops; ++i)
261     OW->Write32(nopEncoding);
262   // FIXME: should this function return false when unable to write exactly
263   // 'Count' bytes with NOP encodings?
264   switch (Count % 4) {
265   default: break; // No leftover bytes to write
266   case 1: OW->Write8(0); break;
267   case 2: OW->Write16(0); break;
268   case 3: OW->Write16(0); OW->Write8(0xa0); break;
269   }
270
271   return true;
272 }
273
274 static unsigned adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
275                                  MCContext *Ctx = NULL) {
276   unsigned Kind = Fixup.getKind();
277   switch (Kind) {
278   default:
279     llvm_unreachable("Unknown fixup kind!");
280   case FK_Data_1:
281   case FK_Data_2:
282   case FK_Data_4:
283     return Value;
284   case ARM::fixup_arm_movt_hi16:
285     Value >>= 16;
286     // Fallthrough
287   case ARM::fixup_arm_movw_lo16:
288   case ARM::fixup_arm_movt_hi16_pcrel:
289   case ARM::fixup_arm_movw_lo16_pcrel: {
290     unsigned Hi4 = (Value & 0xF000) >> 12;
291     unsigned Lo12 = Value & 0x0FFF;
292     // inst{19-16} = Hi4;
293     // inst{11-0} = Lo12;
294     Value = (Hi4 << 16) | (Lo12);
295     return Value;
296   }
297   case ARM::fixup_t2_movt_hi16:
298     Value >>= 16;
299     // Fallthrough
300   case ARM::fixup_t2_movw_lo16:
301   case ARM::fixup_t2_movt_hi16_pcrel:  //FIXME: Shouldn't this be shifted like
302                                        // the other hi16 fixup?
303   case ARM::fixup_t2_movw_lo16_pcrel: {
304     unsigned Hi4 = (Value & 0xF000) >> 12;
305     unsigned i = (Value & 0x800) >> 11;
306     unsigned Mid3 = (Value & 0x700) >> 8;
307     unsigned Lo8 = Value & 0x0FF;
308     // inst{19-16} = Hi4;
309     // inst{26} = i;
310     // inst{14-12} = Mid3;
311     // inst{7-0} = Lo8;
312     Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
313     uint64_t swapped = (Value & 0xFFFF0000) >> 16;
314     swapped |= (Value & 0x0000FFFF) << 16;
315     return swapped;
316   }
317   case ARM::fixup_arm_ldst_pcrel_12:
318     // ARM PC-relative values are offset by 8.
319     Value -= 4;
320     // FALLTHROUGH
321   case ARM::fixup_t2_ldst_pcrel_12: {
322     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
323     Value -= 4;
324     bool isAdd = true;
325     if ((int64_t)Value < 0) {
326       Value = -Value;
327       isAdd = false;
328     }
329     if (Ctx && Value >= 4096)
330       Ctx->FatalError(Fixup.getLoc(), "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_ldst_pcrel_12) {
336       uint64_t swapped = (Value & 0xFFFF0000) >> 16;
337       swapped |= (Value & 0x0000FFFF) << 16;
338       return swapped;
339     }
340
341     return Value;
342   }
343   case ARM::fixup_thumb_adr_pcrel_10:
344     return ((Value - 4) >> 2) & 0xff;
345   case ARM::fixup_arm_adr_pcrel_12: {
346     // ARM PC-relative values are offset by 8.
347     Value -= 8;
348     unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
349     if ((int64_t)Value < 0) {
350       Value = -Value;
351       opc = 2; // 0b0010
352     }
353     if (Ctx && ARM_AM::getSOImmVal(Value) == -1)
354       Ctx->FatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
355     // Encode the immediate and shift the opcode into place.
356     return ARM_AM::getSOImmVal(Value) | (opc << 21);
357   }
358
359   case ARM::fixup_t2_adr_pcrel_12: {
360     Value -= 4;
361     unsigned opc = 0;
362     if ((int64_t)Value < 0) {
363       Value = -Value;
364       opc = 5;
365     }
366
367     uint32_t out = (opc << 21);
368     out |= (Value & 0x800) << 15;
369     out |= (Value & 0x700) << 4;
370     out |= (Value & 0x0FF);
371
372     uint64_t swapped = (out & 0xFFFF0000) >> 16;
373     swapped |= (out & 0x0000FFFF) << 16;
374     return swapped;
375   }
376
377   case ARM::fixup_arm_condbranch:
378   case ARM::fixup_arm_uncondbranch:
379   case ARM::fixup_arm_uncondbl:
380   case ARM::fixup_arm_condbl:
381   case ARM::fixup_arm_blx:
382     // These values don't encode the low two bits since they're always zero.
383     // Offset by 8 just as above.
384     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
385       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
386         return 0;
387     return 0xffffff & ((Value - 8) >> 2);
388   case ARM::fixup_t2_uncondbranch: {
389     Value = Value - 4;
390     Value >>= 1; // Low bit is not encoded.
391
392     uint32_t out = 0;
393     bool I =  Value & 0x800000;
394     bool J1 = Value & 0x400000;
395     bool J2 = Value & 0x200000;
396     J1 ^= I;
397     J2 ^= I;
398
399     out |= I  << 26; // S bit
400     out |= !J1 << 13; // J1 bit
401     out |= !J2 << 11; // J2 bit
402     out |= (Value & 0x1FF800)  << 5; // imm6 field
403     out |= (Value & 0x0007FF);        // imm11 field
404
405     uint64_t swapped = (out & 0xFFFF0000) >> 16;
406     swapped |= (out & 0x0000FFFF) << 16;
407     return swapped;
408   }
409   case ARM::fixup_t2_condbranch: {
410     Value = Value - 4;
411     Value >>= 1; // Low bit is not encoded.
412
413     uint64_t out = 0;
414     out |= (Value & 0x80000) << 7; // S bit
415     out |= (Value & 0x40000) >> 7; // J2 bit
416     out |= (Value & 0x20000) >> 4; // J1 bit
417     out |= (Value & 0x1F800) << 5; // imm6 field
418     out |= (Value & 0x007FF);      // imm11 field
419
420     uint32_t swapped = (out & 0xFFFF0000) >> 16;
421     swapped |= (out & 0x0000FFFF) << 16;
422     return swapped;
423   }
424   case ARM::fixup_arm_thumb_bl: {
425     // The value doesn't encode the low bit (always zero) and is offset by
426     // four. The 32-bit immediate value is encoded as
427     //   imm32 = SignExtend(S:I1:I2:imm10:imm11:0)
428     // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
429     // The value is encoded into disjoint bit positions in the destination
430     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
431     // J = either J1 or J2 bit
432     //
433     //   BL:  xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
434     //
435     // Note that the halfwords are stored high first, low second; so we need
436     // to transpose the fixup value here to map properly.
437     uint32_t offset = (Value - 4) >> 1;
438     uint32_t signBit = (offset & 0x800000) >> 23;
439     uint32_t I1Bit = (offset & 0x400000) >> 22;
440     uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
441     uint32_t I2Bit = (offset & 0x200000) >> 21;
442     uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
443     uint32_t imm10Bits = (offset & 0x1FF800) >> 11;
444     uint32_t imm11Bits = (offset & 0x000007FF);
445
446     uint32_t Binary = 0;
447     uint32_t firstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10Bits);
448     uint32_t secondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
449                           (uint16_t)imm11Bits);
450     Binary |= secondHalf << 16;
451     Binary |= firstHalf;
452     return Binary;
453   }
454   case ARM::fixup_arm_thumb_blx: {
455     // The value doesn't encode the low two bits (always zero) and is offset by
456     // four (see fixup_arm_thumb_cp). The 32-bit immediate value is encoded as
457     //   imm32 = SignExtend(S:I1:I2:imm10H:imm10L:00)
458     // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
459     // The value is encoded into disjoint bit positions in the destination
460     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
461     // J = either J1 or J2 bit, 0 = zero.
462     //
463     //   BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
464     //
465     // Note that the halfwords are stored high first, low second; so we need
466     // to transpose the fixup value here to map properly.
467     uint32_t offset = (Value - 2) >> 2;
468     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
469       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
470         offset = 0;
471     uint32_t signBit = (offset & 0x400000) >> 22;
472     uint32_t I1Bit = (offset & 0x200000) >> 21;
473     uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
474     uint32_t I2Bit = (offset & 0x100000) >> 20;
475     uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
476     uint32_t imm10HBits = (offset & 0xFFC00) >> 10;
477     uint32_t imm10LBits = (offset & 0x3FF);
478
479     uint32_t Binary = 0;
480     uint32_t firstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10HBits);
481     uint32_t secondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
482                           ((uint16_t)imm10LBits) << 1);
483     Binary |= secondHalf << 16;
484     Binary |= firstHalf;
485     return Binary;
486   }
487   case ARM::fixup_arm_thumb_cp:
488     // Offset by 4, and don't encode the low two bits. Two bytes of that
489     // 'off by 4' is implicitly handled by the half-word ordering of the
490     // Thumb encoding, so we only need to adjust by 2 here.
491     return ((Value - 2) >> 2) & 0xff;
492   case ARM::fixup_arm_thumb_cb: {
493     // Offset by 4 and don't encode the lower bit, which is always 0.
494     uint32_t Binary = (Value - 4) >> 1;
495     return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
496   }
497   case ARM::fixup_arm_thumb_br:
498     // Offset by 4 and don't encode the lower bit, which is always 0.
499     return ((Value - 4) >> 1) & 0x7ff;
500   case ARM::fixup_arm_thumb_bcc:
501     // Offset by 4 and don't encode the lower bit, which is always 0.
502     return ((Value - 4) >> 1) & 0xff;
503   case ARM::fixup_arm_pcrel_10_unscaled: {
504     Value = Value - 8; // ARM fixups offset by an additional word and don't
505                        // need to adjust for the half-word ordering.
506     bool isAdd = true;
507     if ((int64_t)Value < 0) {
508       Value = -Value;
509       isAdd = false;
510     }
511     // The value has the low 4 bits encoded in [3:0] and the high 4 in [11:8].
512     if (Ctx && Value >= 256)
513       Ctx->FatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
514     Value = (Value & 0xf) | ((Value & 0xf0) << 4);
515     return Value | (isAdd << 23);
516   }
517   case ARM::fixup_arm_pcrel_10:
518     Value = Value - 4; // ARM fixups offset by an additional word and don't
519                        // need to adjust for the half-word ordering.
520     // Fall through.
521   case ARM::fixup_t2_pcrel_10: {
522     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
523     Value = Value - 4;
524     bool isAdd = true;
525     if ((int64_t)Value < 0) {
526       Value = -Value;
527       isAdd = false;
528     }
529     // These values don't encode the low two bits since they're always zero.
530     Value >>= 2;
531     if (Ctx && Value >= 256)
532       Ctx->FatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
533     Value |= isAdd << 23;
534
535     // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
536     // swapped.
537     if (Kind == ARM::fixup_t2_pcrel_10) {
538       uint32_t swapped = (Value & 0xFFFF0000) >> 16;
539       swapped |= (Value & 0x0000FFFF) << 16;
540       return swapped;
541     }
542
543     return Value;
544   }
545   }
546 }
547
548 void ARMAsmBackend::processFixupValue(const MCAssembler &Asm,
549                                       const MCAsmLayout &Layout,
550                                       const MCFixup &Fixup,
551                                       const MCFragment *DF,
552                                       MCValue &Target, uint64_t &Value,
553                                       bool &IsResolved) {
554   const MCSymbolRefExpr *A = Target.getSymA();
555   // Some fixups to thumb function symbols need the low bit (thumb bit)
556   // twiddled.
557   if ((unsigned)Fixup.getKind() != ARM::fixup_arm_ldst_pcrel_12 &&
558       (unsigned)Fixup.getKind() != ARM::fixup_t2_ldst_pcrel_12 &&
559       (unsigned)Fixup.getKind() != ARM::fixup_arm_adr_pcrel_12 &&
560       (unsigned)Fixup.getKind() != ARM::fixup_thumb_adr_pcrel_10 &&
561       (unsigned)Fixup.getKind() != ARM::fixup_t2_adr_pcrel_12 &&
562       (unsigned)Fixup.getKind() != ARM::fixup_arm_thumb_cp) {
563     if (A) {
564       const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
565       if (Asm.isThumbFunc(&Sym))
566         Value |= 1;
567     }
568   }
569   // For Thumb1 BL instruction, it is possible to be a long jump between
570   // the basic blocks of the same function.  Thus, we would like to resolve
571   // the offset when the destination has the same MCFragment.
572   if (A && (unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_bl) {
573     const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
574     MCSymbolData &SymData = Asm.getSymbolData(Sym);
575     IsResolved = (SymData.getFragment() == DF);
576   }
577   // We must always generate a relocation for BL/BLX instructions if we have
578   // a symbol to reference, as the linker relies on knowing the destination
579   // symbol's thumb-ness to get interworking right.
580   if (A && ((unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_blx ||
581             (unsigned)Fixup.getKind() == ARM::fixup_arm_blx ||
582             (unsigned)Fixup.getKind() == ARM::fixup_arm_uncondbl ||
583             (unsigned)Fixup.getKind() == ARM::fixup_arm_condbl))
584     IsResolved = false;
585
586   // Try to get the encoded value for the fixup as-if we're mapping it into
587   // the instruction. This allows adjustFixupValue() to issue a diagnostic
588   // if the value aren't invalid.
589   (void)adjustFixupValue(Fixup, Value, &Asm.getContext());
590 }
591
592 /// getFixupKindNumBytes - The number of bytes the fixup may change.
593 static unsigned getFixupKindNumBytes(unsigned Kind) {
594   switch (Kind) {
595   default:
596     llvm_unreachable("Unknown fixup kind!");
597
598   case FK_Data_1:
599   case ARM::fixup_arm_thumb_bcc:
600   case ARM::fixup_arm_thumb_cp:
601   case ARM::fixup_thumb_adr_pcrel_10:
602     return 1;
603
604   case FK_Data_2:
605   case ARM::fixup_arm_thumb_br:
606   case ARM::fixup_arm_thumb_cb:
607     return 2;
608
609   case ARM::fixup_arm_pcrel_10_unscaled:
610   case ARM::fixup_arm_ldst_pcrel_12:
611   case ARM::fixup_arm_pcrel_10:
612   case ARM::fixup_arm_adr_pcrel_12:
613   case ARM::fixup_arm_uncondbl:
614   case ARM::fixup_arm_condbl:
615   case ARM::fixup_arm_blx:
616   case ARM::fixup_arm_condbranch:
617   case ARM::fixup_arm_uncondbranch:
618     return 3;
619
620   case FK_Data_4:
621   case ARM::fixup_t2_ldst_pcrel_12:
622   case ARM::fixup_t2_condbranch:
623   case ARM::fixup_t2_uncondbranch:
624   case ARM::fixup_t2_pcrel_10:
625   case ARM::fixup_t2_adr_pcrel_12:
626   case ARM::fixup_arm_thumb_bl:
627   case ARM::fixup_arm_thumb_blx:
628   case ARM::fixup_arm_movt_hi16:
629   case ARM::fixup_arm_movw_lo16:
630   case ARM::fixup_arm_movt_hi16_pcrel:
631   case ARM::fixup_arm_movw_lo16_pcrel:
632   case ARM::fixup_t2_movt_hi16:
633   case ARM::fixup_t2_movw_lo16:
634   case ARM::fixup_t2_movt_hi16_pcrel:
635   case ARM::fixup_t2_movw_lo16_pcrel:
636     return 4;
637   }
638 }
639
640 void ARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
641                                unsigned DataSize, uint64_t Value) const {
642   unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
643   Value = adjustFixupValue(Fixup, Value);
644   if (!Value) return;           // Doesn't change encoding.
645
646   unsigned Offset = Fixup.getOffset();
647   assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
648
649   // For each byte of the fragment that the fixup touches, mask in the bits from
650   // the fixup value. The Value has been "split up" into the appropriate
651   // bitfields above.
652   for (unsigned i = 0; i != NumBytes; ++i)
653     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
654 }
655
656 namespace {
657
658 // FIXME: This should be in a separate file.
659 // ELF is an ELF of course...
660 class ELFARMAsmBackend : public ARMAsmBackend {
661 public:
662   uint8_t OSABI;
663   ELFARMAsmBackend(const Target &T, const StringRef TT,
664                    uint8_t _OSABI)
665     : ARMAsmBackend(T, TT), OSABI(_OSABI) { }
666
667   MCObjectWriter *createObjectWriter(raw_ostream &OS) const override {
668     return createARMELFObjectWriter(OS, OSABI);
669   }
670 };
671
672 // FIXME: This should be in a separate file.
673 class DarwinARMAsmBackend : public ARMAsmBackend {
674 public:
675   const MachO::CPUSubTypeARM Subtype;
676   DarwinARMAsmBackend(const Target &T, const StringRef TT,
677                       MachO::CPUSubTypeARM st)
678     : ARMAsmBackend(T, TT), Subtype(st) {
679       HasDataInCodeSupport = true;
680     }
681
682   MCObjectWriter *createObjectWriter(raw_ostream &OS) const override {
683     return createARMMachObjectWriter(OS, /*Is64Bit=*/false,
684                                      MachO::CPU_TYPE_ARM,
685                                      Subtype);
686   }
687 };
688
689 } // end anonymous namespace
690
691 MCAsmBackend *llvm::createARMAsmBackend(const Target &T,
692                                         const MCRegisterInfo &MRI,
693                                         StringRef TT, StringRef CPU) {
694   Triple TheTriple(TT);
695
696   if (TheTriple.isOSBinFormatMachO()) {
697     MachO::CPUSubTypeARM CS =
698       StringSwitch<MachO::CPUSubTypeARM>(TheTriple.getArchName())
699       .Cases("armv4t", "thumbv4t", MachO::CPU_SUBTYPE_ARM_V4T)
700       .Cases("armv5e", "thumbv5e", MachO::CPU_SUBTYPE_ARM_V5TEJ)
701       .Cases("armv6", "thumbv6", MachO::CPU_SUBTYPE_ARM_V6)
702       .Cases("armv6m", "thumbv6m", MachO::CPU_SUBTYPE_ARM_V6M)
703       .Cases("armv7em", "thumbv7em", MachO::CPU_SUBTYPE_ARM_V7EM)
704       .Cases("armv7k", "thumbv7k", MachO::CPU_SUBTYPE_ARM_V7K)
705       .Cases("armv7m", "thumbv7m", MachO::CPU_SUBTYPE_ARM_V7M)
706       .Cases("armv7s", "thumbv7s", MachO::CPU_SUBTYPE_ARM_V7S)
707       .Default(MachO::CPU_SUBTYPE_ARM_V7);
708
709     return new DarwinARMAsmBackend(T, TT, CS);
710   }
711
712 #if 0
713   // FIXME: Introduce yet another checker but assert(0).
714   if (TheTriple.isOSBinFormatCOFF())
715     assert(0 && "Windows not supported on ARM");
716 #endif
717
718   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(Triple(TT).getOS());
719   return new ELFARMAsmBackend(T, TT, OSABI);
720 }