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