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