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