xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 1f5eb86b51fdc236bd37161b8074da6a93fdea96)
1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/Dwarf.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/BinaryFormat/MachO.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
27 #include "llvm/IR/Comdat.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/MCExpr.h"
43 #include "llvm/MC/MCSectionCOFF.h"
44 #include "llvm/MC/MCSectionELF.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/MC/MCSectionWasm.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::emitModuleMetadata(MCStreamer &Streamer,
95                                                      Module &M) const {
96   auto &C = getContext();
97 
98   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
99     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
100                               ELF::SHF_EXCLUDE);
101 
102     Streamer.SwitchSection(S);
103 
104     for (const auto &Operand : LinkerOptions->operands()) {
105       if (cast<MDNode>(Operand)->getNumOperands() != 2)
106         report_fatal_error("invalid llvm.linker.options");
107       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
108         Streamer.EmitBytes(cast<MDString>(Option)->getString());
109         Streamer.EmitIntValue(0, 1);
110       }
111     }
112   }
113 
114   unsigned Version = 0;
115   unsigned Flags = 0;
116   StringRef Section;
117 
118   GetObjCImageInfo(M, Version, Flags, Section);
119   if (Section.empty())
120     return;
121 
122   auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
123   Streamer.SwitchSection(S);
124   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
125   Streamer.EmitIntValue(Version, 4);
126   Streamer.EmitIntValue(Flags, 4);
127   Streamer.AddBlankLine();
128 }
129 
130 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
131     const GlobalValue *GV, const TargetMachine &TM,
132     MachineModuleInfo *MMI) const {
133   unsigned Encoding = getPersonalityEncoding();
134   if ((Encoding & 0x80) == DW_EH_PE_indirect)
135     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
136                                           TM.getSymbol(GV)->getName());
137   if ((Encoding & 0x70) == DW_EH_PE_absptr)
138     return TM.getSymbol(GV);
139   report_fatal_error("We do not support this DWARF encoding yet!");
140 }
141 
142 void TargetLoweringObjectFileELF::emitPersonalityValue(
143     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
144   SmallString<64> NameData("DW.ref.");
145   NameData += Sym->getName();
146   MCSymbolELF *Label =
147       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
148   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
149   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
150   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
151   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
152                                                    ELF::SHT_PROGBITS, Flags, 0);
153   unsigned Size = DL.getPointerSize();
154   Streamer.SwitchSection(Sec);
155   Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
156   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
157   const MCExpr *E = MCConstantExpr::create(Size, getContext());
158   Streamer.emitELFSize(Label, E);
159   Streamer.EmitLabel(Label);
160 
161   Streamer.EmitSymbolValue(Sym, Size);
162 }
163 
164 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
165     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
166     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
167   if (Encoding & DW_EH_PE_indirect) {
168     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
169 
170     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
171 
172     // Add information about the stub reference to ELFMMI so that the stub
173     // gets emitted by the asmprinter.
174     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
175     if (!StubSym.getPointer()) {
176       MCSymbol *Sym = TM.getSymbol(GV);
177       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
178     }
179 
180     return TargetLoweringObjectFile::
181       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
182                         Encoding & ~DW_EH_PE_indirect, Streamer);
183   }
184 
185   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
186                                                            MMI, Streamer);
187 }
188 
189 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
190   // N.B.: The defaults used in here are not the same ones used in MC.
191   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
192   // both gas and MC will produce a section with no flags. Given
193   // section(".eh_frame") gcc will produce:
194   //
195   //   .section   .eh_frame,"a",@progbits
196 
197   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
198                                       /*AddSegmentInfo=*/false))
199     return SectionKind::getMetadata();
200 
201   if (Name.empty() || Name[0] != '.') return K;
202 
203   // Some lame default implementation based on some magic section names.
204   if (Name == ".bss" ||
205       Name.startswith(".bss.") ||
206       Name.startswith(".gnu.linkonce.b.") ||
207       Name.startswith(".llvm.linkonce.b.") ||
208       Name == ".sbss" ||
209       Name.startswith(".sbss.") ||
210       Name.startswith(".gnu.linkonce.sb.") ||
211       Name.startswith(".llvm.linkonce.sb."))
212     return SectionKind::getBSS();
213 
214   if (Name == ".tdata" ||
215       Name.startswith(".tdata.") ||
216       Name.startswith(".gnu.linkonce.td.") ||
217       Name.startswith(".llvm.linkonce.td."))
218     return SectionKind::getThreadData();
219 
220   if (Name == ".tbss" ||
221       Name.startswith(".tbss.") ||
222       Name.startswith(".gnu.linkonce.tb.") ||
223       Name.startswith(".llvm.linkonce.tb."))
224     return SectionKind::getThreadBSS();
225 
226   return K;
227 }
228 
229 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
230   // Use SHT_NOTE for section whose name starts with ".note" to allow
231   // emitting ELF notes from C variable declaration.
232   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
233   if (Name.startswith(".note"))
234     return ELF::SHT_NOTE;
235 
236   if (Name == ".init_array")
237     return ELF::SHT_INIT_ARRAY;
238 
239   if (Name == ".fini_array")
240     return ELF::SHT_FINI_ARRAY;
241 
242   if (Name == ".preinit_array")
243     return ELF::SHT_PREINIT_ARRAY;
244 
245   if (K.isBSS() || K.isThreadBSS())
246     return ELF::SHT_NOBITS;
247 
248   return ELF::SHT_PROGBITS;
249 }
250 
251 static unsigned getELFSectionFlags(SectionKind K) {
252   unsigned Flags = 0;
253 
254   if (!K.isMetadata())
255     Flags |= ELF::SHF_ALLOC;
256 
257   if (K.isText())
258     Flags |= ELF::SHF_EXECINSTR;
259 
260   if (K.isExecuteOnly())
261     Flags |= ELF::SHF_ARM_PURECODE;
262 
263   if (K.isWriteable())
264     Flags |= ELF::SHF_WRITE;
265 
266   if (K.isThreadLocal())
267     Flags |= ELF::SHF_TLS;
268 
269   if (K.isMergeableCString() || K.isMergeableConst())
270     Flags |= ELF::SHF_MERGE;
271 
272   if (K.isMergeableCString())
273     Flags |= ELF::SHF_STRINGS;
274 
275   return Flags;
276 }
277 
278 static const Comdat *getELFComdat(const GlobalValue *GV) {
279   const Comdat *C = GV->getComdat();
280   if (!C)
281     return nullptr;
282 
283   if (C->getSelectionKind() != Comdat::Any)
284     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
285                        C->getName() + "' cannot be lowered.");
286 
287   return C;
288 }
289 
290 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
291                                               const TargetMachine &TM) {
292   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
293   if (!MD)
294     return nullptr;
295 
296   const MDOperand &Op = MD->getOperand(0);
297   if (!Op.get())
298     return nullptr;
299 
300   auto *VM = dyn_cast<ValueAsMetadata>(Op);
301   if (!VM)
302     report_fatal_error("MD_associated operand is not ValueAsMetadata");
303 
304   GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
305   return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
306 }
307 
308 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
309     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
310   StringRef SectionName = GO->getSection();
311 
312   // Check if '#pragma clang section' name is applicable.
313   // Note that pragma directive overrides -ffunction-section, -fdata-section
314   // and so section name is exactly as user specified and not uniqued.
315   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
316   if (GV && GV->hasImplicitSection()) {
317     auto Attrs = GV->getAttributes();
318     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
319       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
320     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
321       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
322     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
323       SectionName = Attrs.getAttribute("data-section").getValueAsString();
324     }
325   }
326   const Function *F = dyn_cast<Function>(GO);
327   if (F && F->hasFnAttribute("implicit-section-name")) {
328     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
329   }
330 
331   // Infer section flags from the section name if we can.
332   Kind = getELFKindForNamedSection(SectionName, Kind);
333 
334   StringRef Group = "";
335   unsigned Flags = getELFSectionFlags(Kind);
336   if (const Comdat *C = getELFComdat(GO)) {
337     Group = C->getName();
338     Flags |= ELF::SHF_GROUP;
339   }
340 
341   // A section can have at most one associated section. Put each global with
342   // MD_associated in a unique section.
343   unsigned UniqueID = MCContext::GenericSectionID;
344   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
345   if (AssociatedSymbol) {
346     UniqueID = NextUniqueID++;
347     Flags |= ELF::SHF_LINK_ORDER;
348   }
349 
350   MCSectionELF *Section = getContext().getELFSection(
351       SectionName, getELFSectionType(SectionName, Kind), Flags,
352       /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
353   // Make sure that we did not get some other section with incompatible sh_link.
354   // This should not be possible due to UniqueID code above.
355   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
356   return Section;
357 }
358 
359 /// Return the section prefix name used by options FunctionsSections and
360 /// DataSections.
361 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
362   if (Kind.isText())
363     return ".text";
364   if (Kind.isReadOnly())
365     return ".rodata";
366   if (Kind.isBSS())
367     return ".bss";
368   if (Kind.isThreadData())
369     return ".tdata";
370   if (Kind.isThreadBSS())
371     return ".tbss";
372   if (Kind.isData())
373     return ".data";
374   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
375   return ".data.rel.ro";
376 }
377 
378 static MCSectionELF *selectELFSectionForGlobal(
379     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
380     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
381     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
382   unsigned EntrySize = 0;
383   if (Kind.isMergeableCString()) {
384     if (Kind.isMergeable2ByteCString()) {
385       EntrySize = 2;
386     } else if (Kind.isMergeable4ByteCString()) {
387       EntrySize = 4;
388     } else {
389       EntrySize = 1;
390       assert(Kind.isMergeable1ByteCString() && "unknown string width");
391     }
392   } else if (Kind.isMergeableConst()) {
393     if (Kind.isMergeableConst4()) {
394       EntrySize = 4;
395     } else if (Kind.isMergeableConst8()) {
396       EntrySize = 8;
397     } else if (Kind.isMergeableConst16()) {
398       EntrySize = 16;
399     } else {
400       assert(Kind.isMergeableConst32() && "unknown data width");
401       EntrySize = 32;
402     }
403   }
404 
405   StringRef Group = "";
406   if (const Comdat *C = getELFComdat(GO)) {
407     Flags |= ELF::SHF_GROUP;
408     Group = C->getName();
409   }
410 
411   bool UniqueSectionNames = TM.getUniqueSectionNames();
412   SmallString<128> Name;
413   if (Kind.isMergeableCString()) {
414     // We also need alignment here.
415     // FIXME: this is getting the alignment of the character, not the
416     // alignment of the global!
417     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
418         cast<GlobalVariable>(GO));
419 
420     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
421     Name = SizeSpec + utostr(Align);
422   } else if (Kind.isMergeableConst()) {
423     Name = ".rodata.cst";
424     Name += utostr(EntrySize);
425   } else {
426     Name = getSectionPrefixForGlobal(Kind);
427   }
428 
429   if (const auto *F = dyn_cast<Function>(GO)) {
430     const auto &OptionalPrefix = F->getSectionPrefix();
431     if (OptionalPrefix)
432       Name += *OptionalPrefix;
433   }
434 
435   if (EmitUniqueSection && UniqueSectionNames) {
436     Name.push_back('.');
437     TM.getNameWithPrefix(Name, GO, Mang, true);
438   }
439   unsigned UniqueID = MCContext::GenericSectionID;
440   if (EmitUniqueSection && !UniqueSectionNames) {
441     UniqueID = *NextUniqueID;
442     (*NextUniqueID)++;
443   }
444   // Use 0 as the unique ID for execute-only text
445   if (Kind.isExecuteOnly())
446     UniqueID = 0;
447   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
448                            EntrySize, Group, UniqueID, AssociatedSymbol);
449 }
450 
451 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
452     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
453   unsigned Flags = getELFSectionFlags(Kind);
454 
455   // If we have -ffunction-section or -fdata-section then we should emit the
456   // global value to a uniqued section specifically for it.
457   bool EmitUniqueSection = false;
458   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
459     if (Kind.isText())
460       EmitUniqueSection = TM.getFunctionSections();
461     else
462       EmitUniqueSection = TM.getDataSections();
463   }
464   EmitUniqueSection |= GO->hasComdat();
465 
466   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
467   if (AssociatedSymbol) {
468     EmitUniqueSection = true;
469     Flags |= ELF::SHF_LINK_ORDER;
470   }
471 
472   MCSectionELF *Section = selectELFSectionForGlobal(
473       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
474       &NextUniqueID, AssociatedSymbol);
475   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
476   return Section;
477 }
478 
479 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
480     const Function &F, const TargetMachine &TM) const {
481   // If the function can be removed, produce a unique section so that
482   // the table doesn't prevent the removal.
483   const Comdat *C = F.getComdat();
484   bool EmitUniqueSection = TM.getFunctionSections() || C;
485   if (!EmitUniqueSection)
486     return ReadOnlySection;
487 
488   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
489                                    getMangler(), TM, EmitUniqueSection,
490                                    ELF::SHF_ALLOC, &NextUniqueID,
491                                    /* AssociatedSymbol */ nullptr);
492 }
493 
494 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
495     bool UsesLabelDifference, const Function &F) const {
496   // We can always create relative relocations, so use another section
497   // that can be marked non-executable.
498   return false;
499 }
500 
501 /// Given a mergeable constant with the specified size and relocation
502 /// information, return a section that it should be placed in.
503 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
504     const DataLayout &DL, SectionKind Kind, const Constant *C,
505     unsigned &Align) const {
506   if (Kind.isMergeableConst4() && MergeableConst4Section)
507     return MergeableConst4Section;
508   if (Kind.isMergeableConst8() && MergeableConst8Section)
509     return MergeableConst8Section;
510   if (Kind.isMergeableConst16() && MergeableConst16Section)
511     return MergeableConst16Section;
512   if (Kind.isMergeableConst32() && MergeableConst32Section)
513     return MergeableConst32Section;
514   if (Kind.isReadOnly())
515     return ReadOnlySection;
516 
517   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
518   return DataRelROSection;
519 }
520 
521 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
522                                               bool IsCtor, unsigned Priority,
523                                               const MCSymbol *KeySym) {
524   std::string Name;
525   unsigned Type;
526   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
527   StringRef COMDAT = KeySym ? KeySym->getName() : "";
528 
529   if (KeySym)
530     Flags |= ELF::SHF_GROUP;
531 
532   if (UseInitArray) {
533     if (IsCtor) {
534       Type = ELF::SHT_INIT_ARRAY;
535       Name = ".init_array";
536     } else {
537       Type = ELF::SHT_FINI_ARRAY;
538       Name = ".fini_array";
539     }
540     if (Priority != 65535) {
541       Name += '.';
542       Name += utostr(Priority);
543     }
544   } else {
545     // The default scheme is .ctor / .dtor, so we have to invert the priority
546     // numbering.
547     if (IsCtor)
548       Name = ".ctors";
549     else
550       Name = ".dtors";
551     if (Priority != 65535)
552       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
553     Type = ELF::SHT_PROGBITS;
554   }
555 
556   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
557 }
558 
559 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
560     unsigned Priority, const MCSymbol *KeySym) const {
561   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
562                                   KeySym);
563 }
564 
565 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
566     unsigned Priority, const MCSymbol *KeySym) const {
567   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
568                                   KeySym);
569 }
570 
571 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
572     const GlobalValue *LHS, const GlobalValue *RHS,
573     const TargetMachine &TM) const {
574   // We may only use a PLT-relative relocation to refer to unnamed_addr
575   // functions.
576   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
577     return nullptr;
578 
579   // Basic sanity checks.
580   if (LHS->getType()->getPointerAddressSpace() != 0 ||
581       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
582       RHS->isThreadLocal())
583     return nullptr;
584 
585   return MCBinaryExpr::createSub(
586       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
587                               getContext()),
588       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
589 }
590 
591 void
592 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
593   UseInitArray = UseInitArray_;
594   MCContext &Ctx = getContext();
595   if (!UseInitArray) {
596     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
597                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
598 
599     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
600                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
601     return;
602   }
603 
604   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
605                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
606   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
607                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
608 }
609 
610 //===----------------------------------------------------------------------===//
611 //                                 MachO
612 //===----------------------------------------------------------------------===//
613 
614 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
615   : TargetLoweringObjectFile() {
616   SupportIndirectSymViaGOTPCRel = true;
617 }
618 
619 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
620                                                const TargetMachine &TM) {
621   TargetLoweringObjectFile::Initialize(Ctx, TM);
622   if (TM.getRelocationModel() == Reloc::Static) {
623     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
624                                             SectionKind::getData());
625     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
626                                             SectionKind::getData());
627   } else {
628     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
629                                             MachO::S_MOD_INIT_FUNC_POINTERS,
630                                             SectionKind::getData());
631     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
632                                             MachO::S_MOD_TERM_FUNC_POINTERS,
633                                             SectionKind::getData());
634   }
635 }
636 
637 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
638                                                        Module &M) const {
639   // Emit the linker options if present.
640   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
641     for (const auto &Option : LinkerOptions->operands()) {
642       SmallVector<std::string, 4> StrOptions;
643       for (const auto &Piece : cast<MDNode>(Option)->operands())
644         StrOptions.push_back(cast<MDString>(Piece)->getString());
645       Streamer.EmitLinkerOptions(StrOptions);
646     }
647   }
648 
649   unsigned VersionVal = 0;
650   unsigned ImageInfoFlags = 0;
651   StringRef SectionVal;
652 
653   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
654 
655   // The section is mandatory. If we don't have it, then we don't have GC info.
656   if (SectionVal.empty())
657     return;
658 
659   StringRef Segment, Section;
660   unsigned TAA = 0, StubSize = 0;
661   bool TAAParsed;
662   std::string ErrorCode =
663     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
664                                           TAA, TAAParsed, StubSize);
665   if (!ErrorCode.empty())
666     // If invalid, report the error with report_fatal_error.
667     report_fatal_error("Invalid section specifier '" + Section + "': " +
668                        ErrorCode + ".");
669 
670   // Get the section.
671   MCSectionMachO *S = getContext().getMachOSection(
672       Segment, Section, TAA, StubSize, SectionKind::getData());
673   Streamer.SwitchSection(S);
674   Streamer.EmitLabel(getContext().
675                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
676   Streamer.EmitIntValue(VersionVal, 4);
677   Streamer.EmitIntValue(ImageInfoFlags, 4);
678   Streamer.AddBlankLine();
679 }
680 
681 static void checkMachOComdat(const GlobalValue *GV) {
682   const Comdat *C = GV->getComdat();
683   if (!C)
684     return;
685 
686   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
687                      "' cannot be lowered.");
688 }
689 
690 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
691     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
692   // Parse the section specifier and create it if valid.
693   StringRef Segment, Section;
694   unsigned TAA = 0, StubSize = 0;
695   bool TAAParsed;
696 
697   checkMachOComdat(GO);
698 
699   std::string ErrorCode =
700     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
701                                           TAA, TAAParsed, StubSize);
702   if (!ErrorCode.empty()) {
703     // If invalid, report the error with report_fatal_error.
704     report_fatal_error("Global variable '" + GO->getName() +
705                        "' has an invalid section specifier '" +
706                        GO->getSection() + "': " + ErrorCode + ".");
707   }
708 
709   // Get the section.
710   MCSectionMachO *S =
711       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
712 
713   // If TAA wasn't set by ParseSectionSpecifier() above,
714   // use the value returned by getMachOSection() as a default.
715   if (!TAAParsed)
716     TAA = S->getTypeAndAttributes();
717 
718   // Okay, now that we got the section, verify that the TAA & StubSize agree.
719   // If the user declared multiple globals with different section flags, we need
720   // to reject it here.
721   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
722     // If invalid, report the error with report_fatal_error.
723     report_fatal_error("Global variable '" + GO->getName() +
724                        "' section type or attributes does not match previous"
725                        " section specifier");
726   }
727 
728   return S;
729 }
730 
731 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
732     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
733   checkMachOComdat(GO);
734 
735   // Handle thread local data.
736   if (Kind.isThreadBSS()) return TLSBSSSection;
737   if (Kind.isThreadData()) return TLSDataSection;
738 
739   if (Kind.isText())
740     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
741 
742   // If this is weak/linkonce, put this in a coalescable section, either in text
743   // or data depending on if it is writable.
744   if (GO->isWeakForLinker()) {
745     if (Kind.isReadOnly())
746       return ConstTextCoalSection;
747     if (Kind.isReadOnlyWithRel())
748       return ConstDataCoalSection;
749     return DataCoalSection;
750   }
751 
752   // FIXME: Alignment check should be handled by section classifier.
753   if (Kind.isMergeable1ByteCString() &&
754       GO->getParent()->getDataLayout().getPreferredAlignment(
755           cast<GlobalVariable>(GO)) < 32)
756     return CStringSection;
757 
758   // Do not put 16-bit arrays in the UString section if they have an
759   // externally visible label, this runs into issues with certain linker
760   // versions.
761   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
762       GO->getParent()->getDataLayout().getPreferredAlignment(
763           cast<GlobalVariable>(GO)) < 32)
764     return UStringSection;
765 
766   // With MachO only variables whose corresponding symbol starts with 'l' or
767   // 'L' can be merged, so we only try merging GVs with private linkage.
768   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
769     if (Kind.isMergeableConst4())
770       return FourByteConstantSection;
771     if (Kind.isMergeableConst8())
772       return EightByteConstantSection;
773     if (Kind.isMergeableConst16())
774       return SixteenByteConstantSection;
775   }
776 
777   // Otherwise, if it is readonly, but not something we can specially optimize,
778   // just drop it in .const.
779   if (Kind.isReadOnly())
780     return ReadOnlySection;
781 
782   // If this is marked const, put it into a const section.  But if the dynamic
783   // linker needs to write to it, put it in the data segment.
784   if (Kind.isReadOnlyWithRel())
785     return ConstDataSection;
786 
787   // Put zero initialized globals with strong external linkage in the
788   // DATA, __common section with the .zerofill directive.
789   if (Kind.isBSSExtern())
790     return DataCommonSection;
791 
792   // Put zero initialized globals with local linkage in __DATA,__bss directive
793   // with the .zerofill directive (aka .lcomm).
794   if (Kind.isBSSLocal())
795     return DataBSSSection;
796 
797   // Otherwise, just drop the variable in the normal data section.
798   return DataSection;
799 }
800 
801 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
802     const DataLayout &DL, SectionKind Kind, const Constant *C,
803     unsigned &Align) const {
804   // If this constant requires a relocation, we have to put it in the data
805   // segment, not in the text segment.
806   if (Kind.isData() || Kind.isReadOnlyWithRel())
807     return ConstDataSection;
808 
809   if (Kind.isMergeableConst4())
810     return FourByteConstantSection;
811   if (Kind.isMergeableConst8())
812     return EightByteConstantSection;
813   if (Kind.isMergeableConst16())
814     return SixteenByteConstantSection;
815   return ReadOnlySection;  // .const
816 }
817 
818 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
819     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
820     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
821   // The mach-o version of this method defaults to returning a stub reference.
822 
823   if (Encoding & DW_EH_PE_indirect) {
824     MachineModuleInfoMachO &MachOMMI =
825       MMI->getObjFileInfo<MachineModuleInfoMachO>();
826 
827     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
828 
829     // Add information about the stub reference to MachOMMI so that the stub
830     // gets emitted by the asmprinter.
831     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
832     if (!StubSym.getPointer()) {
833       MCSymbol *Sym = TM.getSymbol(GV);
834       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
835     }
836 
837     return TargetLoweringObjectFile::
838       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
839                         Encoding & ~DW_EH_PE_indirect, Streamer);
840   }
841 
842   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
843                                                            MMI, Streamer);
844 }
845 
846 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
847     const GlobalValue *GV, const TargetMachine &TM,
848     MachineModuleInfo *MMI) const {
849   // The mach-o version of this method defaults to returning a stub reference.
850   MachineModuleInfoMachO &MachOMMI =
851     MMI->getObjFileInfo<MachineModuleInfoMachO>();
852 
853   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
854 
855   // Add information about the stub reference to MachOMMI so that the stub
856   // gets emitted by the asmprinter.
857   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
858   if (!StubSym.getPointer()) {
859     MCSymbol *Sym = TM.getSymbol(GV);
860     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
861   }
862 
863   return SSym;
864 }
865 
866 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
867     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
868     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
869   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
870   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
871   // through a non_lazy_ptr stub instead. One advantage is that it allows the
872   // computation of deltas to final external symbols. Example:
873   //
874   //    _extgotequiv:
875   //       .long   _extfoo
876   //
877   //    _delta:
878   //       .long   _extgotequiv-_delta
879   //
880   // is transformed to:
881   //
882   //    _delta:
883   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
884   //
885   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
886   //    L_extfoo$non_lazy_ptr:
887   //       .indirect_symbol        _extfoo
888   //       .long   0
889   //
890   MachineModuleInfoMachO &MachOMMI =
891     MMI->getObjFileInfo<MachineModuleInfoMachO>();
892   MCContext &Ctx = getContext();
893 
894   // The offset must consider the original displacement from the base symbol
895   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
896   Offset = -MV.getConstant();
897   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
898 
899   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
900   // non_lazy_ptr stubs.
901   SmallString<128> Name;
902   StringRef Suffix = "$non_lazy_ptr";
903   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
904   Name += Sym->getName();
905   Name += Suffix;
906   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
907 
908   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
909   if (!StubSym.getPointer())
910     StubSym = MachineModuleInfoImpl::
911       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
912 
913   const MCExpr *BSymExpr =
914     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
915   const MCExpr *LHS =
916     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
917 
918   if (!Offset)
919     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
920 
921   const MCExpr *RHS =
922     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
923   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
924 }
925 
926 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
927                                const MCSection &Section) {
928   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
929     return true;
930 
931   // If it is not dead stripped, it is safe to use private labels.
932   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
933   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
934     return true;
935 
936   return false;
937 }
938 
939 void TargetLoweringObjectFileMachO::getNameWithPrefix(
940     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
941     const TargetMachine &TM) const {
942   bool CannotUsePrivateLabel = true;
943   if (auto *GO = GV->getBaseObject()) {
944     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
945     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
946     CannotUsePrivateLabel =
947         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
948   }
949   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
950 }
951 
952 //===----------------------------------------------------------------------===//
953 //                                  COFF
954 //===----------------------------------------------------------------------===//
955 
956 static unsigned
957 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
958   unsigned Flags = 0;
959   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
960 
961   if (K.isMetadata())
962     Flags |=
963       COFF::IMAGE_SCN_MEM_DISCARDABLE;
964   else if (K.isText())
965     Flags |=
966       COFF::IMAGE_SCN_MEM_EXECUTE |
967       COFF::IMAGE_SCN_MEM_READ |
968       COFF::IMAGE_SCN_CNT_CODE |
969       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
970   else if (K.isBSS())
971     Flags |=
972       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
973       COFF::IMAGE_SCN_MEM_READ |
974       COFF::IMAGE_SCN_MEM_WRITE;
975   else if (K.isThreadLocal())
976     Flags |=
977       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
978       COFF::IMAGE_SCN_MEM_READ |
979       COFF::IMAGE_SCN_MEM_WRITE;
980   else if (K.isReadOnly() || K.isReadOnlyWithRel())
981     Flags |=
982       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
983       COFF::IMAGE_SCN_MEM_READ;
984   else if (K.isWriteable())
985     Flags |=
986       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
987       COFF::IMAGE_SCN_MEM_READ |
988       COFF::IMAGE_SCN_MEM_WRITE;
989 
990   return Flags;
991 }
992 
993 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
994   const Comdat *C = GV->getComdat();
995   assert(C && "expected GV to have a Comdat!");
996 
997   StringRef ComdatGVName = C->getName();
998   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
999   if (!ComdatGV)
1000     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1001                        "' does not exist.");
1002 
1003   if (ComdatGV->getComdat() != C)
1004     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1005                        "' is not a key for its COMDAT.");
1006 
1007   return ComdatGV;
1008 }
1009 
1010 static int getSelectionForCOFF(const GlobalValue *GV) {
1011   if (const Comdat *C = GV->getComdat()) {
1012     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1013     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1014       ComdatKey = GA->getBaseObject();
1015     if (ComdatKey == GV) {
1016       switch (C->getSelectionKind()) {
1017       case Comdat::Any:
1018         return COFF::IMAGE_COMDAT_SELECT_ANY;
1019       case Comdat::ExactMatch:
1020         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1021       case Comdat::Largest:
1022         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1023       case Comdat::NoDuplicates:
1024         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1025       case Comdat::SameSize:
1026         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1027       }
1028     } else {
1029       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1030     }
1031   }
1032   return 0;
1033 }
1034 
1035 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1036     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1037   int Selection = 0;
1038   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1039   StringRef Name = GO->getSection();
1040   StringRef COMDATSymName = "";
1041   if (GO->hasComdat()) {
1042     Selection = getSelectionForCOFF(GO);
1043     const GlobalValue *ComdatGV;
1044     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1045       ComdatGV = getComdatGVForCOFF(GO);
1046     else
1047       ComdatGV = GO;
1048 
1049     if (!ComdatGV->hasPrivateLinkage()) {
1050       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1051       COMDATSymName = Sym->getName();
1052       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1053     } else {
1054       Selection = 0;
1055     }
1056   }
1057 
1058   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1059                                      Selection);
1060 }
1061 
1062 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1063   if (Kind.isText())
1064     return ".text";
1065   if (Kind.isBSS())
1066     return ".bss";
1067   if (Kind.isThreadLocal())
1068     return ".tls$";
1069   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1070     return ".rdata";
1071   return ".data";
1072 }
1073 
1074 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1075     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1076   // If we have -ffunction-sections then we should emit the global value to a
1077   // uniqued section specifically for it.
1078   bool EmitUniquedSection;
1079   if (Kind.isText())
1080     EmitUniquedSection = TM.getFunctionSections();
1081   else
1082     EmitUniquedSection = TM.getDataSections();
1083 
1084   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1085     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1086     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1087 
1088     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1089     int Selection = getSelectionForCOFF(GO);
1090     if (!Selection)
1091       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1092     const GlobalValue *ComdatGV;
1093     if (GO->hasComdat())
1094       ComdatGV = getComdatGVForCOFF(GO);
1095     else
1096       ComdatGV = GO;
1097 
1098     unsigned UniqueID = MCContext::GenericSectionID;
1099     if (EmitUniquedSection)
1100       UniqueID = NextUniqueID++;
1101 
1102     if (!ComdatGV->hasPrivateLinkage()) {
1103       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1104       StringRef COMDATSymName = Sym->getName();
1105       return getContext().getCOFFSection(Name, Characteristics, Kind,
1106                                          COMDATSymName, Selection, UniqueID);
1107     } else {
1108       SmallString<256> TmpData;
1109       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1110       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1111                                          Selection, UniqueID);
1112     }
1113   }
1114 
1115   if (Kind.isText())
1116     return TextSection;
1117 
1118   if (Kind.isThreadLocal())
1119     return TLSDataSection;
1120 
1121   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1122     return ReadOnlySection;
1123 
1124   // Note: we claim that common symbols are put in BSSSection, but they are
1125   // really emitted with the magic .comm directive, which creates a symbol table
1126   // entry but not a section.
1127   if (Kind.isBSS() || Kind.isCommon())
1128     return BSSSection;
1129 
1130   return DataSection;
1131 }
1132 
1133 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1134     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1135     const TargetMachine &TM) const {
1136   bool CannotUsePrivateLabel = false;
1137   if (GV->hasPrivateLinkage() &&
1138       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1139        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1140     CannotUsePrivateLabel = true;
1141 
1142   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1143 }
1144 
1145 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1146     const Function &F, const TargetMachine &TM) const {
1147   // If the function can be removed, produce a unique section so that
1148   // the table doesn't prevent the removal.
1149   const Comdat *C = F.getComdat();
1150   bool EmitUniqueSection = TM.getFunctionSections() || C;
1151   if (!EmitUniqueSection)
1152     return ReadOnlySection;
1153 
1154   // FIXME: we should produce a symbol for F instead.
1155   if (F.hasPrivateLinkage())
1156     return ReadOnlySection;
1157 
1158   MCSymbol *Sym = TM.getSymbol(&F);
1159   StringRef COMDATSymName = Sym->getName();
1160 
1161   SectionKind Kind = SectionKind::getReadOnly();
1162   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1163   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1164   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1165   unsigned UniqueID = NextUniqueID++;
1166 
1167   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1168                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1169 }
1170 
1171 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1172                                                       Module &M) const {
1173   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1174     // Emit the linker options to the linker .drectve section.  According to the
1175     // spec, this section is a space-separated string containing flags for
1176     // linker.
1177     MCSection *Sec = getDrectveSection();
1178     Streamer.SwitchSection(Sec);
1179     for (const auto &Option : LinkerOptions->operands()) {
1180       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1181         // Lead with a space for consistency with our dllexport implementation.
1182         std::string Directive(" ");
1183         Directive.append(cast<MDString>(Piece)->getString());
1184         Streamer.EmitBytes(Directive);
1185       }
1186     }
1187   }
1188 
1189   unsigned Version = 0;
1190   unsigned Flags = 0;
1191   StringRef Section;
1192 
1193   GetObjCImageInfo(M, Version, Flags, Section);
1194   if (Section.empty())
1195     return;
1196 
1197   auto &C = getContext();
1198   auto *S = C.getCOFFSection(
1199       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1200       SectionKind::getReadOnly());
1201   Streamer.SwitchSection(S);
1202   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1203   Streamer.EmitIntValue(Version, 4);
1204   Streamer.EmitIntValue(Flags, 4);
1205   Streamer.AddBlankLine();
1206 }
1207 
1208 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1209                                               const TargetMachine &TM) {
1210   TargetLoweringObjectFile::Initialize(Ctx, TM);
1211   const Triple &T = TM.getTargetTriple();
1212   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1213     StaticCtorSection =
1214         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1215                                            COFF::IMAGE_SCN_MEM_READ,
1216                            SectionKind::getReadOnly());
1217     StaticDtorSection =
1218         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1219                                            COFF::IMAGE_SCN_MEM_READ,
1220                            SectionKind::getReadOnly());
1221   } else {
1222     StaticCtorSection = Ctx.getCOFFSection(
1223         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1224                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1225         SectionKind::getData());
1226     StaticDtorSection = Ctx.getCOFFSection(
1227         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1228                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1229         SectionKind::getData());
1230   }
1231 }
1232 
1233 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1234                                                    const Triple &T, bool IsCtor,
1235                                                    unsigned Priority,
1236                                                    const MCSymbol *KeySym,
1237                                                    MCSectionCOFF *Default) {
1238   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
1239     return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1240 
1241   std::string Name = IsCtor ? ".ctors" : ".dtors";
1242   if (Priority != 65535)
1243     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1244 
1245   return Ctx.getAssociativeCOFFSection(
1246       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1247                                    COFF::IMAGE_SCN_MEM_READ |
1248                                    COFF::IMAGE_SCN_MEM_WRITE,
1249                          SectionKind::getData()),
1250       KeySym, 0);
1251 }
1252 
1253 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1254     unsigned Priority, const MCSymbol *KeySym) const {
1255   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1256                                       Priority, KeySym,
1257                                       cast<MCSectionCOFF>(StaticCtorSection));
1258 }
1259 
1260 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1261     unsigned Priority, const MCSymbol *KeySym) const {
1262   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1263                                       Priority, KeySym,
1264                                       cast<MCSectionCOFF>(StaticDtorSection));
1265 }
1266 
1267 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1268     raw_ostream &OS, const GlobalValue *GV) const {
1269   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1270 }
1271 
1272 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1273     raw_ostream &OS, const GlobalValue *GV) const {
1274   emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1275 }
1276 
1277 //===----------------------------------------------------------------------===//
1278 //                                  Wasm
1279 //===----------------------------------------------------------------------===//
1280 
1281 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1282   const Comdat *C = GV->getComdat();
1283   if (!C)
1284     return nullptr;
1285 
1286   if (C->getSelectionKind() != Comdat::Any)
1287     report_fatal_error("WebAssembly COMDATs only support "
1288                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
1289                        "lowered.");
1290 
1291   return C;
1292 }
1293 
1294 static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1295   // If we're told we have function data, then use that.
1296   if (K.isText())
1297     return SectionKind::getText();
1298 
1299   // Otherwise, ignore whatever section type the generic impl detected and use
1300   // a plain data section.
1301   return SectionKind::getData();
1302 }
1303 
1304 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1305     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1306   StringRef Name = GO->getSection();
1307 
1308   Kind = getWasmKindForNamedSection(Name, Kind);
1309 
1310   StringRef Group = "";
1311   if (const Comdat *C = getWasmComdat(GO)) {
1312     Group = C->getName();
1313   }
1314 
1315   return getContext().getWasmSection(Name, Kind, Group,
1316                                      MCContext::GenericSectionID);
1317 }
1318 
1319 static MCSectionWasm *selectWasmSectionForGlobal(
1320     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1321     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1322   StringRef Group = "";
1323   if (const Comdat *C = getWasmComdat(GO)) {
1324     Group = C->getName();
1325   }
1326 
1327   bool UniqueSectionNames = TM.getUniqueSectionNames();
1328   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1329 
1330   if (const auto *F = dyn_cast<Function>(GO)) {
1331     const auto &OptionalPrefix = F->getSectionPrefix();
1332     if (OptionalPrefix)
1333       Name += *OptionalPrefix;
1334   }
1335 
1336   if (EmitUniqueSection && UniqueSectionNames) {
1337     Name.push_back('.');
1338     TM.getNameWithPrefix(Name, GO, Mang, true);
1339   }
1340   unsigned UniqueID = MCContext::GenericSectionID;
1341   if (EmitUniqueSection && !UniqueSectionNames) {
1342     UniqueID = *NextUniqueID;
1343     (*NextUniqueID)++;
1344   }
1345   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1346 }
1347 
1348 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1349     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1350 
1351   if (Kind.isCommon())
1352     report_fatal_error("mergable sections not supported yet on wasm");
1353 
1354   // If we have -ffunction-section or -fdata-section then we should emit the
1355   // global value to a uniqued section specifically for it.
1356   bool EmitUniqueSection = false;
1357   if (Kind.isText())
1358     EmitUniqueSection = TM.getFunctionSections();
1359   else
1360     EmitUniqueSection = TM.getDataSections();
1361   EmitUniqueSection |= GO->hasComdat();
1362 
1363   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1364                                     EmitUniqueSection, &NextUniqueID);
1365 }
1366 
1367 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1368     bool UsesLabelDifference, const Function &F) const {
1369   // We can always create relative relocations, so use another section
1370   // that can be marked non-executable.
1371   return false;
1372 }
1373 
1374 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1375     const GlobalValue *LHS, const GlobalValue *RHS,
1376     const TargetMachine &TM) const {
1377   // We may only use a PLT-relative relocation to refer to unnamed_addr
1378   // functions.
1379   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1380     return nullptr;
1381 
1382   // Basic sanity checks.
1383   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1384       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1385       RHS->isThreadLocal())
1386     return nullptr;
1387 
1388   return MCBinaryExpr::createSub(
1389       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1390                               getContext()),
1391       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1392 }
1393 
1394 void TargetLoweringObjectFileWasm::InitializeWasm() {
1395   StaticCtorSection =
1396       getContext().getWasmSection(".init_array", SectionKind::getData());
1397 }
1398 
1399 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1400     unsigned Priority, const MCSymbol *KeySym) const {
1401   return Priority == UINT16_MAX ?
1402          StaticCtorSection :
1403          getContext().getWasmSection(".init_array." + utostr(Priority),
1404                                      SectionKind::getData());
1405 }
1406 
1407 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1408     unsigned Priority, const MCSymbol *KeySym) const {
1409   llvm_unreachable("@llvm.global_dtors should have been lowered already");
1410   return nullptr;
1411 }
1412