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