OSDN Git Service

ARM: report an error when attempting to target a misalgined BLX
[android-x86/external-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/ARMAsmBackend.h"
13 #include "MCTargetDesc/ARMAsmBackendDarwin.h"
14 #include "MCTargetDesc/ARMAsmBackendELF.h"
15 #include "MCTargetDesc/ARMAsmBackendWinCOFF.h"
16 #include "MCTargetDesc/ARMBaseInfo.h"
17 #include "MCTargetDesc/ARMFixupKinds.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDirectives.h"
23 #include "llvm/MC/MCELFObjectWriter.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCMachObjectWriter.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/MachO.h"
38 #include "llvm/Support/TargetParser.h"
39 #include "llvm/Support/raw_ostream.h"
40 using namespace llvm;
41
42 namespace {
43 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
44 public:
45   ARMELFObjectWriter(uint8_t OSABI)
46       : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
47                                 /*HasRelocationAddend*/ false) {}
48 };
49 } // end anonymous namespace
50
51 const MCFixupKindInfo &ARMAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
52   const static MCFixupKindInfo InfosLE[ARM::NumTargetFixupKinds] = {
53       // This table *must* be in the order that the fixup_* kinds are defined in
54       // ARMFixupKinds.h.
55       //
56       // Name                      Offset (bits) Size (bits)     Flags
57       {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
58       {"fixup_t2_ldst_pcrel_12", 0, 32,
59        MCFixupKindInfo::FKF_IsPCRel |
60            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
61       {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
62       {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
63       {"fixup_t2_pcrel_10", 0, 32,
64        MCFixupKindInfo::FKF_IsPCRel |
65            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
66       {"fixup_arm_pcrel_9", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
67       {"fixup_t2_pcrel_9", 0, 32,
68        MCFixupKindInfo::FKF_IsPCRel |
69            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
70       {"fixup_thumb_adr_pcrel_10", 0, 8,
71        MCFixupKindInfo::FKF_IsPCRel |
72            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
73       {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
74       {"fixup_t2_adr_pcrel_12", 0, 32,
75        MCFixupKindInfo::FKF_IsPCRel |
76            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
77       {"fixup_arm_condbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
78       {"fixup_arm_uncondbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
79       {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
80       {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
81       {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
82       {"fixup_arm_uncondbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
83       {"fixup_arm_condbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
84       {"fixup_arm_blx", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
85       {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
86       {"fixup_arm_thumb_blx", 0, 32,
87        MCFixupKindInfo::FKF_IsPCRel |
88            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
89       {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
90       {"fixup_arm_thumb_cp", 0, 8,
91        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
95       // - 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       {"fixup_arm_mod_imm", 0, 12, 0},
101   };
102   const static MCFixupKindInfo InfosBE[ARM::NumTargetFixupKinds] = {
103       // This table *must* be in the order that the fixup_* kinds are defined in
104       // ARMFixupKinds.h.
105       //
106       // Name                      Offset (bits) Size (bits)     Flags
107       {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
108       {"fixup_t2_ldst_pcrel_12", 0, 32,
109        MCFixupKindInfo::FKF_IsPCRel |
110            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
111       {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
112       {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
113       {"fixup_t2_pcrel_10", 0, 32,
114        MCFixupKindInfo::FKF_IsPCRel |
115            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
116       {"fixup_arm_pcrel_9", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
117       {"fixup_t2_pcrel_9", 0, 32,
118        MCFixupKindInfo::FKF_IsPCRel |
119            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
120       {"fixup_thumb_adr_pcrel_10", 8, 8,
121        MCFixupKindInfo::FKF_IsPCRel |
122            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
123       {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
124       {"fixup_t2_adr_pcrel_12", 0, 32,
125        MCFixupKindInfo::FKF_IsPCRel |
126            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
127       {"fixup_arm_condbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
128       {"fixup_arm_uncondbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
129       {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
130       {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
131       {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
132       {"fixup_arm_uncondbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
133       {"fixup_arm_condbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
134       {"fixup_arm_blx", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
135       {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
136       {"fixup_arm_thumb_blx", 0, 32,
137        MCFixupKindInfo::FKF_IsPCRel |
138            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
139       {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
140       {"fixup_arm_thumb_cp", 8, 8,
141        MCFixupKindInfo::FKF_IsPCRel |
142            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
143       {"fixup_arm_thumb_bcc", 8, 8, MCFixupKindInfo::FKF_IsPCRel},
144       // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
145       // - 19.
146       {"fixup_arm_movt_hi16", 12, 20, 0},
147       {"fixup_arm_movw_lo16", 12, 20, 0},
148       {"fixup_t2_movt_hi16", 12, 20, 0},
149       {"fixup_t2_movw_lo16", 12, 20, 0},
150       {"fixup_arm_mod_imm", 20, 12, 0},
151   };
152
153   if (Kind < FirstTargetFixupKind)
154     return MCAsmBackend::getFixupKindInfo(Kind);
155
156   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
157          "Invalid kind!");
158   return (IsLittleEndian ? InfosLE : InfosBE)[Kind - FirstTargetFixupKind];
159 }
160
161 void ARMAsmBackend::handleAssemblerFlag(MCAssemblerFlag Flag) {
162   switch (Flag) {
163   default:
164     break;
165   case MCAF_Code16:
166     setIsThumb(true);
167     break;
168   case MCAF_Code32:
169     setIsThumb(false);
170     break;
171   }
172 }
173
174 unsigned ARMAsmBackend::getRelaxedOpcode(unsigned Op) const {
175   bool HasThumb2 = STI->getFeatureBits()[ARM::FeatureThumb2];
176   bool HasV8MBaselineOps = STI->getFeatureBits()[ARM::HasV8MBaselineOps];
177
178   switch (Op) {
179   default:
180     return Op;
181   case ARM::tBcc:
182     return HasThumb2 ? (unsigned)ARM::t2Bcc : Op;
183   case ARM::tLDRpci:
184     return HasThumb2 ? (unsigned)ARM::t2LDRpci : Op;
185   case ARM::tADR:
186     return HasThumb2 ? (unsigned)ARM::t2ADR : Op;
187   case ARM::tB:
188     return HasV8MBaselineOps ? (unsigned)ARM::t2B : Op;
189   case ARM::tCBZ:
190     return ARM::tHINT;
191   case ARM::tCBNZ:
192     return ARM::tHINT;
193   }
194 }
195
196 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
197   if (getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode())
198     return true;
199   return false;
200 }
201
202 const char *ARMAsmBackend::reasonForFixupRelaxation(const MCFixup &Fixup,
203                                                     uint64_t Value) const {
204   switch ((unsigned)Fixup.getKind()) {
205   case ARM::fixup_arm_thumb_br: {
206     // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
207     // low bit being an implied zero. There's an implied +4 offset for the
208     // branch, so we adjust the other way here to determine what's
209     // encodable.
210     //
211     // Relax if the value is too big for a (signed) i8.
212     int64_t Offset = int64_t(Value) - 4;
213     if (Offset > 2046 || Offset < -2048)
214       return "out of range pc-relative fixup value";
215     break;
216   }
217   case ARM::fixup_arm_thumb_bcc: {
218     // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with the
219     // low bit being an implied zero. There's an implied +4 offset for the
220     // branch, so we adjust the other way here to determine what's
221     // encodable.
222     //
223     // Relax if the value is too big for a (signed) i8.
224     int64_t Offset = int64_t(Value) - 4;
225     if (Offset > 254 || Offset < -256)
226       return "out of range pc-relative fixup value";
227     break;
228   }
229   case ARM::fixup_thumb_adr_pcrel_10:
230   case ARM::fixup_arm_thumb_cp: {
231     // If the immediate is negative, greater than 1020, or not a multiple
232     // of four, the wide version of the instruction must be used.
233     int64_t Offset = int64_t(Value) - 4;
234     if (Offset & 3)
235       return "misaligned pc-relative fixup value";
236     else if (Offset > 1020 || Offset < 0)
237       return "out of range pc-relative fixup value";
238     break;
239   }
240   case ARM::fixup_arm_thumb_cb: {
241     // If we have a Thumb CBZ or CBNZ instruction and its target is the next
242     // instruction it is is actually out of range for the instruction.
243     // It will be changed to a NOP.
244     int64_t Offset = (Value & ~1);
245     if (Offset == 2)
246       return "will be converted to nop";
247     break;
248   }
249   default:
250     llvm_unreachable("Unexpected fixup kind in reasonForFixupRelaxation()!");
251   }
252   return nullptr;
253 }
254
255 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
256                                          const MCRelaxableFragment *DF,
257                                          const MCAsmLayout &Layout) const {
258   return reasonForFixupRelaxation(Fixup, Value);
259 }
260
261 void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
262   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
263
264   // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
265   if (RelaxedOp == Inst.getOpcode()) {
266     SmallString<256> Tmp;
267     raw_svector_ostream OS(Tmp);
268     Inst.dump_pretty(OS);
269     OS << "\n";
270     report_fatal_error("unexpected instruction to relax: " + OS.str());
271   }
272
273   // If we are changing Thumb CBZ or CBNZ instruction to a NOP, aka tHINT, we
274   // have to change the operands too.
275   if ((Inst.getOpcode() == ARM::tCBZ || Inst.getOpcode() == ARM::tCBNZ) &&
276       RelaxedOp == ARM::tHINT) {
277     Res.setOpcode(RelaxedOp);
278     Res.addOperand(MCOperand::createImm(0));
279     Res.addOperand(MCOperand::createImm(14));
280     Res.addOperand(MCOperand::createReg(0));
281     return;
282   }
283
284   // The rest of instructions we're relaxing have the same operands.
285   // We just need to update to the proper opcode.
286   Res = Inst;
287   Res.setOpcode(RelaxedOp);
288 }
289
290 bool ARMAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
291   const uint16_t Thumb1_16bitNopEncoding = 0x46c0; // using MOV r8,r8
292   const uint16_t Thumb2_16bitNopEncoding = 0xbf00; // NOP
293   const uint32_t ARMv4_NopEncoding = 0xe1a00000;   // using MOV r0,r0
294   const uint32_t ARMv6T2_NopEncoding = 0xe320f000; // NOP
295   if (isThumb()) {
296     const uint16_t nopEncoding =
297         hasNOP() ? Thumb2_16bitNopEncoding : Thumb1_16bitNopEncoding;
298     uint64_t NumNops = Count / 2;
299     for (uint64_t i = 0; i != NumNops; ++i)
300       OW->write16(nopEncoding);
301     if (Count & 1)
302       OW->write8(0);
303     return true;
304   }
305   // ARM mode
306   const uint32_t nopEncoding =
307       hasNOP() ? ARMv6T2_NopEncoding : ARMv4_NopEncoding;
308   uint64_t NumNops = Count / 4;
309   for (uint64_t i = 0; i != NumNops; ++i)
310     OW->write32(nopEncoding);
311   // FIXME: should this function return false when unable to write exactly
312   // 'Count' bytes with NOP encodings?
313   switch (Count % 4) {
314   default:
315     break; // No leftover bytes to write
316   case 1:
317     OW->write8(0);
318     break;
319   case 2:
320     OW->write16(0);
321     break;
322   case 3:
323     OW->write16(0);
324     OW->write8(0xa0);
325     break;
326   }
327
328   return true;
329 }
330
331 static uint32_t swapHalfWords(uint32_t Value, bool IsLittleEndian) {
332   if (IsLittleEndian) {
333     // Note that the halfwords are stored high first and low second in thumb;
334     // so we need to swap the fixup value here to map properly.
335     uint32_t Swapped = (Value & 0xFFFF0000) >> 16;
336     Swapped |= (Value & 0x0000FFFF) << 16;
337     return Swapped;
338   } else
339     return Value;
340 }
341
342 static uint32_t joinHalfWords(uint32_t FirstHalf, uint32_t SecondHalf,
343                               bool IsLittleEndian) {
344   uint32_t Value;
345
346   if (IsLittleEndian) {
347     Value = (SecondHalf & 0xFFFF) << 16;
348     Value |= (FirstHalf & 0xFFFF);
349   } else {
350     Value = (SecondHalf & 0xFFFF);
351     Value |= (FirstHalf & 0xFFFF) << 16;
352   }
353
354   return Value;
355 }
356
357 unsigned ARMAsmBackend::adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
358                                          bool IsPCRel, MCContext *Ctx,
359                                          bool IsLittleEndian,
360                                          bool IsResolved) const {
361   unsigned Kind = Fixup.getKind();
362   switch (Kind) {
363   default:
364     llvm_unreachable("Unknown fixup kind!");
365   case FK_Data_1:
366   case FK_Data_2:
367   case FK_Data_4:
368     return Value;
369   case FK_SecRel_2:
370     return Value;
371   case FK_SecRel_4:
372     return Value;
373   case ARM::fixup_arm_movt_hi16:
374     if (!IsPCRel)
375       Value >>= 16;
376   // Fallthrough
377   case ARM::fixup_arm_movw_lo16: {
378     unsigned Hi4 = (Value & 0xF000) >> 12;
379     unsigned Lo12 = Value & 0x0FFF;
380     // inst{19-16} = Hi4;
381     // inst{11-0} = Lo12;
382     Value = (Hi4 << 16) | (Lo12);
383     return Value;
384   }
385   case ARM::fixup_t2_movt_hi16:
386     if (!IsPCRel)
387       Value >>= 16;
388   // Fallthrough
389   case ARM::fixup_t2_movw_lo16: {
390     unsigned Hi4 = (Value & 0xF000) >> 12;
391     unsigned i = (Value & 0x800) >> 11;
392     unsigned Mid3 = (Value & 0x700) >> 8;
393     unsigned Lo8 = Value & 0x0FF;
394     // inst{19-16} = Hi4;
395     // inst{26} = i;
396     // inst{14-12} = Mid3;
397     // inst{7-0} = Lo8;
398     Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
399     return swapHalfWords(Value, IsLittleEndian);
400   }
401   case ARM::fixup_arm_ldst_pcrel_12:
402     // ARM PC-relative values are offset by 8.
403     Value -= 4;
404   // FALLTHROUGH
405   case ARM::fixup_t2_ldst_pcrel_12: {
406     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
407     Value -= 4;
408     bool isAdd = true;
409     if ((int64_t)Value < 0) {
410       Value = -Value;
411       isAdd = false;
412     }
413     if (Ctx && Value >= 4096) {
414       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
415       return 0;
416     }
417     Value |= isAdd << 23;
418
419     // Same addressing mode as fixup_arm_pcrel_10,
420     // but with 16-bit halfwords swapped.
421     if (Kind == ARM::fixup_t2_ldst_pcrel_12)
422       return swapHalfWords(Value, IsLittleEndian);
423
424     return Value;
425   }
426   case ARM::fixup_arm_adr_pcrel_12: {
427     // ARM PC-relative values are offset by 8.
428     Value -= 8;
429     unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
430     if ((int64_t)Value < 0) {
431       Value = -Value;
432       opc = 2; // 0b0010
433     }
434     if (Ctx && ARM_AM::getSOImmVal(Value) == -1) {
435       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
436       return 0;
437     }
438     // Encode the immediate and shift the opcode into place.
439     return ARM_AM::getSOImmVal(Value) | (opc << 21);
440   }
441
442   case ARM::fixup_t2_adr_pcrel_12: {
443     Value -= 4;
444     unsigned opc = 0;
445     if ((int64_t)Value < 0) {
446       Value = -Value;
447       opc = 5;
448     }
449
450     uint32_t out = (opc << 21);
451     out |= (Value & 0x800) << 15;
452     out |= (Value & 0x700) << 4;
453     out |= (Value & 0x0FF);
454
455     return swapHalfWords(out, IsLittleEndian);
456   }
457
458   case ARM::fixup_arm_condbranch:
459   case ARM::fixup_arm_uncondbranch:
460   case ARM::fixup_arm_uncondbl:
461   case ARM::fixup_arm_condbl:
462   case ARM::fixup_arm_blx:
463     // These values don't encode the low two bits since they're always zero.
464     // Offset by 8 just as above.
465     if (const MCSymbolRefExpr *SRE =
466             dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
467       if (SRE->getKind() == MCSymbolRefExpr::VK_TLSCALL)
468         return 0;
469     return 0xffffff & ((Value - 8) >> 2);
470   case ARM::fixup_t2_uncondbranch: {
471     Value = Value - 4;
472     Value >>= 1; // Low bit is not encoded.
473
474     uint32_t out = 0;
475     bool I = Value & 0x800000;
476     bool J1 = Value & 0x400000;
477     bool J2 = Value & 0x200000;
478     J1 ^= I;
479     J2 ^= I;
480
481     out |= I << 26;                 // S bit
482     out |= !J1 << 13;               // J1 bit
483     out |= !J2 << 11;               // J2 bit
484     out |= (Value & 0x1FF800) << 5; // imm6 field
485     out |= (Value & 0x0007FF);      // imm11 field
486
487     return swapHalfWords(out, IsLittleEndian);
488   }
489   case ARM::fixup_t2_condbranch: {
490     Value = Value - 4;
491     Value >>= 1; // Low bit is not encoded.
492
493     uint64_t out = 0;
494     out |= (Value & 0x80000) << 7; // S bit
495     out |= (Value & 0x40000) >> 7; // J2 bit
496     out |= (Value & 0x20000) >> 4; // J1 bit
497     out |= (Value & 0x1F800) << 5; // imm6 field
498     out |= (Value & 0x007FF);      // imm11 field
499
500     return swapHalfWords(out, IsLittleEndian);
501   }
502   case ARM::fixup_arm_thumb_bl: {
503     // The value doesn't encode the low bit (always zero) and is offset by
504     // four. The 32-bit immediate value is encoded as
505     //   imm32 = SignExtend(S:I1:I2:imm10:imm11:0)
506     // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
507     // The value is encoded into disjoint bit positions in the destination
508     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
509     // J = either J1 or J2 bit
510     //
511     //   BL:  xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
512     //
513     // Note that the halfwords are stored high first, low second; so we need
514     // to transpose the fixup value here to map properly.
515     uint32_t offset = (Value - 4) >> 1;
516     uint32_t signBit = (offset & 0x800000) >> 23;
517     uint32_t I1Bit = (offset & 0x400000) >> 22;
518     uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
519     uint32_t I2Bit = (offset & 0x200000) >> 21;
520     uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
521     uint32_t imm10Bits = (offset & 0x1FF800) >> 11;
522     uint32_t imm11Bits = (offset & 0x000007FF);
523
524     uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10Bits);
525     uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
526                            (uint16_t)imm11Bits);
527     return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
528   }
529   case ARM::fixup_arm_thumb_blx: {
530     // The value doesn't encode the low two bits (always zero) and is offset by
531     // four (see fixup_arm_thumb_cp). The 32-bit immediate value is encoded as
532     //   imm32 = SignExtend(S:I1:I2:imm10H:imm10L:00)
533     // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
534     // The value is encoded into disjoint bit positions in the destination
535     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
536     // J = either J1 or J2 bit, 0 = zero.
537     //
538     //   BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
539     //
540     // Note that the halfwords are stored high first, low second; so we need
541     // to transpose the fixup value here to map properly.
542     if (Ctx && Value  % 4 != 0) {
543       Ctx->reportError(Fixup.getLoc(), "misaligned ARM call destination");
544       return 0;
545     }
546
547     uint32_t offset = (Value - 4) >> 2;
548     if (const MCSymbolRefExpr *SRE =
549             dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
550       if (SRE->getKind() == MCSymbolRefExpr::VK_TLSCALL)
551         offset = 0;
552     uint32_t signBit = (offset & 0x400000) >> 22;
553     uint32_t I1Bit = (offset & 0x200000) >> 21;
554     uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
555     uint32_t I2Bit = (offset & 0x100000) >> 20;
556     uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
557     uint32_t imm10HBits = (offset & 0xFFC00) >> 10;
558     uint32_t imm10LBits = (offset & 0x3FF);
559
560     uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10HBits);
561     uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
562                            ((uint16_t)imm10LBits) << 1);
563     return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
564   }
565   case ARM::fixup_thumb_adr_pcrel_10:
566   case ARM::fixup_arm_thumb_cp:
567     // On CPUs supporting Thumb2, this will be relaxed to an ldr.w, otherwise we
568     // could have an error on our hands.
569     if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2] && IsResolved) {
570       const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
571       if (FixupDiagnostic) {
572         Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
573         return 0;
574       }
575     }
576     // Offset by 4, and don't encode the low two bits.
577     return ((Value - 4) >> 2) & 0xff;
578   case ARM::fixup_arm_thumb_cb: {
579     // Offset by 4 and don't encode the lower bit, which is always 0.
580     // FIXME: diagnose if no Thumb2
581     uint32_t Binary = (Value - 4) >> 1;
582     return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
583   }
584   case ARM::fixup_arm_thumb_br:
585     // Offset by 4 and don't encode the lower bit, which is always 0.
586     if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2] &&
587                !STI->getFeatureBits()[ARM::HasV8MBaselineOps]) {
588       const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
589       if (FixupDiagnostic) {
590         Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
591         return 0;
592       }
593     }
594     return ((Value - 4) >> 1) & 0x7ff;
595   case ARM::fixup_arm_thumb_bcc:
596     // Offset by 4 and don't encode the lower bit, which is always 0.
597     if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
598       const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
599       if (FixupDiagnostic) {
600         Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
601         return 0;
602       }
603     }
604     return ((Value - 4) >> 1) & 0xff;
605   case ARM::fixup_arm_pcrel_10_unscaled: {
606     Value = Value - 8; // ARM fixups offset by an additional word and don't
607                        // need to adjust for the half-word ordering.
608     bool isAdd = true;
609     if ((int64_t)Value < 0) {
610       Value = -Value;
611       isAdd = false;
612     }
613     // The value has the low 4 bits encoded in [3:0] and the high 4 in [11:8].
614     if (Ctx && Value >= 256) {
615       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
616       return 0;
617     }
618     Value = (Value & 0xf) | ((Value & 0xf0) << 4);
619     return Value | (isAdd << 23);
620   }
621   case ARM::fixup_arm_pcrel_10:
622     Value = Value - 4; // ARM fixups offset by an additional word and don't
623                        // need to adjust for the half-word ordering.
624                        // Fall through.
625   case ARM::fixup_t2_pcrel_10: {
626     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
627     Value = Value - 4;
628     bool isAdd = true;
629     if ((int64_t)Value < 0) {
630       Value = -Value;
631       isAdd = false;
632     }
633     // These values don't encode the low two bits since they're always zero.
634     Value >>= 2;
635     if (Ctx && Value >= 256) {
636       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
637       return 0;
638     }
639     Value |= isAdd << 23;
640
641     // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
642     // swapped.
643     if (Kind == ARM::fixup_t2_pcrel_10)
644       return swapHalfWords(Value, IsLittleEndian);
645
646     return Value;
647   }
648   case ARM::fixup_arm_pcrel_9:
649     Value = Value - 4; // ARM fixups offset by an additional word and don't
650                        // need to adjust for the half-word ordering.
651                        // Fall through.
652   case ARM::fixup_t2_pcrel_9: {
653     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
654     Value = Value - 4;
655     bool isAdd = true;
656     if ((int64_t)Value < 0) {
657       Value = -Value;
658       isAdd = false;
659     }
660     // These values don't encode the low bit since it's always zero.
661     if (Ctx && (Value & 1)) {
662       Ctx->reportError(Fixup.getLoc(), "invalid value for this fixup");
663       return 0;
664     }
665     Value >>= 1;
666     if (Ctx && Value >= 256) {
667       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
668       return 0;
669     }
670     Value |= isAdd << 23;
671
672     // Same addressing mode as fixup_arm_pcrel_9, but with 16-bit halfwords
673     // swapped.
674     if (Kind == ARM::fixup_t2_pcrel_9)
675       return swapHalfWords(Value, IsLittleEndian);
676
677     return Value;
678   }
679   case ARM::fixup_arm_mod_imm:
680     Value = ARM_AM::getSOImmVal(Value);
681     if (Ctx && Value >> 12) {
682       Ctx->reportError(Fixup.getLoc(), "out of range immediate fixup value");
683       return 0;
684     }
685     return Value;
686   }
687 }
688
689 void ARMAsmBackend::processFixupValue(const MCAssembler &Asm,
690                                       const MCAsmLayout &Layout,
691                                       const MCFixup &Fixup,
692                                       const MCFragment *DF,
693                                       const MCValue &Target, uint64_t &Value,
694                                       bool &IsResolved) {
695   const MCSymbolRefExpr *A = Target.getSymA();
696   const MCSymbol *Sym = A ? &A->getSymbol() : nullptr;
697   // Some fixups to thumb function symbols need the low bit (thumb bit)
698   // twiddled.
699   if ((unsigned)Fixup.getKind() != ARM::fixup_arm_ldst_pcrel_12 &&
700       (unsigned)Fixup.getKind() != ARM::fixup_t2_ldst_pcrel_12 &&
701       (unsigned)Fixup.getKind() != ARM::fixup_arm_adr_pcrel_12 &&
702       (unsigned)Fixup.getKind() != ARM::fixup_thumb_adr_pcrel_10 &&
703       (unsigned)Fixup.getKind() != ARM::fixup_t2_adr_pcrel_12 &&
704       (unsigned)Fixup.getKind() != ARM::fixup_arm_thumb_cp) {
705     if (Sym) {
706       if (Asm.isThumbFunc(Sym))
707         Value |= 1;
708     }
709   }
710   if (IsResolved && (unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_bl) {
711     assert(Sym && "How did we resolve this?");
712
713     // If the symbol is external the linker will handle it.
714     // FIXME: Should we handle it as an optimization?
715
716     // If the symbol is out of range, produce a relocation and hope the
717     // linker can handle it. GNU AS produces an error in this case.
718     if (Sym->isExternal() || Value >= 0x400004)
719       IsResolved = false;
720   }
721   // We must always generate a relocation for BL/BLX instructions if we have
722   // a symbol to reference, as the linker relies on knowing the destination
723   // symbol's thumb-ness to get interworking right.
724   if (A && ((unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_blx ||
725             (unsigned)Fixup.getKind() == ARM::fixup_arm_blx ||
726             (unsigned)Fixup.getKind() == ARM::fixup_arm_uncondbl ||
727             (unsigned)Fixup.getKind() == ARM::fixup_arm_condbl))
728     IsResolved = false;
729
730   // Try to get the encoded value for the fixup as-if we're mapping it into
731   // the instruction. This allows adjustFixupValue() to issue a diagnostic
732   // if the value aren't invalid.
733   (void)adjustFixupValue(Fixup, Value, false, &Asm.getContext(),
734                          IsLittleEndian, IsResolved);
735 }
736
737 /// getFixupKindNumBytes - The number of bytes the fixup may change.
738 static unsigned getFixupKindNumBytes(unsigned Kind) {
739   switch (Kind) {
740   default:
741     llvm_unreachable("Unknown fixup kind!");
742
743   case FK_Data_1:
744   case ARM::fixup_arm_thumb_bcc:
745   case ARM::fixup_arm_thumb_cp:
746   case ARM::fixup_thumb_adr_pcrel_10:
747     return 1;
748
749   case FK_Data_2:
750   case ARM::fixup_arm_thumb_br:
751   case ARM::fixup_arm_thumb_cb:
752   case ARM::fixup_arm_mod_imm:
753     return 2;
754
755   case ARM::fixup_arm_pcrel_10_unscaled:
756   case ARM::fixup_arm_ldst_pcrel_12:
757   case ARM::fixup_arm_pcrel_10:
758   case ARM::fixup_arm_pcrel_9:
759   case ARM::fixup_arm_adr_pcrel_12:
760   case ARM::fixup_arm_uncondbl:
761   case ARM::fixup_arm_condbl:
762   case ARM::fixup_arm_blx:
763   case ARM::fixup_arm_condbranch:
764   case ARM::fixup_arm_uncondbranch:
765     return 3;
766
767   case FK_Data_4:
768   case ARM::fixup_t2_ldst_pcrel_12:
769   case ARM::fixup_t2_condbranch:
770   case ARM::fixup_t2_uncondbranch:
771   case ARM::fixup_t2_pcrel_10:
772   case ARM::fixup_t2_pcrel_9:
773   case ARM::fixup_t2_adr_pcrel_12:
774   case ARM::fixup_arm_thumb_bl:
775   case ARM::fixup_arm_thumb_blx:
776   case ARM::fixup_arm_movt_hi16:
777   case ARM::fixup_arm_movw_lo16:
778   case ARM::fixup_t2_movt_hi16:
779   case ARM::fixup_t2_movw_lo16:
780     return 4;
781
782   case FK_SecRel_2:
783     return 2;
784   case FK_SecRel_4:
785     return 4;
786   }
787 }
788
789 /// getFixupKindContainerSizeBytes - The number of bytes of the
790 /// container involved in big endian.
791 static unsigned getFixupKindContainerSizeBytes(unsigned Kind) {
792   switch (Kind) {
793   default:
794     llvm_unreachable("Unknown fixup kind!");
795
796   case FK_Data_1:
797     return 1;
798   case FK_Data_2:
799     return 2;
800   case FK_Data_4:
801     return 4;
802
803   case ARM::fixup_arm_thumb_bcc:
804   case ARM::fixup_arm_thumb_cp:
805   case ARM::fixup_thumb_adr_pcrel_10:
806   case ARM::fixup_arm_thumb_br:
807   case ARM::fixup_arm_thumb_cb:
808     // Instruction size is 2 bytes.
809     return 2;
810
811   case ARM::fixup_arm_pcrel_10_unscaled:
812   case ARM::fixup_arm_ldst_pcrel_12:
813   case ARM::fixup_arm_pcrel_10:
814   case ARM::fixup_arm_adr_pcrel_12:
815   case ARM::fixup_arm_uncondbl:
816   case ARM::fixup_arm_condbl:
817   case ARM::fixup_arm_blx:
818   case ARM::fixup_arm_condbranch:
819   case ARM::fixup_arm_uncondbranch:
820   case ARM::fixup_t2_ldst_pcrel_12:
821   case ARM::fixup_t2_condbranch:
822   case ARM::fixup_t2_uncondbranch:
823   case ARM::fixup_t2_pcrel_10:
824   case ARM::fixup_t2_adr_pcrel_12:
825   case ARM::fixup_arm_thumb_bl:
826   case ARM::fixup_arm_thumb_blx:
827   case ARM::fixup_arm_movt_hi16:
828   case ARM::fixup_arm_movw_lo16:
829   case ARM::fixup_t2_movt_hi16:
830   case ARM::fixup_t2_movw_lo16:
831   case ARM::fixup_arm_mod_imm:
832     // Instruction size is 4 bytes.
833     return 4;
834   }
835 }
836
837 void ARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
838                                unsigned DataSize, uint64_t Value,
839                                bool IsPCRel) const {
840   unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
841   Value =
842       adjustFixupValue(Fixup, Value, IsPCRel, nullptr, IsLittleEndian, true);
843   if (!Value)
844     return; // Doesn't change encoding.
845
846   unsigned Offset = Fixup.getOffset();
847   assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
848
849   // Used to point to big endian bytes.
850   unsigned FullSizeBytes;
851   if (!IsLittleEndian) {
852     FullSizeBytes = getFixupKindContainerSizeBytes(Fixup.getKind());
853     assert((Offset + FullSizeBytes) <= DataSize && "Invalid fixup size!");
854     assert(NumBytes <= FullSizeBytes && "Invalid fixup size!");
855   }
856
857   // For each byte of the fragment that the fixup touches, mask in the bits from
858   // the fixup value. The Value has been "split up" into the appropriate
859   // bitfields above.
860   for (unsigned i = 0; i != NumBytes; ++i) {
861     unsigned Idx = IsLittleEndian ? i : (FullSizeBytes - 1 - i);
862     Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
863   }
864 }
865
866 namespace CU {
867
868 /// \brief Compact unwind encoding values.
869 enum CompactUnwindEncodings {
870   UNWIND_ARM_MODE_MASK                         = 0x0F000000,
871   UNWIND_ARM_MODE_FRAME                        = 0x01000000,
872   UNWIND_ARM_MODE_FRAME_D                      = 0x02000000,
873   UNWIND_ARM_MODE_DWARF                        = 0x04000000,
874
875   UNWIND_ARM_FRAME_STACK_ADJUST_MASK           = 0x00C00000,
876
877   UNWIND_ARM_FRAME_FIRST_PUSH_R4               = 0x00000001,
878   UNWIND_ARM_FRAME_FIRST_PUSH_R5               = 0x00000002,
879   UNWIND_ARM_FRAME_FIRST_PUSH_R6               = 0x00000004,
880
881   UNWIND_ARM_FRAME_SECOND_PUSH_R8              = 0x00000008,
882   UNWIND_ARM_FRAME_SECOND_PUSH_R9              = 0x00000010,
883   UNWIND_ARM_FRAME_SECOND_PUSH_R10             = 0x00000020,
884   UNWIND_ARM_FRAME_SECOND_PUSH_R11             = 0x00000040,
885   UNWIND_ARM_FRAME_SECOND_PUSH_R12             = 0x00000080,
886
887   UNWIND_ARM_FRAME_D_REG_COUNT_MASK            = 0x00000F00,
888
889   UNWIND_ARM_DWARF_SECTION_OFFSET              = 0x00FFFFFF
890 };
891
892 } // end CU namespace
893
894 /// Generate compact unwind encoding for the function based on the CFI
895 /// instructions. If the CFI instructions describe a frame that cannot be
896 /// encoded in compact unwind, the method returns UNWIND_ARM_MODE_DWARF which
897 /// tells the runtime to fallback and unwind using dwarf.
898 uint32_t ARMAsmBackendDarwin::generateCompactUnwindEncoding(
899     ArrayRef<MCCFIInstruction> Instrs) const {
900   DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "generateCU()\n");
901   // Only armv7k uses CFI based unwinding.
902   if (Subtype != MachO::CPU_SUBTYPE_ARM_V7K)
903     return 0;
904   // No .cfi directives means no frame.
905   if (Instrs.empty())
906     return 0;
907   // Start off assuming CFA is at SP+0.
908   int CFARegister = ARM::SP;
909   int CFARegisterOffset = 0;
910   // Mark savable registers as initially unsaved
911   DenseMap<unsigned, int> RegOffsets;
912   int FloatRegCount = 0;
913   // Process each .cfi directive and build up compact unwind info.
914   for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
915     int Reg;
916     const MCCFIInstruction &Inst = Instrs[i];
917     switch (Inst.getOperation()) {
918     case MCCFIInstruction::OpDefCfa: // DW_CFA_def_cfa
919       CFARegisterOffset = -Inst.getOffset();
920       CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
921       break;
922     case MCCFIInstruction::OpDefCfaOffset: // DW_CFA_def_cfa_offset
923       CFARegisterOffset = -Inst.getOffset();
924       break;
925     case MCCFIInstruction::OpDefCfaRegister: // DW_CFA_def_cfa_register
926       CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
927       break;
928     case MCCFIInstruction::OpOffset: // DW_CFA_offset
929       Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
930       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
931         RegOffsets[Reg] = Inst.getOffset();
932       else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
933         RegOffsets[Reg] = Inst.getOffset();
934         ++FloatRegCount;
935       } else {
936         DEBUG_WITH_TYPE("compact-unwind",
937                         llvm::dbgs() << ".cfi_offset on unknown register="
938                                      << Inst.getRegister() << "\n");
939         return CU::UNWIND_ARM_MODE_DWARF;
940       }
941       break;
942     case MCCFIInstruction::OpRelOffset: // DW_CFA_advance_loc
943       // Ignore
944       break;
945     default:
946       // Directive not convertable to compact unwind, bail out.
947       DEBUG_WITH_TYPE("compact-unwind",
948                       llvm::dbgs()
949                           << "CFI directive not compatiable with comact "
950                              "unwind encoding, opcode=" << Inst.getOperation()
951                           << "\n");
952       return CU::UNWIND_ARM_MODE_DWARF;
953       break;
954     }
955   }
956
957   // If no frame set up, return no unwind info.
958   if ((CFARegister == ARM::SP) && (CFARegisterOffset == 0))
959     return 0;
960
961   // Verify standard frame (lr/r7) was used.
962   if (CFARegister != ARM::R7) {
963     DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "frame register is "
964                                                    << CFARegister
965                                                    << " instead of r7\n");
966     return CU::UNWIND_ARM_MODE_DWARF;
967   }
968   int StackAdjust = CFARegisterOffset - 8;
969   if (RegOffsets.lookup(ARM::LR) != (-4 - StackAdjust)) {
970     DEBUG_WITH_TYPE("compact-unwind",
971                     llvm::dbgs()
972                         << "LR not saved as standard frame, StackAdjust="
973                         << StackAdjust
974                         << ", CFARegisterOffset=" << CFARegisterOffset
975                         << ", lr save at offset=" << RegOffsets[14] << "\n");
976     return CU::UNWIND_ARM_MODE_DWARF;
977   }
978   if (RegOffsets.lookup(ARM::R7) != (-8 - StackAdjust)) {
979     DEBUG_WITH_TYPE("compact-unwind",
980                     llvm::dbgs() << "r7 not saved as standard frame\n");
981     return CU::UNWIND_ARM_MODE_DWARF;
982   }
983   uint32_t CompactUnwindEncoding = CU::UNWIND_ARM_MODE_FRAME;
984
985   // If var-args are used, there may be a stack adjust required.
986   switch (StackAdjust) {
987   case 0:
988     break;
989   case 4:
990     CompactUnwindEncoding |= 0x00400000;
991     break;
992   case 8:
993     CompactUnwindEncoding |= 0x00800000;
994     break;
995   case 12:
996     CompactUnwindEncoding |= 0x00C00000;
997     break;
998   default:
999     DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs()
1000                                           << ".cfi_def_cfa stack adjust ("
1001                                           << StackAdjust << ") out of range\n");
1002     return CU::UNWIND_ARM_MODE_DWARF;
1003   }
1004
1005   // If r6 is saved, it must be right below r7.
1006   static struct {
1007     unsigned Reg;
1008     unsigned Encoding;
1009   } GPRCSRegs[] = {{ARM::R6, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R6},
1010                    {ARM::R5, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R5},
1011                    {ARM::R4, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R4},
1012                    {ARM::R12, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R12},
1013                    {ARM::R11, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R11},
1014                    {ARM::R10, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R10},
1015                    {ARM::R9, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R9},
1016                    {ARM::R8, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R8}};
1017
1018   int CurOffset = -8 - StackAdjust;
1019   for (auto CSReg : GPRCSRegs) {
1020     auto Offset = RegOffsets.find(CSReg.Reg);
1021     if (Offset == RegOffsets.end())
1022       continue;
1023
1024     int RegOffset = Offset->second;
1025     if (RegOffset != CurOffset - 4) {
1026       DEBUG_WITH_TYPE("compact-unwind",
1027                       llvm::dbgs() << MRI.getName(CSReg.Reg) << " saved at "
1028                                    << RegOffset << " but only supported at "
1029                                    << CurOffset << "\n");
1030       return CU::UNWIND_ARM_MODE_DWARF;
1031     }
1032     CompactUnwindEncoding |= CSReg.Encoding;
1033     CurOffset -= 4;
1034   }
1035
1036   // If no floats saved, we are done.
1037   if (FloatRegCount == 0)
1038     return CompactUnwindEncoding;
1039
1040   // Switch mode to include D register saving.
1041   CompactUnwindEncoding &= ~CU::UNWIND_ARM_MODE_MASK;
1042   CompactUnwindEncoding |= CU::UNWIND_ARM_MODE_FRAME_D;
1043
1044   // FIXME: supporting more than 4 saved D-registers compactly would be trivial,
1045   // but needs coordination with the linker and libunwind.
1046   if (FloatRegCount > 4) {
1047     DEBUG_WITH_TYPE("compact-unwind",
1048                     llvm::dbgs() << "unsupported number of D registers saved ("
1049                                  << FloatRegCount << ")\n");
1050       return CU::UNWIND_ARM_MODE_DWARF;
1051   }
1052
1053   // Floating point registers must either be saved sequentially, or we defer to
1054   // DWARF. No gaps allowed here so check that each saved d-register is
1055   // precisely where it should be.
1056   static unsigned FPRCSRegs[] = { ARM::D8, ARM::D10, ARM::D12, ARM::D14 };
1057   for (int Idx = FloatRegCount - 1; Idx >= 0; --Idx) {
1058     auto Offset = RegOffsets.find(FPRCSRegs[Idx]);
1059     if (Offset == RegOffsets.end()) {
1060       DEBUG_WITH_TYPE("compact-unwind",
1061                       llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1062                                    << MRI.getName(FPRCSRegs[Idx])
1063                                    << " not saved\n");
1064       return CU::UNWIND_ARM_MODE_DWARF;
1065     } else if (Offset->second != CurOffset - 8) {
1066       DEBUG_WITH_TYPE("compact-unwind",
1067                       llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1068                                    << MRI.getName(FPRCSRegs[Idx])
1069                                    << " saved at " << Offset->second
1070                                    << ", expected at " << CurOffset - 8
1071                                    << "\n");
1072       return CU::UNWIND_ARM_MODE_DWARF;
1073     }
1074     CurOffset -= 8;
1075   }
1076
1077   return CompactUnwindEncoding | ((FloatRegCount - 1) << 8);
1078 }
1079
1080 static MachO::CPUSubTypeARM getMachOSubTypeFromArch(StringRef Arch) {
1081   unsigned AK = ARM::parseArch(Arch);
1082   switch (AK) {
1083   default:
1084     return MachO::CPU_SUBTYPE_ARM_V7;
1085   case ARM::AK_ARMV4T:
1086     return MachO::CPU_SUBTYPE_ARM_V4T;
1087   case ARM::AK_ARMV5T:
1088   case ARM::AK_ARMV5TE:
1089   case ARM::AK_ARMV5TEJ:
1090     return MachO::CPU_SUBTYPE_ARM_V5;
1091   case ARM::AK_ARMV6:
1092   case ARM::AK_ARMV6K:
1093     return MachO::CPU_SUBTYPE_ARM_V6;
1094   case ARM::AK_ARMV7A:
1095     return MachO::CPU_SUBTYPE_ARM_V7;
1096   case ARM::AK_ARMV7S:
1097     return MachO::CPU_SUBTYPE_ARM_V7S;
1098   case ARM::AK_ARMV7K:
1099     return MachO::CPU_SUBTYPE_ARM_V7K;
1100   case ARM::AK_ARMV6M:
1101     return MachO::CPU_SUBTYPE_ARM_V6M;
1102   case ARM::AK_ARMV7M:
1103     return MachO::CPU_SUBTYPE_ARM_V7M;
1104   case ARM::AK_ARMV7EM:
1105     return MachO::CPU_SUBTYPE_ARM_V7EM;
1106   }
1107 }
1108
1109 MCAsmBackend *llvm::createARMAsmBackend(const Target &T,
1110                                         const MCRegisterInfo &MRI,
1111                                         const Triple &TheTriple, StringRef CPU,
1112                                         bool isLittle) {
1113   switch (TheTriple.getObjectFormat()) {
1114   default:
1115     llvm_unreachable("unsupported object format");
1116   case Triple::MachO: {
1117     MachO::CPUSubTypeARM CS = getMachOSubTypeFromArch(TheTriple.getArchName());
1118     return new ARMAsmBackendDarwin(T, TheTriple, MRI, CS);
1119   }
1120   case Triple::COFF:
1121     assert(TheTriple.isOSWindows() && "non-Windows ARM COFF is not supported");
1122     return new ARMAsmBackendWinCOFF(T, TheTriple);
1123   case Triple::ELF:
1124     assert(TheTriple.isOSBinFormatELF() && "using ELF for non-ELF target");
1125     uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1126     return new ARMAsmBackendELF(T, TheTriple, OSABI, isLittle);
1127   }
1128 }
1129
1130 MCAsmBackend *llvm::createARMLEAsmBackend(const Target &T,
1131                                           const MCRegisterInfo &MRI,
1132                                           const Triple &TT, StringRef CPU) {
1133   return createARMAsmBackend(T, MRI, TT, CPU, true);
1134 }
1135
1136 MCAsmBackend *llvm::createARMBEAsmBackend(const Target &T,
1137                                           const MCRegisterInfo &MRI,
1138                                           const Triple &TT, StringRef CPU) {
1139   return createARMAsmBackend(T, MRI, TT, CPU, false);
1140 }
1141
1142 MCAsmBackend *llvm::createThumbLEAsmBackend(const Target &T,
1143                                             const MCRegisterInfo &MRI,
1144                                             const Triple &TT, StringRef CPU) {
1145   return createARMAsmBackend(T, MRI, TT, CPU, true);
1146 }
1147
1148 MCAsmBackend *llvm::createThumbBEAsmBackend(const Target &T,
1149                                             const MCRegisterInfo &MRI,
1150                                             const Triple &TT, StringRef CPU) {
1151   return createARMAsmBackend(T, MRI, TT, CPU, false);
1152 }