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