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