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