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