xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision b36fbbc3ec9fe0e1636c16d38083c65aefbafa7e)
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(
95     MCStreamer &Streamer, Module &M, const TargetMachine &TM) 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 no 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(
638     MCStreamer &Streamer, Module &M, const TargetMachine &TM) 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     return DataCoalSection;
748   }
749 
750   // FIXME: Alignment check should be handled by section classifier.
751   if (Kind.isMergeable1ByteCString() &&
752       GO->getParent()->getDataLayout().getPreferredAlignment(
753           cast<GlobalVariable>(GO)) < 32)
754     return CStringSection;
755 
756   // Do not put 16-bit arrays in the UString section if they have an
757   // externally visible label, this runs into issues with certain linker
758   // versions.
759   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
760       GO->getParent()->getDataLayout().getPreferredAlignment(
761           cast<GlobalVariable>(GO)) < 32)
762     return UStringSection;
763 
764   // With MachO only variables whose corresponding symbol starts with 'l' or
765   // 'L' can be merged, so we only try merging GVs with private linkage.
766   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
767     if (Kind.isMergeableConst4())
768       return FourByteConstantSection;
769     if (Kind.isMergeableConst8())
770       return EightByteConstantSection;
771     if (Kind.isMergeableConst16())
772       return SixteenByteConstantSection;
773   }
774 
775   // Otherwise, if it is readonly, but not something we can specially optimize,
776   // just drop it in .const.
777   if (Kind.isReadOnly())
778     return ReadOnlySection;
779 
780   // If this is marked const, put it into a const section.  But if the dynamic
781   // linker needs to write to it, put it in the data segment.
782   if (Kind.isReadOnlyWithRel())
783     return ConstDataSection;
784 
785   // Put zero initialized globals with strong external linkage in the
786   // DATA, __common section with the .zerofill directive.
787   if (Kind.isBSSExtern())
788     return DataCommonSection;
789 
790   // Put zero initialized globals with local linkage in __DATA,__bss directive
791   // with the .zerofill directive (aka .lcomm).
792   if (Kind.isBSSLocal())
793     return DataBSSSection;
794 
795   // Otherwise, just drop the variable in the normal data section.
796   return DataSection;
797 }
798 
799 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
800     const DataLayout &DL, SectionKind Kind, const Constant *C,
801     unsigned &Align) const {
802   // If this constant requires a relocation, we have to put it in the data
803   // segment, not in the text segment.
804   if (Kind.isData() || Kind.isReadOnlyWithRel())
805     return ConstDataSection;
806 
807   if (Kind.isMergeableConst4())
808     return FourByteConstantSection;
809   if (Kind.isMergeableConst8())
810     return EightByteConstantSection;
811   if (Kind.isMergeableConst16())
812     return SixteenByteConstantSection;
813   return ReadOnlySection;  // .const
814 }
815 
816 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
817     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
818     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
819   // The mach-o version of this method defaults to returning a stub reference.
820 
821   if (Encoding & DW_EH_PE_indirect) {
822     MachineModuleInfoMachO &MachOMMI =
823       MMI->getObjFileInfo<MachineModuleInfoMachO>();
824 
825     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
826 
827     // Add information about the stub reference to MachOMMI so that the stub
828     // gets emitted by the asmprinter.
829     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
830     if (!StubSym.getPointer()) {
831       MCSymbol *Sym = TM.getSymbol(GV);
832       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
833     }
834 
835     return TargetLoweringObjectFile::
836       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
837                         Encoding & ~DW_EH_PE_indirect, Streamer);
838   }
839 
840   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
841                                                            MMI, Streamer);
842 }
843 
844 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
845     const GlobalValue *GV, const TargetMachine &TM,
846     MachineModuleInfo *MMI) const {
847   // The mach-o version of this method defaults to returning a stub reference.
848   MachineModuleInfoMachO &MachOMMI =
849     MMI->getObjFileInfo<MachineModuleInfoMachO>();
850 
851   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
852 
853   // Add information about the stub reference to MachOMMI so that the stub
854   // gets emitted by the asmprinter.
855   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
856   if (!StubSym.getPointer()) {
857     MCSymbol *Sym = TM.getSymbol(GV);
858     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
859   }
860 
861   return SSym;
862 }
863 
864 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
865     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
866     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
867   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
868   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
869   // through a non_lazy_ptr stub instead. One advantage is that it allows the
870   // computation of deltas to final external symbols. Example:
871   //
872   //    _extgotequiv:
873   //       .long   _extfoo
874   //
875   //    _delta:
876   //       .long   _extgotequiv-_delta
877   //
878   // is transformed to:
879   //
880   //    _delta:
881   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
882   //
883   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
884   //    L_extfoo$non_lazy_ptr:
885   //       .indirect_symbol        _extfoo
886   //       .long   0
887   //
888   MachineModuleInfoMachO &MachOMMI =
889     MMI->getObjFileInfo<MachineModuleInfoMachO>();
890   MCContext &Ctx = getContext();
891 
892   // The offset must consider the original displacement from the base symbol
893   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
894   Offset = -MV.getConstant();
895   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
896 
897   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
898   // non_lazy_ptr stubs.
899   SmallString<128> Name;
900   StringRef Suffix = "$non_lazy_ptr";
901   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
902   Name += Sym->getName();
903   Name += Suffix;
904   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
905 
906   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
907   if (!StubSym.getPointer())
908     StubSym = MachineModuleInfoImpl::
909       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
910 
911   const MCExpr *BSymExpr =
912     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
913   const MCExpr *LHS =
914     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
915 
916   if (!Offset)
917     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
918 
919   const MCExpr *RHS =
920     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
921   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
922 }
923 
924 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
925                                const MCSection &Section) {
926   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
927     return true;
928 
929   // If it is not dead stripped, it is safe to use private labels.
930   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
931   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
932     return true;
933 
934   return false;
935 }
936 
937 void TargetLoweringObjectFileMachO::getNameWithPrefix(
938     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
939     const TargetMachine &TM) const {
940   bool CannotUsePrivateLabel = true;
941   if (auto *GO = GV->getBaseObject()) {
942     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
943     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
944     CannotUsePrivateLabel =
945         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
946   }
947   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
948 }
949 
950 //===----------------------------------------------------------------------===//
951 //                                  COFF
952 //===----------------------------------------------------------------------===//
953 
954 static unsigned
955 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
956   unsigned Flags = 0;
957   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
958 
959   if (K.isMetadata())
960     Flags |=
961       COFF::IMAGE_SCN_MEM_DISCARDABLE;
962   else if (K.isText())
963     Flags |=
964       COFF::IMAGE_SCN_MEM_EXECUTE |
965       COFF::IMAGE_SCN_MEM_READ |
966       COFF::IMAGE_SCN_CNT_CODE |
967       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
968   else if (K.isBSS())
969     Flags |=
970       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
971       COFF::IMAGE_SCN_MEM_READ |
972       COFF::IMAGE_SCN_MEM_WRITE;
973   else if (K.isThreadLocal())
974     Flags |=
975       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
976       COFF::IMAGE_SCN_MEM_READ |
977       COFF::IMAGE_SCN_MEM_WRITE;
978   else if (K.isReadOnly() || K.isReadOnlyWithRel())
979     Flags |=
980       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
981       COFF::IMAGE_SCN_MEM_READ;
982   else if (K.isWriteable())
983     Flags |=
984       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
985       COFF::IMAGE_SCN_MEM_READ |
986       COFF::IMAGE_SCN_MEM_WRITE;
987 
988   return Flags;
989 }
990 
991 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
992   const Comdat *C = GV->getComdat();
993   assert(C && "expected GV to have a Comdat!");
994 
995   StringRef ComdatGVName = C->getName();
996   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
997   if (!ComdatGV)
998     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
999                        "' does not exist.");
1000 
1001   if (ComdatGV->getComdat() != C)
1002     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1003                        "' is not a key for its COMDAT.");
1004 
1005   return ComdatGV;
1006 }
1007 
1008 static int getSelectionForCOFF(const GlobalValue *GV) {
1009   if (const Comdat *C = GV->getComdat()) {
1010     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1011     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1012       ComdatKey = GA->getBaseObject();
1013     if (ComdatKey == GV) {
1014       switch (C->getSelectionKind()) {
1015       case Comdat::Any:
1016         return COFF::IMAGE_COMDAT_SELECT_ANY;
1017       case Comdat::ExactMatch:
1018         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1019       case Comdat::Largest:
1020         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1021       case Comdat::NoDuplicates:
1022         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1023       case Comdat::SameSize:
1024         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1025       }
1026     } else {
1027       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1028     }
1029   }
1030   return 0;
1031 }
1032 
1033 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1034     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1035   int Selection = 0;
1036   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1037   StringRef Name = GO->getSection();
1038   StringRef COMDATSymName = "";
1039   if (GO->hasComdat()) {
1040     Selection = getSelectionForCOFF(GO);
1041     const GlobalValue *ComdatGV;
1042     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1043       ComdatGV = getComdatGVForCOFF(GO);
1044     else
1045       ComdatGV = GO;
1046 
1047     if (!ComdatGV->hasPrivateLinkage()) {
1048       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1049       COMDATSymName = Sym->getName();
1050       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1051     } else {
1052       Selection = 0;
1053     }
1054   }
1055 
1056   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1057                                      Selection);
1058 }
1059 
1060 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1061   if (Kind.isText())
1062     return ".text";
1063   if (Kind.isBSS())
1064     return ".bss";
1065   if (Kind.isThreadLocal())
1066     return ".tls$";
1067   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1068     return ".rdata";
1069   return ".data";
1070 }
1071 
1072 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1073     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1074   // If we have -ffunction-sections then we should emit the global value to a
1075   // uniqued section specifically for it.
1076   bool EmitUniquedSection;
1077   if (Kind.isText())
1078     EmitUniquedSection = TM.getFunctionSections();
1079   else
1080     EmitUniquedSection = TM.getDataSections();
1081 
1082   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1083     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1084     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1085 
1086     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1087     int Selection = getSelectionForCOFF(GO);
1088     if (!Selection)
1089       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1090     const GlobalValue *ComdatGV;
1091     if (GO->hasComdat())
1092       ComdatGV = getComdatGVForCOFF(GO);
1093     else
1094       ComdatGV = GO;
1095 
1096     unsigned UniqueID = MCContext::GenericSectionID;
1097     if (EmitUniquedSection)
1098       UniqueID = NextUniqueID++;
1099 
1100     if (!ComdatGV->hasPrivateLinkage()) {
1101       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1102       StringRef COMDATSymName = Sym->getName();
1103       return getContext().getCOFFSection(Name, Characteristics, Kind,
1104                                          COMDATSymName, Selection, UniqueID);
1105     } else {
1106       SmallString<256> TmpData;
1107       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1108       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1109                                          Selection, UniqueID);
1110     }
1111   }
1112 
1113   if (Kind.isText())
1114     return TextSection;
1115 
1116   if (Kind.isThreadLocal())
1117     return TLSDataSection;
1118 
1119   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1120     return ReadOnlySection;
1121 
1122   // Note: we claim that common symbols are put in BSSSection, but they are
1123   // really emitted with the magic .comm directive, which creates a symbol table
1124   // entry but not a section.
1125   if (Kind.isBSS() || Kind.isCommon())
1126     return BSSSection;
1127 
1128   return DataSection;
1129 }
1130 
1131 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1132     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1133     const TargetMachine &TM) const {
1134   bool CannotUsePrivateLabel = false;
1135   if (GV->hasPrivateLinkage() &&
1136       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1137        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1138     CannotUsePrivateLabel = true;
1139 
1140   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1141 }
1142 
1143 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1144     const Function &F, const TargetMachine &TM) const {
1145   // If the function can be removed, produce a unique section so that
1146   // the table doesn't prevent the removal.
1147   const Comdat *C = F.getComdat();
1148   bool EmitUniqueSection = TM.getFunctionSections() || C;
1149   if (!EmitUniqueSection)
1150     return ReadOnlySection;
1151 
1152   // FIXME: we should produce a symbol for F instead.
1153   if (F.hasPrivateLinkage())
1154     return ReadOnlySection;
1155 
1156   MCSymbol *Sym = TM.getSymbol(&F);
1157   StringRef COMDATSymName = Sym->getName();
1158 
1159   SectionKind Kind = SectionKind::getReadOnly();
1160   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1161   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1162   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1163   unsigned UniqueID = NextUniqueID++;
1164 
1165   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1166                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1167 }
1168 
1169 void TargetLoweringObjectFileCOFF::emitModuleMetadata(
1170     MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1171   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1172     // Emit the linker options to the linker .drectve section.  According to the
1173     // spec, this section is a space-separated string containing flags for
1174     // linker.
1175     MCSection *Sec = getDrectveSection();
1176     Streamer.SwitchSection(Sec);
1177     for (const auto &Option : LinkerOptions->operands()) {
1178       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1179         // Lead with a space for consistency with our dllexport implementation.
1180         std::string Directive(" ");
1181         Directive.append(cast<MDString>(Piece)->getString());
1182         Streamer.EmitBytes(Directive);
1183       }
1184     }
1185   }
1186 
1187   unsigned Version = 0;
1188   unsigned Flags = 0;
1189   StringRef Section;
1190 
1191   GetObjCImageInfo(M, Version, Flags, Section);
1192   if (Section.empty())
1193     return;
1194 
1195   auto &C = getContext();
1196   auto *S = C.getCOFFSection(
1197       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1198       SectionKind::getReadOnly());
1199   Streamer.SwitchSection(S);
1200   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1201   Streamer.EmitIntValue(Version, 4);
1202   Streamer.EmitIntValue(Flags, 4);
1203   Streamer.AddBlankLine();
1204 }
1205 
1206 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1207                                               const TargetMachine &TM) {
1208   TargetLoweringObjectFile::Initialize(Ctx, TM);
1209   const Triple &T = TM.getTargetTriple();
1210   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1211     StaticCtorSection =
1212         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1213                                            COFF::IMAGE_SCN_MEM_READ,
1214                            SectionKind::getReadOnly());
1215     StaticDtorSection =
1216         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1217                                            COFF::IMAGE_SCN_MEM_READ,
1218                            SectionKind::getReadOnly());
1219   } else {
1220     StaticCtorSection = Ctx.getCOFFSection(
1221         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1222                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1223         SectionKind::getData());
1224     StaticDtorSection = Ctx.getCOFFSection(
1225         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1226                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1227         SectionKind::getData());
1228   }
1229 }
1230 
1231 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1232                                                    const Triple &T, bool IsCtor,
1233                                                    unsigned Priority,
1234                                                    const MCSymbol *KeySym,
1235                                                    MCSectionCOFF *Default) {
1236   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
1237     return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1238 
1239   std::string Name = IsCtor ? ".ctors" : ".dtors";
1240   if (Priority != 65535)
1241     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1242 
1243   return Ctx.getAssociativeCOFFSection(
1244       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1245                                    COFF::IMAGE_SCN_MEM_READ |
1246                                    COFF::IMAGE_SCN_MEM_WRITE,
1247                          SectionKind::getData()),
1248       KeySym, 0);
1249 }
1250 
1251 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1252     unsigned Priority, const MCSymbol *KeySym) const {
1253   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1254                                       Priority, KeySym,
1255                                       cast<MCSectionCOFF>(StaticCtorSection));
1256 }
1257 
1258 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1259     unsigned Priority, const MCSymbol *KeySym) const {
1260   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1261                                       Priority, KeySym,
1262                                       cast<MCSectionCOFF>(StaticDtorSection));
1263 }
1264 
1265 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1266     raw_ostream &OS, const GlobalValue *GV) const {
1267   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1268 }
1269 
1270 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1271     raw_ostream &OS, const GlobalValue *GV) const {
1272   emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1273 }
1274 
1275 //===----------------------------------------------------------------------===//
1276 //                                  Wasm
1277 //===----------------------------------------------------------------------===//
1278 
1279 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1280   const Comdat *C = GV->getComdat();
1281   if (!C)
1282     return nullptr;
1283 
1284   if (C->getSelectionKind() != Comdat::Any)
1285     report_fatal_error("WebAssembly COMDATs only support "
1286                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
1287                        "lowered.");
1288 
1289   return C;
1290 }
1291 
1292 static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1293   // If we're told we have function data, then use that.
1294   if (K.isText())
1295     return SectionKind::getText();
1296 
1297   // Otherwise, ignore whatever section type the generic impl detected and use
1298   // a plain data section.
1299   return SectionKind::getData();
1300 }
1301 
1302 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1303     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1304   StringRef Name = GO->getSection();
1305 
1306   Kind = getWasmKindForNamedSection(Name, Kind);
1307 
1308   StringRef Group = "";
1309   if (const Comdat *C = getWasmComdat(GO)) {
1310     Group = C->getName();
1311   }
1312 
1313   return getContext().getWasmSection(Name, Kind, Group,
1314                                      MCContext::GenericSectionID);
1315 }
1316 
1317 static MCSectionWasm *selectWasmSectionForGlobal(
1318     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1319     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1320   StringRef Group = "";
1321   if (const Comdat *C = getWasmComdat(GO)) {
1322     Group = C->getName();
1323   }
1324 
1325   bool UniqueSectionNames = TM.getUniqueSectionNames();
1326   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1327 
1328   if (const auto *F = dyn_cast<Function>(GO)) {
1329     const auto &OptionalPrefix = F->getSectionPrefix();
1330     if (OptionalPrefix)
1331       Name += *OptionalPrefix;
1332   }
1333 
1334   if (EmitUniqueSection && UniqueSectionNames) {
1335     Name.push_back('.');
1336     TM.getNameWithPrefix(Name, GO, Mang, true);
1337   }
1338   unsigned UniqueID = MCContext::GenericSectionID;
1339   if (EmitUniqueSection && !UniqueSectionNames) {
1340     UniqueID = *NextUniqueID;
1341     (*NextUniqueID)++;
1342   }
1343   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1344 }
1345 
1346 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1347     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1348 
1349   if (Kind.isCommon())
1350     report_fatal_error("mergable sections not supported yet on wasm");
1351 
1352   // If we have -ffunction-section or -fdata-section then we should emit the
1353   // global value to a uniqued section specifically for it.
1354   bool EmitUniqueSection = false;
1355   if (Kind.isText())
1356     EmitUniqueSection = TM.getFunctionSections();
1357   else
1358     EmitUniqueSection = TM.getDataSections();
1359   EmitUniqueSection |= GO->hasComdat();
1360 
1361   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1362                                     EmitUniqueSection, &NextUniqueID);
1363 }
1364 
1365 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1366     bool UsesLabelDifference, const Function &F) const {
1367   // We can always create relative relocations, so use another section
1368   // that can be marked non-executable.
1369   return false;
1370 }
1371 
1372 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1373     const GlobalValue *LHS, const GlobalValue *RHS,
1374     const TargetMachine &TM) const {
1375   // We may only use a PLT-relative relocation to refer to unnamed_addr
1376   // functions.
1377   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1378     return nullptr;
1379 
1380   // Basic sanity checks.
1381   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1382       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1383       RHS->isThreadLocal())
1384     return nullptr;
1385 
1386   return MCBinaryExpr::createSub(
1387       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1388                               getContext()),
1389       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1390 }
1391 
1392 void TargetLoweringObjectFileWasm::InitializeWasm() {
1393   StaticCtorSection =
1394       getContext().getWasmSection(".init_array", SectionKind::getData());
1395 }
1396 
1397 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1398     unsigned Priority, const MCSymbol *KeySym) const {
1399   return Priority == UINT16_MAX ?
1400          StaticCtorSection :
1401          getContext().getWasmSection(".init_array." + utostr(Priority),
1402                                      SectionKind::getData());
1403 }
1404 
1405 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1406     unsigned Priority, const MCSymbol *KeySym) const {
1407   llvm_unreachable("@llvm.global_dtors should have been lowered already");
1408   return nullptr;
1409 }
1410