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