xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/MCTargetDesc/X86MachObjectWriter.cpp (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===-- X86MachObjectWriter.cpp - X86 Mach-O Writer -----------------------===//
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/X86FixupKinds.h"
10 #include "MCTargetDesc/X86MCAsmInfo.h"
11 #include "MCTargetDesc/X86MCTargetDesc.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/BinaryFormat/MachO.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCAsmInfoDarwin.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCMachObjectWriter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/Format.h"
23 
24 using namespace llvm;
25 
26 namespace {
27 class X86MachObjectWriter : public MCMachObjectTargetWriter {
28   bool recordScatteredRelocation(MachObjectWriter *Writer,
29                                  const MCAssembler &Asm,
30                                  const MCFragment *Fragment,
31                                  const MCFixup &Fixup,
32                                  MCValue Target,
33                                  unsigned Log2Size,
34                                  uint64_t &FixedValue);
35   void recordTLVPRelocation(MachObjectWriter *Writer,
36                             const MCAssembler &Asm,
37                             const MCFragment *Fragment,
38                             const MCFixup &Fixup,
39                             MCValue Target,
40                             uint64_t &FixedValue);
41 
42   void RecordX86Relocation(MachObjectWriter *Writer,
43                               const MCAssembler &Asm,
44                               const MCFragment *Fragment,
45                               const MCFixup &Fixup,
46                               MCValue Target,
47                               uint64_t &FixedValue);
48   void RecordX86_64Relocation(MachObjectWriter *Writer, MCAssembler &Asm,
49                               const MCFragment *Fragment, const MCFixup &Fixup,
50                               MCValue Target, uint64_t &FixedValue);
51 
52 public:
X86MachObjectWriter(bool Is64Bit,uint32_t CPUType,uint32_t CPUSubtype)53   X86MachObjectWriter(bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype)
54       : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype) {}
55 
recordRelocation(MachObjectWriter * Writer,MCAssembler & Asm,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)56   void recordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
57                         const MCFragment *Fragment, const MCFixup &Fixup,
58                         MCValue Target, uint64_t &FixedValue) override {
59     if (Writer->is64Bit())
60       RecordX86_64Relocation(Writer, Asm, Fragment, Fixup, Target, FixedValue);
61     else
62       RecordX86Relocation(Writer, Asm, Fragment, Fixup, Target, FixedValue);
63   }
64 };
65 } // namespace
66 
isFixupKindRIPRel(unsigned Kind)67 static bool isFixupKindRIPRel(unsigned Kind) {
68   return Kind == X86::reloc_riprel_4byte ||
69          Kind == X86::reloc_riprel_4byte_movq_load ||
70          Kind == X86::reloc_riprel_4byte_movq_load_rex2 ||
71          Kind == X86::reloc_riprel_4byte_relax ||
72          Kind == X86::reloc_riprel_4byte_relax_rex ||
73          Kind == X86::reloc_riprel_4byte_relax_rex2 ||
74          Kind == X86::reloc_riprel_4byte_relax_evex;
75 }
76 
getFixupKindLog2Size(unsigned Kind)77 static unsigned getFixupKindLog2Size(unsigned Kind) {
78   switch (Kind) {
79   default:
80     llvm_unreachable("invalid fixup kind!");
81   case FK_Data_1: return 0;
82   case FK_Data_2: return 1;
83     // FIXME: Remove these!!!
84   case X86::reloc_riprel_4byte:
85   case X86::reloc_riprel_4byte_relax:
86   case X86::reloc_riprel_4byte_relax_rex:
87   case X86::reloc_riprel_4byte_relax_rex2:
88   case X86::reloc_riprel_4byte_movq_load:
89   case X86::reloc_riprel_4byte_movq_load_rex2:
90   case X86::reloc_signed_4byte:
91   case X86::reloc_signed_4byte_relax:
92   case X86::reloc_branch_4byte_pcrel:
93   case X86::reloc_riprel_4byte_relax_evex:
94   case FK_Data_4: return 2;
95   case FK_Data_8: return 3;
96   }
97 }
98 
RecordX86_64Relocation(MachObjectWriter * Writer,MCAssembler & Asm,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)99 void X86MachObjectWriter::RecordX86_64Relocation(
100     MachObjectWriter *Writer, MCAssembler &Asm, const MCFragment *Fragment,
101     const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) {
102   unsigned IsPCRel = Fixup.isPCRel();
103   unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
104   unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
105 
106   // See <reloc.h>.
107   uint32_t FixupOffset = Asm.getFragmentOffset(*Fragment) + Fixup.getOffset();
108   uint32_t FixupAddress =
109       Writer->getFragmentAddress(Asm, Fragment) + Fixup.getOffset();
110   int64_t Value = 0;
111   unsigned Index = 0;
112   unsigned IsExtern = 0;
113   unsigned Type = 0;
114   const MCSymbol *RelSymbol = nullptr;
115 
116   Value = Target.getConstant();
117 
118   if (IsPCRel) {
119     // Compensate for the relocation offset, Darwin x86_64 relocations only have
120     // the addend and appear to have attempted to define it to be the actual
121     // expression addend without the PCrel bias. However, instructions with data
122     // following the relocation are not accommodated for (see comment below
123     // regarding SIGNED{1,2,4}), so it isn't exactly that either.
124     Value += 1LL << Log2Size;
125   }
126 
127   if (Target.isAbsolute()) { // constant
128     // SymbolNum of 0 indicates the absolute section.
129     Type = MachO::X86_64_RELOC_UNSIGNED;
130 
131     // FIXME: I believe this is broken, I don't think the linker can understand
132     // it. I think it would require a local relocation, but I'm not sure if that
133     // would work either. The official way to get an absolute PCrel relocation
134     // is to use an absolute symbol (which we don't support yet).
135     if (IsPCRel) {
136       IsExtern = 1;
137       Type = MachO::X86_64_RELOC_BRANCH;
138     }
139   } else if (Target.getSubSym()) { // A - B + constant
140     const MCSymbol *A = Target.getAddSym();
141     if (A->isTemporary())
142       A = &Writer->findAliasedSymbol(*A);
143     const MCSymbol *A_Base = Writer->getAtom(*A);
144 
145     const MCSymbol *B = Target.getSubSym();
146     if (B->isTemporary())
147       B = &Writer->findAliasedSymbol(*B);
148     const MCSymbol *B_Base = Writer->getAtom(*B);
149 
150     // Neither symbol can be modified.
151     if (Target.getSpecifier()) {
152       reportError(Fixup.getLoc(), "unsupported relocation of modified symbol");
153       return;
154     }
155 
156     // We don't support PCrel relocations of differences. Darwin 'as' doesn't
157     // implement most of these correctly.
158     if (IsPCRel) {
159       reportError(Fixup.getLoc(),
160                   "unsupported pc-relative relocation of difference");
161       return;
162     }
163 
164     // The support for the situation where one or both of the symbols would
165     // require a local relocation is handled just like if the symbols were
166     // external.  This is certainly used in the case of debug sections where the
167     // section has only temporary symbols and thus the symbols don't have base
168     // symbols.  This is encoded using the section ordinal and non-extern
169     // relocation entries.
170 
171     // Darwin 'as' doesn't emit correct relocations for this (it ends up with a
172     // single SIGNED relocation); reject it for now.  Except the case where both
173     // symbols don't have a base, equal but both NULL.
174     if (A_Base == B_Base && A_Base) {
175       reportError(Fixup.getLoc(), "unsupported relocation with identical base");
176       return;
177     }
178 
179     // A subtraction expression where either symbol is undefined is a
180     // non-relocatable expression.
181     if (A->isUndefined() || B->isUndefined()) {
182       StringRef Name = A->isUndefined() ? A->getName() : B->getName();
183       reportError(
184           Fixup.getLoc(),
185           "unsupported relocation with subtraction expression, symbol '" +
186               Name + "' can not be undefined in a subtraction expression");
187       return;
188     }
189 
190     Value += Writer->getSymbolAddress(*A) -
191              (!A_Base ? 0 : Writer->getSymbolAddress(*A_Base));
192     Value -= Writer->getSymbolAddress(*B) -
193              (!B_Base ? 0 : Writer->getSymbolAddress(*B_Base));
194 
195     if (!A_Base)
196       Index = A->getFragment()->getParent()->getOrdinal() + 1;
197     Type = MachO::X86_64_RELOC_UNSIGNED;
198 
199     MachO::any_relocation_info MRE;
200     MRE.r_word0 = FixupOffset;
201     MRE.r_word1 =
202         (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
203     Writer->addRelocation(A_Base, Fragment->getParent(), MRE);
204 
205     if (B_Base)
206       RelSymbol = B_Base;
207     else
208       Index = B->getFragment()->getParent()->getOrdinal() + 1;
209     Type = MachO::X86_64_RELOC_SUBTRACTOR;
210   } else {
211     const MCSymbol *Symbol = Target.getAddSym();
212     if (Symbol->isTemporary() && Value) {
213       const MCSection &Sec = Symbol->getSection();
214       if (!MCAsmInfoDarwin::isSectionAtomizableBySymbols(Sec))
215         Symbol->setUsedInReloc();
216     }
217     RelSymbol = Writer->getAtom(*Symbol);
218 
219     // Relocations inside debug sections always use local relocations when
220     // possible. This seems to be done because the debugger doesn't fully
221     // understand x86_64 relocation entries, and expects to find values that
222     // have already been fixed up.
223     if (Symbol->isInSection()) {
224       const MCSectionMachO &Section =
225           static_cast<const MCSectionMachO &>(*Fragment->getParent());
226       if (Section.hasAttribute(MachO::S_ATTR_DEBUG))
227         RelSymbol = nullptr;
228     }
229 
230     // x86_64 almost always uses external relocations, except when there is no
231     // symbol to use as a base address (a local symbol with no preceding
232     // non-local symbol).
233     if (RelSymbol) {
234       // Add the local offset, if needed.
235       if (RelSymbol != Symbol)
236         Value += Asm.getSymbolOffset(*Symbol) - Asm.getSymbolOffset(*RelSymbol);
237     } else if (Symbol->isInSection() && !Symbol->isVariable()) {
238       // The index is the section ordinal (1-based).
239       Index = Symbol->getFragment()->getParent()->getOrdinal() + 1;
240       Value += Writer->getSymbolAddress(*Symbol);
241 
242       if (IsPCRel)
243         Value -= FixupAddress + (1 << Log2Size);
244     } else if (Symbol->isVariable()) {
245       FixedValue = Writer->getSymbolAddress(*Symbol);
246       return;
247     } else {
248       reportError(Fixup.getLoc(),
249                   "unsupported relocation of undefined symbol '" +
250                       Symbol->getName() + "'");
251       return;
252     }
253 
254     auto Specifier = Target.getSpecifier();
255     if (IsPCRel) {
256       if (IsRIPRel) {
257         if (Specifier == X86::S_GOTPCREL) {
258           // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
259           // rewrite the movq to an leaq at link time if the symbol ends up in
260           // the same linkage unit.
261           if (Fixup.getKind() == X86::reloc_riprel_4byte_movq_load)
262             Type = MachO::X86_64_RELOC_GOT_LOAD;
263           else
264             Type = MachO::X86_64_RELOC_GOT;
265         } else if (Specifier == X86::S_TLVP) {
266           Type = MachO::X86_64_RELOC_TLV;
267         } else if (Specifier) {
268           reportError(Fixup.getLoc(),
269                       "unsupported symbol modifier in relocation");
270           return;
271         } else {
272           Type = MachO::X86_64_RELOC_SIGNED;
273 
274           // The Darwin x86_64 relocation format has a problem where it cannot
275           // encode an address (L<foo> + <constant>) which is outside the atom
276           // containing L<foo>. Generally, this shouldn't occur but it does
277           // happen when we have a RIPrel instruction with data following the
278           // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
279           // adjustment Darwin x86_64 uses, the offset is still negative and the
280           // linker has no way to recognize this.
281           //
282           // To work around this, Darwin uses several special relocation types
283           // to indicate the offsets. However, the specification or
284           // implementation of these seems to also be incomplete; they should
285           // adjust the addend as well based on the actual encoded instruction
286           // (the additional bias), but instead appear to just look at the final
287           // offset.
288           switch (-(Target.getConstant() + (1LL << Log2Size))) {
289           case 1: Type = MachO::X86_64_RELOC_SIGNED_1; break;
290           case 2: Type = MachO::X86_64_RELOC_SIGNED_2; break;
291           case 4: Type = MachO::X86_64_RELOC_SIGNED_4; break;
292           }
293         }
294       } else {
295         if (Specifier) {
296           reportError(Fixup.getLoc(),
297                       "unsupported symbol modifier in branch relocation");
298           return;
299         }
300 
301         Type = MachO::X86_64_RELOC_BRANCH;
302       }
303     } else {
304       if (Specifier == X86::S_GOT) {
305         Type = MachO::X86_64_RELOC_GOT;
306       } else if (Specifier == X86::S_GOTPCREL) {
307         // GOTPCREL is allowed as a modifier on non-PCrel instructions, in which
308         // case all we do is set the PCrel bit in the relocation entry; this is
309         // used with exception handling, for example. The source is required to
310         // include any necessary offset directly.
311         Type = MachO::X86_64_RELOC_GOT;
312         IsPCRel = 1;
313       } else if (Specifier == X86::S_TLVP) {
314         reportError(Fixup.getLoc(),
315                     "TLVP symbol modifier should have been rip-rel");
316         return;
317       } else if (Specifier) {
318         reportError(Fixup.getLoc(),
319                     "unsupported symbol modifier in relocation");
320         return;
321       } else {
322         Type = MachO::X86_64_RELOC_UNSIGNED;
323         if (Fixup.getKind() == X86::reloc_signed_4byte) {
324           reportError(
325               Fixup.getLoc(),
326               "32-bit absolute addressing is not supported in 64-bit mode");
327           return;
328         }
329       }
330     }
331   }
332 
333   // x86_64 always writes custom values into the fixups.
334   FixedValue = Value;
335 
336   // struct relocation_info (8 bytes)
337   MachO::any_relocation_info MRE;
338   MRE.r_word0 = FixupOffset;
339   MRE.r_word1 = (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) |
340                 (IsExtern << 27) | (Type << 28);
341   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
342 }
343 
recordScatteredRelocation(MachObjectWriter * Writer,const MCAssembler & Asm,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,unsigned Log2Size,uint64_t & FixedValue)344 bool X86MachObjectWriter::recordScatteredRelocation(MachObjectWriter *Writer,
345                                                     const MCAssembler &Asm,
346                                                     const MCFragment *Fragment,
347                                                     const MCFixup &Fixup,
348                                                     MCValue Target,
349                                                     unsigned Log2Size,
350                                                     uint64_t &FixedValue) {
351   uint64_t OriginalFixedValue = FixedValue;
352   uint32_t FixupOffset = Asm.getFragmentOffset(*Fragment) + Fixup.getOffset();
353   unsigned IsPCRel = Fixup.isPCRel();
354   unsigned Type = MachO::GENERIC_RELOC_VANILLA;
355 
356   // See <reloc.h>.
357   const MCSymbol *A = Target.getAddSym();
358 
359   if (!A->getFragment()) {
360     reportError(Fixup.getLoc(),
361                 "symbol '" + A->getName() +
362                     "' can not be undefined in a subtraction expression");
363     return false;
364   }
365 
366   uint32_t Value = Writer->getSymbolAddress(*A);
367   uint64_t SecAddr = Writer->getSectionAddress(A->getFragment()->getParent());
368   FixedValue += SecAddr;
369   uint32_t Value2 = 0;
370 
371   if (const MCSymbol *SB = Target.getSubSym()) {
372     if (!SB->getFragment()) {
373       reportError(Fixup.getLoc(),
374                   "symbol '" + SB->getName() +
375                       "' can not be undefined in a subtraction expression");
376       return false;
377     }
378 
379     // Select the appropriate difference relocation type.
380     //
381     // Note that there is no longer any semantic difference between these two
382     // relocation types from the linkers point of view, this is done solely for
383     // pedantic compatibility with 'as'.
384     Type = A->isExternal() ? (unsigned)MachO::GENERIC_RELOC_SECTDIFF
385                            : (unsigned)MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
386     Value2 = Writer->getSymbolAddress(*SB);
387     FixedValue -= Writer->getSectionAddress(SB->getFragment()->getParent());
388   }
389 
390   // Relocations are written out in reverse order, so the PAIR comes first.
391   if (Type == MachO::GENERIC_RELOC_SECTDIFF ||
392       Type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
393     // If the offset is too large to fit in a scattered relocation,
394     // we're hosed. It's an unfortunate limitation of the MachO format.
395     if (FixupOffset > 0xffffff) {
396       char Buffer[32];
397       format("0x%x", FixupOffset).print(Buffer, sizeof(Buffer));
398       reportError(Fixup.getLoc(), Twine("Section too large, can't encode "
399                                         "r_address (") +
400                                       Buffer +
401                                       ") into 24 bits of scattered "
402                                       "relocation entry.");
403       return false;
404     }
405 
406     MachO::any_relocation_info MRE;
407     MRE.r_word0 = ((0                         <<  0) | // r_address
408                    (MachO::GENERIC_RELOC_PAIR << 24) | // r_type
409                    (Log2Size                  << 28) |
410                    (IsPCRel                   << 30) |
411                    MachO::R_SCATTERED);
412     MRE.r_word1 = Value2;
413     Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
414   } else {
415     // If the offset is more than 24-bits, it won't fit in a scattered
416     // relocation offset field, so we fall back to using a non-scattered
417     // relocation. This is a bit risky, as if the offset reaches out of
418     // the block and the linker is doing scattered loading on this
419     // symbol, things can go badly.
420     //
421     // Required for 'as' compatibility.
422     if (FixupOffset > 0xffffff) {
423       FixedValue = OriginalFixedValue;
424       return false;
425     }
426   }
427 
428   MachO::any_relocation_info MRE;
429   MRE.r_word0 = ((FixupOffset <<  0) |
430                  (Type        << 24) |
431                  (Log2Size    << 28) |
432                  (IsPCRel     << 30) |
433                  MachO::R_SCATTERED);
434   MRE.r_word1 = Value;
435   Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
436   return true;
437 }
438 
recordTLVPRelocation(MachObjectWriter * Writer,const MCAssembler & Asm,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)439 void X86MachObjectWriter::recordTLVPRelocation(MachObjectWriter *Writer,
440                                                const MCAssembler &Asm,
441                                                const MCFragment *Fragment,
442                                                const MCFixup &Fixup,
443                                                MCValue Target,
444                                                uint64_t &FixedValue) {
445   const MCSymbol *SymA = Target.getAddSym();
446   assert(Target.getSpecifier() == X86::S_TLVP && !is64Bit() &&
447          "Should only be called with a 32-bit TLVP relocation!");
448 
449   unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
450   uint32_t Value = Asm.getFragmentOffset(*Fragment) + Fixup.getOffset();
451   unsigned IsPCRel = 0;
452 
453   // We're only going to have a second symbol in pic mode and it'll be a
454   // subtraction from the picbase. For 32-bit pic the addend is the difference
455   // between the picbase and the next address.  For 32-bit static the addend is
456   // zero.
457   if (auto *SymB = Target.getSubSym()) {
458     // If this is a subtraction then we're pcrel.
459     uint32_t FixupAddress =
460         Writer->getFragmentAddress(Asm, Fragment) + Fixup.getOffset();
461     IsPCRel = 1;
462     FixedValue =
463         FixupAddress - Writer->getSymbolAddress(*SymB) + Target.getConstant();
464     FixedValue += 1ULL << Log2Size;
465   } else {
466     FixedValue = 0;
467   }
468 
469   // struct relocation_info (8 bytes)
470   MachO::any_relocation_info MRE;
471   MRE.r_word0 = Value;
472   MRE.r_word1 =
473       (IsPCRel << 24) | (Log2Size << 25) | (MachO::GENERIC_RELOC_TLV << 28);
474   Writer->addRelocation(SymA, Fragment->getParent(), MRE);
475 }
476 
RecordX86Relocation(MachObjectWriter * Writer,const MCAssembler & Asm,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)477 void X86MachObjectWriter::RecordX86Relocation(MachObjectWriter *Writer,
478                                               const MCAssembler &Asm,
479                                               const MCFragment *Fragment,
480                                               const MCFixup &Fixup,
481                                               MCValue Target,
482                                               uint64_t &FixedValue) {
483   unsigned IsPCRel = Fixup.isPCRel();
484   unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
485   const MCSymbol *A = Target.getAddSym();
486 
487   // If this is a 32-bit TLVP reloc it's handled a bit differently.
488   if (A && Target.getSpecifier() == X86::S_TLVP) {
489     recordTLVPRelocation(Writer, Asm, Fragment, Fixup, Target, FixedValue);
490     return;
491   }
492 
493   // If this is a difference or a defined symbol plus an offset, then we need a
494   // scattered relocation entry. Differences always require scattered
495   // relocations.
496   if (Target.getSubSym()) {
497     recordScatteredRelocation(Writer, Asm, Fragment, Fixup, Target, Log2Size,
498                               FixedValue);
499     return;
500   }
501 
502   // If this is an internal relocation with an offset, it also needs a scattered
503   // relocation entry.
504   uint32_t Offset = Target.getConstant();
505   if (IsPCRel)
506     Offset += 1 << Log2Size;
507 
508   // Try to record the scattered relocation if needed. Fall back to non
509   // scattered if necessary (see comments in recordScatteredRelocation()
510   // for details).
511   if (Offset && A && !Writer->doesSymbolRequireExternRelocation(*A) &&
512       recordScatteredRelocation(Writer, Asm, Fragment, Fixup, Target, Log2Size,
513                                 FixedValue))
514     return;
515 
516   // See <reloc.h>.
517   uint32_t FixupOffset = Asm.getFragmentOffset(*Fragment) + Fixup.getOffset();
518   unsigned Index = 0;
519   unsigned Type = 0;
520   const MCSymbol *RelSymbol = nullptr;
521 
522   if (Target.isAbsolute()) { // constant
523     // SymbolNum of 0 indicates the absolute section.
524     //
525     // FIXME: Currently, these are never generated (see code below). I cannot
526     // find a case where they are actually emitted.
527     Type = MachO::GENERIC_RELOC_VANILLA;
528   } else {
529     assert(A && "Unknown symbol data");
530 
531     // Resolve constant variables.
532     if (A->isVariable()) {
533       MCValue Val;
534       bool Relocatable =
535           A->getVariableValue()->evaluateAsRelocatable(Val, &Asm);
536       int64_t Res = Val.getConstant();
537       bool isAbs = Val.isAbsolute();
538       if (Relocatable && Val.getAddSym() && Val.getSubSym()) {
539         Res += Writer->getSymbolAddress(*Val.getAddSym()) -
540                Writer->getSymbolAddress(*Val.getSubSym());
541         isAbs = true;
542       }
543       if (isAbs) {
544         FixedValue = Res;
545         return;
546       }
547     }
548 
549     // Check whether we need an external or internal relocation.
550     if (Writer->doesSymbolRequireExternRelocation(*A)) {
551       RelSymbol = A;
552       // For external relocations, make sure to offset the fixup value to
553       // compensate for the addend of the symbol address, if it was
554       // undefined. This occurs with weak definitions, for example.
555       if (!A->isUndefined())
556         FixedValue -= Asm.getSymbolOffset(*A);
557     } else {
558       // The index is the section ordinal (1-based).
559       const MCSection &Sec = A->getSection();
560       Index = Sec.getOrdinal() + 1;
561       FixedValue += Writer->getSectionAddress(&Sec);
562     }
563     if (IsPCRel)
564       FixedValue -= Writer->getSectionAddress(Fragment->getParent());
565 
566     Type = MachO::GENERIC_RELOC_VANILLA;
567   }
568 
569   // struct relocation_info (8 bytes)
570   MachO::any_relocation_info MRE;
571   MRE.r_word0 = FixupOffset;
572   MRE.r_word1 =
573       (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
574   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
575 }
576 
577 std::unique_ptr<MCObjectTargetWriter>
createX86MachObjectWriter(bool Is64Bit,uint32_t CPUType,uint32_t CPUSubtype)578 llvm::createX86MachObjectWriter(bool Is64Bit, uint32_t CPUType,
579                                 uint32_t CPUSubtype) {
580   return std::make_unique<X86MachObjectWriter>(Is64Bit, CPUType, CPUSubtype);
581 }
582