xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 302b69c9406b1c690db2e8faaf0a2211dfd46879)
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, getMangler())->getName());
59   if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
60     return TM.getSymbol(GV, getMangler());
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, getMangler());
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 GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
213   StringRef SectionName = GV->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(GV)) {
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 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 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(GV)) {
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 = GV->getParent()->getDataLayout().getPreferredAlignment(
289         cast<GlobalVariable>(GV));
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 Function *F = dyn_cast<Function>(GV)) {
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, GV, 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 GlobalValue *GV, 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 |= GV->hasComdat();
333 
334   return selectELFSectionForGlobal(getContext(), GV, 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, getMangler()), PLTRelativeVariantKind,
447                               getContext()),
448       MCSymbolRefExpr::create(TM.getSymbol(RHS, getMangler()), getContext()),
449       getContext());
450 }
451 
452 void
453 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
454   UseInitArray = UseInitArray_;
455   MCContext &Ctx = getContext();
456   if (!UseInitArray) {
457     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
458                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
459 
460     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
461                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
462     return;
463   }
464 
465   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
466                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
467   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
468                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
469 }
470 
471 //===----------------------------------------------------------------------===//
472 //                                 MachO
473 //===----------------------------------------------------------------------===//
474 
475 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
476   : TargetLoweringObjectFile() {
477   SupportIndirectSymViaGOTPCRel = true;
478 }
479 
480 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
481                                                const TargetMachine &TM) {
482   TargetLoweringObjectFile::Initialize(Ctx, TM);
483   if (TM.getRelocationModel() == Reloc::Static) {
484     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
485                                             SectionKind::getData());
486     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
487                                             SectionKind::getData());
488   } else {
489     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
490                                             MachO::S_MOD_INIT_FUNC_POINTERS,
491                                             SectionKind::getData());
492     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
493                                             MachO::S_MOD_TERM_FUNC_POINTERS,
494                                             SectionKind::getData());
495   }
496 }
497 
498 /// emitModuleFlags - Perform code emission for module flags.
499 void TargetLoweringObjectFileMachO::emitModuleFlags(
500     MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
501     const TargetMachine &TM) const {
502   unsigned VersionVal = 0;
503   unsigned ImageInfoFlags = 0;
504   MDNode *LinkerOptions = nullptr;
505   StringRef SectionVal;
506 
507   for (const auto &MFE : ModuleFlags) {
508     // Ignore flags with 'Require' behavior.
509     if (MFE.Behavior == Module::Require)
510       continue;
511 
512     StringRef Key = MFE.Key->getString();
513     Metadata *Val = MFE.Val;
514 
515     if (Key == "Objective-C Image Info Version") {
516       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
517     } else if (Key == "Objective-C Garbage Collection" ||
518                Key == "Objective-C GC Only" ||
519                Key == "Objective-C Is Simulated" ||
520                Key == "Objective-C Class Properties" ||
521                Key == "Objective-C Image Swift Version") {
522       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
523     } else if (Key == "Objective-C Image Info Section") {
524       SectionVal = cast<MDString>(Val)->getString();
525     } else if (Key == "Linker Options") {
526       LinkerOptions = cast<MDNode>(Val);
527     }
528   }
529 
530   // Emit the linker options if present.
531   if (LinkerOptions) {
532     for (const auto &Option : LinkerOptions->operands()) {
533       SmallVector<std::string, 4> StrOptions;
534       for (const auto &Piece : cast<MDNode>(Option)->operands())
535         StrOptions.push_back(cast<MDString>(Piece)->getString());
536       Streamer.EmitLinkerOptions(StrOptions);
537     }
538   }
539 
540   // The section is mandatory. If we don't have it, then we don't have GC info.
541   if (SectionVal.empty()) return;
542 
543   StringRef Segment, Section;
544   unsigned TAA = 0, StubSize = 0;
545   bool TAAParsed;
546   std::string ErrorCode =
547     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
548                                           TAA, TAAParsed, StubSize);
549   if (!ErrorCode.empty())
550     // If invalid, report the error with report_fatal_error.
551     report_fatal_error("Invalid section specifier '" + Section + "': " +
552                        ErrorCode + ".");
553 
554   // Get the section.
555   MCSectionMachO *S = getContext().getMachOSection(
556       Segment, Section, TAA, StubSize, SectionKind::getData());
557   Streamer.SwitchSection(S);
558   Streamer.EmitLabel(getContext().
559                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
560   Streamer.EmitIntValue(VersionVal, 4);
561   Streamer.EmitIntValue(ImageInfoFlags, 4);
562   Streamer.AddBlankLine();
563 }
564 
565 static void checkMachOComdat(const GlobalValue *GV) {
566   const Comdat *C = GV->getComdat();
567   if (!C)
568     return;
569 
570   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
571                      "' cannot be lowered.");
572 }
573 
574 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
575     const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
576   // Parse the section specifier and create it if valid.
577   StringRef Segment, Section;
578   unsigned TAA = 0, StubSize = 0;
579   bool TAAParsed;
580 
581   checkMachOComdat(GV);
582 
583   std::string ErrorCode =
584     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
585                                           TAA, TAAParsed, StubSize);
586   if (!ErrorCode.empty()) {
587     // If invalid, report the error with report_fatal_error.
588     report_fatal_error("Global variable '" + GV->getName() +
589                        "' has an invalid section specifier '" +
590                        GV->getSection() + "': " + ErrorCode + ".");
591   }
592 
593   // Get the section.
594   MCSectionMachO *S =
595       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
596 
597   // If TAA wasn't set by ParseSectionSpecifier() above,
598   // use the value returned by getMachOSection() as a default.
599   if (!TAAParsed)
600     TAA = S->getTypeAndAttributes();
601 
602   // Okay, now that we got the section, verify that the TAA & StubSize agree.
603   // If the user declared multiple globals with different section flags, we need
604   // to reject it here.
605   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
606     // If invalid, report the error with report_fatal_error.
607     report_fatal_error("Global variable '" + GV->getName() +
608                        "' section type or attributes does not match previous"
609                        " section specifier");
610   }
611 
612   return S;
613 }
614 
615 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
616     const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
617   checkMachOComdat(GV);
618 
619   // Handle thread local data.
620   if (Kind.isThreadBSS()) return TLSBSSSection;
621   if (Kind.isThreadData()) return TLSDataSection;
622 
623   if (Kind.isText())
624     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
625 
626   // If this is weak/linkonce, put this in a coalescable section, either in text
627   // or data depending on if it is writable.
628   if (GV->isWeakForLinker()) {
629     if (Kind.isReadOnly())
630       return ConstTextCoalSection;
631     return DataCoalSection;
632   }
633 
634   // FIXME: Alignment check should be handled by section classifier.
635   if (Kind.isMergeable1ByteCString() &&
636       GV->getParent()->getDataLayout().getPreferredAlignment(
637           cast<GlobalVariable>(GV)) < 32)
638     return CStringSection;
639 
640   // Do not put 16-bit arrays in the UString section if they have an
641   // externally visible label, this runs into issues with certain linker
642   // versions.
643   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
644       GV->getParent()->getDataLayout().getPreferredAlignment(
645           cast<GlobalVariable>(GV)) < 32)
646     return UStringSection;
647 
648   // With MachO only variables whose corresponding symbol starts with 'l' or
649   // 'L' can be merged, so we only try merging GVs with private linkage.
650   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
651     if (Kind.isMergeableConst4())
652       return FourByteConstantSection;
653     if (Kind.isMergeableConst8())
654       return EightByteConstantSection;
655     if (Kind.isMergeableConst16())
656       return SixteenByteConstantSection;
657   }
658 
659   // Otherwise, if it is readonly, but not something we can specially optimize,
660   // just drop it in .const.
661   if (Kind.isReadOnly())
662     return ReadOnlySection;
663 
664   // If this is marked const, put it into a const section.  But if the dynamic
665   // linker needs to write to it, put it in the data segment.
666   if (Kind.isReadOnlyWithRel())
667     return ConstDataSection;
668 
669   // Put zero initialized globals with strong external linkage in the
670   // DATA, __common section with the .zerofill directive.
671   if (Kind.isBSSExtern())
672     return DataCommonSection;
673 
674   // Put zero initialized globals with local linkage in __DATA,__bss directive
675   // with the .zerofill directive (aka .lcomm).
676   if (Kind.isBSSLocal())
677     return DataBSSSection;
678 
679   // Otherwise, just drop the variable in the normal data section.
680   return DataSection;
681 }
682 
683 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
684     const DataLayout &DL, SectionKind Kind, const Constant *C,
685     unsigned &Align) const {
686   // If this constant requires a relocation, we have to put it in the data
687   // segment, not in the text segment.
688   if (Kind.isData() || Kind.isReadOnlyWithRel())
689     return ConstDataSection;
690 
691   if (Kind.isMergeableConst4())
692     return FourByteConstantSection;
693   if (Kind.isMergeableConst8())
694     return EightByteConstantSection;
695   if (Kind.isMergeableConst16())
696     return SixteenByteConstantSection;
697   return ReadOnlySection;  // .const
698 }
699 
700 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
701     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
702     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
703   // The mach-o version of this method defaults to returning a stub reference.
704 
705   if (Encoding & DW_EH_PE_indirect) {
706     MachineModuleInfoMachO &MachOMMI =
707       MMI->getObjFileInfo<MachineModuleInfoMachO>();
708 
709     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
710 
711     // Add information about the stub reference to MachOMMI so that the stub
712     // gets emitted by the asmprinter.
713     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
714     if (!StubSym.getPointer()) {
715       MCSymbol *Sym = TM.getSymbol(GV, getMangler());
716       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
717     }
718 
719     return TargetLoweringObjectFile::
720       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
721                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
722   }
723 
724   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
725                                                            MMI, Streamer);
726 }
727 
728 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
729     const GlobalValue *GV, const TargetMachine &TM,
730     MachineModuleInfo *MMI) const {
731   // The mach-o version of this method defaults to returning a stub reference.
732   MachineModuleInfoMachO &MachOMMI =
733     MMI->getObjFileInfo<MachineModuleInfoMachO>();
734 
735   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
736 
737   // Add information about the stub reference to MachOMMI so that the stub
738   // gets emitted by the asmprinter.
739   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
740   if (!StubSym.getPointer()) {
741     MCSymbol *Sym = TM.getSymbol(GV, getMangler());
742     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
743   }
744 
745   return SSym;
746 }
747 
748 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
749     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
750     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
751   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
752   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
753   // through a non_lazy_ptr stub instead. One advantage is that it allows the
754   // computation of deltas to final external symbols. Example:
755   //
756   //    _extgotequiv:
757   //       .long   _extfoo
758   //
759   //    _delta:
760   //       .long   _extgotequiv-_delta
761   //
762   // is transformed to:
763   //
764   //    _delta:
765   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
766   //
767   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
768   //    L_extfoo$non_lazy_ptr:
769   //       .indirect_symbol        _extfoo
770   //       .long   0
771   //
772   MachineModuleInfoMachO &MachOMMI =
773     MMI->getObjFileInfo<MachineModuleInfoMachO>();
774   MCContext &Ctx = getContext();
775 
776   // The offset must consider the original displacement from the base symbol
777   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
778   Offset = -MV.getConstant();
779   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
780 
781   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
782   // non_lazy_ptr stubs.
783   SmallString<128> Name;
784   StringRef Suffix = "$non_lazy_ptr";
785   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
786   Name += Sym->getName();
787   Name += Suffix;
788   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
789 
790   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
791   if (!StubSym.getPointer())
792     StubSym = MachineModuleInfoImpl::
793       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
794 
795   const MCExpr *BSymExpr =
796     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
797   const MCExpr *LHS =
798     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
799 
800   if (!Offset)
801     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
802 
803   const MCExpr *RHS =
804     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
805   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
806 }
807 
808 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
809                                const MCSection &Section) {
810   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
811     return true;
812 
813   // If it is not dead stripped, it is safe to use private labels.
814   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
815   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
816     return true;
817 
818   return false;
819 }
820 
821 void TargetLoweringObjectFileMachO::getNameWithPrefix(
822     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
823     const TargetMachine &TM) const {
824   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
825   const MCSection *TheSection = SectionForGlobal(GV, GVKind, TM);
826   bool CannotUsePrivateLabel =
827       !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
828   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
829 }
830 
831 //===----------------------------------------------------------------------===//
832 //                                  COFF
833 //===----------------------------------------------------------------------===//
834 
835 static unsigned
836 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
837   unsigned Flags = 0;
838   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
839 
840   if (K.isMetadata())
841     Flags |=
842       COFF::IMAGE_SCN_MEM_DISCARDABLE;
843   else if (K.isText())
844     Flags |=
845       COFF::IMAGE_SCN_MEM_EXECUTE |
846       COFF::IMAGE_SCN_MEM_READ |
847       COFF::IMAGE_SCN_CNT_CODE |
848       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
849   else if (K.isBSS())
850     Flags |=
851       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
852       COFF::IMAGE_SCN_MEM_READ |
853       COFF::IMAGE_SCN_MEM_WRITE;
854   else if (K.isThreadLocal())
855     Flags |=
856       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
857       COFF::IMAGE_SCN_MEM_READ |
858       COFF::IMAGE_SCN_MEM_WRITE;
859   else if (K.isReadOnly() || K.isReadOnlyWithRel())
860     Flags |=
861       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
862       COFF::IMAGE_SCN_MEM_READ;
863   else if (K.isWriteable())
864     Flags |=
865       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
866       COFF::IMAGE_SCN_MEM_READ |
867       COFF::IMAGE_SCN_MEM_WRITE;
868 
869   return Flags;
870 }
871 
872 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
873   const Comdat *C = GV->getComdat();
874   assert(C && "expected GV to have a Comdat!");
875 
876   StringRef ComdatGVName = C->getName();
877   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
878   if (!ComdatGV)
879     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
880                        "' does not exist.");
881 
882   if (ComdatGV->getComdat() != C)
883     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
884                        "' is not a key for its COMDAT.");
885 
886   return ComdatGV;
887 }
888 
889 static int getSelectionForCOFF(const GlobalValue *GV) {
890   if (const Comdat *C = GV->getComdat()) {
891     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
892     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
893       ComdatKey = GA->getBaseObject();
894     if (ComdatKey == GV) {
895       switch (C->getSelectionKind()) {
896       case Comdat::Any:
897         return COFF::IMAGE_COMDAT_SELECT_ANY;
898       case Comdat::ExactMatch:
899         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
900       case Comdat::Largest:
901         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
902       case Comdat::NoDuplicates:
903         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
904       case Comdat::SameSize:
905         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
906       }
907     } else {
908       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
909     }
910   }
911   return 0;
912 }
913 
914 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
915     const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
916   int Selection = 0;
917   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
918   StringRef Name = GV->getSection();
919   StringRef COMDATSymName = "";
920   if (GV->hasComdat()) {
921     Selection = getSelectionForCOFF(GV);
922     const GlobalValue *ComdatGV;
923     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
924       ComdatGV = getComdatGVForCOFF(GV);
925     else
926       ComdatGV = GV;
927 
928     if (!ComdatGV->hasPrivateLinkage()) {
929       MCSymbol *Sym = TM.getSymbol(ComdatGV, getMangler());
930       COMDATSymName = Sym->getName();
931       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
932     } else {
933       Selection = 0;
934     }
935   }
936 
937   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
938                                      Selection);
939 }
940 
941 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
942   if (Kind.isText())
943     return ".text";
944   if (Kind.isBSS())
945     return ".bss";
946   if (Kind.isThreadLocal())
947     return ".tls$";
948   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
949     return ".rdata";
950   return ".data";
951 }
952 
953 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
954     const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
955   // If we have -ffunction-sections then we should emit the global value to a
956   // uniqued section specifically for it.
957   bool EmitUniquedSection;
958   if (Kind.isText())
959     EmitUniquedSection = TM.getFunctionSections();
960   else
961     EmitUniquedSection = TM.getDataSections();
962 
963   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
964     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
965     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
966 
967     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
968     int Selection = getSelectionForCOFF(GV);
969     if (!Selection)
970       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
971     const GlobalValue *ComdatGV;
972     if (GV->hasComdat())
973       ComdatGV = getComdatGVForCOFF(GV);
974     else
975       ComdatGV = GV;
976 
977     unsigned UniqueID = MCContext::GenericSectionID;
978     if (EmitUniquedSection)
979       UniqueID = NextUniqueID++;
980 
981     if (!ComdatGV->hasPrivateLinkage()) {
982       MCSymbol *Sym = TM.getSymbol(ComdatGV, getMangler());
983       StringRef COMDATSymName = Sym->getName();
984       return getContext().getCOFFSection(Name, Characteristics, Kind,
985                                          COMDATSymName, Selection, UniqueID);
986     } else {
987       SmallString<256> TmpData;
988       getMangler().getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
989       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
990                                          Selection, UniqueID);
991     }
992   }
993 
994   if (Kind.isText())
995     return TextSection;
996 
997   if (Kind.isThreadLocal())
998     return TLSDataSection;
999 
1000   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1001     return ReadOnlySection;
1002 
1003   // Note: we claim that common symbols are put in BSSSection, but they are
1004   // really emitted with the magic .comm directive, which creates a symbol table
1005   // entry but not a section.
1006   if (Kind.isBSS() || Kind.isCommon())
1007     return BSSSection;
1008 
1009   return DataSection;
1010 }
1011 
1012 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1013     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1014     const TargetMachine &TM) const {
1015   bool CannotUsePrivateLabel = false;
1016   if (GV->hasPrivateLinkage() &&
1017       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1018        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1019     CannotUsePrivateLabel = true;
1020 
1021   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1022 }
1023 
1024 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1025     const Function &F, const TargetMachine &TM) const {
1026   // If the function can be removed, produce a unique section so that
1027   // the table doesn't prevent the removal.
1028   const Comdat *C = F.getComdat();
1029   bool EmitUniqueSection = TM.getFunctionSections() || C;
1030   if (!EmitUniqueSection)
1031     return ReadOnlySection;
1032 
1033   // FIXME: we should produce a symbol for F instead.
1034   if (F.hasPrivateLinkage())
1035     return ReadOnlySection;
1036 
1037   MCSymbol *Sym = TM.getSymbol(&F, getMangler());
1038   StringRef COMDATSymName = Sym->getName();
1039 
1040   SectionKind Kind = SectionKind::getReadOnly();
1041   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1042   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1043   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1044   unsigned UniqueID = NextUniqueID++;
1045 
1046   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1047                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1048 }
1049 
1050 void TargetLoweringObjectFileCOFF::emitModuleFlags(
1051     MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1052     const TargetMachine &TM) const {
1053   MDNode *LinkerOptions = nullptr;
1054 
1055   for (const auto &MFE : ModuleFlags) {
1056     StringRef Key = MFE.Key->getString();
1057     if (Key == "Linker Options")
1058       LinkerOptions = cast<MDNode>(MFE.Val);
1059   }
1060 
1061   if (LinkerOptions) {
1062     // Emit the linker options to the linker .drectve section.  According to the
1063     // spec, this section is a space-separated string containing flags for
1064     // linker.
1065     MCSection *Sec = getDrectveSection();
1066     Streamer.SwitchSection(Sec);
1067     for (const auto &Option : LinkerOptions->operands()) {
1068       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1069         // Lead with a space for consistency with our dllexport implementation.
1070         std::string Directive(" ");
1071         Directive.append(cast<MDString>(Piece)->getString());
1072         Streamer.EmitBytes(Directive);
1073       }
1074     }
1075   }
1076 }
1077 
1078 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1079                                               const TargetMachine &TM) {
1080   TargetLoweringObjectFile::Initialize(Ctx, TM);
1081   const Triple &T = TM.getTargetTriple();
1082   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1083     StaticCtorSection =
1084         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1085                                            COFF::IMAGE_SCN_MEM_READ,
1086                            SectionKind::getReadOnly());
1087     StaticDtorSection =
1088         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1089                                            COFF::IMAGE_SCN_MEM_READ,
1090                            SectionKind::getReadOnly());
1091   } else {
1092     StaticCtorSection = Ctx.getCOFFSection(
1093         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1094                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1095         SectionKind::getData());
1096     StaticDtorSection = Ctx.getCOFFSection(
1097         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1098                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1099         SectionKind::getData());
1100   }
1101 }
1102 
1103 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1104     unsigned Priority, const MCSymbol *KeySym) const {
1105   return getContext().getAssociativeCOFFSection(
1106       cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1107 }
1108 
1109 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1110     unsigned Priority, const MCSymbol *KeySym) const {
1111   return getContext().getAssociativeCOFFSection(
1112       cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1113 }
1114 
1115 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1116     raw_ostream &OS, const GlobalValue *GV) const {
1117   if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1118     return;
1119 
1120   const Triple &TT = getTargetTriple();
1121 
1122   if (TT.isKnownWindowsMSVCEnvironment())
1123     OS << " /EXPORT:";
1124   else
1125     OS << " -export:";
1126 
1127   if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1128     std::string Flag;
1129     raw_string_ostream FlagOS(Flag);
1130     getMangler().getNameWithPrefix(FlagOS, GV, false);
1131     FlagOS.flush();
1132     if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1133       OS << Flag.substr(1);
1134     else
1135       OS << Flag;
1136   } else {
1137     getMangler().getNameWithPrefix(OS, GV, false);
1138   }
1139 
1140   if (!GV->getValueType()->isFunctionTy()) {
1141     if (TT.isKnownWindowsMSVCEnvironment())
1142       OS << ",DATA";
1143     else
1144       OS << ",data";
1145   }
1146 }
1147