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