xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 68fa249cb5a9755f05e437db618d85e0097de8c3)
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/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 using namespace llvm;
42 using namespace dwarf;
43 
44 //===----------------------------------------------------------------------===//
45 //                                  ELF
46 //===----------------------------------------------------------------------===//
47 
48 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50     MachineModuleInfo *MMI) const {
51   unsigned Encoding = getPersonalityEncoding();
52   if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
53     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
54                                           TM.getSymbol(GV, Mang)->getName());
55   if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
56     return TM.getSymbol(GV, Mang);
57   report_fatal_error("We do not support this DWARF encoding yet!");
58 }
59 
60 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61                                                        const TargetMachine &TM,
62                                                        const MCSymbol *Sym) const {
63   SmallString<64> NameData("DW.ref.");
64   NameData += Sym->getName();
65   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
66   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
68   StringRef Prefix = ".data.";
69   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
70   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
71   const MCSection *Sec = getContext().getELFSection(NameData,
72                                                     ELF::SHT_PROGBITS,
73                                                     Flags,
74                                                     0, Label->getName());
75   unsigned Size = TM.getDataLayout()->getPointerSize();
76   Streamer.SwitchSection(Sec);
77   Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
78   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
79   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
80   Streamer.EmitELFSize(Label, E);
81   Streamer.EmitLabel(Label);
82 
83   Streamer.EmitSymbolValue(Sym, Size);
84 }
85 
86 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
88     const TargetMachine &TM, MachineModuleInfo *MMI,
89     MCStreamer &Streamer) const {
90 
91   if (Encoding & dwarf::DW_EH_PE_indirect) {
92     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
93 
94     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
95 
96     // Add information about the stub reference to ELFMMI so that the stub
97     // gets emitted by the asmprinter.
98     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
99     if (!StubSym.getPointer()) {
100       MCSymbol *Sym = TM.getSymbol(GV, Mang);
101       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
102     }
103 
104     return TargetLoweringObjectFile::
105       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
107   }
108 
109   return TargetLoweringObjectFile::
110     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
111 }
112 
113 static SectionKind
114 getELFKindForNamedSection(StringRef Name, SectionKind K) {
115   // N.B.: The defaults used in here are no the same ones used in MC.
116   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
117   // both gas and MC will produce a section with no flags. Given
118   // section(".eh_frame") gcc will produce:
119   //
120   //   .section   .eh_frame,"a",@progbits
121   if (Name.empty() || Name[0] != '.') return K;
122 
123   // Some lame default implementation based on some magic section names.
124   if (Name == ".bss" ||
125       Name.startswith(".bss.") ||
126       Name.startswith(".gnu.linkonce.b.") ||
127       Name.startswith(".llvm.linkonce.b.") ||
128       Name == ".sbss" ||
129       Name.startswith(".sbss.") ||
130       Name.startswith(".gnu.linkonce.sb.") ||
131       Name.startswith(".llvm.linkonce.sb."))
132     return SectionKind::getBSS();
133 
134   if (Name == ".tdata" ||
135       Name.startswith(".tdata.") ||
136       Name.startswith(".gnu.linkonce.td.") ||
137       Name.startswith(".llvm.linkonce.td."))
138     return SectionKind::getThreadData();
139 
140   if (Name == ".tbss" ||
141       Name.startswith(".tbss.") ||
142       Name.startswith(".gnu.linkonce.tb.") ||
143       Name.startswith(".llvm.linkonce.tb."))
144     return SectionKind::getThreadBSS();
145 
146   return K;
147 }
148 
149 
150 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
151 
152   if (Name == ".init_array")
153     return ELF::SHT_INIT_ARRAY;
154 
155   if (Name == ".fini_array")
156     return ELF::SHT_FINI_ARRAY;
157 
158   if (Name == ".preinit_array")
159     return ELF::SHT_PREINIT_ARRAY;
160 
161   if (K.isBSS() || K.isThreadBSS())
162     return ELF::SHT_NOBITS;
163 
164   return ELF::SHT_PROGBITS;
165 }
166 
167 
168 static unsigned
169 getELFSectionFlags(SectionKind K, bool InCOMDAT) {
170   unsigned Flags = 0;
171 
172   if (!K.isMetadata())
173     Flags |= ELF::SHF_ALLOC;
174 
175   if (K.isText())
176     Flags |= ELF::SHF_EXECINSTR;
177 
178   if (K.isWriteable())
179     Flags |= ELF::SHF_WRITE;
180 
181   if (K.isThreadLocal())
182     Flags |= ELF::SHF_TLS;
183 
184   // FIXME: There is nothing in ELF preventing an SHF_MERGE from being
185   // in a comdat. We just avoid it for now because we don't print
186   // those .sections correctly.
187   if (!InCOMDAT && (K.isMergeableCString() || K.isMergeableConst()))
188     Flags |= ELF::SHF_MERGE;
189 
190   if (K.isMergeableCString())
191     Flags |= ELF::SHF_STRINGS;
192 
193   return Flags;
194 }
195 
196 static const Comdat *getELFComdat(const GlobalValue *GV) {
197   const Comdat *C = GV->getComdat();
198   if (!C)
199     return nullptr;
200 
201   if (C->getSelectionKind() != Comdat::Any)
202     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
203                        C->getName() + "' cannot be lowered.");
204 
205   return C;
206 }
207 
208 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
209     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
210     const TargetMachine &TM) const {
211   StringRef SectionName = GV->getSection();
212 
213   // Infer section flags from the section name if we can.
214   Kind = getELFKindForNamedSection(SectionName, Kind);
215 
216   StringRef Group = "";
217   unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
218   if (const Comdat *C = getELFComdat(GV)) {
219     Group = C->getName();
220     Flags |= ELF::SHF_GROUP;
221   }
222   return getContext().getELFSection(SectionName,
223                                     getELFSectionType(SectionName, Kind), Flags,
224                                     /*EntrySize=*/0, Group);
225 }
226 
227 /// Return the section prefix name used by options FunctionsSections and
228 /// DataSections.
229 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
230   if (Kind.isText())
231     return ".text";
232   if (Kind.isReadOnly())
233     return ".rodata";
234   if (Kind.isBSS())
235     return ".bss";
236   if (Kind.isThreadData())
237     return ".tdata";
238   if (Kind.isThreadBSS())
239     return ".tbss";
240   if (Kind.isDataNoRel())
241     return ".data";
242   if (Kind.isDataRelLocal())
243     return ".data.rel.local";
244   if (Kind.isDataRel())
245     return ".data.rel";
246   if (Kind.isReadOnlyWithRelLocal())
247     return ".data.rel.ro.local";
248   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
249   return ".data.rel.ro";
250 }
251 
252 const MCSection *TargetLoweringObjectFileELF::
253 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
254                        Mangler &Mang, const TargetMachine &TM) const {
255   unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
256 
257   // If we have -ffunction-section or -fdata-section then we should emit the
258   // global value to a uniqued section specifically for it.
259   bool EmitUniquedSection = false;
260   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
261     if (Kind.isText())
262       EmitUniquedSection = TM.getFunctionSections();
263     else
264       EmitUniquedSection = TM.getDataSections();
265   }
266 
267   if (EmitUniquedSection || GV->hasComdat()) {
268     StringRef Prefix = getSectionPrefixForGlobal(Kind);
269 
270     SmallString<128> Name(Prefix);
271     bool UniqueSectionNames = TM.getUniqueSectionNames();
272     if (UniqueSectionNames) {
273       Name.push_back('.');
274       TM.getNameWithPrefix(Name, GV, Mang, true);
275     }
276     StringRef Group = "";
277     if (const Comdat *C = getELFComdat(GV)) {
278       Flags |= ELF::SHF_GROUP;
279       Group = C->getName();
280     }
281 
282     return getContext().getELFSection(Name, getELFSectionType(Name, Kind),
283                                       Flags, 0, Group, !UniqueSectionNames);
284   }
285 
286   if (Kind.isText()) return TextSection;
287 
288   if (Kind.isMergeableCString()) {
289 
290     // We also need alignment here.
291     // FIXME: this is getting the alignment of the character, not the
292     // alignment of the global!
293     unsigned Align =
294         TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
295 
296     unsigned EntrySize = 1;
297     if (Kind.isMergeable2ByteCString())
298       EntrySize = 2;
299     else if (Kind.isMergeable4ByteCString())
300       EntrySize = 4;
301     else
302       assert(Kind.isMergeable1ByteCString() && "unknown string width");
303 
304     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
305     std::string Name = SizeSpec + utostr(Align);
306     return getContext().getELFSection(
307         Name, ELF::SHT_PROGBITS,
308         ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
309   }
310 
311   if (Kind.isMergeableConst()) {
312     if (Kind.isMergeableConst4() && MergeableConst4Section)
313       return MergeableConst4Section;
314     if (Kind.isMergeableConst8() && MergeableConst8Section)
315       return MergeableConst8Section;
316     if (Kind.isMergeableConst16() && MergeableConst16Section)
317       return MergeableConst16Section;
318     return ReadOnlySection;  // .const
319   }
320 
321   if (Kind.isReadOnly())             return ReadOnlySection;
322 
323   if (Kind.isThreadData())           return TLSDataSection;
324   if (Kind.isThreadBSS())            return TLSBSSSection;
325 
326   // Note: we claim that common symbols are put in BSSSection, but they are
327   // really emitted with the magic .comm directive, which creates a symbol table
328   // entry but not a section.
329   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
330 
331   if (Kind.isDataNoRel())            return DataSection;
332   if (Kind.isDataRelLocal())         return DataRelLocalSection;
333   if (Kind.isDataRel())              return DataRelSection;
334   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
335 
336   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
337   return DataRelROSection;
338 }
339 
340 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
341     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
342   // If the function can be removed, produce a unique section so that
343   // the table doesn't prevent the removal.
344   const Comdat *C = F.getComdat();
345   bool EmitUniqueSection = TM.getFunctionSections() || C;
346   if (!EmitUniqueSection)
347     return ReadOnlySection;
348 
349   SmallString<128> Name(".rodata.");
350   TM.getNameWithPrefix(Name, &F, Mang, true);
351 
352   unsigned Flags = ELF::SHF_ALLOC;
353   StringRef Group = "";
354   if (C) {
355     Flags |= ELF::SHF_GROUP;
356     Group = C->getName();
357   }
358 
359   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 0, Group);
360 }
361 
362 /// getSectionForConstant - Given a mergeable constant with the
363 /// specified size and relocation information, return a section that it
364 /// should be placed in.
365 const MCSection *
366 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
367                                                    const Constant *C) const {
368   if (Kind.isMergeableConst4() && MergeableConst4Section)
369     return MergeableConst4Section;
370   if (Kind.isMergeableConst8() && MergeableConst8Section)
371     return MergeableConst8Section;
372   if (Kind.isMergeableConst16() && MergeableConst16Section)
373     return MergeableConst16Section;
374   if (Kind.isReadOnly())
375     return ReadOnlySection;
376 
377   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
378   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
379   return DataRelROSection;
380 }
381 
382 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
383                                                     bool UseInitArray,
384                                                     bool IsCtor,
385                                                     unsigned Priority,
386                                                     const MCSymbol *KeySym) {
387   std::string Name;
388   unsigned Type;
389   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
390   StringRef COMDAT = KeySym ? KeySym->getName() : "";
391 
392   if (KeySym)
393     Flags |= ELF::SHF_GROUP;
394 
395   if (UseInitArray) {
396     if (IsCtor) {
397       Type = ELF::SHT_INIT_ARRAY;
398       Name = ".init_array";
399     } else {
400       Type = ELF::SHT_FINI_ARRAY;
401       Name = ".fini_array";
402     }
403     if (Priority != 65535) {
404       Name += '.';
405       Name += utostr(Priority);
406     }
407   } else {
408     // The default scheme is .ctor / .dtor, so we have to invert the priority
409     // numbering.
410     if (IsCtor)
411       Name = ".ctors";
412     else
413       Name = ".dtors";
414     if (Priority != 65535) {
415       Name += '.';
416       Name += utostr(65535 - Priority);
417     }
418     Type = ELF::SHT_PROGBITS;
419   }
420 
421   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
422 }
423 
424 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
425     unsigned Priority, const MCSymbol *KeySym) const {
426   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
427                                   KeySym);
428 }
429 
430 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
431     unsigned Priority, const MCSymbol *KeySym) const {
432   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
433                                   KeySym);
434 }
435 
436 void
437 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
438   UseInitArray = UseInitArray_;
439   if (!UseInitArray)
440     return;
441 
442   StaticCtorSection = getContext().getELFSection(
443       ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
444   StaticDtorSection = getContext().getELFSection(
445       ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
446 }
447 
448 //===----------------------------------------------------------------------===//
449 //                                 MachO
450 //===----------------------------------------------------------------------===//
451 
452 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
453 /// option string. Returns StringRef() if the option does not specify a library.
454 StringRef TargetLoweringObjectFileMachO::
455 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
456   const char *LibCmd = "-l";
457   if (LinkerOption.startswith(LibCmd))
458     return LinkerOption.substr(strlen(LibCmd));
459   return StringRef();
460 }
461 
462 /// emitModuleFlags - Perform code emission for module flags.
463 void TargetLoweringObjectFileMachO::
464 emitModuleFlags(MCStreamer &Streamer,
465                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
466                 Mangler &Mang, const TargetMachine &TM) const {
467   unsigned VersionVal = 0;
468   unsigned ImageInfoFlags = 0;
469   MDNode *LinkerOptions = nullptr;
470   StringRef SectionVal;
471 
472   for (ArrayRef<Module::ModuleFlagEntry>::iterator
473          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
474     const Module::ModuleFlagEntry &MFE = *i;
475 
476     // Ignore flags with 'Require' behavior.
477     if (MFE.Behavior == Module::Require)
478       continue;
479 
480     StringRef Key = MFE.Key->getString();
481     Metadata *Val = MFE.Val;
482 
483     if (Key == "Objective-C Image Info Version") {
484       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
485     } else if (Key == "Objective-C Garbage Collection" ||
486                Key == "Objective-C GC Only" ||
487                Key == "Objective-C Is Simulated" ||
488                Key == "Objective-C Image Swift Version") {
489       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
490     } else if (Key == "Objective-C Image Info Section") {
491       SectionVal = cast<MDString>(Val)->getString();
492     } else if (Key == "Linker Options") {
493       LinkerOptions = cast<MDNode>(Val);
494     }
495   }
496 
497   // Emit the linker options if present.
498   if (LinkerOptions) {
499     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
500       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
501       SmallVector<std::string, 4> StrOptions;
502 
503       // Convert to strings.
504       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
505         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
506         StrOptions.push_back(MDOption->getString());
507       }
508 
509       Streamer.EmitLinkerOptions(StrOptions);
510     }
511   }
512 
513   // The section is mandatory. If we don't have it, then we don't have GC info.
514   if (SectionVal.empty()) return;
515 
516   StringRef Segment, Section;
517   unsigned TAA = 0, StubSize = 0;
518   bool TAAParsed;
519   std::string ErrorCode =
520     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
521                                           TAA, TAAParsed, StubSize);
522   if (!ErrorCode.empty())
523     // If invalid, report the error with report_fatal_error.
524     report_fatal_error("Invalid section specifier '" + Section + "': " +
525                        ErrorCode + ".");
526 
527   // Get the section.
528   const MCSectionMachO *S =
529     getContext().getMachOSection(Segment, Section, TAA, StubSize,
530                                  SectionKind::getDataNoRel());
531   Streamer.SwitchSection(S);
532   Streamer.EmitLabel(getContext().
533                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
534   Streamer.EmitIntValue(VersionVal, 4);
535   Streamer.EmitIntValue(ImageInfoFlags, 4);
536   Streamer.AddBlankLine();
537 }
538 
539 static void checkMachOComdat(const GlobalValue *GV) {
540   const Comdat *C = GV->getComdat();
541   if (!C)
542     return;
543 
544   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
545                      "' cannot be lowered.");
546 }
547 
548 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
549     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
550     const TargetMachine &TM) const {
551   // Parse the section specifier and create it if valid.
552   StringRef Segment, Section;
553   unsigned TAA = 0, StubSize = 0;
554   bool TAAParsed;
555 
556   checkMachOComdat(GV);
557 
558   std::string ErrorCode =
559     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
560                                           TAA, TAAParsed, StubSize);
561   if (!ErrorCode.empty()) {
562     // If invalid, report the error with report_fatal_error.
563     report_fatal_error("Global variable '" + GV->getName() +
564                        "' has an invalid section specifier '" +
565                        GV->getSection() + "': " + ErrorCode + ".");
566   }
567 
568   // Get the section.
569   const MCSectionMachO *S =
570     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
571 
572   // If TAA wasn't set by ParseSectionSpecifier() above,
573   // use the value returned by getMachOSection() as a default.
574   if (!TAAParsed)
575     TAA = S->getTypeAndAttributes();
576 
577   // Okay, now that we got the section, verify that the TAA & StubSize agree.
578   // If the user declared multiple globals with different section flags, we need
579   // to reject it here.
580   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
581     // If invalid, report the error with report_fatal_error.
582     report_fatal_error("Global variable '" + GV->getName() +
583                        "' section type or attributes does not match previous"
584                        " section specifier");
585   }
586 
587   return S;
588 }
589 
590 const MCSection *TargetLoweringObjectFileMachO::
591 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
592                        Mangler &Mang, const TargetMachine &TM) const {
593   checkMachOComdat(GV);
594 
595   // Handle thread local data.
596   if (Kind.isThreadBSS()) return TLSBSSSection;
597   if (Kind.isThreadData()) return TLSDataSection;
598 
599   if (Kind.isText())
600     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
601 
602   // If this is weak/linkonce, put this in a coalescable section, either in text
603   // or data depending on if it is writable.
604   if (GV->isWeakForLinker()) {
605     if (Kind.isReadOnly())
606       return ConstTextCoalSection;
607     return DataCoalSection;
608   }
609 
610   // FIXME: Alignment check should be handled by section classifier.
611   if (Kind.isMergeable1ByteCString() &&
612       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
613     return CStringSection;
614 
615   // Do not put 16-bit arrays in the UString section if they have an
616   // externally visible label, this runs into issues with certain linker
617   // versions.
618   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
619       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
620     return UStringSection;
621 
622   // With MachO only variables whose corresponding symbol starts with 'l' or
623   // 'L' can be merged, so we only try merging GVs with private linkage.
624   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
625     if (Kind.isMergeableConst4())
626       return FourByteConstantSection;
627     if (Kind.isMergeableConst8())
628       return EightByteConstantSection;
629     if (Kind.isMergeableConst16())
630       return SixteenByteConstantSection;
631   }
632 
633   // Otherwise, if it is readonly, but not something we can specially optimize,
634   // just drop it in .const.
635   if (Kind.isReadOnly())
636     return ReadOnlySection;
637 
638   // If this is marked const, put it into a const section.  But if the dynamic
639   // linker needs to write to it, put it in the data segment.
640   if (Kind.isReadOnlyWithRel())
641     return ConstDataSection;
642 
643   // Put zero initialized globals with strong external linkage in the
644   // DATA, __common section with the .zerofill directive.
645   if (Kind.isBSSExtern())
646     return DataCommonSection;
647 
648   // Put zero initialized globals with local linkage in __DATA,__bss directive
649   // with the .zerofill directive (aka .lcomm).
650   if (Kind.isBSSLocal())
651     return DataBSSSection;
652 
653   // Otherwise, just drop the variable in the normal data section.
654   return DataSection;
655 }
656 
657 const MCSection *
658 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
659                                                      const Constant *C) const {
660   // If this constant requires a relocation, we have to put it in the data
661   // segment, not in the text segment.
662   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
663     return ConstDataSection;
664 
665   if (Kind.isMergeableConst4())
666     return FourByteConstantSection;
667   if (Kind.isMergeableConst8())
668     return EightByteConstantSection;
669   if (Kind.isMergeableConst16())
670     return SixteenByteConstantSection;
671   return ReadOnlySection;  // .const
672 }
673 
674 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
675     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
676     const TargetMachine &TM, MachineModuleInfo *MMI,
677     MCStreamer &Streamer) const {
678   // The mach-o version of this method defaults to returning a stub reference.
679 
680   if (Encoding & DW_EH_PE_indirect) {
681     MachineModuleInfoMachO &MachOMMI =
682       MMI->getObjFileInfo<MachineModuleInfoMachO>();
683 
684     MCSymbol *SSym =
685         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
686 
687     // Add information about the stub reference to MachOMMI so that the stub
688     // gets emitted by the asmprinter.
689     MachineModuleInfoImpl::StubValueTy &StubSym =
690       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
691                                   MachOMMI.getGVStubEntry(SSym);
692     if (!StubSym.getPointer()) {
693       MCSymbol *Sym = TM.getSymbol(GV, Mang);
694       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
695     }
696 
697     return TargetLoweringObjectFile::
698       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
699                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
700   }
701 
702   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
703                                                            TM, MMI, Streamer);
704 }
705 
706 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
707     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
708     MachineModuleInfo *MMI) const {
709   // The mach-o version of this method defaults to returning a stub reference.
710   MachineModuleInfoMachO &MachOMMI =
711     MMI->getObjFileInfo<MachineModuleInfoMachO>();
712 
713   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
714 
715   // Add information about the stub reference to MachOMMI so that the stub
716   // gets emitted by the asmprinter.
717   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
718   if (!StubSym.getPointer()) {
719     MCSymbol *Sym = TM.getSymbol(GV, Mang);
720     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
721   }
722 
723   return SSym;
724 }
725 
726 //===----------------------------------------------------------------------===//
727 //                                  COFF
728 //===----------------------------------------------------------------------===//
729 
730 static unsigned
731 getCOFFSectionFlags(SectionKind K) {
732   unsigned Flags = 0;
733 
734   if (K.isMetadata())
735     Flags |=
736       COFF::IMAGE_SCN_MEM_DISCARDABLE;
737   else if (K.isText())
738     Flags |=
739       COFF::IMAGE_SCN_MEM_EXECUTE |
740       COFF::IMAGE_SCN_MEM_READ |
741       COFF::IMAGE_SCN_CNT_CODE;
742   else if (K.isBSS())
743     Flags |=
744       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
745       COFF::IMAGE_SCN_MEM_READ |
746       COFF::IMAGE_SCN_MEM_WRITE;
747   else if (K.isThreadLocal())
748     Flags |=
749       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
750       COFF::IMAGE_SCN_MEM_READ |
751       COFF::IMAGE_SCN_MEM_WRITE;
752   else if (K.isReadOnly() || K.isReadOnlyWithRel())
753     Flags |=
754       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
755       COFF::IMAGE_SCN_MEM_READ;
756   else if (K.isWriteable())
757     Flags |=
758       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
759       COFF::IMAGE_SCN_MEM_READ |
760       COFF::IMAGE_SCN_MEM_WRITE;
761 
762   return Flags;
763 }
764 
765 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
766   const Comdat *C = GV->getComdat();
767   assert(C && "expected GV to have a Comdat!");
768 
769   StringRef ComdatGVName = C->getName();
770   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
771   if (!ComdatGV)
772     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
773                        "' does not exist.");
774 
775   if (ComdatGV->getComdat() != C)
776     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
777                        "' is not a key for its COMDAT.");
778 
779   return ComdatGV;
780 }
781 
782 static int getSelectionForCOFF(const GlobalValue *GV) {
783   if (const Comdat *C = GV->getComdat()) {
784     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
785     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
786       ComdatKey = GA->getBaseObject();
787     if (ComdatKey == GV) {
788       switch (C->getSelectionKind()) {
789       case Comdat::Any:
790         return COFF::IMAGE_COMDAT_SELECT_ANY;
791       case Comdat::ExactMatch:
792         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
793       case Comdat::Largest:
794         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
795       case Comdat::NoDuplicates:
796         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
797       case Comdat::SameSize:
798         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
799       }
800     } else {
801       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
802     }
803   } else if (GV->isWeakForLinker()) {
804     return COFF::IMAGE_COMDAT_SELECT_ANY;
805   }
806   return 0;
807 }
808 
809 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
810     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
811     const TargetMachine &TM) const {
812   int Selection = 0;
813   unsigned Characteristics = getCOFFSectionFlags(Kind);
814   StringRef Name = GV->getSection();
815   StringRef COMDATSymName = "";
816   if (GV->hasComdat()) {
817     Selection = getSelectionForCOFF(GV);
818     const GlobalValue *ComdatGV;
819     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
820       ComdatGV = getComdatGVForCOFF(GV);
821     else
822       ComdatGV = GV;
823 
824     if (!ComdatGV->hasPrivateLinkage()) {
825       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
826       COMDATSymName = Sym->getName();
827       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
828     } else {
829       Selection = 0;
830     }
831   }
832   return getContext().getCOFFSection(Name,
833                                      Characteristics,
834                                      Kind,
835                                      COMDATSymName,
836                                      Selection);
837 }
838 
839 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
840   if (Kind.isText())
841     return ".text";
842   if (Kind.isBSS())
843     return ".bss";
844   if (Kind.isThreadLocal())
845     return ".tls$";
846   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
847     return ".rdata";
848   return ".data";
849 }
850 
851 
852 const MCSection *TargetLoweringObjectFileCOFF::
853 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
854                        Mangler &Mang, const TargetMachine &TM) const {
855   // If we have -ffunction-sections then we should emit the global value to a
856   // uniqued section specifically for it.
857   bool EmitUniquedSection;
858   if (Kind.isText())
859     EmitUniquedSection = TM.getFunctionSections();
860   else
861     EmitUniquedSection = TM.getDataSections();
862 
863   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
864     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
865     unsigned Characteristics = getCOFFSectionFlags(Kind);
866 
867     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
868     int Selection = getSelectionForCOFF(GV);
869     if (!Selection)
870       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
871     const GlobalValue *ComdatGV;
872     if (GV->hasComdat())
873       ComdatGV = getComdatGVForCOFF(GV);
874     else
875       ComdatGV = GV;
876 
877     if (!ComdatGV->hasPrivateLinkage()) {
878       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
879       StringRef COMDATSymName = Sym->getName();
880       return getContext().getCOFFSection(Name, Characteristics, Kind,
881                                          COMDATSymName, Selection);
882     }
883   }
884 
885   if (Kind.isText())
886     return TextSection;
887 
888   if (Kind.isThreadLocal())
889     return TLSDataSection;
890 
891   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
892     return ReadOnlySection;
893 
894   // Note: we claim that common symbols are put in BSSSection, but they are
895   // really emitted with the magic .comm directive, which creates a symbol table
896   // entry but not a section.
897   if (Kind.isBSS() || Kind.isCommon())
898     return BSSSection;
899 
900   return DataSection;
901 }
902 
903 StringRef TargetLoweringObjectFileCOFF::
904 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
905   const char *LibCmd = "/DEFAULTLIB:";
906   if (LinkerOption.startswith(LibCmd))
907     return LinkerOption.substr(strlen(LibCmd));
908   return StringRef();
909 }
910 
911 void TargetLoweringObjectFileCOFF::
912 emitModuleFlags(MCStreamer &Streamer,
913                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
914                 Mangler &Mang, const TargetMachine &TM) const {
915   MDNode *LinkerOptions = nullptr;
916 
917   // Look for the "Linker Options" flag, since it's the only one we support.
918   for (ArrayRef<Module::ModuleFlagEntry>::iterator
919        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
920     const Module::ModuleFlagEntry &MFE = *i;
921     StringRef Key = MFE.Key->getString();
922     Metadata *Val = MFE.Val;
923     if (Key == "Linker Options") {
924       LinkerOptions = cast<MDNode>(Val);
925       break;
926     }
927   }
928   if (!LinkerOptions)
929     return;
930 
931   // Emit the linker options to the linker .drectve section.  According to the
932   // spec, this section is a space-separated string containing flags for linker.
933   const MCSection *Sec = getDrectveSection();
934   Streamer.SwitchSection(Sec);
935   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
936     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
937     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
938       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
939       // Lead with a space for consistency with our dllexport implementation.
940       std::string Directive(" ");
941       Directive.append(MDOption->getString());
942       Streamer.EmitBytes(Directive);
943     }
944   }
945 }
946 
947 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
948     unsigned Priority, const MCSymbol *KeySym) const {
949   return getContext().getAssociativeCOFFSection(
950       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
951 }
952 
953 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
954     unsigned Priority, const MCSymbol *KeySym) const {
955   return getContext().getAssociativeCOFFSection(
956       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
957 }
958