Use short names for jumptable sections.
[oota-llvm.git] / lib / CodeGen / TargetLoweringObjectFileImpl.cpp
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 static const MCSection *
253 getUniqueELFSection(MCContext &Ctx, const GlobalValue &GV, SectionKind Kind,
254                     Mangler &Mang, const TargetMachine &TM, unsigned Flags) {
255   StringRef Prefix = getSectionPrefixForGlobal(Kind);
256
257   SmallString<128> Name(Prefix);
258   bool UniqueSectionNames = TM.getUniqueSectionNames();
259   if (UniqueSectionNames) {
260     Name.push_back('.');
261     TM.getNameWithPrefix(Name, &GV, Mang, true);
262   }
263   StringRef Group = "";
264   if (const Comdat *C = getELFComdat(&GV)) {
265     Flags |= ELF::SHF_GROUP;
266     Group = C->getName();
267   }
268
269   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 0, Group,
270                            !UniqueSectionNames);
271 }
272
273 const MCSection *TargetLoweringObjectFileELF::
274 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
275                        Mangler &Mang, const TargetMachine &TM) const {
276   unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
277
278   // If we have -ffunction-section or -fdata-section then we should emit the
279   // global value to a uniqued section specifically for it.
280   bool EmitUniquedSection = false;
281   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
282     if (Kind.isText())
283       EmitUniquedSection = TM.getFunctionSections();
284     else
285       EmitUniquedSection = TM.getDataSections();
286   }
287
288   if (EmitUniquedSection || GV->hasComdat())
289     return getUniqueELFSection(getContext(), *GV, Kind, Mang, TM, Flags);
290
291   if (Kind.isText()) return TextSection;
292
293   if (Kind.isMergeableCString()) {
294
295     // We also need alignment here.
296     // FIXME: this is getting the alignment of the character, not the
297     // alignment of the global!
298     unsigned Align =
299         TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
300
301     unsigned EntrySize = 1;
302     if (Kind.isMergeable2ByteCString())
303       EntrySize = 2;
304     else if (Kind.isMergeable4ByteCString())
305       EntrySize = 4;
306     else
307       assert(Kind.isMergeable1ByteCString() && "unknown string width");
308
309     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
310     std::string Name = SizeSpec + utostr(Align);
311     return getContext().getELFSection(
312         Name, ELF::SHT_PROGBITS,
313         ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
314   }
315
316   if (Kind.isMergeableConst()) {
317     if (Kind.isMergeableConst4() && MergeableConst4Section)
318       return MergeableConst4Section;
319     if (Kind.isMergeableConst8() && MergeableConst8Section)
320       return MergeableConst8Section;
321     if (Kind.isMergeableConst16() && MergeableConst16Section)
322       return MergeableConst16Section;
323     return ReadOnlySection;  // .const
324   }
325
326   if (Kind.isReadOnly())             return ReadOnlySection;
327
328   if (Kind.isThreadData())           return TLSDataSection;
329   if (Kind.isThreadBSS())            return TLSBSSSection;
330
331   // Note: we claim that common symbols are put in BSSSection, but they are
332   // really emitted with the magic .comm directive, which creates a symbol table
333   // entry but not a section.
334   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
335
336   if (Kind.isDataNoRel())            return DataSection;
337   if (Kind.isDataRelLocal())         return DataRelLocalSection;
338   if (Kind.isDataRel())              return DataRelSection;
339   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
340
341   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
342   return DataRelROSection;
343 }
344
345 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
346     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
347   // If the function can be removed, produce a unique section so that
348   // the table doesn't prevent the removal.
349   const Comdat *C = F.getComdat();
350   bool EmitUniqueSection = TM.getFunctionSections() || C;
351   if (!EmitUniqueSection)
352     return ReadOnlySection;
353
354   return getUniqueELFSection(getContext(), F, SectionKind::getReadOnly(), Mang,
355                              TM, ELF::SHF_ALLOC);
356 }
357
358 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
359     bool UsesLabelDifference, const Function &F) const {
360   // We can always create relative relocations, so use another section
361   // that can be marked non-executable.
362   return false;
363 }
364
365 /// getSectionForConstant - Given a mergeable constant with the
366 /// specified size and relocation information, return a section that it
367 /// should be placed in.
368 const MCSection *
369 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
370                                                    const Constant *C) const {
371   if (Kind.isMergeableConst4() && MergeableConst4Section)
372     return MergeableConst4Section;
373   if (Kind.isMergeableConst8() && MergeableConst8Section)
374     return MergeableConst8Section;
375   if (Kind.isMergeableConst16() && MergeableConst16Section)
376     return MergeableConst16Section;
377   if (Kind.isReadOnly())
378     return ReadOnlySection;
379
380   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
381   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
382   return DataRelROSection;
383 }
384
385 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
386                                                     bool UseInitArray,
387                                                     bool IsCtor,
388                                                     unsigned Priority,
389                                                     const MCSymbol *KeySym) {
390   std::string Name;
391   unsigned Type;
392   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
393   StringRef COMDAT = KeySym ? KeySym->getName() : "";
394
395   if (KeySym)
396     Flags |= ELF::SHF_GROUP;
397
398   if (UseInitArray) {
399     if (IsCtor) {
400       Type = ELF::SHT_INIT_ARRAY;
401       Name = ".init_array";
402     } else {
403       Type = ELF::SHT_FINI_ARRAY;
404       Name = ".fini_array";
405     }
406     if (Priority != 65535) {
407       Name += '.';
408       Name += utostr(Priority);
409     }
410   } else {
411     // The default scheme is .ctor / .dtor, so we have to invert the priority
412     // numbering.
413     if (IsCtor)
414       Name = ".ctors";
415     else
416       Name = ".dtors";
417     if (Priority != 65535) {
418       Name += '.';
419       Name += utostr(65535 - Priority);
420     }
421     Type = ELF::SHT_PROGBITS;
422   }
423
424   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
425 }
426
427 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
428     unsigned Priority, const MCSymbol *KeySym) const {
429   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
430                                   KeySym);
431 }
432
433 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
434     unsigned Priority, const MCSymbol *KeySym) const {
435   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
436                                   KeySym);
437 }
438
439 void
440 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
441   UseInitArray = UseInitArray_;
442   if (!UseInitArray)
443     return;
444
445   StaticCtorSection = getContext().getELFSection(
446       ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
447   StaticDtorSection = getContext().getELFSection(
448       ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
449 }
450
451 //===----------------------------------------------------------------------===//
452 //                                 MachO
453 //===----------------------------------------------------------------------===//
454
455 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
456 /// option string. Returns StringRef() if the option does not specify a library.
457 StringRef TargetLoweringObjectFileMachO::
458 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
459   const char *LibCmd = "-l";
460   if (LinkerOption.startswith(LibCmd))
461     return LinkerOption.substr(strlen(LibCmd));
462   return StringRef();
463 }
464
465 /// emitModuleFlags - Perform code emission for module flags.
466 void TargetLoweringObjectFileMachO::
467 emitModuleFlags(MCStreamer &Streamer,
468                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
469                 Mangler &Mang, const TargetMachine &TM) const {
470   unsigned VersionVal = 0;
471   unsigned ImageInfoFlags = 0;
472   MDNode *LinkerOptions = nullptr;
473   StringRef SectionVal;
474
475   for (ArrayRef<Module::ModuleFlagEntry>::iterator
476          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
477     const Module::ModuleFlagEntry &MFE = *i;
478
479     // Ignore flags with 'Require' behavior.
480     if (MFE.Behavior == Module::Require)
481       continue;
482
483     StringRef Key = MFE.Key->getString();
484     Metadata *Val = MFE.Val;
485
486     if (Key == "Objective-C Image Info Version") {
487       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
488     } else if (Key == "Objective-C Garbage Collection" ||
489                Key == "Objective-C GC Only" ||
490                Key == "Objective-C Is Simulated" ||
491                Key == "Objective-C Image Swift Version") {
492       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
493     } else if (Key == "Objective-C Image Info Section") {
494       SectionVal = cast<MDString>(Val)->getString();
495     } else if (Key == "Linker Options") {
496       LinkerOptions = cast<MDNode>(Val);
497     }
498   }
499
500   // Emit the linker options if present.
501   if (LinkerOptions) {
502     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
503       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
504       SmallVector<std::string, 4> StrOptions;
505
506       // Convert to strings.
507       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
508         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
509         StrOptions.push_back(MDOption->getString());
510       }
511
512       Streamer.EmitLinkerOptions(StrOptions);
513     }
514   }
515
516   // The section is mandatory. If we don't have it, then we don't have GC info.
517   if (SectionVal.empty()) return;
518
519   StringRef Segment, Section;
520   unsigned TAA = 0, StubSize = 0;
521   bool TAAParsed;
522   std::string ErrorCode =
523     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
524                                           TAA, TAAParsed, StubSize);
525   if (!ErrorCode.empty())
526     // If invalid, report the error with report_fatal_error.
527     report_fatal_error("Invalid section specifier '" + Section + "': " +
528                        ErrorCode + ".");
529
530   // Get the section.
531   const MCSectionMachO *S =
532     getContext().getMachOSection(Segment, Section, TAA, StubSize,
533                                  SectionKind::getDataNoRel());
534   Streamer.SwitchSection(S);
535   Streamer.EmitLabel(getContext().
536                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
537   Streamer.EmitIntValue(VersionVal, 4);
538   Streamer.EmitIntValue(ImageInfoFlags, 4);
539   Streamer.AddBlankLine();
540 }
541
542 static void checkMachOComdat(const GlobalValue *GV) {
543   const Comdat *C = GV->getComdat();
544   if (!C)
545     return;
546
547   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
548                      "' cannot be lowered.");
549 }
550
551 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
552     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
553     const TargetMachine &TM) const {
554   // Parse the section specifier and create it if valid.
555   StringRef Segment, Section;
556   unsigned TAA = 0, StubSize = 0;
557   bool TAAParsed;
558
559   checkMachOComdat(GV);
560
561   std::string ErrorCode =
562     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
563                                           TAA, TAAParsed, StubSize);
564   if (!ErrorCode.empty()) {
565     // If invalid, report the error with report_fatal_error.
566     report_fatal_error("Global variable '" + GV->getName() +
567                        "' has an invalid section specifier '" +
568                        GV->getSection() + "': " + ErrorCode + ".");
569   }
570
571   // Get the section.
572   const MCSectionMachO *S =
573     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
574
575   // If TAA wasn't set by ParseSectionSpecifier() above,
576   // use the value returned by getMachOSection() as a default.
577   if (!TAAParsed)
578     TAA = S->getTypeAndAttributes();
579
580   // Okay, now that we got the section, verify that the TAA & StubSize agree.
581   // If the user declared multiple globals with different section flags, we need
582   // to reject it here.
583   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
584     // If invalid, report the error with report_fatal_error.
585     report_fatal_error("Global variable '" + GV->getName() +
586                        "' section type or attributes does not match previous"
587                        " section specifier");
588   }
589
590   return S;
591 }
592
593 const MCSection *TargetLoweringObjectFileMachO::
594 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
595                        Mangler &Mang, const TargetMachine &TM) const {
596   checkMachOComdat(GV);
597
598   // Handle thread local data.
599   if (Kind.isThreadBSS()) return TLSBSSSection;
600   if (Kind.isThreadData()) return TLSDataSection;
601
602   if (Kind.isText())
603     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
604
605   // If this is weak/linkonce, put this in a coalescable section, either in text
606   // or data depending on if it is writable.
607   if (GV->isWeakForLinker()) {
608     if (Kind.isReadOnly())
609       return ConstTextCoalSection;
610     return DataCoalSection;
611   }
612
613   // FIXME: Alignment check should be handled by section classifier.
614   if (Kind.isMergeable1ByteCString() &&
615       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
616     return CStringSection;
617
618   // Do not put 16-bit arrays in the UString section if they have an
619   // externally visible label, this runs into issues with certain linker
620   // versions.
621   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
622       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
623     return UStringSection;
624
625   // With MachO only variables whose corresponding symbol starts with 'l' or
626   // 'L' can be merged, so we only try merging GVs with private linkage.
627   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
628     if (Kind.isMergeableConst4())
629       return FourByteConstantSection;
630     if (Kind.isMergeableConst8())
631       return EightByteConstantSection;
632     if (Kind.isMergeableConst16())
633       return SixteenByteConstantSection;
634   }
635
636   // Otherwise, if it is readonly, but not something we can specially optimize,
637   // just drop it in .const.
638   if (Kind.isReadOnly())
639     return ReadOnlySection;
640
641   // If this is marked const, put it into a const section.  But if the dynamic
642   // linker needs to write to it, put it in the data segment.
643   if (Kind.isReadOnlyWithRel())
644     return ConstDataSection;
645
646   // Put zero initialized globals with strong external linkage in the
647   // DATA, __common section with the .zerofill directive.
648   if (Kind.isBSSExtern())
649     return DataCommonSection;
650
651   // Put zero initialized globals with local linkage in __DATA,__bss directive
652   // with the .zerofill directive (aka .lcomm).
653   if (Kind.isBSSLocal())
654     return DataBSSSection;
655
656   // Otherwise, just drop the variable in the normal data section.
657   return DataSection;
658 }
659
660 const MCSection *
661 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
662                                                      const Constant *C) const {
663   // If this constant requires a relocation, we have to put it in the data
664   // segment, not in the text segment.
665   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
666     return ConstDataSection;
667
668   if (Kind.isMergeableConst4())
669     return FourByteConstantSection;
670   if (Kind.isMergeableConst8())
671     return EightByteConstantSection;
672   if (Kind.isMergeableConst16())
673     return SixteenByteConstantSection;
674   return ReadOnlySection;  // .const
675 }
676
677 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
678     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
679     const TargetMachine &TM, MachineModuleInfo *MMI,
680     MCStreamer &Streamer) const {
681   // The mach-o version of this method defaults to returning a stub reference.
682
683   if (Encoding & DW_EH_PE_indirect) {
684     MachineModuleInfoMachO &MachOMMI =
685       MMI->getObjFileInfo<MachineModuleInfoMachO>();
686
687     MCSymbol *SSym =
688         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
689
690     // Add information about the stub reference to MachOMMI so that the stub
691     // gets emitted by the asmprinter.
692     MachineModuleInfoImpl::StubValueTy &StubSym =
693       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
694                                   MachOMMI.getGVStubEntry(SSym);
695     if (!StubSym.getPointer()) {
696       MCSymbol *Sym = TM.getSymbol(GV, Mang);
697       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
698     }
699
700     return TargetLoweringObjectFile::
701       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
702                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
703   }
704
705   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
706                                                            TM, MMI, Streamer);
707 }
708
709 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
710     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
711     MachineModuleInfo *MMI) const {
712   // The mach-o version of this method defaults to returning a stub reference.
713   MachineModuleInfoMachO &MachOMMI =
714     MMI->getObjFileInfo<MachineModuleInfoMachO>();
715
716   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
717
718   // Add information about the stub reference to MachOMMI so that the stub
719   // gets emitted by the asmprinter.
720   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
721   if (!StubSym.getPointer()) {
722     MCSymbol *Sym = TM.getSymbol(GV, Mang);
723     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
724   }
725
726   return SSym;
727 }
728
729 //===----------------------------------------------------------------------===//
730 //                                  COFF
731 //===----------------------------------------------------------------------===//
732
733 static unsigned
734 getCOFFSectionFlags(SectionKind K) {
735   unsigned Flags = 0;
736
737   if (K.isMetadata())
738     Flags |=
739       COFF::IMAGE_SCN_MEM_DISCARDABLE;
740   else if (K.isText())
741     Flags |=
742       COFF::IMAGE_SCN_MEM_EXECUTE |
743       COFF::IMAGE_SCN_MEM_READ |
744       COFF::IMAGE_SCN_CNT_CODE;
745   else if (K.isBSS())
746     Flags |=
747       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
748       COFF::IMAGE_SCN_MEM_READ |
749       COFF::IMAGE_SCN_MEM_WRITE;
750   else if (K.isThreadLocal())
751     Flags |=
752       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
753       COFF::IMAGE_SCN_MEM_READ |
754       COFF::IMAGE_SCN_MEM_WRITE;
755   else if (K.isReadOnly() || K.isReadOnlyWithRel())
756     Flags |=
757       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
758       COFF::IMAGE_SCN_MEM_READ;
759   else if (K.isWriteable())
760     Flags |=
761       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
762       COFF::IMAGE_SCN_MEM_READ |
763       COFF::IMAGE_SCN_MEM_WRITE;
764
765   return Flags;
766 }
767
768 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
769   const Comdat *C = GV->getComdat();
770   assert(C && "expected GV to have a Comdat!");
771
772   StringRef ComdatGVName = C->getName();
773   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
774   if (!ComdatGV)
775     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
776                        "' does not exist.");
777
778   if (ComdatGV->getComdat() != C)
779     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
780                        "' is not a key for its COMDAT.");
781
782   return ComdatGV;
783 }
784
785 static int getSelectionForCOFF(const GlobalValue *GV) {
786   if (const Comdat *C = GV->getComdat()) {
787     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
788     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
789       ComdatKey = GA->getBaseObject();
790     if (ComdatKey == GV) {
791       switch (C->getSelectionKind()) {
792       case Comdat::Any:
793         return COFF::IMAGE_COMDAT_SELECT_ANY;
794       case Comdat::ExactMatch:
795         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
796       case Comdat::Largest:
797         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
798       case Comdat::NoDuplicates:
799         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
800       case Comdat::SameSize:
801         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
802       }
803     } else {
804       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
805     }
806   } else if (GV->isWeakForLinker()) {
807     return COFF::IMAGE_COMDAT_SELECT_ANY;
808   }
809   return 0;
810 }
811
812 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
813     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
814     const TargetMachine &TM) const {
815   int Selection = 0;
816   unsigned Characteristics = getCOFFSectionFlags(Kind);
817   StringRef Name = GV->getSection();
818   StringRef COMDATSymName = "";
819   if (GV->hasComdat()) {
820     Selection = getSelectionForCOFF(GV);
821     const GlobalValue *ComdatGV;
822     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
823       ComdatGV = getComdatGVForCOFF(GV);
824     else
825       ComdatGV = GV;
826
827     if (!ComdatGV->hasPrivateLinkage()) {
828       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
829       COMDATSymName = Sym->getName();
830       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
831     } else {
832       Selection = 0;
833     }
834   }
835   return getContext().getCOFFSection(Name,
836                                      Characteristics,
837                                      Kind,
838                                      COMDATSymName,
839                                      Selection);
840 }
841
842 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
843   if (Kind.isText())
844     return ".text";
845   if (Kind.isBSS())
846     return ".bss";
847   if (Kind.isThreadLocal())
848     return ".tls$";
849   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
850     return ".rdata";
851   return ".data";
852 }
853
854
855 const MCSection *TargetLoweringObjectFileCOFF::
856 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
857                        Mangler &Mang, const TargetMachine &TM) const {
858   // If we have -ffunction-sections then we should emit the global value to a
859   // uniqued section specifically for it.
860   bool EmitUniquedSection;
861   if (Kind.isText())
862     EmitUniquedSection = TM.getFunctionSections();
863   else
864     EmitUniquedSection = TM.getDataSections();
865
866   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
867     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
868     unsigned Characteristics = getCOFFSectionFlags(Kind);
869
870     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
871     int Selection = getSelectionForCOFF(GV);
872     if (!Selection)
873       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
874     const GlobalValue *ComdatGV;
875     if (GV->hasComdat())
876       ComdatGV = getComdatGVForCOFF(GV);
877     else
878       ComdatGV = GV;
879
880     if (!ComdatGV->hasPrivateLinkage()) {
881       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
882       StringRef COMDATSymName = Sym->getName();
883       return getContext().getCOFFSection(Name, Characteristics, Kind,
884                                          COMDATSymName, Selection);
885     }
886   }
887
888   if (Kind.isText())
889     return TextSection;
890
891   if (Kind.isThreadLocal())
892     return TLSDataSection;
893
894   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
895     return ReadOnlySection;
896
897   // Note: we claim that common symbols are put in BSSSection, but they are
898   // really emitted with the magic .comm directive, which creates a symbol table
899   // entry but not a section.
900   if (Kind.isBSS() || Kind.isCommon())
901     return BSSSection;
902
903   return DataSection;
904 }
905
906 StringRef TargetLoweringObjectFileCOFF::
907 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
908   const char *LibCmd = "/DEFAULTLIB:";
909   if (LinkerOption.startswith(LibCmd))
910     return LinkerOption.substr(strlen(LibCmd));
911   return StringRef();
912 }
913
914 void TargetLoweringObjectFileCOFF::
915 emitModuleFlags(MCStreamer &Streamer,
916                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
917                 Mangler &Mang, const TargetMachine &TM) const {
918   MDNode *LinkerOptions = nullptr;
919
920   // Look for the "Linker Options" flag, since it's the only one we support.
921   for (ArrayRef<Module::ModuleFlagEntry>::iterator
922        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
923     const Module::ModuleFlagEntry &MFE = *i;
924     StringRef Key = MFE.Key->getString();
925     Metadata *Val = MFE.Val;
926     if (Key == "Linker Options") {
927       LinkerOptions = cast<MDNode>(Val);
928       break;
929     }
930   }
931   if (!LinkerOptions)
932     return;
933
934   // Emit the linker options to the linker .drectve section.  According to the
935   // spec, this section is a space-separated string containing flags for linker.
936   const MCSection *Sec = getDrectveSection();
937   Streamer.SwitchSection(Sec);
938   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
939     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
940     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
941       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
942       // Lead with a space for consistency with our dllexport implementation.
943       std::string Directive(" ");
944       Directive.append(MDOption->getString());
945       Streamer.EmitBytes(Directive);
946     }
947   }
948 }
949
950 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
951     unsigned Priority, const MCSymbol *KeySym) const {
952   return getContext().getAssociativeCOFFSection(
953       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
954 }
955
956 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
957     unsigned Priority, const MCSymbol *KeySym) const {
958   return getContext().getAssociativeCOFFSection(
959       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
960 }