xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision dd1ea9de2e3e3ac80a620f71411a9a36449f2697)
1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
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 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/BinaryFormat/MachO.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Mangler.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSectionCOFF.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/MC/MCSectionWasm.h"
46 #include "llvm/MC/MCSectionXCOFF.h"
47 #include "llvm/MC/MCStreamer.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/MC/MCSymbolELF.h"
50 #include "llvm/MC/MCValue.h"
51 #include "llvm/MC/SectionKind.h"
52 #include "llvm/ProfileData/InstrProf.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetMachine.h"
59 #include <cassert>
60 #include <string>
61 
62 using namespace llvm;
63 using namespace dwarf;
64 
65 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
66                              StringRef &Section) {
67   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
68   M.getModuleFlagsMetadata(ModuleFlags);
69 
70   for (const auto &MFE: ModuleFlags) {
71     // Ignore flags with 'Require' behaviour.
72     if (MFE.Behavior == Module::Require)
73       continue;
74 
75     StringRef Key = MFE.Key->getString();
76     if (Key == "Objective-C Image Info Version") {
77       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78     } else if (Key == "Objective-C Garbage Collection" ||
79                Key == "Objective-C GC Only" ||
80                Key == "Objective-C Is Simulated" ||
81                Key == "Objective-C Class Properties" ||
82                Key == "Objective-C Image Swift Version") {
83       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84     } else if (Key == "Objective-C Image Info Section") {
85       Section = cast<MDString>(MFE.Val)->getString();
86     }
87   }
88 }
89 
90 //===----------------------------------------------------------------------===//
91 //                                  ELF
92 //===----------------------------------------------------------------------===//
93 
94 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
95                                              const TargetMachine &TgtM) {
96   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
97   TM = &TgtM;
98 
99   CodeModel::Model CM = TgtM.getCodeModel();
100 
101   switch (TgtM.getTargetTriple().getArch()) {
102   case Triple::arm:
103   case Triple::armeb:
104   case Triple::thumb:
105   case Triple::thumbeb:
106     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
107       break;
108     // Fallthrough if not using EHABI
109     LLVM_FALLTHROUGH;
110   case Triple::ppc:
111   case Triple::x86:
112     PersonalityEncoding = isPositionIndependent()
113                               ? dwarf::DW_EH_PE_indirect |
114                                     dwarf::DW_EH_PE_pcrel |
115                                     dwarf::DW_EH_PE_sdata4
116                               : dwarf::DW_EH_PE_absptr;
117     LSDAEncoding = isPositionIndependent()
118                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
119                        : dwarf::DW_EH_PE_absptr;
120     TTypeEncoding = isPositionIndependent()
121                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
122                               dwarf::DW_EH_PE_sdata4
123                         : dwarf::DW_EH_PE_absptr;
124     break;
125   case Triple::x86_64:
126     if (isPositionIndependent()) {
127       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
128         ((CM == CodeModel::Small || CM == CodeModel::Medium)
129          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
130       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
131         (CM == CodeModel::Small
132          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
133       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
134         ((CM == CodeModel::Small || CM == CodeModel::Medium)
135          ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
136     } else {
137       PersonalityEncoding =
138         (CM == CodeModel::Small || CM == CodeModel::Medium)
139         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
140       LSDAEncoding = (CM == CodeModel::Small)
141         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
142       TTypeEncoding = (CM == CodeModel::Small)
143         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
144     }
145     break;
146   case Triple::hexagon:
147     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
148     LSDAEncoding = dwarf::DW_EH_PE_absptr;
149     TTypeEncoding = dwarf::DW_EH_PE_absptr;
150     if (isPositionIndependent()) {
151       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
152       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
153       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
154     }
155     break;
156   case Triple::aarch64:
157   case Triple::aarch64_be:
158   case Triple::aarch64_32:
159     // The small model guarantees static code/data size < 4GB, but not where it
160     // will be in memory. Most of these could end up >2GB away so even a signed
161     // pc-relative 32-bit address is insufficient, theoretically.
162     if (isPositionIndependent()) {
163       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
164         dwarf::DW_EH_PE_sdata8;
165       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
166       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
167         dwarf::DW_EH_PE_sdata8;
168     } else {
169       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
170       LSDAEncoding = dwarf::DW_EH_PE_absptr;
171       TTypeEncoding = dwarf::DW_EH_PE_absptr;
172     }
173     break;
174   case Triple::lanai:
175     LSDAEncoding = dwarf::DW_EH_PE_absptr;
176     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
177     TTypeEncoding = dwarf::DW_EH_PE_absptr;
178     break;
179   case Triple::mips:
180   case Triple::mipsel:
181   case Triple::mips64:
182   case Triple::mips64el:
183     // MIPS uses indirect pointer to refer personality functions and types, so
184     // that the eh_frame section can be read-only. DW.ref.personality will be
185     // generated for relocation.
186     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
187     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
188     //        identify N64 from just a triple.
189     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
190                     dwarf::DW_EH_PE_sdata4;
191     // We don't support PC-relative LSDA references in GAS so we use the default
192     // DW_EH_PE_absptr for those.
193 
194     // FreeBSD must be explicit about the data size and using pcrel since it's
195     // assembler/linker won't do the automatic conversion that the Linux tools
196     // do.
197     if (TgtM.getTargetTriple().isOSFreeBSD()) {
198       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
199       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
200     }
201     break;
202   case Triple::ppc64:
203   case Triple::ppc64le:
204     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
205       dwarf::DW_EH_PE_udata8;
206     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
207     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
208       dwarf::DW_EH_PE_udata8;
209     break;
210   case Triple::sparcel:
211   case Triple::sparc:
212     if (isPositionIndependent()) {
213       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
214       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
215         dwarf::DW_EH_PE_sdata4;
216       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
217         dwarf::DW_EH_PE_sdata4;
218     } else {
219       LSDAEncoding = dwarf::DW_EH_PE_absptr;
220       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
221       TTypeEncoding = dwarf::DW_EH_PE_absptr;
222     }
223     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
224     break;
225   case Triple::riscv32:
226   case Triple::riscv64:
227     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
228     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
229                           dwarf::DW_EH_PE_sdata4;
230     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
231                     dwarf::DW_EH_PE_sdata4;
232     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
233     break;
234   case Triple::sparcv9:
235     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
236     if (isPositionIndependent()) {
237       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
238         dwarf::DW_EH_PE_sdata4;
239       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
240         dwarf::DW_EH_PE_sdata4;
241     } else {
242       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
243       TTypeEncoding = dwarf::DW_EH_PE_absptr;
244     }
245     break;
246   case Triple::systemz:
247     // All currently-defined code models guarantee that 4-byte PC-relative
248     // values will be in range.
249     if (isPositionIndependent()) {
250       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
251         dwarf::DW_EH_PE_sdata4;
252       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
253       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
254         dwarf::DW_EH_PE_sdata4;
255     } else {
256       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
257       LSDAEncoding = dwarf::DW_EH_PE_absptr;
258       TTypeEncoding = dwarf::DW_EH_PE_absptr;
259     }
260     break;
261   default:
262     break;
263   }
264 }
265 
266 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
267                                                      Module &M) const {
268   auto &C = getContext();
269 
270   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
271     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
272                               ELF::SHF_EXCLUDE);
273 
274     Streamer.SwitchSection(S);
275 
276     for (const auto *Operand : LinkerOptions->operands()) {
277       if (cast<MDNode>(Operand)->getNumOperands() != 2)
278         report_fatal_error("invalid llvm.linker.options");
279       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
280         Streamer.emitBytes(cast<MDString>(Option)->getString());
281         Streamer.emitIntValue(0, 1);
282       }
283     }
284   }
285 
286   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
287     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
288                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
289 
290     Streamer.SwitchSection(S);
291 
292     for (const auto *Operand : DependentLibraries->operands()) {
293       Streamer.emitBytes(
294           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
295       Streamer.emitIntValue(0, 1);
296     }
297   }
298 
299   unsigned Version = 0;
300   unsigned Flags = 0;
301   StringRef Section;
302 
303   GetObjCImageInfo(M, Version, Flags, Section);
304   if (!Section.empty()) {
305     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
306     Streamer.SwitchSection(S);
307     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
308     Streamer.emitIntValue(Version, 4);
309     Streamer.emitIntValue(Flags, 4);
310     Streamer.AddBlankLine();
311   }
312 
313   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
314   M.getModuleFlagsMetadata(ModuleFlags);
315 
316   MDNode *CFGProfile = nullptr;
317 
318   for (const auto &MFE : ModuleFlags) {
319     StringRef Key = MFE.Key->getString();
320     if (Key == "CG Profile") {
321       CFGProfile = cast<MDNode>(MFE.Val);
322       break;
323     }
324   }
325 
326   if (!CFGProfile)
327     return;
328 
329   auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
330     if (!MDO)
331       return nullptr;
332     auto V = cast<ValueAsMetadata>(MDO);
333     const Function *F = cast<Function>(V->getValue());
334     return TM->getSymbol(F);
335   };
336 
337   for (const auto &Edge : CFGProfile->operands()) {
338     MDNode *E = cast<MDNode>(Edge);
339     const MCSymbol *From = GetSym(E->getOperand(0));
340     const MCSymbol *To = GetSym(E->getOperand(1));
341     // Skip null functions. This can happen if functions are dead stripped after
342     // the CGProfile pass has been run.
343     if (!From || !To)
344       continue;
345     uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
346                          ->getValue()
347                          ->getUniqueInteger()
348                          .getZExtValue();
349     Streamer.emitCGProfileEntry(
350         MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
351         MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
352   }
353 }
354 
355 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
356     const GlobalValue *GV, const TargetMachine &TM,
357     MachineModuleInfo *MMI) const {
358   unsigned Encoding = getPersonalityEncoding();
359   if ((Encoding & 0x80) == DW_EH_PE_indirect)
360     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
361                                           TM.getSymbol(GV)->getName());
362   if ((Encoding & 0x70) == DW_EH_PE_absptr)
363     return TM.getSymbol(GV);
364   report_fatal_error("We do not support this DWARF encoding yet!");
365 }
366 
367 void TargetLoweringObjectFileELF::emitPersonalityValue(
368     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
369   SmallString<64> NameData("DW.ref.");
370   NameData += Sym->getName();
371   MCSymbolELF *Label =
372       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
373   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
374   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
375   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
376   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
377                                                    ELF::SHT_PROGBITS, Flags, 0);
378   unsigned Size = DL.getPointerSize();
379   Streamer.SwitchSection(Sec);
380   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
381   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
382   const MCExpr *E = MCConstantExpr::create(Size, getContext());
383   Streamer.emitELFSize(Label, E);
384   Streamer.emitLabel(Label);
385 
386   Streamer.emitSymbolValue(Sym, Size);
387 }
388 
389 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
390     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
391     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
392   if (Encoding & DW_EH_PE_indirect) {
393     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
394 
395     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
396 
397     // Add information about the stub reference to ELFMMI so that the stub
398     // gets emitted by the asmprinter.
399     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
400     if (!StubSym.getPointer()) {
401       MCSymbol *Sym = TM.getSymbol(GV);
402       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
403     }
404 
405     return TargetLoweringObjectFile::
406       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
407                         Encoding & ~DW_EH_PE_indirect, Streamer);
408   }
409 
410   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
411                                                            MMI, Streamer);
412 }
413 
414 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
415   // N.B.: The defaults used in here are not the same ones used in MC.
416   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
417   // both gas and MC will produce a section with no flags. Given
418   // section(".eh_frame") gcc will produce:
419   //
420   //   .section   .eh_frame,"a",@progbits
421 
422   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
423                                       /*AddSegmentInfo=*/false) ||
424       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
425                                       /*AddSegmentInfo=*/false))
426     return SectionKind::getMetadata();
427 
428   if (Name.empty() || Name[0] != '.') return K;
429 
430   // Default implementation based on some magic section names.
431   if (Name == ".bss" ||
432       Name.startswith(".bss.") ||
433       Name.startswith(".gnu.linkonce.b.") ||
434       Name.startswith(".llvm.linkonce.b.") ||
435       Name == ".sbss" ||
436       Name.startswith(".sbss.") ||
437       Name.startswith(".gnu.linkonce.sb.") ||
438       Name.startswith(".llvm.linkonce.sb."))
439     return SectionKind::getBSS();
440 
441   if (Name == ".tdata" ||
442       Name.startswith(".tdata.") ||
443       Name.startswith(".gnu.linkonce.td.") ||
444       Name.startswith(".llvm.linkonce.td."))
445     return SectionKind::getThreadData();
446 
447   if (Name == ".tbss" ||
448       Name.startswith(".tbss.") ||
449       Name.startswith(".gnu.linkonce.tb.") ||
450       Name.startswith(".llvm.linkonce.tb."))
451     return SectionKind::getThreadBSS();
452 
453   return K;
454 }
455 
456 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
457   // Use SHT_NOTE for section whose name starts with ".note" to allow
458   // emitting ELF notes from C variable declaration.
459   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
460   if (Name.startswith(".note"))
461     return ELF::SHT_NOTE;
462 
463   if (Name == ".init_array")
464     return ELF::SHT_INIT_ARRAY;
465 
466   if (Name == ".fini_array")
467     return ELF::SHT_FINI_ARRAY;
468 
469   if (Name == ".preinit_array")
470     return ELF::SHT_PREINIT_ARRAY;
471 
472   if (K.isBSS() || K.isThreadBSS())
473     return ELF::SHT_NOBITS;
474 
475   return ELF::SHT_PROGBITS;
476 }
477 
478 static unsigned getELFSectionFlags(SectionKind K) {
479   unsigned Flags = 0;
480 
481   if (!K.isMetadata())
482     Flags |= ELF::SHF_ALLOC;
483 
484   if (K.isText())
485     Flags |= ELF::SHF_EXECINSTR;
486 
487   if (K.isExecuteOnly())
488     Flags |= ELF::SHF_ARM_PURECODE;
489 
490   if (K.isWriteable())
491     Flags |= ELF::SHF_WRITE;
492 
493   if (K.isThreadLocal())
494     Flags |= ELF::SHF_TLS;
495 
496   if (K.isMergeableCString() || K.isMergeableConst())
497     Flags |= ELF::SHF_MERGE;
498 
499   if (K.isMergeableCString())
500     Flags |= ELF::SHF_STRINGS;
501 
502   return Flags;
503 }
504 
505 static const Comdat *getELFComdat(const GlobalValue *GV) {
506   const Comdat *C = GV->getComdat();
507   if (!C)
508     return nullptr;
509 
510   if (C->getSelectionKind() != Comdat::Any)
511     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
512                        C->getName() + "' cannot be lowered.");
513 
514   return C;
515 }
516 
517 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
518                                             const TargetMachine &TM) {
519   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
520   if (!MD)
521     return nullptr;
522 
523   const MDOperand &Op = MD->getOperand(0);
524   if (!Op.get())
525     return nullptr;
526 
527   auto *VM = dyn_cast<ValueAsMetadata>(Op);
528   if (!VM)
529     report_fatal_error("MD_associated operand is not ValueAsMetadata");
530 
531   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
532   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
533 }
534 
535 static unsigned getEntrySizeForKind(SectionKind Kind) {
536   if (Kind.isMergeable1ByteCString())
537     return 1;
538   else if (Kind.isMergeable2ByteCString())
539     return 2;
540   else if (Kind.isMergeable4ByteCString())
541     return 4;
542   else if (Kind.isMergeableConst4())
543     return 4;
544   else if (Kind.isMergeableConst8())
545     return 8;
546   else if (Kind.isMergeableConst16())
547     return 16;
548   else if (Kind.isMergeableConst32())
549     return 32;
550   else {
551     // We shouldn't have mergeable C strings or mergeable constants that we
552     // didn't handle above.
553     assert(!Kind.isMergeableCString() && "unknown string width");
554     assert(!Kind.isMergeableConst() && "unknown data width");
555     return 0;
556   }
557 }
558 
559 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
560     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
561   StringRef SectionName = GO->getSection();
562 
563   // Check if '#pragma clang section' name is applicable.
564   // Note that pragma directive overrides -ffunction-section, -fdata-section
565   // and so section name is exactly as user specified and not uniqued.
566   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
567   if (GV && GV->hasImplicitSection()) {
568     auto Attrs = GV->getAttributes();
569     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
570       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
571     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
572       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
573     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
574       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
575     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
576       SectionName = Attrs.getAttribute("data-section").getValueAsString();
577     }
578   }
579   const Function *F = dyn_cast<Function>(GO);
580   if (F && F->hasFnAttribute("implicit-section-name")) {
581     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
582   }
583 
584   // Infer section flags from the section name if we can.
585   Kind = getELFKindForNamedSection(SectionName, Kind);
586 
587   StringRef Group = "";
588   unsigned Flags = getELFSectionFlags(Kind);
589   if (const Comdat *C = getELFComdat(GO)) {
590     Group = C->getName();
591     Flags |= ELF::SHF_GROUP;
592   }
593 
594   // A section can have at most one associated section. Put each global with
595   // MD_associated in a unique section.
596   unsigned UniqueID = MCContext::GenericSectionID;
597   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
598   if (LinkedToSym) {
599     UniqueID = NextUniqueID++;
600     Flags |= ELF::SHF_LINK_ORDER;
601   }
602 
603   MCSectionELF *Section = getContext().getELFSection(
604       SectionName, getELFSectionType(SectionName, Kind), Flags,
605       getEntrySizeForKind(Kind), Group, UniqueID, LinkedToSym);
606   // Make sure that we did not get some other section with incompatible sh_link.
607   // This should not be possible due to UniqueID code above.
608   assert(Section->getLinkedToSymbol() == LinkedToSym &&
609          "Associated symbol mismatch between sections");
610   return Section;
611 }
612 
613 /// Return the section prefix name used by options FunctionsSections and
614 /// DataSections.
615 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
616   if (Kind.isText())
617     return ".text";
618   if (Kind.isReadOnly())
619     return ".rodata";
620   if (Kind.isBSS())
621     return ".bss";
622   if (Kind.isThreadData())
623     return ".tdata";
624   if (Kind.isThreadBSS())
625     return ".tbss";
626   if (Kind.isData())
627     return ".data";
628   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
629   return ".data.rel.ro";
630 }
631 
632 static MCSectionELF *selectELFSectionForGlobal(
633     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
634     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
635     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
636 
637   StringRef Group = "";
638   if (const Comdat *C = getELFComdat(GO)) {
639     Flags |= ELF::SHF_GROUP;
640     Group = C->getName();
641   }
642 
643   // Get the section entry size based on the kind.
644   unsigned EntrySize = getEntrySizeForKind(Kind);
645 
646   SmallString<128> Name;
647   if (Kind.isMergeableCString()) {
648     // We also need alignment here.
649     // FIXME: this is getting the alignment of the character, not the
650     // alignment of the global!
651     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
652         cast<GlobalVariable>(GO));
653 
654     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
655     Name = SizeSpec + utostr(Align);
656   } else if (Kind.isMergeableConst()) {
657     Name = ".rodata.cst";
658     Name += utostr(EntrySize);
659   } else {
660     Name = getSectionPrefixForGlobal(Kind);
661   }
662 
663   if (const auto *F = dyn_cast<Function>(GO)) {
664     const auto &OptionalPrefix = F->getSectionPrefix();
665     if (OptionalPrefix)
666       Name += *OptionalPrefix;
667   }
668 
669   unsigned UniqueID = MCContext::GenericSectionID;
670   if (EmitUniqueSection) {
671     if (TM.getUniqueSectionNames()) {
672       Name.push_back('.');
673       TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
674     } else {
675       UniqueID = *NextUniqueID;
676       (*NextUniqueID)++;
677     }
678   }
679   // Use 0 as the unique ID for execute-only text.
680   if (Kind.isExecuteOnly())
681     UniqueID = 0;
682   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
683                            EntrySize, Group, UniqueID, AssociatedSymbol);
684 }
685 
686 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
687     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
688   unsigned Flags = getELFSectionFlags(Kind);
689 
690   // If we have -ffunction-section or -fdata-section then we should emit the
691   // global value to a uniqued section specifically for it.
692   bool EmitUniqueSection = false;
693   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
694     if (Kind.isText())
695       EmitUniqueSection = TM.getFunctionSections();
696     else
697       EmitUniqueSection = TM.getDataSections();
698   }
699   EmitUniqueSection |= GO->hasComdat();
700 
701   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
702   if (LinkedToSym) {
703     EmitUniqueSection = true;
704     Flags |= ELF::SHF_LINK_ORDER;
705   }
706 
707   MCSectionELF *Section = selectELFSectionForGlobal(
708       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
709       &NextUniqueID, LinkedToSym);
710   assert(Section->getLinkedToSymbol() == LinkedToSym);
711   return Section;
712 }
713 
714 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
715     const Function &F, const TargetMachine &TM) const {
716   // If the function can be removed, produce a unique section so that
717   // the table doesn't prevent the removal.
718   const Comdat *C = F.getComdat();
719   bool EmitUniqueSection = TM.getFunctionSections() || C;
720   if (!EmitUniqueSection)
721     return ReadOnlySection;
722 
723   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
724                                    getMangler(), TM, EmitUniqueSection,
725                                    ELF::SHF_ALLOC, &NextUniqueID,
726                                    /* AssociatedSymbol */ nullptr);
727 }
728 
729 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
730     bool UsesLabelDifference, const Function &F) const {
731   // We can always create relative relocations, so use another section
732   // that can be marked non-executable.
733   return false;
734 }
735 
736 /// Given a mergeable constant with the specified size and relocation
737 /// information, return a section that it should be placed in.
738 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
739     const DataLayout &DL, SectionKind Kind, const Constant *C,
740     unsigned &Align) const {
741   if (Kind.isMergeableConst4() && MergeableConst4Section)
742     return MergeableConst4Section;
743   if (Kind.isMergeableConst8() && MergeableConst8Section)
744     return MergeableConst8Section;
745   if (Kind.isMergeableConst16() && MergeableConst16Section)
746     return MergeableConst16Section;
747   if (Kind.isMergeableConst32() && MergeableConst32Section)
748     return MergeableConst32Section;
749   if (Kind.isReadOnly())
750     return ReadOnlySection;
751 
752   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
753   return DataRelROSection;
754 }
755 
756 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
757                                               bool IsCtor, unsigned Priority,
758                                               const MCSymbol *KeySym) {
759   std::string Name;
760   unsigned Type;
761   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
762   StringRef COMDAT = KeySym ? KeySym->getName() : "";
763 
764   if (KeySym)
765     Flags |= ELF::SHF_GROUP;
766 
767   if (UseInitArray) {
768     if (IsCtor) {
769       Type = ELF::SHT_INIT_ARRAY;
770       Name = ".init_array";
771     } else {
772       Type = ELF::SHT_FINI_ARRAY;
773       Name = ".fini_array";
774     }
775     if (Priority != 65535) {
776       Name += '.';
777       Name += utostr(Priority);
778     }
779   } else {
780     // The default scheme is .ctor / .dtor, so we have to invert the priority
781     // numbering.
782     if (IsCtor)
783       Name = ".ctors";
784     else
785       Name = ".dtors";
786     if (Priority != 65535)
787       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
788     Type = ELF::SHT_PROGBITS;
789   }
790 
791   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
792 }
793 
794 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
795     unsigned Priority, const MCSymbol *KeySym) const {
796   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
797                                   KeySym);
798 }
799 
800 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
801     unsigned Priority, const MCSymbol *KeySym) const {
802   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
803                                   KeySym);
804 }
805 
806 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
807     const GlobalValue *LHS, const GlobalValue *RHS,
808     const TargetMachine &TM) const {
809   // We may only use a PLT-relative relocation to refer to unnamed_addr
810   // functions.
811   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
812     return nullptr;
813 
814   // Basic sanity checks.
815   if (LHS->getType()->getPointerAddressSpace() != 0 ||
816       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
817       RHS->isThreadLocal())
818     return nullptr;
819 
820   return MCBinaryExpr::createSub(
821       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
822                               getContext()),
823       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
824 }
825 
826 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
827   // Use ".GCC.command.line" since this feature is to support clang's
828   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
829   // same name.
830   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
831                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
832 }
833 
834 void
835 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
836   UseInitArray = UseInitArray_;
837   MCContext &Ctx = getContext();
838   if (!UseInitArray) {
839     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
840                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
841 
842     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
843                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
844     return;
845   }
846 
847   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
848                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
849   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
850                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
851 }
852 
853 //===----------------------------------------------------------------------===//
854 //                                 MachO
855 //===----------------------------------------------------------------------===//
856 
857 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
858   : TargetLoweringObjectFile() {
859   SupportIndirectSymViaGOTPCRel = true;
860 }
861 
862 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
863                                                const TargetMachine &TM) {
864   TargetLoweringObjectFile::Initialize(Ctx, TM);
865   if (TM.getRelocationModel() == Reloc::Static) {
866     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
867                                             SectionKind::getData());
868     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
869                                             SectionKind::getData());
870   } else {
871     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
872                                             MachO::S_MOD_INIT_FUNC_POINTERS,
873                                             SectionKind::getData());
874     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
875                                             MachO::S_MOD_TERM_FUNC_POINTERS,
876                                             SectionKind::getData());
877   }
878 
879   PersonalityEncoding =
880       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
881   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
882   TTypeEncoding =
883       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
884 }
885 
886 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
887                                                        Module &M) const {
888   // Emit the linker options if present.
889   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
890     for (const auto *Option : LinkerOptions->operands()) {
891       SmallVector<std::string, 4> StrOptions;
892       for (const auto &Piece : cast<MDNode>(Option)->operands())
893         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
894       Streamer.emitLinkerOptions(StrOptions);
895     }
896   }
897 
898   unsigned VersionVal = 0;
899   unsigned ImageInfoFlags = 0;
900   StringRef SectionVal;
901 
902   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
903 
904   // The section is mandatory. If we don't have it, then we don't have GC info.
905   if (SectionVal.empty())
906     return;
907 
908   StringRef Segment, Section;
909   unsigned TAA = 0, StubSize = 0;
910   bool TAAParsed;
911   std::string ErrorCode =
912     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
913                                           TAA, TAAParsed, StubSize);
914   if (!ErrorCode.empty())
915     // If invalid, report the error with report_fatal_error.
916     report_fatal_error("Invalid section specifier '" + Section + "': " +
917                        ErrorCode + ".");
918 
919   // Get the section.
920   MCSectionMachO *S = getContext().getMachOSection(
921       Segment, Section, TAA, StubSize, SectionKind::getData());
922   Streamer.SwitchSection(S);
923   Streamer.emitLabel(getContext().
924                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
925   Streamer.emitIntValue(VersionVal, 4);
926   Streamer.emitIntValue(ImageInfoFlags, 4);
927   Streamer.AddBlankLine();
928 }
929 
930 static void checkMachOComdat(const GlobalValue *GV) {
931   const Comdat *C = GV->getComdat();
932   if (!C)
933     return;
934 
935   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
936                      "' cannot be lowered.");
937 }
938 
939 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
940     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
941   // Parse the section specifier and create it if valid.
942   StringRef Segment, Section;
943   unsigned TAA = 0, StubSize = 0;
944   bool TAAParsed;
945 
946   checkMachOComdat(GO);
947 
948   std::string ErrorCode =
949     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
950                                           TAA, TAAParsed, StubSize);
951   if (!ErrorCode.empty()) {
952     // If invalid, report the error with report_fatal_error.
953     report_fatal_error("Global variable '" + GO->getName() +
954                        "' has an invalid section specifier '" +
955                        GO->getSection() + "': " + ErrorCode + ".");
956   }
957 
958   // Get the section.
959   MCSectionMachO *S =
960       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
961 
962   // If TAA wasn't set by ParseSectionSpecifier() above,
963   // use the value returned by getMachOSection() as a default.
964   if (!TAAParsed)
965     TAA = S->getTypeAndAttributes();
966 
967   // Okay, now that we got the section, verify that the TAA & StubSize agree.
968   // If the user declared multiple globals with different section flags, we need
969   // to reject it here.
970   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
971     // If invalid, report the error with report_fatal_error.
972     report_fatal_error("Global variable '" + GO->getName() +
973                        "' section type or attributes does not match previous"
974                        " section specifier");
975   }
976 
977   return S;
978 }
979 
980 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
981     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
982   checkMachOComdat(GO);
983 
984   // Handle thread local data.
985   if (Kind.isThreadBSS()) return TLSBSSSection;
986   if (Kind.isThreadData()) return TLSDataSection;
987 
988   if (Kind.isText())
989     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
990 
991   // If this is weak/linkonce, put this in a coalescable section, either in text
992   // or data depending on if it is writable.
993   if (GO->isWeakForLinker()) {
994     if (Kind.isReadOnly())
995       return ConstTextCoalSection;
996     if (Kind.isReadOnlyWithRel())
997       return ConstDataCoalSection;
998     return DataCoalSection;
999   }
1000 
1001   // FIXME: Alignment check should be handled by section classifier.
1002   if (Kind.isMergeable1ByteCString() &&
1003       GO->getParent()->getDataLayout().getPreferredAlignment(
1004           cast<GlobalVariable>(GO)) < 32)
1005     return CStringSection;
1006 
1007   // Do not put 16-bit arrays in the UString section if they have an
1008   // externally visible label, this runs into issues with certain linker
1009   // versions.
1010   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1011       GO->getParent()->getDataLayout().getPreferredAlignment(
1012           cast<GlobalVariable>(GO)) < 32)
1013     return UStringSection;
1014 
1015   // With MachO only variables whose corresponding symbol starts with 'l' or
1016   // 'L' can be merged, so we only try merging GVs with private linkage.
1017   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1018     if (Kind.isMergeableConst4())
1019       return FourByteConstantSection;
1020     if (Kind.isMergeableConst8())
1021       return EightByteConstantSection;
1022     if (Kind.isMergeableConst16())
1023       return SixteenByteConstantSection;
1024   }
1025 
1026   // Otherwise, if it is readonly, but not something we can specially optimize,
1027   // just drop it in .const.
1028   if (Kind.isReadOnly())
1029     return ReadOnlySection;
1030 
1031   // If this is marked const, put it into a const section.  But if the dynamic
1032   // linker needs to write to it, put it in the data segment.
1033   if (Kind.isReadOnlyWithRel())
1034     return ConstDataSection;
1035 
1036   // Put zero initialized globals with strong external linkage in the
1037   // DATA, __common section with the .zerofill directive.
1038   if (Kind.isBSSExtern())
1039     return DataCommonSection;
1040 
1041   // Put zero initialized globals with local linkage in __DATA,__bss directive
1042   // with the .zerofill directive (aka .lcomm).
1043   if (Kind.isBSSLocal())
1044     return DataBSSSection;
1045 
1046   // Otherwise, just drop the variable in the normal data section.
1047   return DataSection;
1048 }
1049 
1050 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1051     const DataLayout &DL, SectionKind Kind, const Constant *C,
1052     unsigned &Align) const {
1053   // If this constant requires a relocation, we have to put it in the data
1054   // segment, not in the text segment.
1055   if (Kind.isData() || Kind.isReadOnlyWithRel())
1056     return ConstDataSection;
1057 
1058   if (Kind.isMergeableConst4())
1059     return FourByteConstantSection;
1060   if (Kind.isMergeableConst8())
1061     return EightByteConstantSection;
1062   if (Kind.isMergeableConst16())
1063     return SixteenByteConstantSection;
1064   return ReadOnlySection;  // .const
1065 }
1066 
1067 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1068     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1069     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1070   // The mach-o version of this method defaults to returning a stub reference.
1071 
1072   if (Encoding & DW_EH_PE_indirect) {
1073     MachineModuleInfoMachO &MachOMMI =
1074       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1075 
1076     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1077 
1078     // Add information about the stub reference to MachOMMI so that the stub
1079     // gets emitted by the asmprinter.
1080     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1081     if (!StubSym.getPointer()) {
1082       MCSymbol *Sym = TM.getSymbol(GV);
1083       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1084     }
1085 
1086     return TargetLoweringObjectFile::
1087       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1088                         Encoding & ~DW_EH_PE_indirect, Streamer);
1089   }
1090 
1091   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1092                                                            MMI, Streamer);
1093 }
1094 
1095 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1096     const GlobalValue *GV, const TargetMachine &TM,
1097     MachineModuleInfo *MMI) const {
1098   // The mach-o version of this method defaults to returning a stub reference.
1099   MachineModuleInfoMachO &MachOMMI =
1100     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1101 
1102   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1103 
1104   // Add information about the stub reference to MachOMMI so that the stub
1105   // gets emitted by the asmprinter.
1106   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1107   if (!StubSym.getPointer()) {
1108     MCSymbol *Sym = TM.getSymbol(GV);
1109     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1110   }
1111 
1112   return SSym;
1113 }
1114 
1115 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1116     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1117     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1118   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1119   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1120   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1121   // computation of deltas to final external symbols. Example:
1122   //
1123   //    _extgotequiv:
1124   //       .long   _extfoo
1125   //
1126   //    _delta:
1127   //       .long   _extgotequiv-_delta
1128   //
1129   // is transformed to:
1130   //
1131   //    _delta:
1132   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1133   //
1134   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1135   //    L_extfoo$non_lazy_ptr:
1136   //       .indirect_symbol        _extfoo
1137   //       .long   0
1138   //
1139   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1140   // may point to both local (same translation unit) and global (other
1141   // translation units) symbols. Example:
1142   //
1143   // .section __DATA,__pointers,non_lazy_symbol_pointers
1144   // L1:
1145   //    .indirect_symbol _myGlobal
1146   //    .long 0
1147   // L2:
1148   //    .indirect_symbol _myLocal
1149   //    .long _myLocal
1150   //
1151   // If the symbol is local, instead of the symbol's index, the assembler
1152   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1153   // Then the linker will notice the constant in the table and will look at the
1154   // content of the symbol.
1155   MachineModuleInfoMachO &MachOMMI =
1156     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1157   MCContext &Ctx = getContext();
1158 
1159   // The offset must consider the original displacement from the base symbol
1160   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1161   Offset = -MV.getConstant();
1162   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1163 
1164   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1165   // non_lazy_ptr stubs.
1166   SmallString<128> Name;
1167   StringRef Suffix = "$non_lazy_ptr";
1168   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1169   Name += Sym->getName();
1170   Name += Suffix;
1171   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1172 
1173   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1174 
1175   if (!StubSym.getPointer())
1176     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1177                                                  !GV->hasLocalLinkage());
1178 
1179   const MCExpr *BSymExpr =
1180     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1181   const MCExpr *LHS =
1182     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1183 
1184   if (!Offset)
1185     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1186 
1187   const MCExpr *RHS =
1188     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1189   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1190 }
1191 
1192 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1193                                const MCSection &Section) {
1194   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1195     return true;
1196 
1197   // If it is not dead stripped, it is safe to use private labels.
1198   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1199   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1200     return true;
1201 
1202   return false;
1203 }
1204 
1205 void TargetLoweringObjectFileMachO::getNameWithPrefix(
1206     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1207     const TargetMachine &TM) const {
1208   bool CannotUsePrivateLabel = true;
1209   if (auto *GO = GV->getBaseObject()) {
1210     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1211     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1212     CannotUsePrivateLabel =
1213         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1214   }
1215   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1216 }
1217 
1218 //===----------------------------------------------------------------------===//
1219 //                                  COFF
1220 //===----------------------------------------------------------------------===//
1221 
1222 static unsigned
1223 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1224   unsigned Flags = 0;
1225   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1226 
1227   if (K.isMetadata())
1228     Flags |=
1229       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1230   else if (K.isText())
1231     Flags |=
1232       COFF::IMAGE_SCN_MEM_EXECUTE |
1233       COFF::IMAGE_SCN_MEM_READ |
1234       COFF::IMAGE_SCN_CNT_CODE |
1235       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1236   else if (K.isBSS())
1237     Flags |=
1238       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1239       COFF::IMAGE_SCN_MEM_READ |
1240       COFF::IMAGE_SCN_MEM_WRITE;
1241   else if (K.isThreadLocal())
1242     Flags |=
1243       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1244       COFF::IMAGE_SCN_MEM_READ |
1245       COFF::IMAGE_SCN_MEM_WRITE;
1246   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1247     Flags |=
1248       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1249       COFF::IMAGE_SCN_MEM_READ;
1250   else if (K.isWriteable())
1251     Flags |=
1252       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1253       COFF::IMAGE_SCN_MEM_READ |
1254       COFF::IMAGE_SCN_MEM_WRITE;
1255 
1256   return Flags;
1257 }
1258 
1259 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1260   const Comdat *C = GV->getComdat();
1261   assert(C && "expected GV to have a Comdat!");
1262 
1263   StringRef ComdatGVName = C->getName();
1264   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1265   if (!ComdatGV)
1266     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1267                        "' does not exist.");
1268 
1269   if (ComdatGV->getComdat() != C)
1270     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1271                        "' is not a key for its COMDAT.");
1272 
1273   return ComdatGV;
1274 }
1275 
1276 static int getSelectionForCOFF(const GlobalValue *GV) {
1277   if (const Comdat *C = GV->getComdat()) {
1278     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1279     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1280       ComdatKey = GA->getBaseObject();
1281     if (ComdatKey == GV) {
1282       switch (C->getSelectionKind()) {
1283       case Comdat::Any:
1284         return COFF::IMAGE_COMDAT_SELECT_ANY;
1285       case Comdat::ExactMatch:
1286         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1287       case Comdat::Largest:
1288         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1289       case Comdat::NoDuplicates:
1290         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1291       case Comdat::SameSize:
1292         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1293       }
1294     } else {
1295       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1296     }
1297   }
1298   return 0;
1299 }
1300 
1301 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1302     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1303   int Selection = 0;
1304   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1305   StringRef Name = GO->getSection();
1306   StringRef COMDATSymName = "";
1307   if (GO->hasComdat()) {
1308     Selection = getSelectionForCOFF(GO);
1309     const GlobalValue *ComdatGV;
1310     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1311       ComdatGV = getComdatGVForCOFF(GO);
1312     else
1313       ComdatGV = GO;
1314 
1315     if (!ComdatGV->hasPrivateLinkage()) {
1316       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1317       COMDATSymName = Sym->getName();
1318       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1319     } else {
1320       Selection = 0;
1321     }
1322   }
1323 
1324   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1325                                      Selection);
1326 }
1327 
1328 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1329   if (Kind.isText())
1330     return ".text";
1331   if (Kind.isBSS())
1332     return ".bss";
1333   if (Kind.isThreadLocal())
1334     return ".tls$";
1335   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1336     return ".rdata";
1337   return ".data";
1338 }
1339 
1340 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1341     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1342   // If we have -ffunction-sections then we should emit the global value to a
1343   // uniqued section specifically for it.
1344   bool EmitUniquedSection;
1345   if (Kind.isText())
1346     EmitUniquedSection = TM.getFunctionSections();
1347   else
1348     EmitUniquedSection = TM.getDataSections();
1349 
1350   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1351     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1352 
1353     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1354 
1355     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1356     int Selection = getSelectionForCOFF(GO);
1357     if (!Selection)
1358       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1359     const GlobalValue *ComdatGV;
1360     if (GO->hasComdat())
1361       ComdatGV = getComdatGVForCOFF(GO);
1362     else
1363       ComdatGV = GO;
1364 
1365     unsigned UniqueID = MCContext::GenericSectionID;
1366     if (EmitUniquedSection)
1367       UniqueID = NextUniqueID++;
1368 
1369     if (!ComdatGV->hasPrivateLinkage()) {
1370       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1371       StringRef COMDATSymName = Sym->getName();
1372 
1373       // Append "$symbol" to the section name *before* IR-level mangling is
1374       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1375       // COFF linker will not properly handle comdats otherwise.
1376       if (getTargetTriple().isWindowsGNUEnvironment())
1377         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1378 
1379       return getContext().getCOFFSection(Name, Characteristics, Kind,
1380                                          COMDATSymName, Selection, UniqueID);
1381     } else {
1382       SmallString<256> TmpData;
1383       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1384       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1385                                          Selection, UniqueID);
1386     }
1387   }
1388 
1389   if (Kind.isText())
1390     return TextSection;
1391 
1392   if (Kind.isThreadLocal())
1393     return TLSDataSection;
1394 
1395   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1396     return ReadOnlySection;
1397 
1398   // Note: we claim that common symbols are put in BSSSection, but they are
1399   // really emitted with the magic .comm directive, which creates a symbol table
1400   // entry but not a section.
1401   if (Kind.isBSS() || Kind.isCommon())
1402     return BSSSection;
1403 
1404   return DataSection;
1405 }
1406 
1407 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1408     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1409     const TargetMachine &TM) const {
1410   bool CannotUsePrivateLabel = false;
1411   if (GV->hasPrivateLinkage() &&
1412       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1413        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1414     CannotUsePrivateLabel = true;
1415 
1416   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1417 }
1418 
1419 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1420     const Function &F, const TargetMachine &TM) const {
1421   // If the function can be removed, produce a unique section so that
1422   // the table doesn't prevent the removal.
1423   const Comdat *C = F.getComdat();
1424   bool EmitUniqueSection = TM.getFunctionSections() || C;
1425   if (!EmitUniqueSection)
1426     return ReadOnlySection;
1427 
1428   // FIXME: we should produce a symbol for F instead.
1429   if (F.hasPrivateLinkage())
1430     return ReadOnlySection;
1431 
1432   MCSymbol *Sym = TM.getSymbol(&F);
1433   StringRef COMDATSymName = Sym->getName();
1434 
1435   SectionKind Kind = SectionKind::getReadOnly();
1436   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1437   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1438   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1439   unsigned UniqueID = NextUniqueID++;
1440 
1441   return getContext().getCOFFSection(
1442       SecName, Characteristics, Kind, COMDATSymName,
1443       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1444 }
1445 
1446 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1447                                                       Module &M) const {
1448   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1449     // Emit the linker options to the linker .drectve section.  According to the
1450     // spec, this section is a space-separated string containing flags for
1451     // linker.
1452     MCSection *Sec = getDrectveSection();
1453     Streamer.SwitchSection(Sec);
1454     for (const auto *Option : LinkerOptions->operands()) {
1455       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1456         // Lead with a space for consistency with our dllexport implementation.
1457         std::string Directive(" ");
1458         Directive.append(std::string(cast<MDString>(Piece)->getString()));
1459         Streamer.emitBytes(Directive);
1460       }
1461     }
1462   }
1463 
1464   unsigned Version = 0;
1465   unsigned Flags = 0;
1466   StringRef Section;
1467 
1468   GetObjCImageInfo(M, Version, Flags, Section);
1469   if (Section.empty())
1470     return;
1471 
1472   auto &C = getContext();
1473   auto *S = C.getCOFFSection(
1474       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1475       SectionKind::getReadOnly());
1476   Streamer.SwitchSection(S);
1477   Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1478   Streamer.emitIntValue(Version, 4);
1479   Streamer.emitIntValue(Flags, 4);
1480   Streamer.AddBlankLine();
1481 }
1482 
1483 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1484                                               const TargetMachine &TM) {
1485   TargetLoweringObjectFile::Initialize(Ctx, TM);
1486   const Triple &T = TM.getTargetTriple();
1487   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1488     StaticCtorSection =
1489         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1490                                            COFF::IMAGE_SCN_MEM_READ,
1491                            SectionKind::getReadOnly());
1492     StaticDtorSection =
1493         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1494                                            COFF::IMAGE_SCN_MEM_READ,
1495                            SectionKind::getReadOnly());
1496   } else {
1497     StaticCtorSection = Ctx.getCOFFSection(
1498         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1499                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1500         SectionKind::getData());
1501     StaticDtorSection = Ctx.getCOFFSection(
1502         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1503                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1504         SectionKind::getData());
1505   }
1506 }
1507 
1508 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1509                                                    const Triple &T, bool IsCtor,
1510                                                    unsigned Priority,
1511                                                    const MCSymbol *KeySym,
1512                                                    MCSectionCOFF *Default) {
1513   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1514     // If the priority is the default, use .CRT$XCU, possibly associative.
1515     if (Priority == 65535)
1516       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1517 
1518     // Otherwise, we need to compute a new section name. Low priorities should
1519     // run earlier. The linker will sort sections ASCII-betically, and we need a
1520     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1521     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1522     // low priorities need to sort before 'L', since the CRT uses that
1523     // internally, so we use ".CRT$XCA00001" for them.
1524     SmallString<24> Name;
1525     raw_svector_ostream OS(Name);
1526     OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
1527         (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1528     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1529         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1530         SectionKind::getReadOnly());
1531     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1532   }
1533 
1534   std::string Name = IsCtor ? ".ctors" : ".dtors";
1535   if (Priority != 65535)
1536     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1537 
1538   return Ctx.getAssociativeCOFFSection(
1539       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1540                                    COFF::IMAGE_SCN_MEM_READ |
1541                                    COFF::IMAGE_SCN_MEM_WRITE,
1542                          SectionKind::getData()),
1543       KeySym, 0);
1544 }
1545 
1546 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1547     unsigned Priority, const MCSymbol *KeySym) const {
1548   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1549                                       Priority, KeySym,
1550                                       cast<MCSectionCOFF>(StaticCtorSection));
1551 }
1552 
1553 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1554     unsigned Priority, const MCSymbol *KeySym) const {
1555   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1556                                       Priority, KeySym,
1557                                       cast<MCSectionCOFF>(StaticDtorSection));
1558 }
1559 
1560 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1561     raw_ostream &OS, const GlobalValue *GV) const {
1562   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1563 }
1564 
1565 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1566     raw_ostream &OS, const GlobalValue *GV) const {
1567   emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1568 }
1569 
1570 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1571     const GlobalValue *LHS, const GlobalValue *RHS,
1572     const TargetMachine &TM) const {
1573   const Triple &T = TM.getTargetTriple();
1574   if (T.isOSCygMing())
1575     return nullptr;
1576 
1577   // Our symbols should exist in address space zero, cowardly no-op if
1578   // otherwise.
1579   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1580       RHS->getType()->getPointerAddressSpace() != 0)
1581     return nullptr;
1582 
1583   // Both ptrtoint instructions must wrap global objects:
1584   // - Only global variables are eligible for image relative relocations.
1585   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1586   // We expect __ImageBase to be a global variable without a section, externally
1587   // defined.
1588   //
1589   // It should look something like this: @__ImageBase = external constant i8
1590   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1591       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1592       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1593       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1594     return nullptr;
1595 
1596   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1597                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
1598                                  getContext());
1599 }
1600 
1601 static std::string APIntToHexString(const APInt &AI) {
1602   unsigned Width = (AI.getBitWidth() / 8) * 2;
1603   std::string HexString = AI.toString(16, /*Signed=*/false);
1604   transform(HexString.begin(), HexString.end(), HexString.begin(), tolower);
1605   unsigned Size = HexString.size();
1606   assert(Width >= Size && "hex string is too large!");
1607   HexString.insert(HexString.begin(), Width - Size, '0');
1608 
1609   return HexString;
1610 }
1611 
1612 static std::string scalarConstantToHexString(const Constant *C) {
1613   Type *Ty = C->getType();
1614   if (isa<UndefValue>(C)) {
1615     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1616   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1617     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1618   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1619     return APIntToHexString(CI->getValue());
1620   } else {
1621     unsigned NumElements;
1622     if (isa<VectorType>(Ty))
1623       NumElements = Ty->getVectorNumElements();
1624     else
1625       NumElements = Ty->getArrayNumElements();
1626     std::string HexString;
1627     for (int I = NumElements - 1, E = -1; I != E; --I)
1628       HexString += scalarConstantToHexString(C->getAggregateElement(I));
1629     return HexString;
1630   }
1631 }
1632 
1633 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1634     const DataLayout &DL, SectionKind Kind, const Constant *C,
1635     unsigned &Align) const {
1636   if (Kind.isMergeableConst() && C &&
1637       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1638     // This creates comdat sections with the given symbol name, but unless
1639     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1640     // will be created with a null storage class, which makes GNU binutils
1641     // error out.
1642     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1643                                      COFF::IMAGE_SCN_MEM_READ |
1644                                      COFF::IMAGE_SCN_LNK_COMDAT;
1645     std::string COMDATSymName;
1646     if (Kind.isMergeableConst4()) {
1647       if (Align <= 4) {
1648         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1649         Align = 4;
1650       }
1651     } else if (Kind.isMergeableConst8()) {
1652       if (Align <= 8) {
1653         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1654         Align = 8;
1655       }
1656     } else if (Kind.isMergeableConst16()) {
1657       // FIXME: These may not be appropriate for non-x86 architectures.
1658       if (Align <= 16) {
1659         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1660         Align = 16;
1661       }
1662     } else if (Kind.isMergeableConst32()) {
1663       if (Align <= 32) {
1664         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1665         Align = 32;
1666       }
1667     }
1668 
1669     if (!COMDATSymName.empty())
1670       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1671                                          COMDATSymName,
1672                                          COFF::IMAGE_COMDAT_SELECT_ANY);
1673   }
1674 
1675   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1676 }
1677 
1678 
1679 //===----------------------------------------------------------------------===//
1680 //                                  Wasm
1681 //===----------------------------------------------------------------------===//
1682 
1683 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1684   const Comdat *C = GV->getComdat();
1685   if (!C)
1686     return nullptr;
1687 
1688   if (C->getSelectionKind() != Comdat::Any)
1689     report_fatal_error("WebAssembly COMDATs only support "
1690                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
1691                        "lowered.");
1692 
1693   return C;
1694 }
1695 
1696 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1697     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1698   // We don't support explict section names for functions in the wasm object
1699   // format.  Each function has to be in its own unique section.
1700   if (isa<Function>(GO)) {
1701     return SelectSectionForGlobal(GO, Kind, TM);
1702   }
1703 
1704   StringRef Name = GO->getSection();
1705 
1706   StringRef Group = "";
1707   if (const Comdat *C = getWasmComdat(GO)) {
1708     Group = C->getName();
1709   }
1710 
1711   MCSectionWasm* Section =
1712       getContext().getWasmSection(Name, Kind, Group,
1713                                   MCContext::GenericSectionID);
1714 
1715   return Section;
1716 }
1717 
1718 static MCSectionWasm *selectWasmSectionForGlobal(
1719     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1720     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1721   StringRef Group = "";
1722   if (const Comdat *C = getWasmComdat(GO)) {
1723     Group = C->getName();
1724   }
1725 
1726   bool UniqueSectionNames = TM.getUniqueSectionNames();
1727   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1728 
1729   if (const auto *F = dyn_cast<Function>(GO)) {
1730     const auto &OptionalPrefix = F->getSectionPrefix();
1731     if (OptionalPrefix)
1732       Name += *OptionalPrefix;
1733   }
1734 
1735   if (EmitUniqueSection && UniqueSectionNames) {
1736     Name.push_back('.');
1737     TM.getNameWithPrefix(Name, GO, Mang, true);
1738   }
1739   unsigned UniqueID = MCContext::GenericSectionID;
1740   if (EmitUniqueSection && !UniqueSectionNames) {
1741     UniqueID = *NextUniqueID;
1742     (*NextUniqueID)++;
1743   }
1744 
1745   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1746 }
1747 
1748 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1749     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1750 
1751   if (Kind.isCommon())
1752     report_fatal_error("mergable sections not supported yet on wasm");
1753 
1754   // If we have -ffunction-section or -fdata-section then we should emit the
1755   // global value to a uniqued section specifically for it.
1756   bool EmitUniqueSection = false;
1757   if (Kind.isText())
1758     EmitUniqueSection = TM.getFunctionSections();
1759   else
1760     EmitUniqueSection = TM.getDataSections();
1761   EmitUniqueSection |= GO->hasComdat();
1762 
1763   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1764                                     EmitUniqueSection, &NextUniqueID);
1765 }
1766 
1767 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1768     bool UsesLabelDifference, const Function &F) const {
1769   // We can always create relative relocations, so use another section
1770   // that can be marked non-executable.
1771   return false;
1772 }
1773 
1774 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1775     const GlobalValue *LHS, const GlobalValue *RHS,
1776     const TargetMachine &TM) const {
1777   // We may only use a PLT-relative relocation to refer to unnamed_addr
1778   // functions.
1779   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1780     return nullptr;
1781 
1782   // Basic sanity checks.
1783   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1784       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1785       RHS->isThreadLocal())
1786     return nullptr;
1787 
1788   return MCBinaryExpr::createSub(
1789       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1790                               getContext()),
1791       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1792 }
1793 
1794 void TargetLoweringObjectFileWasm::InitializeWasm() {
1795   StaticCtorSection =
1796       getContext().getWasmSection(".init_array", SectionKind::getData());
1797 
1798   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
1799   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
1800   TTypeEncoding = dwarf::DW_EH_PE_absptr;
1801 }
1802 
1803 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1804     unsigned Priority, const MCSymbol *KeySym) const {
1805   return Priority == UINT16_MAX ?
1806          StaticCtorSection :
1807          getContext().getWasmSection(".init_array." + utostr(Priority),
1808                                      SectionKind::getData());
1809 }
1810 
1811 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1812     unsigned Priority, const MCSymbol *KeySym) const {
1813   llvm_unreachable("@llvm.global_dtors should have been lowered already");
1814   return nullptr;
1815 }
1816 
1817 //===----------------------------------------------------------------------===//
1818 //                                  XCOFF
1819 //===----------------------------------------------------------------------===//
1820 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
1821     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1822   report_fatal_error("XCOFF explicit sections not yet implemented.");
1823 }
1824 
1825 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
1826     const GlobalObject *GO, const TargetMachine &TM) const {
1827   assert(GO->isDeclaration() &&
1828          "Tried to get ER section for a defined global.");
1829 
1830   SmallString<128> Name;
1831   getNameWithPrefix(Name, GO, TM);
1832   XCOFF::StorageClass SC =
1833       TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
1834 
1835   // Externals go into a csect of type ER.
1836   return getContext().getXCOFFSection(
1837       Name, isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA, XCOFF::XTY_ER,
1838       SC, SectionKind::getMetadata());
1839 }
1840 
1841 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
1842     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1843   assert(!TM.getFunctionSections() && !TM.getDataSections() &&
1844          "XCOFF unique sections not yet implemented.");
1845 
1846   // Common symbols go into a csect with matching name which will get mapped
1847   // into the .bss section.
1848   if (Kind.isBSSLocal() || Kind.isCommon()) {
1849     SmallString<128> Name;
1850     getNameWithPrefix(Name, GO, TM);
1851     XCOFF::StorageClass SC =
1852         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
1853     return getContext().getXCOFFSection(
1854         Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM,
1855         SC, Kind, /* BeginSymbolName */ nullptr);
1856   }
1857 
1858   if (Kind.isMergeableCString()) {
1859     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
1860         cast<GlobalVariable>(GO));
1861 
1862     unsigned EntrySize = getEntrySizeForKind(Kind);
1863     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
1864     SmallString<128> Name;
1865     Name = SizeSpec + utostr(Align);
1866 
1867     return getContext().getXCOFFSection(
1868         Name, XCOFF::XMC_RO, XCOFF::XTY_SD,
1869         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO),
1870         Kind, /* BeginSymbolName */ nullptr);
1871   }
1872 
1873   if (Kind.isText())
1874     return TextSection;
1875 
1876   if (Kind.isData() || Kind.isReadOnlyWithRel())
1877     // TODO: We may put this under option control, because user may want to
1878     // have read-only data with relocations placed into a read-only section by
1879     // the compiler.
1880     return DataSection;
1881 
1882   // Zero initialized data must be emitted to the .data section because external
1883   // linkage control sections that get mapped to the .bss section will be linked
1884   // as tentative defintions, which is only appropriate for SectionKind::Common.
1885   if (Kind.isBSS())
1886     return DataSection;
1887 
1888   if (Kind.isReadOnly())
1889     return ReadOnlySection;
1890 
1891   report_fatal_error("XCOFF other section types not yet implemented.");
1892 }
1893 
1894 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
1895     const Function &F, const TargetMachine &TM) const {
1896   assert (!TM.getFunctionSections() && "Unique sections not supported on XCOFF"
1897           " yet.");
1898   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
1899   //TODO: Enable emiting jump table to unique sections when we support it.
1900   return ReadOnlySection;
1901 }
1902 
1903 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
1904     bool UsesLabelDifference, const Function &F) const {
1905   return false;
1906 }
1907 
1908 /// Given a mergeable constant with the specified size and relocation
1909 /// information, return a section that it should be placed in.
1910 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
1911     const DataLayout &DL, SectionKind Kind, const Constant *C,
1912     unsigned &Align) const {
1913   //TODO: Enable emiting constant pool to unique sections when we support it.
1914   return ReadOnlySection;
1915 }
1916 
1917 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
1918                                                const TargetMachine &TgtM) {
1919   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
1920   TTypeEncoding = 0;
1921   PersonalityEncoding = 0;
1922   LSDAEncoding = 0;
1923 }
1924 
1925 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
1926     unsigned Priority, const MCSymbol *KeySym) const {
1927   report_fatal_error("XCOFF ctor section not yet implemented.");
1928 }
1929 
1930 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
1931     unsigned Priority, const MCSymbol *KeySym) const {
1932   report_fatal_error("XCOFF dtor section not yet implemented.");
1933 }
1934 
1935 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
1936     const GlobalValue *LHS, const GlobalValue *RHS,
1937     const TargetMachine &TM) const {
1938   report_fatal_error("XCOFF not yet implemented.");
1939 }
1940 
1941 XCOFF::StorageClass TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(
1942     const GlobalObject *GO) {
1943   switch (GO->getLinkage()) {
1944   case GlobalValue::InternalLinkage:
1945   case GlobalValue::PrivateLinkage:
1946     return XCOFF::C_HIDEXT;
1947   case GlobalValue::ExternalLinkage:
1948   case GlobalValue::CommonLinkage:
1949     return XCOFF::C_EXT;
1950   case GlobalValue::ExternalWeakLinkage:
1951     return XCOFF::C_WEAKEXT;
1952   default:
1953     report_fatal_error(
1954         "Unhandled linkage when mapping linkage to StorageClass.");
1955   }
1956 }
1957 
1958 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
1959     const MCSymbol *FuncSym) const {
1960   return getContext().getXCOFFSection(FuncSym->getName(), XCOFF::XMC_DS,
1961                                       XCOFF::XTY_SD, XCOFF::C_HIDEXT,
1962                                       SectionKind::getData());
1963 }
1964 
1965 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
1966     const MCSymbol *Sym) const {
1967   return getContext().getXCOFFSection(
1968       cast<MCSymbolXCOFF>(Sym)->getUnqualifiedName(), XCOFF::XMC_TC,
1969       XCOFF::XTY_SD, XCOFF::C_HIDEXT, SectionKind::getData());
1970 }
1971