Assume lane masks are always precise
[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/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbolELF.h"
35 #include "llvm/MC/MCValue.h"
36 #include "llvm/Support/COFF.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ELF.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 using namespace llvm;
45 using namespace dwarf;
46
47 //===----------------------------------------------------------------------===//
48 //                                  ELF
49 //===----------------------------------------------------------------------===//
50
51 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
52     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
53     MachineModuleInfo *MMI) const {
54   unsigned Encoding = getPersonalityEncoding();
55   if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
56     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
57                                           TM.getSymbol(GV, Mang)->getName());
58   if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
59     return TM.getSymbol(GV, Mang);
60   report_fatal_error("We do not support this DWARF encoding yet!");
61 }
62
63 void TargetLoweringObjectFileELF::emitPersonalityValue(
64     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
65   SmallString<64> NameData("DW.ref.");
66   NameData += Sym->getName();
67   MCSymbolELF *Label =
68       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
69   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
70   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
71   StringRef Prefix = ".data.";
72   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
73   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
74   MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
75                                               Flags, 0, Label->getName());
76   unsigned Size = DL.getPointerSize();
77   Streamer.SwitchSection(Sec);
78   Streamer.EmitValueToAlignment(DL.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 static unsigned getELFSectionFlags(SectionKind K) {
169   unsigned Flags = 0;
170
171   if (!K.isMetadata())
172     Flags |= ELF::SHF_ALLOC;
173
174   if (K.isText())
175     Flags |= ELF::SHF_EXECINSTR;
176
177   if (K.isWriteable())
178     Flags |= ELF::SHF_WRITE;
179
180   if (K.isThreadLocal())
181     Flags |= ELF::SHF_TLS;
182
183   if (K.isMergeableCString() || K.isMergeableConst())
184     Flags |= ELF::SHF_MERGE;
185
186   if (K.isMergeableCString())
187     Flags |= ELF::SHF_STRINGS;
188
189   return Flags;
190 }
191
192 static const Comdat *getELFComdat(const GlobalValue *GV) {
193   const Comdat *C = GV->getComdat();
194   if (!C)
195     return nullptr;
196
197   if (C->getSelectionKind() != Comdat::Any)
198     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
199                        C->getName() + "' cannot be lowered.");
200
201   return C;
202 }
203
204 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
205     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
206     const TargetMachine &TM) const {
207   StringRef SectionName = GV->getSection();
208
209   // Infer section flags from the section name if we can.
210   Kind = getELFKindForNamedSection(SectionName, Kind);
211
212   StringRef Group = "";
213   unsigned Flags = getELFSectionFlags(Kind);
214   if (const Comdat *C = getELFComdat(GV)) {
215     Group = C->getName();
216     Flags |= ELF::SHF_GROUP;
217   }
218   return getContext().getELFSection(SectionName,
219                                     getELFSectionType(SectionName, Kind), Flags,
220                                     /*EntrySize=*/0, Group);
221 }
222
223 /// Return the section prefix name used by options FunctionsSections and
224 /// DataSections.
225 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
226   if (Kind.isText())
227     return ".text";
228   if (Kind.isReadOnly())
229     return ".rodata";
230   if (Kind.isBSS())
231     return ".bss";
232   if (Kind.isThreadData())
233     return ".tdata";
234   if (Kind.isThreadBSS())
235     return ".tbss";
236   if (Kind.isDataNoRel())
237     return ".data";
238   if (Kind.isDataRelLocal())
239     return ".data.rel.local";
240   if (Kind.isDataRel())
241     return ".data.rel";
242   if (Kind.isReadOnlyWithRelLocal())
243     return ".data.rel.ro.local";
244   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
245   return ".data.rel.ro";
246 }
247
248 static MCSectionELF *
249 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
250                           SectionKind Kind, Mangler &Mang,
251                           const TargetMachine &TM, bool EmitUniqueSection,
252                           unsigned Flags, unsigned *NextUniqueID) {
253   unsigned EntrySize = 0;
254   if (Kind.isMergeableCString()) {
255     if (Kind.isMergeable2ByteCString()) {
256       EntrySize = 2;
257     } else if (Kind.isMergeable4ByteCString()) {
258       EntrySize = 4;
259     } else {
260       EntrySize = 1;
261       assert(Kind.isMergeable1ByteCString() && "unknown string width");
262     }
263   } else if (Kind.isMergeableConst()) {
264     if (Kind.isMergeableConst4()) {
265       EntrySize = 4;
266     } else if (Kind.isMergeableConst8()) {
267       EntrySize = 8;
268     } else {
269       assert(Kind.isMergeableConst16() && "unknown data width");
270       EntrySize = 16;
271     }
272   }
273
274   StringRef Group = "";
275   if (const Comdat *C = getELFComdat(GV)) {
276     Flags |= ELF::SHF_GROUP;
277     Group = C->getName();
278   }
279
280   bool UniqueSectionNames = TM.getUniqueSectionNames();
281   SmallString<128> Name;
282   if (Kind.isMergeableCString()) {
283     // We also need alignment here.
284     // FIXME: this is getting the alignment of the character, not the
285     // alignment of the global!
286     unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
287         cast<GlobalVariable>(GV));
288
289     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
290     Name = SizeSpec + utostr(Align);
291   } else if (Kind.isMergeableConst()) {
292     Name = ".rodata.cst";
293     Name += utostr(EntrySize);
294   } else {
295     Name = getSectionPrefixForGlobal(Kind);
296   }
297
298   if (EmitUniqueSection && UniqueSectionNames) {
299     Name.push_back('.');
300     TM.getNameWithPrefix(Name, GV, Mang, true);
301   }
302   unsigned UniqueID = ~0;
303   if (EmitUniqueSection && !UniqueSectionNames) {
304     UniqueID = *NextUniqueID;
305     (*NextUniqueID)++;
306   }
307   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
308                            EntrySize, Group, UniqueID);
309 }
310
311 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
312     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
313     const TargetMachine &TM) const {
314   unsigned Flags = getELFSectionFlags(Kind);
315
316   // If we have -ffunction-section or -fdata-section then we should emit the
317   // global value to a uniqued section specifically for it.
318   bool EmitUniqueSection = false;
319   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
320     if (Kind.isText())
321       EmitUniqueSection = TM.getFunctionSections();
322     else
323       EmitUniqueSection = TM.getDataSections();
324   }
325   EmitUniqueSection |= GV->hasComdat();
326
327   return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
328                                    EmitUniqueSection, Flags, &NextUniqueID);
329 }
330
331 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
332     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
333   // If the function can be removed, produce a unique section so that
334   // the table doesn't prevent the removal.
335   const Comdat *C = F.getComdat();
336   bool EmitUniqueSection = TM.getFunctionSections() || C;
337   if (!EmitUniqueSection)
338     return ReadOnlySection;
339
340   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
341                                    Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
342                                    &NextUniqueID);
343 }
344
345 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
346     bool UsesLabelDifference, const Function &F) const {
347   // We can always create relative relocations, so use another section
348   // that can be marked non-executable.
349   return false;
350 }
351
352 /// Given a mergeable constant with the specified size and relocation
353 /// information, return a section that it should be placed in.
354 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
355     const DataLayout &DL, SectionKind Kind, const Constant *C) const {
356   if (Kind.isMergeableConst4() && MergeableConst4Section)
357     return MergeableConst4Section;
358   if (Kind.isMergeableConst8() && MergeableConst8Section)
359     return MergeableConst8Section;
360   if (Kind.isMergeableConst16() && MergeableConst16Section)
361     return MergeableConst16Section;
362   if (Kind.isReadOnly())
363     return ReadOnlySection;
364
365   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
366   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
367   return DataRelROSection;
368 }
369
370 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
371                                               bool IsCtor, unsigned Priority,
372                                               const MCSymbol *KeySym) {
373   std::string Name;
374   unsigned Type;
375   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
376   StringRef COMDAT = KeySym ? KeySym->getName() : "";
377
378   if (KeySym)
379     Flags |= ELF::SHF_GROUP;
380
381   if (UseInitArray) {
382     if (IsCtor) {
383       Type = ELF::SHT_INIT_ARRAY;
384       Name = ".init_array";
385     } else {
386       Type = ELF::SHT_FINI_ARRAY;
387       Name = ".fini_array";
388     }
389     if (Priority != 65535) {
390       Name += '.';
391       Name += utostr(Priority);
392     }
393   } else {
394     // The default scheme is .ctor / .dtor, so we have to invert the priority
395     // numbering.
396     if (IsCtor)
397       Name = ".ctors";
398     else
399       Name = ".dtors";
400     if (Priority != 65535) {
401       Name += '.';
402       Name += utostr(65535 - Priority);
403     }
404     Type = ELF::SHT_PROGBITS;
405   }
406
407   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
408 }
409
410 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
411     unsigned Priority, const MCSymbol *KeySym) const {
412   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
413                                   KeySym);
414 }
415
416 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
417     unsigned Priority, const MCSymbol *KeySym) const {
418   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
419                                   KeySym);
420 }
421
422 void
423 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
424   UseInitArray = UseInitArray_;
425   if (!UseInitArray)
426     return;
427
428   StaticCtorSection = getContext().getELFSection(
429       ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
430   StaticDtorSection = getContext().getELFSection(
431       ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
432 }
433
434 //===----------------------------------------------------------------------===//
435 //                                 MachO
436 //===----------------------------------------------------------------------===//
437
438 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
439   : TargetLoweringObjectFile() {
440   SupportIndirectSymViaGOTPCRel = true;
441 }
442
443 /// emitModuleFlags - Perform code emission for module flags.
444 void TargetLoweringObjectFileMachO::
445 emitModuleFlags(MCStreamer &Streamer,
446                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
447                 Mangler &Mang, const TargetMachine &TM) const {
448   unsigned VersionVal = 0;
449   unsigned ImageInfoFlags = 0;
450   MDNode *LinkerOptions = nullptr;
451   StringRef SectionVal;
452
453   for (ArrayRef<Module::ModuleFlagEntry>::iterator
454          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
455     const Module::ModuleFlagEntry &MFE = *i;
456
457     // Ignore flags with 'Require' behavior.
458     if (MFE.Behavior == Module::Require)
459       continue;
460
461     StringRef Key = MFE.Key->getString();
462     Metadata *Val = MFE.Val;
463
464     if (Key == "Objective-C Image Info Version") {
465       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
466     } else if (Key == "Objective-C Garbage Collection" ||
467                Key == "Objective-C GC Only" ||
468                Key == "Objective-C Is Simulated" ||
469                Key == "Objective-C Image Swift Version") {
470       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
471     } else if (Key == "Objective-C Image Info Section") {
472       SectionVal = cast<MDString>(Val)->getString();
473     } else if (Key == "Linker Options") {
474       LinkerOptions = cast<MDNode>(Val);
475     }
476   }
477
478   // Emit the linker options if present.
479   if (LinkerOptions) {
480     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
481       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
482       SmallVector<std::string, 4> StrOptions;
483
484       // Convert to strings.
485       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
486         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
487         StrOptions.push_back(MDOption->getString());
488       }
489
490       Streamer.EmitLinkerOptions(StrOptions);
491     }
492   }
493
494   // The section is mandatory. If we don't have it, then we don't have GC info.
495   if (SectionVal.empty()) return;
496
497   StringRef Segment, Section;
498   unsigned TAA = 0, StubSize = 0;
499   bool TAAParsed;
500   std::string ErrorCode =
501     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
502                                           TAA, TAAParsed, StubSize);
503   if (!ErrorCode.empty())
504     // If invalid, report the error with report_fatal_error.
505     report_fatal_error("Invalid section specifier '" + Section + "': " +
506                        ErrorCode + ".");
507
508   // Get the section.
509   MCSectionMachO *S = getContext().getMachOSection(
510       Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
511   Streamer.SwitchSection(S);
512   Streamer.EmitLabel(getContext().
513                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
514   Streamer.EmitIntValue(VersionVal, 4);
515   Streamer.EmitIntValue(ImageInfoFlags, 4);
516   Streamer.AddBlankLine();
517 }
518
519 static void checkMachOComdat(const GlobalValue *GV) {
520   const Comdat *C = GV->getComdat();
521   if (!C)
522     return;
523
524   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
525                      "' cannot be lowered.");
526 }
527
528 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
529     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
530     const TargetMachine &TM) const {
531   // Parse the section specifier and create it if valid.
532   StringRef Segment, Section;
533   unsigned TAA = 0, StubSize = 0;
534   bool TAAParsed;
535
536   checkMachOComdat(GV);
537
538   std::string ErrorCode =
539     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
540                                           TAA, TAAParsed, StubSize);
541   if (!ErrorCode.empty()) {
542     // If invalid, report the error with report_fatal_error.
543     report_fatal_error("Global variable '" + GV->getName() +
544                        "' has an invalid section specifier '" +
545                        GV->getSection() + "': " + ErrorCode + ".");
546   }
547
548   // Get the section.
549   MCSectionMachO *S =
550       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
551
552   // If TAA wasn't set by ParseSectionSpecifier() above,
553   // use the value returned by getMachOSection() as a default.
554   if (!TAAParsed)
555     TAA = S->getTypeAndAttributes();
556
557   // Okay, now that we got the section, verify that the TAA & StubSize agree.
558   // If the user declared multiple globals with different section flags, we need
559   // to reject it here.
560   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
561     // If invalid, report the error with report_fatal_error.
562     report_fatal_error("Global variable '" + GV->getName() +
563                        "' section type or attributes does not match previous"
564                        " section specifier");
565   }
566
567   return S;
568 }
569
570 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
571     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
572     const TargetMachine &TM) const {
573   checkMachOComdat(GV);
574
575   // Handle thread local data.
576   if (Kind.isThreadBSS()) return TLSBSSSection;
577   if (Kind.isThreadData()) return TLSDataSection;
578
579   if (Kind.isText())
580     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
581
582   // If this is weak/linkonce, put this in a coalescable section, either in text
583   // or data depending on if it is writable.
584   if (GV->isWeakForLinker()) {
585     if (Kind.isReadOnly())
586       return ConstTextCoalSection;
587     return DataCoalSection;
588   }
589
590   // FIXME: Alignment check should be handled by section classifier.
591   if (Kind.isMergeable1ByteCString() &&
592       GV->getParent()->getDataLayout().getPreferredAlignment(
593           cast<GlobalVariable>(GV)) < 32)
594     return CStringSection;
595
596   // Do not put 16-bit arrays in the UString section if they have an
597   // externally visible label, this runs into issues with certain linker
598   // versions.
599   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
600       GV->getParent()->getDataLayout().getPreferredAlignment(
601           cast<GlobalVariable>(GV)) < 32)
602     return UStringSection;
603
604   // With MachO only variables whose corresponding symbol starts with 'l' or
605   // 'L' can be merged, so we only try merging GVs with private linkage.
606   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
607     if (Kind.isMergeableConst4())
608       return FourByteConstantSection;
609     if (Kind.isMergeableConst8())
610       return EightByteConstantSection;
611     if (Kind.isMergeableConst16())
612       return SixteenByteConstantSection;
613   }
614
615   // Otherwise, if it is readonly, but not something we can specially optimize,
616   // just drop it in .const.
617   if (Kind.isReadOnly())
618     return ReadOnlySection;
619
620   // If this is marked const, put it into a const section.  But if the dynamic
621   // linker needs to write to it, put it in the data segment.
622   if (Kind.isReadOnlyWithRel())
623     return ConstDataSection;
624
625   // Put zero initialized globals with strong external linkage in the
626   // DATA, __common section with the .zerofill directive.
627   if (Kind.isBSSExtern())
628     return DataCommonSection;
629
630   // Put zero initialized globals with local linkage in __DATA,__bss directive
631   // with the .zerofill directive (aka .lcomm).
632   if (Kind.isBSSLocal())
633     return DataBSSSection;
634
635   // Otherwise, just drop the variable in the normal data section.
636   return DataSection;
637 }
638
639 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
640     const DataLayout &DL, SectionKind Kind, const Constant *C) const {
641   // If this constant requires a relocation, we have to put it in the data
642   // segment, not in the text segment.
643   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
644     return ConstDataSection;
645
646   if (Kind.isMergeableConst4())
647     return FourByteConstantSection;
648   if (Kind.isMergeableConst8())
649     return EightByteConstantSection;
650   if (Kind.isMergeableConst16())
651     return SixteenByteConstantSection;
652   return ReadOnlySection;  // .const
653 }
654
655 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
656     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
657     const TargetMachine &TM, MachineModuleInfo *MMI,
658     MCStreamer &Streamer) const {
659   // The mach-o version of this method defaults to returning a stub reference.
660
661   if (Encoding & DW_EH_PE_indirect) {
662     MachineModuleInfoMachO &MachOMMI =
663       MMI->getObjFileInfo<MachineModuleInfoMachO>();
664
665     MCSymbol *SSym =
666         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
667
668     // Add information about the stub reference to MachOMMI so that the stub
669     // gets emitted by the asmprinter.
670     MachineModuleInfoImpl::StubValueTy &StubSym =
671       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
672                                   MachOMMI.getGVStubEntry(SSym);
673     if (!StubSym.getPointer()) {
674       MCSymbol *Sym = TM.getSymbol(GV, Mang);
675       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
676     }
677
678     return TargetLoweringObjectFile::
679       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
680                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
681   }
682
683   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
684                                                            TM, MMI, Streamer);
685 }
686
687 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
688     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
689     MachineModuleInfo *MMI) const {
690   // The mach-o version of this method defaults to returning a stub reference.
691   MachineModuleInfoMachO &MachOMMI =
692     MMI->getObjFileInfo<MachineModuleInfoMachO>();
693
694   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
695
696   // Add information about the stub reference to MachOMMI so that the stub
697   // gets emitted by the asmprinter.
698   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
699   if (!StubSym.getPointer()) {
700     MCSymbol *Sym = TM.getSymbol(GV, Mang);
701     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
702   }
703
704   return SSym;
705 }
706
707 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
708     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
709     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
710   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
711   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
712   // through a non_lazy_ptr stub instead. One advantage is that it allows the
713   // computation of deltas to final external symbols. Example:
714   //
715   //    _extgotequiv:
716   //       .long   _extfoo
717   //
718   //    _delta:
719   //       .long   _extgotequiv-_delta
720   //
721   // is transformed to:
722   //
723   //    _delta:
724   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
725   //
726   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
727   //    L_extfoo$non_lazy_ptr:
728   //       .indirect_symbol        _extfoo
729   //       .long   0
730   //
731   MachineModuleInfoMachO &MachOMMI =
732     MMI->getObjFileInfo<MachineModuleInfoMachO>();
733   MCContext &Ctx = getContext();
734
735   // The offset must consider the original displacement from the base symbol
736   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
737   Offset = -MV.getConstant();
738   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
739
740   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
741   // non_lazy_ptr stubs.
742   SmallString<128> Name;
743   StringRef Suffix = "$non_lazy_ptr";
744   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
745   Name += Sym->getName();
746   Name += Suffix;
747   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
748
749   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
750   if (!StubSym.getPointer())
751     StubSym = MachineModuleInfoImpl::
752       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
753
754   const MCExpr *BSymExpr =
755     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
756   const MCExpr *LHS =
757     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
758
759   if (!Offset)
760     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
761
762   const MCExpr *RHS =
763     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
764   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
765 }
766
767 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
768                                const MCSection &Section) {
769   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
770     return true;
771
772   // If it is not dead stripped, it is safe to use private labels.
773   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
774   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
775     return true;
776
777   return false;
778 }
779
780 void TargetLoweringObjectFileMachO::getNameWithPrefix(
781     SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
782     const TargetMachine &TM) const {
783   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
784   const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
785   bool CannotUsePrivateLabel =
786       !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
787   Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
788 }
789
790 //===----------------------------------------------------------------------===//
791 //                                  COFF
792 //===----------------------------------------------------------------------===//
793
794 static unsigned
795 getCOFFSectionFlags(SectionKind K) {
796   unsigned Flags = 0;
797
798   if (K.isMetadata())
799     Flags |=
800       COFF::IMAGE_SCN_MEM_DISCARDABLE;
801   else if (K.isText())
802     Flags |=
803       COFF::IMAGE_SCN_MEM_EXECUTE |
804       COFF::IMAGE_SCN_MEM_READ |
805       COFF::IMAGE_SCN_CNT_CODE;
806   else if (K.isBSS())
807     Flags |=
808       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
809       COFF::IMAGE_SCN_MEM_READ |
810       COFF::IMAGE_SCN_MEM_WRITE;
811   else if (K.isThreadLocal())
812     Flags |=
813       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
814       COFF::IMAGE_SCN_MEM_READ |
815       COFF::IMAGE_SCN_MEM_WRITE;
816   else if (K.isReadOnly() || K.isReadOnlyWithRel())
817     Flags |=
818       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
819       COFF::IMAGE_SCN_MEM_READ;
820   else if (K.isWriteable())
821     Flags |=
822       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
823       COFF::IMAGE_SCN_MEM_READ |
824       COFF::IMAGE_SCN_MEM_WRITE;
825
826   return Flags;
827 }
828
829 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
830   const Comdat *C = GV->getComdat();
831   assert(C && "expected GV to have a Comdat!");
832
833   StringRef ComdatGVName = C->getName();
834   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
835   if (!ComdatGV)
836     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
837                        "' does not exist.");
838
839   if (ComdatGV->getComdat() != C)
840     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
841                        "' is not a key for its COMDAT.");
842
843   return ComdatGV;
844 }
845
846 static int getSelectionForCOFF(const GlobalValue *GV) {
847   if (const Comdat *C = GV->getComdat()) {
848     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
849     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
850       ComdatKey = GA->getBaseObject();
851     if (ComdatKey == GV) {
852       switch (C->getSelectionKind()) {
853       case Comdat::Any:
854         return COFF::IMAGE_COMDAT_SELECT_ANY;
855       case Comdat::ExactMatch:
856         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
857       case Comdat::Largest:
858         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
859       case Comdat::NoDuplicates:
860         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
861       case Comdat::SameSize:
862         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
863       }
864     } else {
865       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
866     }
867   }
868   return 0;
869 }
870
871 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
872     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
873     const TargetMachine &TM) const {
874   int Selection = 0;
875   unsigned Characteristics = getCOFFSectionFlags(Kind);
876   StringRef Name = GV->getSection();
877   StringRef COMDATSymName = "";
878   if (GV->hasComdat()) {
879     Selection = getSelectionForCOFF(GV);
880     const GlobalValue *ComdatGV;
881     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
882       ComdatGV = getComdatGVForCOFF(GV);
883     else
884       ComdatGV = GV;
885
886     if (!ComdatGV->hasPrivateLinkage()) {
887       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
888       COMDATSymName = Sym->getName();
889       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
890     } else {
891       Selection = 0;
892     }
893   }
894   return getContext().getCOFFSection(Name,
895                                      Characteristics,
896                                      Kind,
897                                      COMDATSymName,
898                                      Selection);
899 }
900
901 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
902   if (Kind.isText())
903     return ".text";
904   if (Kind.isBSS())
905     return ".bss";
906   if (Kind.isThreadLocal())
907     return ".tls$";
908   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
909     return ".rdata";
910   return ".data";
911 }
912
913 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
914     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
915     const TargetMachine &TM) const {
916   // If we have -ffunction-sections then we should emit the global value to a
917   // uniqued section specifically for it.
918   bool EmitUniquedSection;
919   if (Kind.isText())
920     EmitUniquedSection = TM.getFunctionSections();
921   else
922     EmitUniquedSection = TM.getDataSections();
923
924   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
925     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
926     unsigned Characteristics = getCOFFSectionFlags(Kind);
927
928     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
929     int Selection = getSelectionForCOFF(GV);
930     if (!Selection)
931       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
932     const GlobalValue *ComdatGV;
933     if (GV->hasComdat())
934       ComdatGV = getComdatGVForCOFF(GV);
935     else
936       ComdatGV = GV;
937
938     if (!ComdatGV->hasPrivateLinkage()) {
939       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
940       StringRef COMDATSymName = Sym->getName();
941       return getContext().getCOFFSection(Name, Characteristics, Kind,
942                                          COMDATSymName, Selection);
943     } else {
944       SmallString<256> TmpData;
945       Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
946       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
947                                          Selection);
948     }
949   }
950
951   if (Kind.isText())
952     return TextSection;
953
954   if (Kind.isThreadLocal())
955     return TLSDataSection;
956
957   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
958     return ReadOnlySection;
959
960   // Note: we claim that common symbols are put in BSSSection, but they are
961   // really emitted with the magic .comm directive, which creates a symbol table
962   // entry but not a section.
963   if (Kind.isBSS() || Kind.isCommon())
964     return BSSSection;
965
966   return DataSection;
967 }
968
969 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
970     SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
971     const TargetMachine &TM) const {
972   bool CannotUsePrivateLabel = false;
973   if (GV->hasPrivateLinkage() &&
974       ((isa<Function>(GV) && TM.getFunctionSections()) ||
975        (isa<GlobalVariable>(GV) && TM.getDataSections())))
976     CannotUsePrivateLabel = true;
977
978   Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
979 }
980
981 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
982     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
983   // If the function can be removed, produce a unique section so that
984   // the table doesn't prevent the removal.
985   const Comdat *C = F.getComdat();
986   bool EmitUniqueSection = TM.getFunctionSections() || C;
987   if (!EmitUniqueSection)
988     return ReadOnlySection;
989
990   // FIXME: we should produce a symbol for F instead.
991   if (F.hasPrivateLinkage())
992     return ReadOnlySection;
993
994   MCSymbol *Sym = TM.getSymbol(&F, Mang);
995   StringRef COMDATSymName = Sym->getName();
996
997   SectionKind Kind = SectionKind::getReadOnly();
998   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
999   unsigned Characteristics = getCOFFSectionFlags(Kind);
1000   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1001
1002   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1003                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
1004 }
1005
1006 void TargetLoweringObjectFileCOFF::
1007 emitModuleFlags(MCStreamer &Streamer,
1008                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1009                 Mangler &Mang, const TargetMachine &TM) const {
1010   MDNode *LinkerOptions = nullptr;
1011
1012   // Look for the "Linker Options" flag, since it's the only one we support.
1013   for (ArrayRef<Module::ModuleFlagEntry>::iterator
1014        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1015     const Module::ModuleFlagEntry &MFE = *i;
1016     StringRef Key = MFE.Key->getString();
1017     Metadata *Val = MFE.Val;
1018     if (Key == "Linker Options") {
1019       LinkerOptions = cast<MDNode>(Val);
1020       break;
1021     }
1022   }
1023   if (!LinkerOptions)
1024     return;
1025
1026   // Emit the linker options to the linker .drectve section.  According to the
1027   // spec, this section is a space-separated string containing flags for linker.
1028   MCSection *Sec = getDrectveSection();
1029   Streamer.SwitchSection(Sec);
1030   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1031     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1032     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1033       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1034       // Lead with a space for consistency with our dllexport implementation.
1035       std::string Directive(" ");
1036       Directive.append(MDOption->getString());
1037       Streamer.EmitBytes(Directive);
1038     }
1039   }
1040 }
1041
1042 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1043     unsigned Priority, const MCSymbol *KeySym) const {
1044   return getContext().getAssociativeCOFFSection(
1045       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1046 }
1047
1048 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1049     unsigned Priority, const MCSymbol *KeySym) const {
1050   return getContext().getAssociativeCOFFSection(
1051       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
1052 }
1053
1054 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1055     raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1056   if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1057     return;
1058
1059   const Triple &TT = getTargetTriple();
1060
1061   if (TT.isKnownWindowsMSVCEnvironment())
1062     OS << " /EXPORT:";
1063   else
1064     OS << " -export:";
1065
1066   if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1067     std::string Flag;
1068     raw_string_ostream FlagOS(Flag);
1069     Mang.getNameWithPrefix(FlagOS, GV, false);
1070     FlagOS.flush();
1071     if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1072       OS << Flag.substr(1);
1073     else
1074       OS << Flag;
1075   } else {
1076     Mang.getNameWithPrefix(OS, GV, false);
1077   }
1078
1079   if (!GV->getValueType()->isFunctionTy()) {
1080     if (TT.isKnownWindowsMSVCEnvironment())
1081       OS << ",DATA";
1082     else
1083       OS << ",data";
1084   }
1085 }