Add r224985 back with a fix.
[oota-llvm.git] / lib / Target / AArch64 / MCTargetDesc / AArch64MachObjectWriter.cpp
1 //===-- AArch64MachObjectWriter.cpp - ARM Mach Object Writer --------------===//
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/AArch64FixupKinds.h"
11 #include "MCTargetDesc/AArch64MCTargetDesc.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCFixup.h"
19 #include "llvm/MC/MCMachObjectWriter.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MachO.h"
24 using namespace llvm;
25
26 namespace {
27 class AArch64MachObjectWriter : public MCMachObjectTargetWriter {
28   bool getAArch64FixupKindMachOInfo(const MCFixup &Fixup, unsigned &RelocType,
29                                   const MCSymbolRefExpr *Sym,
30                                   unsigned &Log2Size, const MCAssembler &Asm);
31
32 public:
33   AArch64MachObjectWriter(uint32_t CPUType, uint32_t CPUSubtype)
34       : MCMachObjectTargetWriter(true /* is64Bit */, CPUType, CPUSubtype,
35                                  /*UseAggressiveSymbolFolding=*/true) {}
36
37   void RecordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
38                         const MCAsmLayout &Layout, const MCFragment *Fragment,
39                         const MCFixup &Fixup, MCValue Target,
40                         uint64_t &FixedValue) override;
41 };
42 }
43
44 bool AArch64MachObjectWriter::getAArch64FixupKindMachOInfo(
45     const MCFixup &Fixup, unsigned &RelocType, const MCSymbolRefExpr *Sym,
46     unsigned &Log2Size, const MCAssembler &Asm) {
47   RelocType = unsigned(MachO::ARM64_RELOC_UNSIGNED);
48   Log2Size = ~0U;
49
50   switch ((unsigned)Fixup.getKind()) {
51   default:
52     return false;
53
54   case FK_Data_1:
55     Log2Size = llvm::Log2_32(1);
56     return true;
57   case FK_Data_2:
58     Log2Size = llvm::Log2_32(2);
59     return true;
60   case FK_Data_4:
61     Log2Size = llvm::Log2_32(4);
62     if (Sym->getKind() == MCSymbolRefExpr::VK_GOT)
63       RelocType = unsigned(MachO::ARM64_RELOC_POINTER_TO_GOT);
64     return true;
65   case FK_Data_8:
66     Log2Size = llvm::Log2_32(8);
67     if (Sym->getKind() == MCSymbolRefExpr::VK_GOT)
68       RelocType = unsigned(MachO::ARM64_RELOC_POINTER_TO_GOT);
69     return true;
70   case AArch64::fixup_aarch64_add_imm12:
71   case AArch64::fixup_aarch64_ldst_imm12_scale1:
72   case AArch64::fixup_aarch64_ldst_imm12_scale2:
73   case AArch64::fixup_aarch64_ldst_imm12_scale4:
74   case AArch64::fixup_aarch64_ldst_imm12_scale8:
75   case AArch64::fixup_aarch64_ldst_imm12_scale16:
76     Log2Size = llvm::Log2_32(4);
77     switch (Sym->getKind()) {
78     default:
79       llvm_unreachable("Unexpected symbol reference variant kind!");
80     case MCSymbolRefExpr::VK_PAGEOFF:
81       RelocType = unsigned(MachO::ARM64_RELOC_PAGEOFF12);
82       return true;
83     case MCSymbolRefExpr::VK_GOTPAGEOFF:
84       RelocType = unsigned(MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12);
85       return true;
86     case MCSymbolRefExpr::VK_TLVPPAGEOFF:
87       RelocType = unsigned(MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12);
88       return true;
89     }
90   case AArch64::fixup_aarch64_pcrel_adrp_imm21:
91     Log2Size = llvm::Log2_32(4);
92     // This encompasses the relocation for the whole 21-bit value.
93     switch (Sym->getKind()) {
94     default:
95       Asm.getContext().FatalError(Fixup.getLoc(),
96                                   "ADR/ADRP relocations must be GOT relative");
97     case MCSymbolRefExpr::VK_PAGE:
98       RelocType = unsigned(MachO::ARM64_RELOC_PAGE21);
99       return true;
100     case MCSymbolRefExpr::VK_GOTPAGE:
101       RelocType = unsigned(MachO::ARM64_RELOC_GOT_LOAD_PAGE21);
102       return true;
103     case MCSymbolRefExpr::VK_TLVPPAGE:
104       RelocType = unsigned(MachO::ARM64_RELOC_TLVP_LOAD_PAGE21);
105       return true;
106     }
107     return true;
108   case AArch64::fixup_aarch64_pcrel_branch26:
109   case AArch64::fixup_aarch64_pcrel_call26:
110     Log2Size = llvm::Log2_32(4);
111     RelocType = unsigned(MachO::ARM64_RELOC_BRANCH26);
112     return true;
113   }
114 }
115
116 void AArch64MachObjectWriter::RecordRelocation(
117     MachObjectWriter *Writer, MCAssembler &Asm, const MCAsmLayout &Layout,
118     const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target,
119     uint64_t &FixedValue) {
120   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
121
122   // See <reloc.h>.
123   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment);
124   unsigned Log2Size = 0;
125   int64_t Value = 0;
126   unsigned Index = 0;
127   unsigned Type = 0;
128   unsigned Kind = Fixup.getKind();
129   const MCSymbolData *RelSymbol = nullptr;
130
131   FixupOffset += Fixup.getOffset();
132
133   // AArch64 pcrel relocation addends do not include the section offset.
134   if (IsPCRel)
135     FixedValue += FixupOffset;
136
137   // ADRP fixups use relocations for the whole symbol value and only
138   // put the addend in the instruction itself. Clear out any value the
139   // generic code figured out from the sybmol definition.
140   if (Kind == AArch64::fixup_aarch64_pcrel_adrp_imm21)
141     FixedValue = 0;
142
143   // imm19 relocations are for conditional branches, which require
144   // assembler local symbols. If we got here, that's not what we have,
145   // so complain loudly.
146   if (Kind == AArch64::fixup_aarch64_pcrel_branch19) {
147     Asm.getContext().FatalError(Fixup.getLoc(),
148                                 "conditional branch requires assembler-local"
149                                 " label. '" +
150                                     Target.getSymA()->getSymbol().getName() +
151                                     "' is external.");
152     return;
153   }
154
155   // 14-bit branch relocations should only target internal labels, and so
156   // should never get here.
157   if (Kind == AArch64::fixup_aarch64_pcrel_branch14) {
158     Asm.getContext().FatalError(Fixup.getLoc(),
159                                 "Invalid relocation on conditional branch!");
160     return;
161   }
162
163   if (!getAArch64FixupKindMachOInfo(Fixup, Type, Target.getSymA(), Log2Size,
164                                   Asm)) {
165     Asm.getContext().FatalError(Fixup.getLoc(), "unknown AArch64 fixup kind!");
166     return;
167   }
168
169   Value = Target.getConstant();
170
171   if (Target.isAbsolute()) { // constant
172     // FIXME: Should this always be extern?
173     // SymbolNum of 0 indicates the absolute section.
174     Type = MachO::ARM64_RELOC_UNSIGNED;
175
176     if (IsPCRel) {
177       Asm.getContext().FatalError(Fixup.getLoc(),
178                                   "PC relative absolute relocation!");
179
180       // FIXME: x86_64 sets the type to a branch reloc here. Should we do
181       // something similar?
182     }
183   } else if (Target.getSymB()) { // A - B + constant
184     const MCSymbol *A = &Target.getSymA()->getSymbol();
185     const MCSymbolData &A_SD = Asm.getSymbolData(*A);
186     const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
187
188     const MCSymbol *B = &Target.getSymB()->getSymbol();
189     const MCSymbolData &B_SD = Asm.getSymbolData(*B);
190     const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
191
192     // Check for "_foo@got - .", which comes through here as:
193     // Ltmp0:
194     //    ... _foo@got - Ltmp0
195     if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_GOT &&
196         Target.getSymB()->getKind() == MCSymbolRefExpr::VK_None &&
197         Layout.getSymbolOffset(&B_SD) ==
198             Layout.getFragmentOffset(Fragment) + Fixup.getOffset()) {
199       // SymB is the PC, so use a PC-rel pointer-to-GOT relocation.
200       Type = MachO::ARM64_RELOC_POINTER_TO_GOT;
201       IsPCRel = 1;
202       MachO::any_relocation_info MRE;
203       MRE.r_word0 = FixupOffset;
204       MRE.r_word1 = (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
205       Writer->addRelocation(A_Base, Fragment->getParent(), MRE);
206       return;
207     } else if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
208                Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
209       // Otherwise, neither symbol can be modified.
210       Asm.getContext().FatalError(Fixup.getLoc(),
211                                   "unsupported relocation of modified symbol");
212
213     // We don't support PCrel relocations of differences.
214     if (IsPCRel)
215       Asm.getContext().FatalError(Fixup.getLoc(),
216                                   "unsupported pc-relative relocation of "
217                                   "difference");
218
219     // AArch64 always uses external relocations. If there is no symbol to use as
220     // a base address (a local symbol with no preceding non-local symbol),
221     // error out.
222     //
223     // FIXME: We should probably just synthesize an external symbol and use
224     // that.
225     if (!A_Base)
226       Asm.getContext().FatalError(
227           Fixup.getLoc(),
228           "unsupported relocation of local symbol '" + A->getName() +
229               "'. Must have non-local symbol earlier in section.");
230     if (!B_Base)
231       Asm.getContext().FatalError(
232           Fixup.getLoc(),
233           "unsupported relocation of local symbol '" + B->getName() +
234               "'. Must have non-local symbol earlier in section.");
235
236     if (A_Base == B_Base && A_Base)
237       Asm.getContext().FatalError(Fixup.getLoc(),
238                                   "unsupported relocation with identical base");
239
240     Value += (!A_SD.getFragment() ? 0
241                                   : Writer->getSymbolAddress(&A_SD, Layout)) -
242              (!A_Base || !A_Base->getFragment()
243                   ? 0
244                   : Writer->getSymbolAddress(A_Base, Layout));
245     Value -= (!B_SD.getFragment() ? 0
246                                   : Writer->getSymbolAddress(&B_SD, Layout)) -
247              (!B_Base || !B_Base->getFragment()
248                   ? 0
249                   : Writer->getSymbolAddress(B_Base, Layout));
250
251     Type = MachO::ARM64_RELOC_UNSIGNED;
252
253     MachO::any_relocation_info MRE;
254     MRE.r_word0 = FixupOffset;
255     MRE.r_word1 = (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
256     Writer->addRelocation(A_Base, Fragment->getParent(), MRE);
257
258     RelSymbol = B_Base;
259     Type = MachO::ARM64_RELOC_SUBTRACTOR;
260   } else { // A + constant
261     const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
262     const MCSectionMachO &Section = static_cast<const MCSectionMachO &>(
263         Fragment->getParent()->getSection());
264
265     // Pointer-sized relocations can use a local relocation. Otherwise,
266     // we have to be in a debug info section.
267     bool CanUseLocalRelocation =
268         Section.hasAttribute(MachO::S_ATTR_DEBUG) || Log2Size == 3;
269
270     if (Symbol->isTemporary() && (Value || !CanUseLocalRelocation)) {
271       const MCSection &Sec = Symbol->getSection();
272       if (!Asm.getContext().getAsmInfo()->isSectionAtomizableBySymbols(Sec))
273         Asm.addLocalUsedInReloc(*Symbol);
274     }
275
276     const MCSymbolData &SD = Asm.getSymbolData(*Symbol);
277     const MCSymbolData *Base = Asm.getAtom(&SD);
278
279     // If the symbol is a variable and we weren't able to get a Base for it
280     // (i.e., it's not in the symbol table associated with a section) resolve
281     // the relocation based its expansion instead.
282     if (Symbol->isVariable() && !Base) {
283       // If the evaluation is an absolute value, just use that directly
284       // to keep things easy.
285       int64_t Res;
286       if (SD.getSymbol().getVariableValue()->EvaluateAsAbsolute(
287               Res, Layout, Writer->getSectionAddressMap())) {
288         FixedValue = Res;
289         return;
290       }
291
292       // FIXME: Will the Target we already have ever have any data in it
293       // we need to preserve and merge with the new Target? How about
294       // the FixedValue?
295       if (!Symbol->getVariableValue()->EvaluateAsRelocatable(Target, &Layout,
296                                                              &Fixup))
297         Asm.getContext().FatalError(Fixup.getLoc(),
298                                     "unable to resolve variable '" +
299                                         Symbol->getName() + "'");
300       return RecordRelocation(Writer, Asm, Layout, Fragment, Fixup, Target,
301                               FixedValue);
302     }
303
304     // Relocations inside debug sections always use local relocations when
305     // possible. This seems to be done because the debugger doesn't fully
306     // understand relocation entries and expects to find values that
307     // have already been fixed up.
308     if (Symbol->isInSection()) {
309       if (Section.hasAttribute(MachO::S_ATTR_DEBUG))
310         Base = nullptr;
311     }
312
313     // AArch64 uses external relocations as much as possible. For debug
314     // sections, and for pointer-sized relocations (.quad), we allow section
315     // relocations.  It's code sections that run into trouble.
316     if (Base) {
317       RelSymbol = Base;
318
319       // Add the local offset, if needed.
320       if (Base != &SD)
321         Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
322     } else if (Symbol->isInSection()) {
323       if (!CanUseLocalRelocation)
324         Asm.getContext().FatalError(
325             Fixup.getLoc(),
326             "unsupported relocation of local symbol '" + Symbol->getName() +
327                 "'. Must have non-local symbol earlier in section.");
328       // Adjust the relocation to be section-relative.
329       // The index is the section ordinal (1-based).
330       const MCSectionData &SymSD =
331           Asm.getSectionData(SD.getSymbol().getSection());
332       Index = SymSD.getOrdinal() + 1;
333       Value += Writer->getSymbolAddress(&SD, Layout);
334
335       if (IsPCRel)
336         Value -= Writer->getFragmentAddress(Fragment, Layout) +
337                  Fixup.getOffset() + (1ULL << Log2Size);
338     } else {
339       // Resolve constant variables.
340       if (SD.getSymbol().isVariable()) {
341         int64_t Res;
342         if (SD.getSymbol().getVariableValue()->EvaluateAsAbsolute(
343                 Res, Layout, Writer->getSectionAddressMap())) {
344           FixedValue = Res;
345           return;
346         }
347       }
348       Asm.getContext().FatalError(Fixup.getLoc(),
349                                   "unsupported relocation of variable '" +
350                                       Symbol->getName() + "'");
351     }
352   }
353
354   // If the relocation kind is Branch26, Page21, or Pageoff12, any addend
355   // is represented via an Addend relocation, not encoded directly into
356   // the instruction.
357   if ((Type == MachO::ARM64_RELOC_BRANCH26 ||
358        Type == MachO::ARM64_RELOC_PAGE21 ||
359        Type == MachO::ARM64_RELOC_PAGEOFF12) &&
360       Value) {
361     assert((Value & 0xff000000) == 0 && "Added relocation out of range!");
362
363     MachO::any_relocation_info MRE;
364     MRE.r_word0 = FixupOffset;
365     MRE.r_word1 =
366         (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
367     Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
368
369     // Now set up the Addend relocation.
370     Type = MachO::ARM64_RELOC_ADDEND;
371     Index = Value;
372     RelSymbol = nullptr;
373     IsPCRel = 0;
374     Log2Size = 2;
375
376     // Put zero into the instruction itself. The addend is in the relocation.
377     Value = 0;
378   }
379
380   // If there's any addend left to handle, encode it in the instruction.
381   FixedValue = Value;
382
383   // struct relocation_info (8 bytes)
384   MachO::any_relocation_info MRE;
385   MRE.r_word0 = FixupOffset;
386   MRE.r_word1 =
387       (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
388   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
389 }
390
391 MCObjectWriter *llvm::createAArch64MachObjectWriter(raw_ostream &OS,
392                                                   uint32_t CPUType,
393                                                   uint32_t CPUSubtype) {
394   return createMachObjectWriter(
395       new AArch64MachObjectWriter(CPUType, CPUSubtype), OS,
396       /*IsLittleEndian=*/true);
397 }