1 //===-- AArch64AsmBackend.cpp - AArch64 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/AArch64FixupKinds.h"
10 #include "MCTargetDesc/AArch64MCExpr.h"
11 #include "MCTargetDesc/AArch64MCTargetDesc.h"
12 #include "Utils/AArch64BaseInfo.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCDirectives.h"
19 #include "llvm/MC/MCELFObjectWriter.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionELF.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCTargetOptions.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/TargetRegistry.h"
29 using namespace llvm;
30 
31 namespace {
32 
33 class AArch64AsmBackend : public MCAsmBackend {
34   static const unsigned PCRelFlagVal =
35       MCFixupKindInfo::FKF_IsAlignedDownTo32Bits | MCFixupKindInfo::FKF_IsPCRel;
36   Triple TheTriple;
37 
38 public:
39   AArch64AsmBackend(const Target &T, const Triple &TT, bool IsLittleEndian)
40       : MCAsmBackend(IsLittleEndian ? support::little : support::big),
41         TheTriple(TT) {}
42 
43   unsigned getNumFixupKinds() const override {
44     return AArch64::NumTargetFixupKinds;
45   }
46 
47   Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
48 
49   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
50     const static MCFixupKindInfo Infos[AArch64::NumTargetFixupKinds] = {
51         // This table *must* be in the order that the fixup_* kinds are defined
52         // in AArch64FixupKinds.h.
53         //
54         // Name                           Offset (bits) Size (bits)     Flags
55         {"fixup_aarch64_pcrel_adr_imm21", 0, 32, PCRelFlagVal},
56         {"fixup_aarch64_pcrel_adrp_imm21", 0, 32, PCRelFlagVal},
57         {"fixup_aarch64_add_imm12", 10, 12, 0},
58         {"fixup_aarch64_ldst_imm12_scale1", 10, 12, 0},
59         {"fixup_aarch64_ldst_imm12_scale2", 10, 12, 0},
60         {"fixup_aarch64_ldst_imm12_scale4", 10, 12, 0},
61         {"fixup_aarch64_ldst_imm12_scale8", 10, 12, 0},
62         {"fixup_aarch64_ldst_imm12_scale16", 10, 12, 0},
63         {"fixup_aarch64_ldr_pcrel_imm19", 5, 19, PCRelFlagVal},
64         {"fixup_aarch64_movw", 5, 16, 0},
65         {"fixup_aarch64_pcrel_branch14", 5, 14, PCRelFlagVal},
66         {"fixup_aarch64_pcrel_branch19", 5, 19, PCRelFlagVal},
67         {"fixup_aarch64_pcrel_branch26", 0, 26, PCRelFlagVal},
68         {"fixup_aarch64_pcrel_call26", 0, 26, PCRelFlagVal},
69         {"fixup_aarch64_tlsdesc_call", 0, 0, 0}};
70 
71     if (Kind < FirstTargetFixupKind)
72       return MCAsmBackend::getFixupKindInfo(Kind);
73 
74     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
75            "Invalid kind!");
76     return Infos[Kind - FirstTargetFixupKind];
77   }
78 
79   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
80                   const MCValue &Target, MutableArrayRef<char> Data,
81                   uint64_t Value, bool IsResolved,
82                   const MCSubtargetInfo *STI) const override;
83 
84   bool mayNeedRelaxation(const MCInst &Inst,
85                          const MCSubtargetInfo &STI) const override;
86   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
87                             const MCRelaxableFragment *DF,
88                             const MCAsmLayout &Layout) const override;
89   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
90                         MCInst &Res) const override;
91   bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
92 
93   void HandleAssemblerFlag(MCAssemblerFlag Flag) {}
94 
95   unsigned getPointerSize() const { return 8; }
96 
97   unsigned getFixupKindContainereSizeInBytes(unsigned Kind) const;
98 
99   bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
100                              const MCValue &Target) override;
101 };
102 
103 } // end anonymous namespace
104 
105 /// The number of bytes the fixup may change.
106 static unsigned getFixupKindNumBytes(unsigned Kind) {
107   switch (Kind) {
108   default:
109     llvm_unreachable("Unknown fixup kind!");
110 
111   case FK_NONE:
112   case AArch64::fixup_aarch64_tlsdesc_call:
113     return 0;
114 
115   case FK_Data_1:
116     return 1;
117 
118   case FK_Data_2:
119   case FK_SecRel_2:
120     return 2;
121 
122   case AArch64::fixup_aarch64_movw:
123   case AArch64::fixup_aarch64_pcrel_branch14:
124   case AArch64::fixup_aarch64_add_imm12:
125   case AArch64::fixup_aarch64_ldst_imm12_scale1:
126   case AArch64::fixup_aarch64_ldst_imm12_scale2:
127   case AArch64::fixup_aarch64_ldst_imm12_scale4:
128   case AArch64::fixup_aarch64_ldst_imm12_scale8:
129   case AArch64::fixup_aarch64_ldst_imm12_scale16:
130   case AArch64::fixup_aarch64_ldr_pcrel_imm19:
131   case AArch64::fixup_aarch64_pcrel_branch19:
132     return 3;
133 
134   case AArch64::fixup_aarch64_pcrel_adr_imm21:
135   case AArch64::fixup_aarch64_pcrel_adrp_imm21:
136   case AArch64::fixup_aarch64_pcrel_branch26:
137   case AArch64::fixup_aarch64_pcrel_call26:
138   case FK_Data_4:
139   case FK_SecRel_4:
140     return 4;
141 
142   case FK_Data_8:
143     return 8;
144   }
145 }
146 
147 static unsigned AdrImmBits(unsigned Value) {
148   unsigned lo2 = Value & 0x3;
149   unsigned hi19 = (Value & 0x1ffffc) >> 2;
150   return (hi19 << 5) | (lo2 << 29);
151 }
152 
153 static uint64_t adjustFixupValue(const MCFixup &Fixup, const MCValue &Target,
154                                  uint64_t Value, MCContext &Ctx,
155                                  const Triple &TheTriple, bool IsResolved) {
156   unsigned Kind = Fixup.getKind();
157   int64_t SignedValue = static_cast<int64_t>(Value);
158   switch (Kind) {
159   default:
160     llvm_unreachable("Unknown fixup kind!");
161   case AArch64::fixup_aarch64_pcrel_adr_imm21:
162     if (SignedValue > 2097151 || SignedValue < -2097152)
163       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
164     return AdrImmBits(Value & 0x1fffffULL);
165   case AArch64::fixup_aarch64_pcrel_adrp_imm21:
166     assert(!IsResolved);
167     if (TheTriple.isOSBinFormatCOFF())
168       return AdrImmBits(Value & 0x1fffffULL);
169     return AdrImmBits((Value & 0x1fffff000ULL) >> 12);
170   case AArch64::fixup_aarch64_ldr_pcrel_imm19:
171   case AArch64::fixup_aarch64_pcrel_branch19:
172     // Signed 21-bit immediate
173     if (SignedValue > 2097151 || SignedValue < -2097152)
174       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
175     if (Value & 0x3)
176       Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
177     // Low two bits are not encoded.
178     return (Value >> 2) & 0x7ffff;
179   case AArch64::fixup_aarch64_add_imm12:
180   case AArch64::fixup_aarch64_ldst_imm12_scale1:
181     if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
182       Value &= 0xfff;
183     // Unsigned 12-bit immediate
184     if (Value >= 0x1000)
185       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
186     return Value;
187   case AArch64::fixup_aarch64_ldst_imm12_scale2:
188     if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
189       Value &= 0xfff;
190     // Unsigned 12-bit immediate which gets multiplied by 2
191     if (Value >= 0x2000)
192       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
193     if (Value & 0x1)
194       Ctx.reportError(Fixup.getLoc(), "fixup must be 2-byte aligned");
195     return Value >> 1;
196   case AArch64::fixup_aarch64_ldst_imm12_scale4:
197     if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
198       Value &= 0xfff;
199     // Unsigned 12-bit immediate which gets multiplied by 4
200     if (Value >= 0x4000)
201       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
202     if (Value & 0x3)
203       Ctx.reportError(Fixup.getLoc(), "fixup must be 4-byte aligned");
204     return Value >> 2;
205   case AArch64::fixup_aarch64_ldst_imm12_scale8:
206     if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
207       Value &= 0xfff;
208     // Unsigned 12-bit immediate which gets multiplied by 8
209     if (Value >= 0x8000)
210       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
211     if (Value & 0x7)
212       Ctx.reportError(Fixup.getLoc(), "fixup must be 8-byte aligned");
213     return Value >> 3;
214   case AArch64::fixup_aarch64_ldst_imm12_scale16:
215     if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
216       Value &= 0xfff;
217     // Unsigned 12-bit immediate which gets multiplied by 16
218     if (Value >= 0x10000)
219       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
220     if (Value & 0xf)
221       Ctx.reportError(Fixup.getLoc(), "fixup must be 16-byte aligned");
222     return Value >> 4;
223   case AArch64::fixup_aarch64_movw: {
224     AArch64MCExpr::VariantKind RefKind =
225         static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
226     if (AArch64MCExpr::getSymbolLoc(RefKind) != AArch64MCExpr::VK_ABS &&
227         AArch64MCExpr::getSymbolLoc(RefKind) != AArch64MCExpr::VK_SABS) {
228       // VK_GOTTPREL, VK_TPREL, VK_DTPREL are movw fixups, but they can't
229       // ever be resolved in the assembler.
230       Ctx.reportError(Fixup.getLoc(),
231                       "relocation for a thread-local variable points to an "
232                       "absolute symbol");
233       return Value;
234     }
235 
236     if (!IsResolved) {
237       // FIXME: Figure out when this can actually happen, and verify our
238       // behavior.
239       Ctx.reportError(Fixup.getLoc(), "unresolved movw fixup not yet "
240                                       "implemented");
241       return Value;
242     }
243 
244     if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
245       switch (AArch64MCExpr::getAddressFrag(RefKind)) {
246       case AArch64MCExpr::VK_G0:
247         break;
248       case AArch64MCExpr::VK_G1:
249         SignedValue = SignedValue >> 16;
250         break;
251       case AArch64MCExpr::VK_G2:
252         SignedValue = SignedValue >> 32;
253         break;
254       case AArch64MCExpr::VK_G3:
255         SignedValue = SignedValue >> 48;
256         break;
257       default:
258         llvm_unreachable("Variant kind doesn't correspond to fixup");
259       }
260 
261     } else {
262       switch (AArch64MCExpr::getAddressFrag(RefKind)) {
263       case AArch64MCExpr::VK_G0:
264         break;
265       case AArch64MCExpr::VK_G1:
266         Value = Value >> 16;
267         break;
268       case AArch64MCExpr::VK_G2:
269         Value = Value >> 32;
270         break;
271       case AArch64MCExpr::VK_G3:
272         Value = Value >> 48;
273         break;
274       default:
275         llvm_unreachable("Variant kind doesn't correspond to fixup");
276       }
277     }
278 
279     if (RefKind & AArch64MCExpr::VK_NC) {
280       Value &= 0xFFFF;
281     }
282     else if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
283       if (SignedValue > 0xFFFF || SignedValue < -0xFFFF)
284         Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
285 
286       // Invert the negative immediate because it will feed into a MOVN.
287       if (SignedValue < 0)
288         SignedValue = ~SignedValue;
289       Value = static_cast<uint64_t>(SignedValue);
290     }
291     else if (Value > 0xFFFF) {
292       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
293     }
294     return Value;
295   }
296   case AArch64::fixup_aarch64_pcrel_branch14:
297     // Signed 16-bit immediate
298     if (SignedValue > 32767 || SignedValue < -32768)
299       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
300     // Low two bits are not encoded (4-byte alignment assumed).
301     if (Value & 0x3)
302       Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
303     return (Value >> 2) & 0x3fff;
304   case AArch64::fixup_aarch64_pcrel_branch26:
305   case AArch64::fixup_aarch64_pcrel_call26:
306     // Signed 28-bit immediate
307     if (SignedValue > 134217727 || SignedValue < -134217728)
308       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
309     // Low two bits are not encoded (4-byte alignment assumed).
310     if (Value & 0x3)
311       Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
312     return (Value >> 2) & 0x3ffffff;
313   case FK_NONE:
314   case FK_Data_1:
315   case FK_Data_2:
316   case FK_Data_4:
317   case FK_Data_8:
318   case FK_SecRel_2:
319   case FK_SecRel_4:
320     return Value;
321   }
322 }
323 
324 Optional<MCFixupKind> AArch64AsmBackend::getFixupKind(StringRef Name) const {
325   if (TheTriple.isOSBinFormatELF() && Name == "R_AARCH64_NONE")
326     return FK_NONE;
327   return MCAsmBackend::getFixupKind(Name);
328 }
329 
330 /// getFixupKindContainereSizeInBytes - The number of bytes of the
331 /// container involved in big endian or 0 if the item is little endian
332 unsigned AArch64AsmBackend::getFixupKindContainereSizeInBytes(unsigned Kind) const {
333   if (Endian == support::little)
334     return 0;
335 
336   switch (Kind) {
337   default:
338     llvm_unreachable("Unknown fixup kind!");
339 
340   case FK_Data_1:
341     return 1;
342   case FK_Data_2:
343     return 2;
344   case FK_Data_4:
345     return 4;
346   case FK_Data_8:
347     return 8;
348 
349   case AArch64::fixup_aarch64_tlsdesc_call:
350   case AArch64::fixup_aarch64_movw:
351   case AArch64::fixup_aarch64_pcrel_branch14:
352   case AArch64::fixup_aarch64_add_imm12:
353   case AArch64::fixup_aarch64_ldst_imm12_scale1:
354   case AArch64::fixup_aarch64_ldst_imm12_scale2:
355   case AArch64::fixup_aarch64_ldst_imm12_scale4:
356   case AArch64::fixup_aarch64_ldst_imm12_scale8:
357   case AArch64::fixup_aarch64_ldst_imm12_scale16:
358   case AArch64::fixup_aarch64_ldr_pcrel_imm19:
359   case AArch64::fixup_aarch64_pcrel_branch19:
360   case AArch64::fixup_aarch64_pcrel_adr_imm21:
361   case AArch64::fixup_aarch64_pcrel_adrp_imm21:
362   case AArch64::fixup_aarch64_pcrel_branch26:
363   case AArch64::fixup_aarch64_pcrel_call26:
364     // Instructions are always little endian
365     return 0;
366   }
367 }
368 
369 void AArch64AsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
370                                    const MCValue &Target,
371                                    MutableArrayRef<char> Data, uint64_t Value,
372                                    bool IsResolved,
373                                    const MCSubtargetInfo *STI) const {
374   unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
375   if (!Value)
376     return; // Doesn't change encoding.
377   MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
378   MCContext &Ctx = Asm.getContext();
379   int64_t SignedValue = static_cast<int64_t>(Value);
380   // Apply any target-specific value adjustments.
381   Value = adjustFixupValue(Fixup, Target, Value, Ctx, TheTriple, IsResolved);
382 
383   // Shift the value into position.
384   Value <<= Info.TargetOffset;
385 
386   unsigned Offset = Fixup.getOffset();
387   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
388 
389   // Used to point to big endian bytes.
390   unsigned FulleSizeInBytes = getFixupKindContainereSizeInBytes(Fixup.getKind());
391 
392   // For each byte of the fragment that the fixup touches, mask in the
393   // bits from the fixup value.
394   if (FulleSizeInBytes == 0) {
395     // Handle as little-endian
396     for (unsigned i = 0; i != NumBytes; ++i) {
397       Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
398     }
399   } else {
400     // Handle as big-endian
401     assert((Offset + FulleSizeInBytes) <= Data.size() && "Invalid fixup size!");
402     assert(NumBytes <= FulleSizeInBytes && "Invalid fixup size!");
403     for (unsigned i = 0; i != NumBytes; ++i) {
404       unsigned Idx = FulleSizeInBytes - 1 - i;
405       Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
406     }
407   }
408 
409   // FIXME: getFixupKindInfo() and getFixupKindNumBytes() could be fixed to
410   // handle this more cleanly. This may affect the output of -show-mc-encoding.
411   AArch64MCExpr::VariantKind RefKind =
412     static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
413   if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
414     // If the immediate is negative, generate MOVN else MOVZ.
415     // (Bit 30 = 0) ==> MOVN, (Bit 30 = 1) ==> MOVZ.
416     if (SignedValue < 0)
417       Data[Offset + 3] &= ~(1 << 6);
418     else
419       Data[Offset + 3] |= (1 << 6);
420   }
421 }
422 
423 bool AArch64AsmBackend::mayNeedRelaxation(const MCInst &Inst,
424                                           const MCSubtargetInfo &STI) const {
425   return false;
426 }
427 
428 bool AArch64AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
429                                              uint64_t Value,
430                                              const MCRelaxableFragment *DF,
431                                              const MCAsmLayout &Layout) const {
432   // FIXME:  This isn't correct for AArch64. Just moving the "generic" logic
433   // into the targets for now.
434   //
435   // Relax if the value is too big for a (signed) i8.
436   return int64_t(Value) != int64_t(int8_t(Value));
437 }
438 
439 void AArch64AsmBackend::relaxInstruction(const MCInst &Inst,
440                                          const MCSubtargetInfo &STI,
441                                          MCInst &Res) const {
442   llvm_unreachable("AArch64AsmBackend::relaxInstruction() unimplemented");
443 }
444 
445 bool AArch64AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
446   // If the count is not 4-byte aligned, we must be writing data into the text
447   // section (otherwise we have unaligned instructions, and thus have far
448   // bigger problems), so just write zeros instead.
449   OS.write_zeros(Count % 4);
450 
451   // We are properly aligned, so write NOPs as requested.
452   Count /= 4;
453   for (uint64_t i = 0; i != Count; ++i)
454     support::endian::write<uint32_t>(OS, 0xd503201f, Endian);
455   return true;
456 }
457 
458 bool AArch64AsmBackend::shouldForceRelocation(const MCAssembler &Asm,
459                                               const MCFixup &Fixup,
460                                               const MCValue &Target) {
461   unsigned Kind = Fixup.getKind();
462   if (Kind == FK_NONE)
463     return true;
464 
465   // The ADRP instruction adds some multiple of 0x1000 to the current PC &
466   // ~0xfff. This means that the required offset to reach a symbol can vary by
467   // up to one step depending on where the ADRP is in memory. For example:
468   //
469   //     ADRP x0, there
470   //  there:
471   //
472   // If the ADRP occurs at address 0xffc then "there" will be at 0x1000 and
473   // we'll need that as an offset. At any other address "there" will be in the
474   // same page as the ADRP and the instruction should encode 0x0. Assuming the
475   // section isn't 0x1000-aligned, we therefore need to delegate this decision
476   // to the linker -- a relocation!
477   if (Kind == AArch64::fixup_aarch64_pcrel_adrp_imm21)
478     return true;
479 
480   AArch64MCExpr::VariantKind RefKind =
481       static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
482   AArch64MCExpr::VariantKind SymLoc = AArch64MCExpr::getSymbolLoc(RefKind);
483   // LDR GOT relocations need a relocation
484   if (Kind == AArch64::fixup_aarch64_ldr_pcrel_imm19 &&
485       SymLoc == AArch64MCExpr::VK_GOT)
486     return true;
487   return false;
488 }
489 
490 namespace {
491 
492 namespace CU {
493 
494 /// Compact unwind encoding values.
495 enum CompactUnwindEncodings {
496   /// A "frameless" leaf function, where no non-volatile registers are
497   /// saved. The return remains in LR throughout the function.
498   UNWIND_ARM64_MODE_FRAMELESS = 0x02000000,
499 
500   /// No compact unwind encoding available. Instead the low 23-bits of
501   /// the compact unwind encoding is the offset of the DWARF FDE in the
502   /// __eh_frame section. This mode is never used in object files. It is only
503   /// generated by the linker in final linked images, which have only DWARF info
504   /// for a function.
505   UNWIND_ARM64_MODE_DWARF = 0x03000000,
506 
507   /// This is a standard arm64 prologue where FP/LR are immediately
508   /// pushed on the stack, then SP is copied to FP. If there are any
509   /// non-volatile register saved, they are copied into the stack fame in pairs
510   /// in a contiguous ranger right below the saved FP/LR pair. Any subset of the
511   /// five X pairs and four D pairs can be saved, but the memory layout must be
512   /// in register number order.
513   UNWIND_ARM64_MODE_FRAME = 0x04000000,
514 
515   /// Frame register pair encodings.
516   UNWIND_ARM64_FRAME_X19_X20_PAIR = 0x00000001,
517   UNWIND_ARM64_FRAME_X21_X22_PAIR = 0x00000002,
518   UNWIND_ARM64_FRAME_X23_X24_PAIR = 0x00000004,
519   UNWIND_ARM64_FRAME_X25_X26_PAIR = 0x00000008,
520   UNWIND_ARM64_FRAME_X27_X28_PAIR = 0x00000010,
521   UNWIND_ARM64_FRAME_D8_D9_PAIR = 0x00000100,
522   UNWIND_ARM64_FRAME_D10_D11_PAIR = 0x00000200,
523   UNWIND_ARM64_FRAME_D12_D13_PAIR = 0x00000400,
524   UNWIND_ARM64_FRAME_D14_D15_PAIR = 0x00000800
525 };
526 
527 } // end CU namespace
528 
529 // FIXME: This should be in a separate file.
530 class DarwinAArch64AsmBackend : public AArch64AsmBackend {
531   const MCRegisterInfo &MRI;
532   bool IsILP32;
533 
534   /// Encode compact unwind stack adjustment for frameless functions.
535   /// See UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK in compact_unwind_encoding.h.
536   /// The stack size always needs to be 16 byte aligned.
537   uint32_t encodeStackAdjustment(uint32_t StackSize) const {
538     return (StackSize / 16) << 12;
539   }
540 
541 public:
542   DarwinAArch64AsmBackend(const Target &T, const Triple &TT,
543                           const MCRegisterInfo &MRI, bool IsILP32)
544       : AArch64AsmBackend(T, TT, /*IsLittleEndian*/ true), MRI(MRI),
545         IsILP32(IsILP32) {}
546 
547   std::unique_ptr<MCObjectTargetWriter>
548   createObjectTargetWriter() const override {
549     if (IsILP32)
550       return createAArch64MachObjectWriter(
551           MachO::CPU_TYPE_ARM64_32, MachO::CPU_SUBTYPE_ARM64_32_V8, true);
552     else
553       return createAArch64MachObjectWriter(MachO::CPU_TYPE_ARM64,
554                                            MachO::CPU_SUBTYPE_ARM64_ALL, false);
555   }
556 
557   /// Generate the compact unwind encoding from the CFI directives.
558   uint32_t generateCompactUnwindEncoding(
559                              ArrayRef<MCCFIInstruction> Instrs) const override {
560     if (Instrs.empty())
561       return CU::UNWIND_ARM64_MODE_FRAMELESS;
562 
563     bool HasFP = false;
564     unsigned StackSize = 0;
565 
566     uint32_t CompactUnwindEncoding = 0;
567     for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
568       const MCCFIInstruction &Inst = Instrs[i];
569 
570       switch (Inst.getOperation()) {
571       default:
572         // Cannot handle this directive:  bail out.
573         return CU::UNWIND_ARM64_MODE_DWARF;
574       case MCCFIInstruction::OpDefCfa: {
575         // Defines a frame pointer.
576         unsigned XReg =
577             getXRegFromWReg(MRI.getLLVMRegNum(Inst.getRegister(), true));
578 
579         // Other CFA registers than FP are not supported by compact unwind.
580         // Fallback on DWARF.
581         // FIXME: When opt-remarks are supported in MC, add a remark to notify
582         // the user.
583         if (XReg != AArch64::FP)
584           return CU::UNWIND_ARM64_MODE_DWARF;
585 
586         assert(XReg == AArch64::FP && "Invalid frame pointer!");
587         assert(i + 2 < e && "Insufficient CFI instructions to define a frame!");
588 
589         const MCCFIInstruction &LRPush = Instrs[++i];
590         assert(LRPush.getOperation() == MCCFIInstruction::OpOffset &&
591                "Link register not pushed!");
592         const MCCFIInstruction &FPPush = Instrs[++i];
593         assert(FPPush.getOperation() == MCCFIInstruction::OpOffset &&
594                "Frame pointer not pushed!");
595 
596         unsigned LRReg = MRI.getLLVMRegNum(LRPush.getRegister(), true);
597         unsigned FPReg = MRI.getLLVMRegNum(FPPush.getRegister(), true);
598 
599         LRReg = getXRegFromWReg(LRReg);
600         FPReg = getXRegFromWReg(FPReg);
601 
602         assert(LRReg == AArch64::LR && FPReg == AArch64::FP &&
603                "Pushing invalid registers for frame!");
604 
605         // Indicate that the function has a frame.
606         CompactUnwindEncoding |= CU::UNWIND_ARM64_MODE_FRAME;
607         HasFP = true;
608         break;
609       }
610       case MCCFIInstruction::OpDefCfaOffset: {
611         assert(StackSize == 0 && "We already have the CFA offset!");
612         StackSize = std::abs(Inst.getOffset());
613         break;
614       }
615       case MCCFIInstruction::OpOffset: {
616         // Registers are saved in pairs. We expect there to be two consecutive
617         // `.cfi_offset' instructions with the appropriate registers specified.
618         unsigned Reg1 = MRI.getLLVMRegNum(Inst.getRegister(), true);
619         if (i + 1 == e)
620           return CU::UNWIND_ARM64_MODE_DWARF;
621 
622         const MCCFIInstruction &Inst2 = Instrs[++i];
623         if (Inst2.getOperation() != MCCFIInstruction::OpOffset)
624           return CU::UNWIND_ARM64_MODE_DWARF;
625         unsigned Reg2 = MRI.getLLVMRegNum(Inst2.getRegister(), true);
626 
627         // N.B. The encodings must be in register number order, and the X
628         // registers before the D registers.
629 
630         // X19/X20 pair = 0x00000001,
631         // X21/X22 pair = 0x00000002,
632         // X23/X24 pair = 0x00000004,
633         // X25/X26 pair = 0x00000008,
634         // X27/X28 pair = 0x00000010
635         Reg1 = getXRegFromWReg(Reg1);
636         Reg2 = getXRegFromWReg(Reg2);
637 
638         if (Reg1 == AArch64::X19 && Reg2 == AArch64::X20 &&
639             (CompactUnwindEncoding & 0xF1E) == 0)
640           CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X19_X20_PAIR;
641         else if (Reg1 == AArch64::X21 && Reg2 == AArch64::X22 &&
642                  (CompactUnwindEncoding & 0xF1C) == 0)
643           CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X21_X22_PAIR;
644         else if (Reg1 == AArch64::X23 && Reg2 == AArch64::X24 &&
645                  (CompactUnwindEncoding & 0xF18) == 0)
646           CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X23_X24_PAIR;
647         else if (Reg1 == AArch64::X25 && Reg2 == AArch64::X26 &&
648                  (CompactUnwindEncoding & 0xF10) == 0)
649           CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X25_X26_PAIR;
650         else if (Reg1 == AArch64::X27 && Reg2 == AArch64::X28 &&
651                  (CompactUnwindEncoding & 0xF00) == 0)
652           CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X27_X28_PAIR;
653         else {
654           Reg1 = getDRegFromBReg(Reg1);
655           Reg2 = getDRegFromBReg(Reg2);
656 
657           // D8/D9 pair   = 0x00000100,
658           // D10/D11 pair = 0x00000200,
659           // D12/D13 pair = 0x00000400,
660           // D14/D15 pair = 0x00000800
661           if (Reg1 == AArch64::D8 && Reg2 == AArch64::D9 &&
662               (CompactUnwindEncoding & 0xE00) == 0)
663             CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D8_D9_PAIR;
664           else if (Reg1 == AArch64::D10 && Reg2 == AArch64::D11 &&
665                    (CompactUnwindEncoding & 0xC00) == 0)
666             CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D10_D11_PAIR;
667           else if (Reg1 == AArch64::D12 && Reg2 == AArch64::D13 &&
668                    (CompactUnwindEncoding & 0x800) == 0)
669             CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D12_D13_PAIR;
670           else if (Reg1 == AArch64::D14 && Reg2 == AArch64::D15)
671             CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D14_D15_PAIR;
672           else
673             // A pair was pushed which we cannot handle.
674             return CU::UNWIND_ARM64_MODE_DWARF;
675         }
676 
677         break;
678       }
679       }
680     }
681 
682     if (!HasFP) {
683       // With compact unwind info we can only represent stack adjustments of up
684       // to 65520 bytes.
685       if (StackSize > 65520)
686         return CU::UNWIND_ARM64_MODE_DWARF;
687 
688       CompactUnwindEncoding |= CU::UNWIND_ARM64_MODE_FRAMELESS;
689       CompactUnwindEncoding |= encodeStackAdjustment(StackSize);
690     }
691 
692     return CompactUnwindEncoding;
693   }
694 };
695 
696 } // end anonymous namespace
697 
698 namespace {
699 
700 class ELFAArch64AsmBackend : public AArch64AsmBackend {
701 public:
702   uint8_t OSABI;
703   bool IsILP32;
704 
705   ELFAArch64AsmBackend(const Target &T, const Triple &TT, uint8_t OSABI,
706                        bool IsLittleEndian, bool IsILP32)
707       : AArch64AsmBackend(T, TT, IsLittleEndian), OSABI(OSABI),
708         IsILP32(IsILP32) {}
709 
710   std::unique_ptr<MCObjectTargetWriter>
711   createObjectTargetWriter() const override {
712     return createAArch64ELFObjectWriter(OSABI, IsILP32);
713   }
714 };
715 
716 }
717 
718 namespace {
719 class COFFAArch64AsmBackend : public AArch64AsmBackend {
720 public:
721   COFFAArch64AsmBackend(const Target &T, const Triple &TheTriple)
722       : AArch64AsmBackend(T, TheTriple, /*IsLittleEndian*/ true) {}
723 
724   std::unique_ptr<MCObjectTargetWriter>
725   createObjectTargetWriter() const override {
726     return createAArch64WinCOFFObjectWriter();
727   }
728 };
729 }
730 
731 MCAsmBackend *llvm::createAArch64leAsmBackend(const Target &T,
732                                               const MCSubtargetInfo &STI,
733                                               const MCRegisterInfo &MRI,
734                                               const MCTargetOptions &Options) {
735   const Triple &TheTriple = STI.getTargetTriple();
736   if (TheTriple.isOSBinFormatMachO()) {
737     const bool IsILP32 = TheTriple.isArch32Bit();
738     return new DarwinAArch64AsmBackend(T, TheTriple, MRI, IsILP32);
739   }
740 
741   if (TheTriple.isOSBinFormatCOFF())
742     return new COFFAArch64AsmBackend(T, TheTriple);
743 
744   assert(TheTriple.isOSBinFormatELF() && "Invalid target");
745 
746   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
747   bool IsILP32 = Options.getABIName() == "ilp32";
748   return new ELFAArch64AsmBackend(T, TheTriple, OSABI, /*IsLittleEndian=*/true,
749                                   IsILP32);
750 }
751 
752 MCAsmBackend *llvm::createAArch64beAsmBackend(const Target &T,
753                                               const MCSubtargetInfo &STI,
754                                               const MCRegisterInfo &MRI,
755                                               const MCTargetOptions &Options) {
756   const Triple &TheTriple = STI.getTargetTriple();
757   assert(TheTriple.isOSBinFormatELF() &&
758          "Big endian is only supported for ELF targets!");
759   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
760   bool IsILP32 = Options.getABIName() == "ilp32";
761   return new ELFAArch64AsmBackend(T, TheTriple, OSABI, /*IsLittleEndian=*/false,
762                                   IsILP32);
763 }
764