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