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