xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision a1e1dcabe4fb1f24401f3153409583fe133ffd46)
1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/BinaryFormat/MachO.h"
24 #include "llvm/CodeGen/BasicBlockSectionUtils.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
29 #include "llvm/IR/Comdat.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/DiagnosticPrinter.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalAlias.h"
37 #include "llvm/IR/GlobalObject.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Mangler.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/PseudoProbe.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSectionCOFF.h"
49 #include "llvm/MC/MCSectionELF.h"
50 #include "llvm/MC/MCSectionMachO.h"
51 #include "llvm/MC/MCSectionWasm.h"
52 #include "llvm/MC/MCSectionXCOFF.h"
53 #include "llvm/MC/MCStreamer.h"
54 #include "llvm/MC/MCSymbol.h"
55 #include "llvm/MC/MCSymbolELF.h"
56 #include "llvm/MC/MCValue.h"
57 #include "llvm/MC/SectionKind.h"
58 #include "llvm/ProfileData/InstrProf.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/Format.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include <cassert>
66 #include <string>
67 
68 using namespace llvm;
69 using namespace dwarf;
70 
71 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
72                              StringRef &Section) {
73   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
74   M.getModuleFlagsMetadata(ModuleFlags);
75 
76   for (const auto &MFE: ModuleFlags) {
77     // Ignore flags with 'Require' behaviour.
78     if (MFE.Behavior == Module::Require)
79       continue;
80 
81     StringRef Key = MFE.Key->getString();
82     if (Key == "Objective-C Image Info Version") {
83       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84     } else if (Key == "Objective-C Garbage Collection" ||
85                Key == "Objective-C GC Only" ||
86                Key == "Objective-C Is Simulated" ||
87                Key == "Objective-C Class Properties" ||
88                Key == "Objective-C Image Swift Version") {
89       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
90     } else if (Key == "Objective-C Image Info Section") {
91       Section = cast<MDString>(MFE.Val)->getString();
92     }
93     // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
94     // "Objective-C Garbage Collection".
95     else if (Key == "Swift ABI Version") {
96       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
97     } else if (Key == "Swift Major Version") {
98       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
99     } else if (Key == "Swift Minor Version") {
100       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
101     }
102   }
103 }
104 
105 //===----------------------------------------------------------------------===//
106 //                                  ELF
107 //===----------------------------------------------------------------------===//
108 
109 TargetLoweringObjectFileELF::TargetLoweringObjectFileELF()
110     : TargetLoweringObjectFile() {
111   SupportDSOLocalEquivalentLowering = true;
112 }
113 
114 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
115                                              const TargetMachine &TgtM) {
116   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
117 
118   CodeModel::Model CM = TgtM.getCodeModel();
119   InitializeELF(TgtM.Options.UseInitArray);
120 
121   switch (TgtM.getTargetTriple().getArch()) {
122   case Triple::arm:
123   case Triple::armeb:
124   case Triple::thumb:
125   case Triple::thumbeb:
126     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
127       break;
128     // Fallthrough if not using EHABI
129     LLVM_FALLTHROUGH;
130   case Triple::ppc:
131   case Triple::x86:
132     PersonalityEncoding = isPositionIndependent()
133                               ? dwarf::DW_EH_PE_indirect |
134                                     dwarf::DW_EH_PE_pcrel |
135                                     dwarf::DW_EH_PE_sdata4
136                               : dwarf::DW_EH_PE_absptr;
137     LSDAEncoding = isPositionIndependent()
138                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
139                        : dwarf::DW_EH_PE_absptr;
140     TTypeEncoding = isPositionIndependent()
141                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
142                               dwarf::DW_EH_PE_sdata4
143                         : dwarf::DW_EH_PE_absptr;
144     break;
145   case Triple::x86_64:
146     if (isPositionIndependent()) {
147       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
148         ((CM == CodeModel::Small || CM == CodeModel::Medium)
149          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
150       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
151         (CM == CodeModel::Small
152          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
153       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
154         ((CM == CodeModel::Small || CM == CodeModel::Medium)
155          ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
156     } else {
157       PersonalityEncoding =
158         (CM == CodeModel::Small || CM == CodeModel::Medium)
159         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
160       LSDAEncoding = (CM == CodeModel::Small)
161         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
162       TTypeEncoding = (CM == CodeModel::Small)
163         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
164     }
165     break;
166   case Triple::hexagon:
167     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
168     LSDAEncoding = dwarf::DW_EH_PE_absptr;
169     TTypeEncoding = dwarf::DW_EH_PE_absptr;
170     if (isPositionIndependent()) {
171       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
172       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
173       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
174     }
175     break;
176   case Triple::aarch64:
177   case Triple::aarch64_be:
178   case Triple::aarch64_32:
179     // The small model guarantees static code/data size < 4GB, but not where it
180     // will be in memory. Most of these could end up >2GB away so even a signed
181     // pc-relative 32-bit address is insufficient, theoretically.
182     if (isPositionIndependent()) {
183       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
184         dwarf::DW_EH_PE_sdata8;
185       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
186       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
187         dwarf::DW_EH_PE_sdata8;
188     } else {
189       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
190       LSDAEncoding = dwarf::DW_EH_PE_absptr;
191       TTypeEncoding = dwarf::DW_EH_PE_absptr;
192     }
193     break;
194   case Triple::lanai:
195     LSDAEncoding = dwarf::DW_EH_PE_absptr;
196     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
197     TTypeEncoding = dwarf::DW_EH_PE_absptr;
198     break;
199   case Triple::mips:
200   case Triple::mipsel:
201   case Triple::mips64:
202   case Triple::mips64el:
203     // MIPS uses indirect pointer to refer personality functions and types, so
204     // that the eh_frame section can be read-only. DW.ref.personality will be
205     // generated for relocation.
206     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
207     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
208     //        identify N64 from just a triple.
209     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
210                     dwarf::DW_EH_PE_sdata4;
211     // We don't support PC-relative LSDA references in GAS so we use the default
212     // DW_EH_PE_absptr for those.
213 
214     // FreeBSD must be explicit about the data size and using pcrel since it's
215     // assembler/linker won't do the automatic conversion that the Linux tools
216     // do.
217     if (TgtM.getTargetTriple().isOSFreeBSD()) {
218       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
219       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
220     }
221     break;
222   case Triple::ppc64:
223   case Triple::ppc64le:
224     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
225       dwarf::DW_EH_PE_udata8;
226     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
227     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
228       dwarf::DW_EH_PE_udata8;
229     break;
230   case Triple::sparcel:
231   case Triple::sparc:
232     if (isPositionIndependent()) {
233       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
234       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
235         dwarf::DW_EH_PE_sdata4;
236       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
237         dwarf::DW_EH_PE_sdata4;
238     } else {
239       LSDAEncoding = dwarf::DW_EH_PE_absptr;
240       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
241       TTypeEncoding = dwarf::DW_EH_PE_absptr;
242     }
243     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
244     break;
245   case Triple::riscv32:
246   case Triple::riscv64:
247     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
248     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
249                           dwarf::DW_EH_PE_sdata4;
250     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
251                     dwarf::DW_EH_PE_sdata4;
252     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
253     break;
254   case Triple::sparcv9:
255     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
256     if (isPositionIndependent()) {
257       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
258         dwarf::DW_EH_PE_sdata4;
259       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
260         dwarf::DW_EH_PE_sdata4;
261     } else {
262       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
263       TTypeEncoding = dwarf::DW_EH_PE_absptr;
264     }
265     break;
266   case Triple::systemz:
267     // All currently-defined code models guarantee that 4-byte PC-relative
268     // values will be in range.
269     if (isPositionIndependent()) {
270       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
271         dwarf::DW_EH_PE_sdata4;
272       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
273       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
274         dwarf::DW_EH_PE_sdata4;
275     } else {
276       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
277       LSDAEncoding = dwarf::DW_EH_PE_absptr;
278       TTypeEncoding = dwarf::DW_EH_PE_absptr;
279     }
280     break;
281   default:
282     break;
283   }
284 }
285 
286 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
287                                                      Module &M) const {
288   auto &C = getContext();
289 
290   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
291     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
292                               ELF::SHF_EXCLUDE);
293 
294     Streamer.SwitchSection(S);
295 
296     for (const auto *Operand : LinkerOptions->operands()) {
297       if (cast<MDNode>(Operand)->getNumOperands() != 2)
298         report_fatal_error("invalid llvm.linker.options");
299       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
300         Streamer.emitBytes(cast<MDString>(Option)->getString());
301         Streamer.emitInt8(0);
302       }
303     }
304   }
305 
306   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
307     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
308                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
309 
310     Streamer.SwitchSection(S);
311 
312     for (const auto *Operand : DependentLibraries->operands()) {
313       Streamer.emitBytes(
314           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
315       Streamer.emitInt8(0);
316     }
317   }
318 
319   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
320     // Emit a descriptor for every function including functions that have an
321     // available external linkage. We may not want this for imported functions
322     // that has code in another thinLTO module but we don't have a good way to
323     // tell them apart from inline functions defined in header files. Therefore
324     // we put each descriptor in a separate comdat section and rely on the
325     // linker to deduplicate.
326     for (const auto *Operand : FuncInfo->operands()) {
327       const auto *MD = cast<MDNode>(Operand);
328       auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
329       auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
330       auto *Name = cast<MDString>(MD->getOperand(2));
331       auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
332           TM->getFunctionSections() ? Name->getString() : StringRef());
333 
334       Streamer.SwitchSection(S);
335       Streamer.emitInt64(GUID->getZExtValue());
336       Streamer.emitInt64(Hash->getZExtValue());
337       Streamer.emitULEB128IntValue(Name->getString().size());
338       Streamer.emitBytes(Name->getString());
339     }
340   }
341 
342   unsigned Version = 0;
343   unsigned Flags = 0;
344   StringRef Section;
345 
346   GetObjCImageInfo(M, Version, Flags, Section);
347   if (!Section.empty()) {
348     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
349     Streamer.SwitchSection(S);
350     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
351     Streamer.emitInt32(Version);
352     Streamer.emitInt32(Flags);
353     Streamer.AddBlankLine();
354   }
355 
356   emitCGProfileMetadata(Streamer, M);
357 }
358 
359 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
360     const GlobalValue *GV, const TargetMachine &TM,
361     MachineModuleInfo *MMI) const {
362   unsigned Encoding = getPersonalityEncoding();
363   if ((Encoding & 0x80) == DW_EH_PE_indirect)
364     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
365                                           TM.getSymbol(GV)->getName());
366   if ((Encoding & 0x70) == DW_EH_PE_absptr)
367     return TM.getSymbol(GV);
368   report_fatal_error("We do not support this DWARF encoding yet!");
369 }
370 
371 void TargetLoweringObjectFileELF::emitPersonalityValue(
372     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
373   SmallString<64> NameData("DW.ref.");
374   NameData += Sym->getName();
375   MCSymbolELF *Label =
376       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
377   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
378   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
379   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
380   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
381                                                    ELF::SHT_PROGBITS, Flags, 0);
382   unsigned Size = DL.getPointerSize();
383   Streamer.SwitchSection(Sec);
384   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
385   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
386   const MCExpr *E = MCConstantExpr::create(Size, getContext());
387   Streamer.emitELFSize(Label, E);
388   Streamer.emitLabel(Label);
389 
390   Streamer.emitSymbolValue(Sym, Size);
391 }
392 
393 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
394     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
395     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
396   if (Encoding & DW_EH_PE_indirect) {
397     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
398 
399     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
400 
401     // Add information about the stub reference to ELFMMI so that the stub
402     // gets emitted by the asmprinter.
403     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
404     if (!StubSym.getPointer()) {
405       MCSymbol *Sym = TM.getSymbol(GV);
406       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
407     }
408 
409     return TargetLoweringObjectFile::
410       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
411                         Encoding & ~DW_EH_PE_indirect, Streamer);
412   }
413 
414   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
415                                                            MMI, Streamer);
416 }
417 
418 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
419   // N.B.: The defaults used in here are not the same ones used in MC.
420   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
421   // both gas and MC will produce a section with no flags. Given
422   // section(".eh_frame") gcc will produce:
423   //
424   //   .section   .eh_frame,"a",@progbits
425 
426   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
427                                       /*AddSegmentInfo=*/false) ||
428       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
429                                       /*AddSegmentInfo=*/false) ||
430       Name == ".llvmbc" || Name == ".llvmcmd")
431     return SectionKind::getMetadata();
432 
433   if (Name.empty() || Name[0] != '.') return K;
434 
435   // Default implementation based on some magic section names.
436   if (Name == ".bss" ||
437       Name.startswith(".bss.") ||
438       Name.startswith(".gnu.linkonce.b.") ||
439       Name.startswith(".llvm.linkonce.b.") ||
440       Name == ".sbss" ||
441       Name.startswith(".sbss.") ||
442       Name.startswith(".gnu.linkonce.sb.") ||
443       Name.startswith(".llvm.linkonce.sb."))
444     return SectionKind::getBSS();
445 
446   if (Name == ".tdata" ||
447       Name.startswith(".tdata.") ||
448       Name.startswith(".gnu.linkonce.td.") ||
449       Name.startswith(".llvm.linkonce.td."))
450     return SectionKind::getThreadData();
451 
452   if (Name == ".tbss" ||
453       Name.startswith(".tbss.") ||
454       Name.startswith(".gnu.linkonce.tb.") ||
455       Name.startswith(".llvm.linkonce.tb."))
456     return SectionKind::getThreadBSS();
457 
458   return K;
459 }
460 
461 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
462   // Use SHT_NOTE for section whose name starts with ".note" to allow
463   // emitting ELF notes from C variable declaration.
464   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
465   if (Name.startswith(".note"))
466     return ELF::SHT_NOTE;
467 
468   if (Name == ".init_array")
469     return ELF::SHT_INIT_ARRAY;
470 
471   if (Name == ".fini_array")
472     return ELF::SHT_FINI_ARRAY;
473 
474   if (Name == ".preinit_array")
475     return ELF::SHT_PREINIT_ARRAY;
476 
477   if (K.isBSS() || K.isThreadBSS())
478     return ELF::SHT_NOBITS;
479 
480   return ELF::SHT_PROGBITS;
481 }
482 
483 static unsigned getELFSectionFlags(SectionKind K) {
484   unsigned Flags = 0;
485 
486   if (!K.isMetadata())
487     Flags |= ELF::SHF_ALLOC;
488 
489   if (K.isText())
490     Flags |= ELF::SHF_EXECINSTR;
491 
492   if (K.isExecuteOnly())
493     Flags |= ELF::SHF_ARM_PURECODE;
494 
495   if (K.isWriteable())
496     Flags |= ELF::SHF_WRITE;
497 
498   if (K.isThreadLocal())
499     Flags |= ELF::SHF_TLS;
500 
501   if (K.isMergeableCString() || K.isMergeableConst())
502     Flags |= ELF::SHF_MERGE;
503 
504   if (K.isMergeableCString())
505     Flags |= ELF::SHF_STRINGS;
506 
507   return Flags;
508 }
509 
510 static const Comdat *getELFComdat(const GlobalValue *GV) {
511   const Comdat *C = GV->getComdat();
512   if (!C)
513     return nullptr;
514 
515   if (C->getSelectionKind() != Comdat::Any)
516     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
517                        C->getName() + "' cannot be lowered.");
518 
519   return C;
520 }
521 
522 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
523                                             const TargetMachine &TM) {
524   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
525   if (!MD)
526     return nullptr;
527 
528   const MDOperand &Op = MD->getOperand(0);
529   if (!Op.get())
530     return nullptr;
531 
532   auto *VM = dyn_cast<ValueAsMetadata>(Op);
533   if (!VM)
534     report_fatal_error("MD_associated operand is not ValueAsMetadata");
535 
536   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
537   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
538 }
539 
540 static unsigned getEntrySizeForKind(SectionKind Kind) {
541   if (Kind.isMergeable1ByteCString())
542     return 1;
543   else if (Kind.isMergeable2ByteCString())
544     return 2;
545   else if (Kind.isMergeable4ByteCString())
546     return 4;
547   else if (Kind.isMergeableConst4())
548     return 4;
549   else if (Kind.isMergeableConst8())
550     return 8;
551   else if (Kind.isMergeableConst16())
552     return 16;
553   else if (Kind.isMergeableConst32())
554     return 32;
555   else {
556     // We shouldn't have mergeable C strings or mergeable constants that we
557     // didn't handle above.
558     assert(!Kind.isMergeableCString() && "unknown string width");
559     assert(!Kind.isMergeableConst() && "unknown data width");
560     return 0;
561   }
562 }
563 
564 /// Return the section prefix name used by options FunctionsSections and
565 /// DataSections.
566 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
567   if (Kind.isText())
568     return ".text";
569   if (Kind.isReadOnly())
570     return ".rodata";
571   if (Kind.isBSS())
572     return ".bss";
573   if (Kind.isThreadData())
574     return ".tdata";
575   if (Kind.isThreadBSS())
576     return ".tbss";
577   if (Kind.isData())
578     return ".data";
579   if (Kind.isReadOnlyWithRel())
580     return ".data.rel.ro";
581   llvm_unreachable("Unknown section kind");
582 }
583 
584 static SmallString<128>
585 getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
586                            Mangler &Mang, const TargetMachine &TM,
587                            unsigned EntrySize, bool UniqueSectionName) {
588   SmallString<128> Name;
589   if (Kind.isMergeableCString()) {
590     // We also need alignment here.
591     // FIXME: this is getting the alignment of the character, not the
592     // alignment of the global!
593     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
594         cast<GlobalVariable>(GO));
595 
596     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
597     Name = SizeSpec + utostr(Alignment.value());
598   } else if (Kind.isMergeableConst()) {
599     Name = ".rodata.cst";
600     Name += utostr(EntrySize);
601   } else {
602     Name = getSectionPrefixForGlobal(Kind);
603   }
604 
605   bool HasPrefix = false;
606   if (const auto *F = dyn_cast<Function>(GO)) {
607     if (Optional<StringRef> Prefix = F->getSectionPrefix()) {
608       raw_svector_ostream(Name) << '.' << *Prefix;
609       HasPrefix = true;
610     }
611   }
612 
613   if (UniqueSectionName) {
614     Name.push_back('.');
615     TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
616   } else if (HasPrefix)
617     Name.push_back('.');
618   return Name;
619 }
620 
621 namespace {
622 class LoweringDiagnosticInfo : public DiagnosticInfo {
623   const Twine &Msg;
624 
625 public:
626   LoweringDiagnosticInfo(const Twine &DiagMsg,
627                          DiagnosticSeverity Severity = DS_Error)
628       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
629   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
630 };
631 }
632 
633 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
634     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
635   StringRef SectionName = GO->getSection();
636 
637   // Check if '#pragma clang section' name is applicable.
638   // Note that pragma directive overrides -ffunction-section, -fdata-section
639   // and so section name is exactly as user specified and not uniqued.
640   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
641   if (GV && GV->hasImplicitSection()) {
642     auto Attrs = GV->getAttributes();
643     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
644       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
645     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
646       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
647     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
648       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
649     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
650       SectionName = Attrs.getAttribute("data-section").getValueAsString();
651     }
652   }
653   const Function *F = dyn_cast<Function>(GO);
654   if (F && F->hasFnAttribute("implicit-section-name")) {
655     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
656   }
657 
658   // Infer section flags from the section name if we can.
659   Kind = getELFKindForNamedSection(SectionName, Kind);
660 
661   StringRef Group = "";
662   unsigned Flags = getELFSectionFlags(Kind);
663   if (const Comdat *C = getELFComdat(GO)) {
664     Group = C->getName();
665     Flags |= ELF::SHF_GROUP;
666   }
667 
668   unsigned EntrySize = getEntrySizeForKind(Kind);
669 
670   // A section can have at most one associated section. Put each global with
671   // MD_associated in a unique section.
672   unsigned UniqueID = MCContext::GenericSectionID;
673   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
674   if (GO->getMetadata(LLVMContext::MD_associated)) {
675     UniqueID = NextUniqueID++;
676     Flags |= ELF::SHF_LINK_ORDER;
677   } else {
678     if (getContext().getAsmInfo()->useIntegratedAssembler()) {
679       // Symbols must be placed into sections with compatible entry
680       // sizes. Generate unique sections for symbols that have not
681       // been assigned to compatible sections.
682       if (Flags & ELF::SHF_MERGE) {
683         auto maybeID = getContext().getELFUniqueIDForEntsize(SectionName, Flags,
684                                                              EntrySize);
685         if (maybeID)
686           UniqueID = *maybeID;
687         else {
688           // If the user has specified the same section name as would be created
689           // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
690           // to unique the section as the entry size for this symbol will be
691           // compatible with implicitly created sections.
692           SmallString<128> ImplicitSectionNameStem = getELFSectionNameForGlobal(
693               GO, Kind, getMangler(), TM, EntrySize, false);
694           if (!(getContext().isELFImplicitMergeableSectionNamePrefix(
695                     SectionName) &&
696                 SectionName.startswith(ImplicitSectionNameStem)))
697             UniqueID = NextUniqueID++;
698         }
699       } else {
700         // We need to unique the section if the user has explicity
701         // assigned a non-mergeable symbol to a section name for
702         // a generic mergeable section.
703         if (getContext().isELFGenericMergeableSection(SectionName)) {
704           auto maybeID = getContext().getELFUniqueIDForEntsize(
705               SectionName, Flags, EntrySize);
706           UniqueID = maybeID ? *maybeID : NextUniqueID++;
707         }
708       }
709     } else {
710       // If two symbols with differing sizes end up in the same mergeable
711       // section that section can be assigned an incorrect entry size. To avoid
712       // this we usually put symbols of the same size into distinct mergeable
713       // sections with the same name. Doing so relies on the ",unique ,"
714       // assembly feature. This feature is not avalible until bintuils
715       // version 2.35 (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
716       Flags &= ~ELF::SHF_MERGE;
717       EntrySize = 0;
718     }
719   }
720 
721   MCSectionELF *Section = getContext().getELFSection(
722       SectionName, getELFSectionType(SectionName, Kind), Flags,
723       EntrySize, Group, UniqueID, LinkedToSym);
724   // Make sure that we did not get some other section with incompatible sh_link.
725   // This should not be possible due to UniqueID code above.
726   assert(Section->getLinkedToSymbol() == LinkedToSym &&
727          "Associated symbol mismatch between sections");
728 
729   if (!getContext().getAsmInfo()->useIntegratedAssembler()) {
730     // If we are not using the integrated assembler then this symbol might have
731     // been placed in an incompatible mergeable section. Emit an error if this
732     // is the case to avoid creating broken output.
733     if ((Section->getFlags() & ELF::SHF_MERGE) &&
734         (Section->getEntrySize() != getEntrySizeForKind(Kind)))
735       GO->getContext().diagnose(LoweringDiagnosticInfo(
736           "Symbol '" + GO->getName() + "' from module '" +
737           (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
738           "' required a section with entry-size=" +
739           Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
740           SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
741           ": Explicit assignment by pragma or attribute of an incompatible "
742           "symbol to this section?"));
743   }
744 
745   return Section;
746 }
747 
748 static MCSectionELF *selectELFSectionForGlobal(
749     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
750     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
751     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
752 
753   StringRef Group = "";
754   if (const Comdat *C = getELFComdat(GO)) {
755     Flags |= ELF::SHF_GROUP;
756     Group = C->getName();
757   }
758 
759   // Get the section entry size based on the kind.
760   unsigned EntrySize = getEntrySizeForKind(Kind);
761 
762   bool UniqueSectionName = false;
763   unsigned UniqueID = MCContext::GenericSectionID;
764   if (EmitUniqueSection) {
765     if (TM.getUniqueSectionNames()) {
766       UniqueSectionName = true;
767     } else {
768       UniqueID = *NextUniqueID;
769       (*NextUniqueID)++;
770     }
771   }
772   SmallString<128> Name = getELFSectionNameForGlobal(
773       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
774 
775   // Use 0 as the unique ID for execute-only text.
776   if (Kind.isExecuteOnly())
777     UniqueID = 0;
778   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
779                            EntrySize, Group, UniqueID, AssociatedSymbol);
780 }
781 
782 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
783     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
784   unsigned Flags = getELFSectionFlags(Kind);
785 
786   // If we have -ffunction-section or -fdata-section then we should emit the
787   // global value to a uniqued section specifically for it.
788   bool EmitUniqueSection = false;
789   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
790     if (Kind.isText())
791       EmitUniqueSection = TM.getFunctionSections();
792     else
793       EmitUniqueSection = TM.getDataSections();
794   }
795   EmitUniqueSection |= GO->hasComdat();
796 
797   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
798   if (LinkedToSym) {
799     EmitUniqueSection = true;
800     Flags |= ELF::SHF_LINK_ORDER;
801   }
802 
803   MCSectionELF *Section = selectELFSectionForGlobal(
804       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
805       &NextUniqueID, LinkedToSym);
806   assert(Section->getLinkedToSymbol() == LinkedToSym);
807   return Section;
808 }
809 
810 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
811     const Function &F, const TargetMachine &TM) const {
812   // If the function can be removed, produce a unique section so that
813   // the table doesn't prevent the removal.
814   const Comdat *C = F.getComdat();
815   bool EmitUniqueSection = TM.getFunctionSections() || C;
816   if (!EmitUniqueSection)
817     return ReadOnlySection;
818 
819   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
820                                    getMangler(), TM, EmitUniqueSection,
821                                    ELF::SHF_ALLOC, &NextUniqueID,
822                                    /* AssociatedSymbol */ nullptr);
823 }
824 
825 MCSection *
826 TargetLoweringObjectFileELF::getSectionForLSDA(const Function &F,
827                                                const TargetMachine &TM) const {
828   // If neither COMDAT nor function sections, use the monolithic LSDA section.
829   // Re-use this path if LSDASection is null as in the Arm EHABI.
830   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
831     return LSDASection;
832 
833   const auto *LSDA = cast<MCSectionELF>(LSDASection);
834   unsigned Flags = LSDA->getFlags();
835   StringRef Group;
836   if (F.hasComdat()) {
837     Group = F.getComdat()->getName();
838     Flags |= ELF::SHF_GROUP;
839   }
840 
841   // Append the function name as the suffix like GCC, assuming
842   // -funique-section-names applies to .gcc_except_table sections.
843   if (TM.getUniqueSectionNames())
844     return getContext().getELFSection(LSDA->getName() + "." + F.getName(),
845                                       LSDA->getType(), Flags, 0, Group,
846                                       MCSection::NonUniqueID, nullptr);
847 
848   // Allocate a unique ID if function sections && (integrated assembler or GNU
849   // as>=2.35). Note we could use SHF_LINK_ORDER to facilitate --gc-sections but
850   // that would require that we know the linker is a modern LLD (12.0 or later).
851   // GNU ld as of 2.35 does not support mixed SHF_LINK_ORDER &
852   // non-SHF_LINK_ORDER components in an output section
853   // https://sourceware.org/bugzilla/show_bug.cgi?id=26256
854   unsigned ID = TM.getFunctionSections() &&
855                         getContext().getAsmInfo()->useIntegratedAssembler()
856                     ? NextUniqueID++
857                     : MCSection::NonUniqueID;
858   return getContext().getELFSection(LSDA->getName(), LSDA->getType(), Flags, 0,
859                                     Group, ID, nullptr);
860 }
861 
862 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
863     bool UsesLabelDifference, const Function &F) const {
864   // We can always create relative relocations, so use another section
865   // that can be marked non-executable.
866   return false;
867 }
868 
869 /// Given a mergeable constant with the specified size and relocation
870 /// information, return a section that it should be placed in.
871 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
872     const DataLayout &DL, SectionKind Kind, const Constant *C,
873     Align &Alignment) const {
874   if (Kind.isMergeableConst4() && MergeableConst4Section)
875     return MergeableConst4Section;
876   if (Kind.isMergeableConst8() && MergeableConst8Section)
877     return MergeableConst8Section;
878   if (Kind.isMergeableConst16() && MergeableConst16Section)
879     return MergeableConst16Section;
880   if (Kind.isMergeableConst32() && MergeableConst32Section)
881     return MergeableConst32Section;
882   if (Kind.isReadOnly())
883     return ReadOnlySection;
884 
885   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
886   return DataRelROSection;
887 }
888 
889 /// Returns a unique section for the given machine basic block.
890 MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
891     const Function &F, const MachineBasicBlock &MBB,
892     const TargetMachine &TM) const {
893   assert(MBB.isBeginSection() && "Basic block does not start a section!");
894   unsigned UniqueID = MCContext::GenericSectionID;
895 
896   // For cold sections use the .text.split. prefix along with the parent
897   // function name. All cold blocks for the same function go to the same
898   // section. Similarly all exception blocks are grouped by symbol name
899   // under the .text.eh prefix. For regular sections, we either use a unique
900   // name, or a unique ID for the section.
901   SmallString<128> Name;
902   if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
903     Name += BBSectionsColdTextPrefix;
904     Name += MBB.getParent()->getName();
905   } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
906     Name += ".text.eh.";
907     Name += MBB.getParent()->getName();
908   } else {
909     Name += MBB.getParent()->getSection()->getName();
910     if (TM.getUniqueBasicBlockSectionNames()) {
911       Name += ".";
912       Name += MBB.getSymbol()->getName();
913     } else {
914       UniqueID = NextUniqueID++;
915     }
916   }
917 
918   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
919   std::string GroupName = "";
920   if (F.hasComdat()) {
921     Flags |= ELF::SHF_GROUP;
922     GroupName = F.getComdat()->getName().str();
923   }
924   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
925                                     0 /* Entry Size */, GroupName, UniqueID,
926                                     nullptr);
927 }
928 
929 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
930                                               bool IsCtor, unsigned Priority,
931                                               const MCSymbol *KeySym) {
932   std::string Name;
933   unsigned Type;
934   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
935   StringRef COMDAT = KeySym ? KeySym->getName() : "";
936 
937   if (KeySym)
938     Flags |= ELF::SHF_GROUP;
939 
940   if (UseInitArray) {
941     if (IsCtor) {
942       Type = ELF::SHT_INIT_ARRAY;
943       Name = ".init_array";
944     } else {
945       Type = ELF::SHT_FINI_ARRAY;
946       Name = ".fini_array";
947     }
948     if (Priority != 65535) {
949       Name += '.';
950       Name += utostr(Priority);
951     }
952   } else {
953     // The default scheme is .ctor / .dtor, so we have to invert the priority
954     // numbering.
955     if (IsCtor)
956       Name = ".ctors";
957     else
958       Name = ".dtors";
959     if (Priority != 65535)
960       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
961     Type = ELF::SHT_PROGBITS;
962   }
963 
964   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
965 }
966 
967 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
968     unsigned Priority, const MCSymbol *KeySym) const {
969   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
970                                   KeySym);
971 }
972 
973 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
974     unsigned Priority, const MCSymbol *KeySym) const {
975   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
976                                   KeySym);
977 }
978 
979 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
980     const GlobalValue *LHS, const GlobalValue *RHS,
981     const TargetMachine &TM) const {
982   // We may only use a PLT-relative relocation to refer to unnamed_addr
983   // functions.
984   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
985     return nullptr;
986 
987   // Basic sanity checks.
988   if (LHS->getType()->getPointerAddressSpace() != 0 ||
989       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
990       RHS->isThreadLocal())
991     return nullptr;
992 
993   return MCBinaryExpr::createSub(
994       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
995                               getContext()),
996       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
997 }
998 
999 const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1000     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1001   assert(supportDSOLocalEquivalentLowering());
1002 
1003   const auto *GV = Equiv->getGlobalValue();
1004 
1005   // A PLT entry is not needed for dso_local globals.
1006   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1007     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1008 
1009   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1010                                  getContext());
1011 }
1012 
1013 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
1014   // Use ".GCC.command.line" since this feature is to support clang's
1015   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1016   // same name.
1017   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1018                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
1019 }
1020 
1021 void
1022 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
1023   UseInitArray = UseInitArray_;
1024   MCContext &Ctx = getContext();
1025   if (!UseInitArray) {
1026     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1027                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1028 
1029     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1030                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1031     return;
1032   }
1033 
1034   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1035                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1036   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1037                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1038 }
1039 
1040 //===----------------------------------------------------------------------===//
1041 //                                 MachO
1042 //===----------------------------------------------------------------------===//
1043 
1044 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
1045   : TargetLoweringObjectFile() {
1046   SupportIndirectSymViaGOTPCRel = true;
1047 }
1048 
1049 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1050                                                const TargetMachine &TM) {
1051   TargetLoweringObjectFile::Initialize(Ctx, TM);
1052   if (TM.getRelocationModel() == Reloc::Static) {
1053     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1054                                             SectionKind::getData());
1055     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1056                                             SectionKind::getData());
1057   } else {
1058     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1059                                             MachO::S_MOD_INIT_FUNC_POINTERS,
1060                                             SectionKind::getData());
1061     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1062                                             MachO::S_MOD_TERM_FUNC_POINTERS,
1063                                             SectionKind::getData());
1064   }
1065 
1066   PersonalityEncoding =
1067       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1068   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1069   TTypeEncoding =
1070       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1071 }
1072 
1073 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1074                                                        Module &M) const {
1075   // Emit the linker options if present.
1076   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1077     for (const auto *Option : LinkerOptions->operands()) {
1078       SmallVector<std::string, 4> StrOptions;
1079       for (const auto &Piece : cast<MDNode>(Option)->operands())
1080         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1081       Streamer.emitLinkerOptions(StrOptions);
1082     }
1083   }
1084 
1085   unsigned VersionVal = 0;
1086   unsigned ImageInfoFlags = 0;
1087   StringRef SectionVal;
1088 
1089   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1090 
1091   // The section is mandatory. If we don't have it, then we don't have GC info.
1092   if (SectionVal.empty())
1093     return;
1094 
1095   StringRef Segment, Section;
1096   unsigned TAA = 0, StubSize = 0;
1097   bool TAAParsed;
1098   std::string ErrorCode =
1099     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
1100                                           TAA, TAAParsed, StubSize);
1101   if (!ErrorCode.empty())
1102     // If invalid, report the error with report_fatal_error.
1103     report_fatal_error("Invalid section specifier '" + Section + "': " +
1104                        ErrorCode + ".");
1105 
1106   // Get the section.
1107   MCSectionMachO *S = getContext().getMachOSection(
1108       Segment, Section, TAA, StubSize, SectionKind::getData());
1109   Streamer.SwitchSection(S);
1110   Streamer.emitLabel(getContext().
1111                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1112   Streamer.emitInt32(VersionVal);
1113   Streamer.emitInt32(ImageInfoFlags);
1114   Streamer.AddBlankLine();
1115 }
1116 
1117 static void checkMachOComdat(const GlobalValue *GV) {
1118   const Comdat *C = GV->getComdat();
1119   if (!C)
1120     return;
1121 
1122   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1123                      "' cannot be lowered.");
1124 }
1125 
1126 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1127     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1128   // Parse the section specifier and create it if valid.
1129   StringRef Segment, Section;
1130   unsigned TAA = 0, StubSize = 0;
1131   bool TAAParsed;
1132 
1133   checkMachOComdat(GO);
1134 
1135   std::string ErrorCode =
1136     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
1137                                           TAA, TAAParsed, StubSize);
1138   if (!ErrorCode.empty()) {
1139     // If invalid, report the error with report_fatal_error.
1140     report_fatal_error("Global variable '" + GO->getName() +
1141                        "' has an invalid section specifier '" +
1142                        GO->getSection() + "': " + ErrorCode + ".");
1143   }
1144 
1145   // Get the section.
1146   MCSectionMachO *S =
1147       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1148 
1149   // If TAA wasn't set by ParseSectionSpecifier() above,
1150   // use the value returned by getMachOSection() as a default.
1151   if (!TAAParsed)
1152     TAA = S->getTypeAndAttributes();
1153 
1154   // Okay, now that we got the section, verify that the TAA & StubSize agree.
1155   // If the user declared multiple globals with different section flags, we need
1156   // to reject it here.
1157   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1158     // If invalid, report the error with report_fatal_error.
1159     report_fatal_error("Global variable '" + GO->getName() +
1160                        "' section type or attributes does not match previous"
1161                        " section specifier");
1162   }
1163 
1164   return S;
1165 }
1166 
1167 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1168     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1169   checkMachOComdat(GO);
1170 
1171   // Handle thread local data.
1172   if (Kind.isThreadBSS()) return TLSBSSSection;
1173   if (Kind.isThreadData()) return TLSDataSection;
1174 
1175   if (Kind.isText())
1176     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
1177 
1178   // If this is weak/linkonce, put this in a coalescable section, either in text
1179   // or data depending on if it is writable.
1180   if (GO->isWeakForLinker()) {
1181     if (Kind.isReadOnly())
1182       return ConstTextCoalSection;
1183     if (Kind.isReadOnlyWithRel())
1184       return ConstDataCoalSection;
1185     return DataCoalSection;
1186   }
1187 
1188   // FIXME: Alignment check should be handled by section classifier.
1189   if (Kind.isMergeable1ByteCString() &&
1190       GO->getParent()->getDataLayout().getPreferredAlign(
1191           cast<GlobalVariable>(GO)) < Align(32))
1192     return CStringSection;
1193 
1194   // Do not put 16-bit arrays in the UString section if they have an
1195   // externally visible label, this runs into issues with certain linker
1196   // versions.
1197   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1198       GO->getParent()->getDataLayout().getPreferredAlign(
1199           cast<GlobalVariable>(GO)) < Align(32))
1200     return UStringSection;
1201 
1202   // With MachO only variables whose corresponding symbol starts with 'l' or
1203   // 'L' can be merged, so we only try merging GVs with private linkage.
1204   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1205     if (Kind.isMergeableConst4())
1206       return FourByteConstantSection;
1207     if (Kind.isMergeableConst8())
1208       return EightByteConstantSection;
1209     if (Kind.isMergeableConst16())
1210       return SixteenByteConstantSection;
1211   }
1212 
1213   // Otherwise, if it is readonly, but not something we can specially optimize,
1214   // just drop it in .const.
1215   if (Kind.isReadOnly())
1216     return ReadOnlySection;
1217 
1218   // If this is marked const, put it into a const section.  But if the dynamic
1219   // linker needs to write to it, put it in the data segment.
1220   if (Kind.isReadOnlyWithRel())
1221     return ConstDataSection;
1222 
1223   // Put zero initialized globals with strong external linkage in the
1224   // DATA, __common section with the .zerofill directive.
1225   if (Kind.isBSSExtern())
1226     return DataCommonSection;
1227 
1228   // Put zero initialized globals with local linkage in __DATA,__bss directive
1229   // with the .zerofill directive (aka .lcomm).
1230   if (Kind.isBSSLocal())
1231     return DataBSSSection;
1232 
1233   // Otherwise, just drop the variable in the normal data section.
1234   return DataSection;
1235 }
1236 
1237 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1238     const DataLayout &DL, SectionKind Kind, const Constant *C,
1239     Align &Alignment) const {
1240   // If this constant requires a relocation, we have to put it in the data
1241   // segment, not in the text segment.
1242   if (Kind.isData() || Kind.isReadOnlyWithRel())
1243     return ConstDataSection;
1244 
1245   if (Kind.isMergeableConst4())
1246     return FourByteConstantSection;
1247   if (Kind.isMergeableConst8())
1248     return EightByteConstantSection;
1249   if (Kind.isMergeableConst16())
1250     return SixteenByteConstantSection;
1251   return ReadOnlySection;  // .const
1252 }
1253 
1254 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1255     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1256     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1257   // The mach-o version of this method defaults to returning a stub reference.
1258 
1259   if (Encoding & DW_EH_PE_indirect) {
1260     MachineModuleInfoMachO &MachOMMI =
1261       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1262 
1263     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1264 
1265     // Add information about the stub reference to MachOMMI so that the stub
1266     // gets emitted by the asmprinter.
1267     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1268     if (!StubSym.getPointer()) {
1269       MCSymbol *Sym = TM.getSymbol(GV);
1270       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1271     }
1272 
1273     return TargetLoweringObjectFile::
1274       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1275                         Encoding & ~DW_EH_PE_indirect, Streamer);
1276   }
1277 
1278   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1279                                                            MMI, Streamer);
1280 }
1281 
1282 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1283     const GlobalValue *GV, const TargetMachine &TM,
1284     MachineModuleInfo *MMI) const {
1285   // The mach-o version of this method defaults to returning a stub reference.
1286   MachineModuleInfoMachO &MachOMMI =
1287     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1288 
1289   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1290 
1291   // Add information about the stub reference to MachOMMI so that the stub
1292   // gets emitted by the asmprinter.
1293   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1294   if (!StubSym.getPointer()) {
1295     MCSymbol *Sym = TM.getSymbol(GV);
1296     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1297   }
1298 
1299   return SSym;
1300 }
1301 
1302 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1303     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1304     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1305   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1306   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1307   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1308   // computation of deltas to final external symbols. Example:
1309   //
1310   //    _extgotequiv:
1311   //       .long   _extfoo
1312   //
1313   //    _delta:
1314   //       .long   _extgotequiv-_delta
1315   //
1316   // is transformed to:
1317   //
1318   //    _delta:
1319   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1320   //
1321   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1322   //    L_extfoo$non_lazy_ptr:
1323   //       .indirect_symbol        _extfoo
1324   //       .long   0
1325   //
1326   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1327   // may point to both local (same translation unit) and global (other
1328   // translation units) symbols. Example:
1329   //
1330   // .section __DATA,__pointers,non_lazy_symbol_pointers
1331   // L1:
1332   //    .indirect_symbol _myGlobal
1333   //    .long 0
1334   // L2:
1335   //    .indirect_symbol _myLocal
1336   //    .long _myLocal
1337   //
1338   // If the symbol is local, instead of the symbol's index, the assembler
1339   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1340   // Then the linker will notice the constant in the table and will look at the
1341   // content of the symbol.
1342   MachineModuleInfoMachO &MachOMMI =
1343     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1344   MCContext &Ctx = getContext();
1345 
1346   // The offset must consider the original displacement from the base symbol
1347   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1348   Offset = -MV.getConstant();
1349   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1350 
1351   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1352   // non_lazy_ptr stubs.
1353   SmallString<128> Name;
1354   StringRef Suffix = "$non_lazy_ptr";
1355   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1356   Name += Sym->getName();
1357   Name += Suffix;
1358   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1359 
1360   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1361 
1362   if (!StubSym.getPointer())
1363     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1364                                                  !GV->hasLocalLinkage());
1365 
1366   const MCExpr *BSymExpr =
1367     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1368   const MCExpr *LHS =
1369     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1370 
1371   if (!Offset)
1372     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1373 
1374   const MCExpr *RHS =
1375     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1376   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1377 }
1378 
1379 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1380                                const MCSection &Section) {
1381   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1382     return true;
1383 
1384   // If it is not dead stripped, it is safe to use private labels.
1385   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1386   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1387     return true;
1388 
1389   return false;
1390 }
1391 
1392 void TargetLoweringObjectFileMachO::getNameWithPrefix(
1393     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1394     const TargetMachine &TM) const {
1395   bool CannotUsePrivateLabel = true;
1396   if (auto *GO = GV->getBaseObject()) {
1397     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1398     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1399     CannotUsePrivateLabel =
1400         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1401   }
1402   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1403 }
1404 
1405 //===----------------------------------------------------------------------===//
1406 //                                  COFF
1407 //===----------------------------------------------------------------------===//
1408 
1409 static unsigned
1410 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1411   unsigned Flags = 0;
1412   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1413 
1414   if (K.isMetadata())
1415     Flags |=
1416       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1417   else if (K.isText())
1418     Flags |=
1419       COFF::IMAGE_SCN_MEM_EXECUTE |
1420       COFF::IMAGE_SCN_MEM_READ |
1421       COFF::IMAGE_SCN_CNT_CODE |
1422       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1423   else if (K.isBSS())
1424     Flags |=
1425       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1426       COFF::IMAGE_SCN_MEM_READ |
1427       COFF::IMAGE_SCN_MEM_WRITE;
1428   else if (K.isThreadLocal())
1429     Flags |=
1430       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1431       COFF::IMAGE_SCN_MEM_READ |
1432       COFF::IMAGE_SCN_MEM_WRITE;
1433   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1434     Flags |=
1435       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1436       COFF::IMAGE_SCN_MEM_READ;
1437   else if (K.isWriteable())
1438     Flags |=
1439       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1440       COFF::IMAGE_SCN_MEM_READ |
1441       COFF::IMAGE_SCN_MEM_WRITE;
1442 
1443   return Flags;
1444 }
1445 
1446 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1447   const Comdat *C = GV->getComdat();
1448   assert(C && "expected GV to have a Comdat!");
1449 
1450   StringRef ComdatGVName = C->getName();
1451   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1452   if (!ComdatGV)
1453     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1454                        "' does not exist.");
1455 
1456   if (ComdatGV->getComdat() != C)
1457     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1458                        "' is not a key for its COMDAT.");
1459 
1460   return ComdatGV;
1461 }
1462 
1463 static int getSelectionForCOFF(const GlobalValue *GV) {
1464   if (const Comdat *C = GV->getComdat()) {
1465     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1466     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1467       ComdatKey = GA->getBaseObject();
1468     if (ComdatKey == GV) {
1469       switch (C->getSelectionKind()) {
1470       case Comdat::Any:
1471         return COFF::IMAGE_COMDAT_SELECT_ANY;
1472       case Comdat::ExactMatch:
1473         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1474       case Comdat::Largest:
1475         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1476       case Comdat::NoDuplicates:
1477         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1478       case Comdat::SameSize:
1479         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1480       }
1481     } else {
1482       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1483     }
1484   }
1485   return 0;
1486 }
1487 
1488 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1489     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1490   int Selection = 0;
1491   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1492   StringRef Name = GO->getSection();
1493   StringRef COMDATSymName = "";
1494   if (GO->hasComdat()) {
1495     Selection = getSelectionForCOFF(GO);
1496     const GlobalValue *ComdatGV;
1497     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1498       ComdatGV = getComdatGVForCOFF(GO);
1499     else
1500       ComdatGV = GO;
1501 
1502     if (!ComdatGV->hasPrivateLinkage()) {
1503       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1504       COMDATSymName = Sym->getName();
1505       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1506     } else {
1507       Selection = 0;
1508     }
1509   }
1510 
1511   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1512                                      Selection);
1513 }
1514 
1515 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1516   if (Kind.isText())
1517     return ".text";
1518   if (Kind.isBSS())
1519     return ".bss";
1520   if (Kind.isThreadLocal())
1521     return ".tls$";
1522   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1523     return ".rdata";
1524   return ".data";
1525 }
1526 
1527 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1528     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1529   // If we have -ffunction-sections then we should emit the global value to a
1530   // uniqued section specifically for it.
1531   bool EmitUniquedSection;
1532   if (Kind.isText())
1533     EmitUniquedSection = TM.getFunctionSections();
1534   else
1535     EmitUniquedSection = TM.getDataSections();
1536 
1537   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1538     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1539 
1540     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1541 
1542     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1543     int Selection = getSelectionForCOFF(GO);
1544     if (!Selection)
1545       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1546     const GlobalValue *ComdatGV;
1547     if (GO->hasComdat())
1548       ComdatGV = getComdatGVForCOFF(GO);
1549     else
1550       ComdatGV = GO;
1551 
1552     unsigned UniqueID = MCContext::GenericSectionID;
1553     if (EmitUniquedSection)
1554       UniqueID = NextUniqueID++;
1555 
1556     if (!ComdatGV->hasPrivateLinkage()) {
1557       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1558       StringRef COMDATSymName = Sym->getName();
1559 
1560       if (const auto *F = dyn_cast<Function>(GO))
1561         if (Optional<StringRef> Prefix = F->getSectionPrefix())
1562           raw_svector_ostream(Name) << '$' << *Prefix;
1563 
1564       // Append "$symbol" to the section name *before* IR-level mangling is
1565       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1566       // COFF linker will not properly handle comdats otherwise.
1567       if (getTargetTriple().isWindowsGNUEnvironment())
1568         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1569 
1570       return getContext().getCOFFSection(Name, Characteristics, Kind,
1571                                          COMDATSymName, Selection, UniqueID);
1572     } else {
1573       SmallString<256> TmpData;
1574       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1575       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1576                                          Selection, UniqueID);
1577     }
1578   }
1579 
1580   if (Kind.isText())
1581     return TextSection;
1582 
1583   if (Kind.isThreadLocal())
1584     return TLSDataSection;
1585 
1586   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1587     return ReadOnlySection;
1588 
1589   // Note: we claim that common symbols are put in BSSSection, but they are
1590   // really emitted with the magic .comm directive, which creates a symbol table
1591   // entry but not a section.
1592   if (Kind.isBSS() || Kind.isCommon())
1593     return BSSSection;
1594 
1595   return DataSection;
1596 }
1597 
1598 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1599     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1600     const TargetMachine &TM) const {
1601   bool CannotUsePrivateLabel = false;
1602   if (GV->hasPrivateLinkage() &&
1603       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1604        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1605     CannotUsePrivateLabel = true;
1606 
1607   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1608 }
1609 
1610 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1611     const Function &F, const TargetMachine &TM) const {
1612   // If the function can be removed, produce a unique section so that
1613   // the table doesn't prevent the removal.
1614   const Comdat *C = F.getComdat();
1615   bool EmitUniqueSection = TM.getFunctionSections() || C;
1616   if (!EmitUniqueSection)
1617     return ReadOnlySection;
1618 
1619   // FIXME: we should produce a symbol for F instead.
1620   if (F.hasPrivateLinkage())
1621     return ReadOnlySection;
1622 
1623   MCSymbol *Sym = TM.getSymbol(&F);
1624   StringRef COMDATSymName = Sym->getName();
1625 
1626   SectionKind Kind = SectionKind::getReadOnly();
1627   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1628   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1629   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1630   unsigned UniqueID = NextUniqueID++;
1631 
1632   return getContext().getCOFFSection(
1633       SecName, Characteristics, Kind, COMDATSymName,
1634       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1635 }
1636 
1637 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1638                                                       Module &M) const {
1639   emitLinkerDirectives(Streamer, M);
1640 
1641   unsigned Version = 0;
1642   unsigned Flags = 0;
1643   StringRef Section;
1644 
1645   GetObjCImageInfo(M, Version, Flags, Section);
1646   if (!Section.empty()) {
1647     auto &C = getContext();
1648     auto *S = C.getCOFFSection(Section,
1649                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1650                                    COFF::IMAGE_SCN_MEM_READ,
1651                                SectionKind::getReadOnly());
1652     Streamer.SwitchSection(S);
1653     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1654     Streamer.emitInt32(Version);
1655     Streamer.emitInt32(Flags);
1656     Streamer.AddBlankLine();
1657   }
1658 
1659   emitCGProfileMetadata(Streamer, M);
1660 }
1661 
1662 void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1663     MCStreamer &Streamer, Module &M) const {
1664   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1665     // Emit the linker options to the linker .drectve section.  According to the
1666     // spec, this section is a space-separated string containing flags for
1667     // linker.
1668     MCSection *Sec = getDrectveSection();
1669     Streamer.SwitchSection(Sec);
1670     for (const auto *Option : LinkerOptions->operands()) {
1671       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1672         // Lead with a space for consistency with our dllexport implementation.
1673         std::string Directive(" ");
1674         Directive.append(std::string(cast<MDString>(Piece)->getString()));
1675         Streamer.emitBytes(Directive);
1676       }
1677     }
1678   }
1679 
1680   // Emit /EXPORT: flags for each exported global as necessary.
1681   std::string Flags;
1682   for (const GlobalValue &GV : M.global_values()) {
1683     raw_string_ostream OS(Flags);
1684     emitLinkerFlagsForGlobalCOFF(OS, &GV, getTargetTriple(), getMangler());
1685     OS.flush();
1686     if (!Flags.empty()) {
1687       Streamer.SwitchSection(getDrectveSection());
1688       Streamer.emitBytes(Flags);
1689     }
1690     Flags.clear();
1691   }
1692 
1693   // Emit /INCLUDE: flags for each used global as necessary.
1694   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1695     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1696     assert(isa<ArrayType>(LU->getValueType()) &&
1697            "expected llvm.used to be an array type");
1698     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1699       for (const Value *Op : A->operands()) {
1700         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1701         // Global symbols with internal or private linkage are not visible to
1702         // the linker, and thus would cause an error when the linker tried to
1703         // preserve the symbol due to the `/include:` directive.
1704         if (GV->hasLocalLinkage())
1705           continue;
1706 
1707         raw_string_ostream OS(Flags);
1708         emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1709         OS.flush();
1710 
1711         if (!Flags.empty()) {
1712           Streamer.SwitchSection(getDrectveSection());
1713           Streamer.emitBytes(Flags);
1714         }
1715         Flags.clear();
1716       }
1717     }
1718   }
1719 }
1720 
1721 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1722                                               const TargetMachine &TM) {
1723   TargetLoweringObjectFile::Initialize(Ctx, TM);
1724   this->TM = &TM;
1725   const Triple &T = TM.getTargetTriple();
1726   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1727     StaticCtorSection =
1728         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1729                                            COFF::IMAGE_SCN_MEM_READ,
1730                            SectionKind::getReadOnly());
1731     StaticDtorSection =
1732         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1733                                            COFF::IMAGE_SCN_MEM_READ,
1734                            SectionKind::getReadOnly());
1735   } else {
1736     StaticCtorSection = Ctx.getCOFFSection(
1737         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1738                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1739         SectionKind::getData());
1740     StaticDtorSection = Ctx.getCOFFSection(
1741         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1742                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1743         SectionKind::getData());
1744   }
1745 }
1746 
1747 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1748                                                    const Triple &T, bool IsCtor,
1749                                                    unsigned Priority,
1750                                                    const MCSymbol *KeySym,
1751                                                    MCSectionCOFF *Default) {
1752   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1753     // If the priority is the default, use .CRT$XCU, possibly associative.
1754     if (Priority == 65535)
1755       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1756 
1757     // Otherwise, we need to compute a new section name. Low priorities should
1758     // run earlier. The linker will sort sections ASCII-betically, and we need a
1759     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1760     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1761     // low priorities need to sort before 'L', since the CRT uses that
1762     // internally, so we use ".CRT$XCA00001" for them.
1763     SmallString<24> Name;
1764     raw_svector_ostream OS(Name);
1765     OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
1766         (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1767     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1768         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1769         SectionKind::getReadOnly());
1770     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1771   }
1772 
1773   std::string Name = IsCtor ? ".ctors" : ".dtors";
1774   if (Priority != 65535)
1775     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1776 
1777   return Ctx.getAssociativeCOFFSection(
1778       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1779                                    COFF::IMAGE_SCN_MEM_READ |
1780                                    COFF::IMAGE_SCN_MEM_WRITE,
1781                          SectionKind::getData()),
1782       KeySym, 0);
1783 }
1784 
1785 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1786     unsigned Priority, const MCSymbol *KeySym) const {
1787   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1788                                       Priority, KeySym,
1789                                       cast<MCSectionCOFF>(StaticCtorSection));
1790 }
1791 
1792 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1793     unsigned Priority, const MCSymbol *KeySym) const {
1794   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1795                                       Priority, KeySym,
1796                                       cast<MCSectionCOFF>(StaticDtorSection));
1797 }
1798 
1799 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1800     const GlobalValue *LHS, const GlobalValue *RHS,
1801     const TargetMachine &TM) const {
1802   const Triple &T = TM.getTargetTriple();
1803   if (T.isOSCygMing())
1804     return nullptr;
1805 
1806   // Our symbols should exist in address space zero, cowardly no-op if
1807   // otherwise.
1808   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1809       RHS->getType()->getPointerAddressSpace() != 0)
1810     return nullptr;
1811 
1812   // Both ptrtoint instructions must wrap global objects:
1813   // - Only global variables are eligible for image relative relocations.
1814   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1815   // We expect __ImageBase to be a global variable without a section, externally
1816   // defined.
1817   //
1818   // It should look something like this: @__ImageBase = external constant i8
1819   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1820       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1821       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1822       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1823     return nullptr;
1824 
1825   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1826                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
1827                                  getContext());
1828 }
1829 
1830 static std::string APIntToHexString(const APInt &AI) {
1831   unsigned Width = (AI.getBitWidth() / 8) * 2;
1832   std::string HexString = AI.toString(16, /*Signed=*/false);
1833   llvm::transform(HexString, HexString.begin(), tolower);
1834   unsigned Size = HexString.size();
1835   assert(Width >= Size && "hex string is too large!");
1836   HexString.insert(HexString.begin(), Width - Size, '0');
1837 
1838   return HexString;
1839 }
1840 
1841 static std::string scalarConstantToHexString(const Constant *C) {
1842   Type *Ty = C->getType();
1843   if (isa<UndefValue>(C)) {
1844     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1845   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1846     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1847   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1848     return APIntToHexString(CI->getValue());
1849   } else {
1850     unsigned NumElements;
1851     if (auto *VTy = dyn_cast<VectorType>(Ty))
1852       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
1853     else
1854       NumElements = Ty->getArrayNumElements();
1855     std::string HexString;
1856     for (int I = NumElements - 1, E = -1; I != E; --I)
1857       HexString += scalarConstantToHexString(C->getAggregateElement(I));
1858     return HexString;
1859   }
1860 }
1861 
1862 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1863     const DataLayout &DL, SectionKind Kind, const Constant *C,
1864     Align &Alignment) const {
1865   if (Kind.isMergeableConst() && C &&
1866       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1867     // This creates comdat sections with the given symbol name, but unless
1868     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1869     // will be created with a null storage class, which makes GNU binutils
1870     // error out.
1871     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1872                                      COFF::IMAGE_SCN_MEM_READ |
1873                                      COFF::IMAGE_SCN_LNK_COMDAT;
1874     std::string COMDATSymName;
1875     if (Kind.isMergeableConst4()) {
1876       if (Alignment <= 4) {
1877         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1878         Alignment = Align(4);
1879       }
1880     } else if (Kind.isMergeableConst8()) {
1881       if (Alignment <= 8) {
1882         COMDATSymName = "__real@" + scalarConstantToHexString(C);
1883         Alignment = Align(8);
1884       }
1885     } else if (Kind.isMergeableConst16()) {
1886       // FIXME: These may not be appropriate for non-x86 architectures.
1887       if (Alignment <= 16) {
1888         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1889         Alignment = Align(16);
1890       }
1891     } else if (Kind.isMergeableConst32()) {
1892       if (Alignment <= 32) {
1893         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1894         Alignment = Align(32);
1895       }
1896     }
1897 
1898     if (!COMDATSymName.empty())
1899       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1900                                          COMDATSymName,
1901                                          COFF::IMAGE_COMDAT_SELECT_ANY);
1902   }
1903 
1904   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
1905                                                          Alignment);
1906 }
1907 
1908 //===----------------------------------------------------------------------===//
1909 //                                  Wasm
1910 //===----------------------------------------------------------------------===//
1911 
1912 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1913   const Comdat *C = GV->getComdat();
1914   if (!C)
1915     return nullptr;
1916 
1917   if (C->getSelectionKind() != Comdat::Any)
1918     report_fatal_error("WebAssembly COMDATs only support "
1919                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
1920                        "lowered.");
1921 
1922   return C;
1923 }
1924 
1925 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1926     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1927   // We don't support explict section names for functions in the wasm object
1928   // format.  Each function has to be in its own unique section.
1929   if (isa<Function>(GO)) {
1930     return SelectSectionForGlobal(GO, Kind, TM);
1931   }
1932 
1933   StringRef Name = GO->getSection();
1934 
1935   // Certain data sections we treat as named custom sections rather than
1936   // segments within the data section.
1937   // This could be avoided if all data segements (the wasm sense) were
1938   // represented as their own sections (in the llvm sense).
1939   // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
1940   if (Name == ".llvmcmd" || Name == ".llvmbc")
1941     Kind = SectionKind::getMetadata();
1942 
1943   StringRef Group = "";
1944   if (const Comdat *C = getWasmComdat(GO)) {
1945     Group = C->getName();
1946   }
1947 
1948   MCSectionWasm* Section =
1949       getContext().getWasmSection(Name, Kind, Group,
1950                                   MCContext::GenericSectionID);
1951 
1952   return Section;
1953 }
1954 
1955 static MCSectionWasm *selectWasmSectionForGlobal(
1956     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1957     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1958   StringRef Group = "";
1959   if (const Comdat *C = getWasmComdat(GO)) {
1960     Group = C->getName();
1961   }
1962 
1963   bool UniqueSectionNames = TM.getUniqueSectionNames();
1964   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1965 
1966   if (const auto *F = dyn_cast<Function>(GO)) {
1967     const auto &OptionalPrefix = F->getSectionPrefix();
1968     if (OptionalPrefix)
1969       raw_svector_ostream(Name) << '.' << *OptionalPrefix;
1970   }
1971 
1972   if (EmitUniqueSection && UniqueSectionNames) {
1973     Name.push_back('.');
1974     TM.getNameWithPrefix(Name, GO, Mang, true);
1975   }
1976   unsigned UniqueID = MCContext::GenericSectionID;
1977   if (EmitUniqueSection && !UniqueSectionNames) {
1978     UniqueID = *NextUniqueID;
1979     (*NextUniqueID)++;
1980   }
1981 
1982   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1983 }
1984 
1985 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1986     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1987 
1988   if (Kind.isCommon())
1989     report_fatal_error("mergable sections not supported yet on wasm");
1990 
1991   // If we have -ffunction-section or -fdata-section then we should emit the
1992   // global value to a uniqued section specifically for it.
1993   bool EmitUniqueSection = false;
1994   if (Kind.isText())
1995     EmitUniqueSection = TM.getFunctionSections();
1996   else
1997     EmitUniqueSection = TM.getDataSections();
1998   EmitUniqueSection |= GO->hasComdat();
1999 
2000   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2001                                     EmitUniqueSection, &NextUniqueID);
2002 }
2003 
2004 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
2005     bool UsesLabelDifference, const Function &F) const {
2006   // We can always create relative relocations, so use another section
2007   // that can be marked non-executable.
2008   return false;
2009 }
2010 
2011 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
2012     const GlobalValue *LHS, const GlobalValue *RHS,
2013     const TargetMachine &TM) const {
2014   // We may only use a PLT-relative relocation to refer to unnamed_addr
2015   // functions.
2016   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2017     return nullptr;
2018 
2019   // Basic sanity checks.
2020   if (LHS->getType()->getPointerAddressSpace() != 0 ||
2021       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2022       RHS->isThreadLocal())
2023     return nullptr;
2024 
2025   return MCBinaryExpr::createSub(
2026       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
2027                               getContext()),
2028       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
2029 }
2030 
2031 void TargetLoweringObjectFileWasm::InitializeWasm() {
2032   StaticCtorSection =
2033       getContext().getWasmSection(".init_array", SectionKind::getData());
2034 
2035   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2036   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2037   TTypeEncoding = dwarf::DW_EH_PE_absptr;
2038 }
2039 
2040 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
2041     unsigned Priority, const MCSymbol *KeySym) const {
2042   return Priority == UINT16_MAX ?
2043          StaticCtorSection :
2044          getContext().getWasmSection(".init_array." + utostr(Priority),
2045                                      SectionKind::getData());
2046 }
2047 
2048 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
2049     unsigned Priority, const MCSymbol *KeySym) const {
2050   llvm_unreachable("@llvm.global_dtors should have been lowered already");
2051   return nullptr;
2052 }
2053 
2054 //===----------------------------------------------------------------------===//
2055 //                                  XCOFF
2056 //===----------------------------------------------------------------------===//
2057 bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
2058     const MachineFunction *MF) {
2059   if (!MF->getLandingPads().empty())
2060     return true;
2061 
2062   const Function &F = MF->getFunction();
2063   if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2064     return false;
2065 
2066   const Function *Per =
2067       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2068   if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
2069     return false;
2070 
2071   return true;
2072 }
2073 
2074 MCSymbol *
2075 TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
2076   return MF->getMMI().getContext().getOrCreateSymbol(
2077       "__ehinfo." + Twine(MF->getFunctionNumber()));
2078 }
2079 
2080 MCSymbol *
2081 TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
2082                                                const TargetMachine &TM) const {
2083   // We always use a qualname symbol for a GV that represents
2084   // a declaration, a function descriptor, or a common symbol.
2085   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2086   // also return a qualname so that a label symbol could be avoided.
2087   // It is inherently ambiguous when the GO represents the address of a
2088   // function, as the GO could either represent a function descriptor or a
2089   // function entry point. We choose to always return a function descriptor
2090   // here.
2091   if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2092     if (GO->isDeclarationForLinker())
2093       return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2094           ->getQualNameSymbol();
2095 
2096     SectionKind GOKind = getKindForGlobal(GO, TM);
2097     if (GOKind.isText())
2098       return cast<MCSectionXCOFF>(
2099                  getSectionForFunctionDescriptor(cast<Function>(GO), TM))
2100           ->getQualNameSymbol();
2101     if ((TM.getDataSections() && !GO->hasSection()) || GOKind.isCommon() ||
2102         GOKind.isBSSLocal())
2103       return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
2104           ->getQualNameSymbol();
2105   }
2106 
2107   // For all other cases, fall back to getSymbol to return the unqualified name.
2108   return nullptr;
2109 }
2110 
2111 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
2112     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2113   if (!GO->hasSection())
2114     report_fatal_error("#pragma clang section is not yet supported");
2115 
2116   StringRef SectionName = GO->getSection();
2117   XCOFF::StorageMappingClass MappingClass;
2118   if (Kind.isText())
2119     MappingClass = XCOFF::XMC_PR;
2120   else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
2121     MappingClass = XCOFF::XMC_RW;
2122   else if (Kind.isReadOnly())
2123     MappingClass = XCOFF::XMC_RO;
2124   else
2125     report_fatal_error("XCOFF other section types not yet implemented.");
2126 
2127   return getContext().getXCOFFSection(SectionName, MappingClass, XCOFF::XTY_SD,
2128                                       Kind, /* MultiSymbolsAllowed*/ true);
2129 }
2130 
2131 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
2132     const GlobalObject *GO, const TargetMachine &TM) const {
2133   assert(GO->isDeclarationForLinker() &&
2134          "Tried to get ER section for a defined global.");
2135 
2136   SmallString<128> Name;
2137   getNameWithPrefix(Name, GO, TM);
2138 
2139   // Externals go into a csect of type ER.
2140   return getContext().getXCOFFSection(
2141       Name, isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA, XCOFF::XTY_ER,
2142       SectionKind::getMetadata());
2143 }
2144 
2145 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
2146     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2147   // Common symbols go into a csect with matching name which will get mapped
2148   // into the .bss section.
2149   if (Kind.isBSSLocal() || Kind.isCommon()) {
2150     SmallString<128> Name;
2151     getNameWithPrefix(Name, GO, TM);
2152     return getContext().getXCOFFSection(
2153         Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM,
2154         Kind);
2155   }
2156 
2157   if (Kind.isMergeableCString()) {
2158     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
2159         cast<GlobalVariable>(GO));
2160 
2161     unsigned EntrySize = getEntrySizeForKind(Kind);
2162     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
2163     SmallString<128> Name;
2164     Name = SizeSpec + utostr(Alignment.value());
2165 
2166     if (TM.getDataSections())
2167       getNameWithPrefix(Name, GO, TM);
2168 
2169     return getContext().getXCOFFSection(
2170         Name, XCOFF::XMC_RO, XCOFF::XTY_SD, Kind,
2171         /* MultiSymbolsAllowed*/ !TM.getDataSections());
2172   }
2173 
2174   if (Kind.isText()) {
2175     if (TM.getFunctionSections()) {
2176       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2177           ->getRepresentedCsect();
2178     }
2179     return TextSection;
2180   }
2181 
2182   // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
2183   // user may want to have read-only data with relocations placed into a
2184   // read-only section by the compiler.
2185   // For BSS kind, zero initialized data must be emitted to the .data section
2186   // because external linkage control sections that get mapped to the .bss
2187   // section will be linked as tentative defintions, which is only appropriate
2188   // for SectionKind::Common.
2189   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2190     if (TM.getDataSections()) {
2191       SmallString<128> Name;
2192       getNameWithPrefix(Name, GO, TM);
2193       return getContext().getXCOFFSection(Name, XCOFF::XMC_RW, XCOFF::XTY_SD,
2194                                           SectionKind::getData());
2195     }
2196     return DataSection;
2197   }
2198 
2199   if (Kind.isReadOnly()) {
2200     if (TM.getDataSections()) {
2201       SmallString<128> Name;
2202       getNameWithPrefix(Name, GO, TM);
2203       return getContext().getXCOFFSection(Name, XCOFF::XMC_RO, XCOFF::XTY_SD,
2204                                           SectionKind::getReadOnly());
2205     }
2206     return ReadOnlySection;
2207   }
2208 
2209   report_fatal_error("XCOFF other section types not yet implemented.");
2210 }
2211 
2212 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2213     const Function &F, const TargetMachine &TM) const {
2214   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2215 
2216   if (!TM.getFunctionSections())
2217     return ReadOnlySection;
2218 
2219   // If the function can be removed, produce a unique section so that
2220   // the table doesn't prevent the removal.
2221   SmallString<128> NameStr(".rodata.jmp..");
2222   getNameWithPrefix(NameStr, &F, TM);
2223   return getContext().getXCOFFSection(NameStr, XCOFF::XMC_RO, XCOFF::XTY_SD,
2224                                       SectionKind::getReadOnly());
2225 }
2226 
2227 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
2228     bool UsesLabelDifference, const Function &F) const {
2229   return false;
2230 }
2231 
2232 /// Given a mergeable constant with the specified size and relocation
2233 /// information, return a section that it should be placed in.
2234 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2235     const DataLayout &DL, SectionKind Kind, const Constant *C,
2236     Align &Alignment) const {
2237   //TODO: Enable emiting constant pool to unique sections when we support it.
2238   return ReadOnlySection;
2239 }
2240 
2241 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
2242                                                const TargetMachine &TgtM) {
2243   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2244   TTypeEncoding =
2245       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
2246       (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2247                                             : dwarf::DW_EH_PE_sdata8);
2248   PersonalityEncoding = 0;
2249   LSDAEncoding = 0;
2250   CallSiteEncoding = dwarf::DW_EH_PE_udata4;
2251 }
2252 
2253 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
2254 	unsigned Priority, const MCSymbol *KeySym) const {
2255   report_fatal_error("no static constructor section on AIX");
2256 }
2257 
2258 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
2259 	unsigned Priority, const MCSymbol *KeySym) const {
2260   report_fatal_error("no static destructor section on AIX");
2261 }
2262 
2263 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
2264     const GlobalValue *LHS, const GlobalValue *RHS,
2265     const TargetMachine &TM) const {
2266   report_fatal_error("XCOFF not yet implemented.");
2267 }
2268 
2269 XCOFF::StorageClass
2270 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2271   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2272 
2273   switch (GV->getLinkage()) {
2274   case GlobalValue::InternalLinkage:
2275   case GlobalValue::PrivateLinkage:
2276     return XCOFF::C_HIDEXT;
2277   case GlobalValue::ExternalLinkage:
2278   case GlobalValue::CommonLinkage:
2279   case GlobalValue::AvailableExternallyLinkage:
2280     return XCOFF::C_EXT;
2281   case GlobalValue::ExternalWeakLinkage:
2282   case GlobalValue::LinkOnceAnyLinkage:
2283   case GlobalValue::LinkOnceODRLinkage:
2284   case GlobalValue::WeakAnyLinkage:
2285   case GlobalValue::WeakODRLinkage:
2286     return XCOFF::C_WEAKEXT;
2287   case GlobalValue::AppendingLinkage:
2288     report_fatal_error(
2289         "There is no mapping that implements AppendingLinkage for XCOFF.");
2290   }
2291   llvm_unreachable("Unknown linkage type!");
2292 }
2293 
2294 MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2295     const GlobalValue *Func, const TargetMachine &TM) const {
2296   assert(
2297       (isa<Function>(Func) ||
2298        (isa<GlobalAlias>(Func) &&
2299         isa_and_nonnull<Function>(cast<GlobalAlias>(Func)->getBaseObject()))) &&
2300       "Func must be a function or an alias which has a function as base "
2301       "object.");
2302 
2303   SmallString<128> NameStr;
2304   NameStr.push_back('.');
2305   getNameWithPrefix(NameStr, Func, TM);
2306 
2307   // When -function-sections is enabled and explicit section is not specified,
2308   // it's not necessary to emit function entry point label any more. We will use
2309   // function entry point csect instead. And for function delcarations, the
2310   // undefined symbols gets treated as csect with XTY_ER property.
2311   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2312        Func->isDeclaration()) &&
2313       isa<Function>(Func)) {
2314     return getContext()
2315         .getXCOFFSection(NameStr, XCOFF::XMC_PR,
2316                          Func->isDeclaration() ? XCOFF::XTY_ER : XCOFF::XTY_SD,
2317                          SectionKind::getText())
2318         ->getQualNameSymbol();
2319   }
2320 
2321   return getContext().getOrCreateSymbol(NameStr);
2322 }
2323 
2324 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
2325     const Function *F, const TargetMachine &TM) const {
2326   SmallString<128> NameStr;
2327   getNameWithPrefix(NameStr, F, TM);
2328   return getContext().getXCOFFSection(NameStr, XCOFF::XMC_DS, XCOFF::XTY_SD,
2329                                       SectionKind::getData());
2330 }
2331 
2332 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2333     const MCSymbol *Sym, const TargetMachine &TM) const {
2334   // Use TE storage-mapping class when large code model is enabled so that
2335   // the chance of needing -bbigtoc is decreased.
2336   return getContext().getXCOFFSection(
2337       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(),
2338       TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
2339       XCOFF::XTY_SD, SectionKind::getData());
2340 }
2341