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