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