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