1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
12 //===----------------------------------------------------------------------===//
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"
67 using namespace dwarf;
69 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
71 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
72 M.getModuleFlagsMetadata(ModuleFlags);
74 for (const auto &MFE: ModuleFlags) {
75 // Ignore flags with 'Require' behaviour.
76 if (MFE.Behavior == Module::Require)
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();
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;
103 //===----------------------------------------------------------------------===//
105 //===----------------------------------------------------------------------===//
107 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
108 const TargetMachine &TgtM) {
109 TargetLoweringObjectFile::Initialize(Ctx, TgtM);
112 CodeModel::Model CM = TgtM.getCodeModel();
113 InitializeELF(TgtM.Options.UseInitArray);
115 switch (TgtM.getTargetTriple().getArch()) {
119 case Triple::thumbeb:
120 if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
122 // Fallthrough if not using EHABI
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;
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);
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;
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;
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;
183 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
184 LSDAEncoding = dwarf::DW_EH_PE_absptr;
185 TTypeEncoding = dwarf::DW_EH_PE_absptr;
189 LSDAEncoding = dwarf::DW_EH_PE_absptr;
190 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
191 TTypeEncoding = dwarf::DW_EH_PE_absptr;
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.
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
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;
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;
224 case Triple::sparcel:
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;
233 LSDAEncoding = dwarf::DW_EH_PE_absptr;
234 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
235 TTypeEncoding = dwarf::DW_EH_PE_absptr;
237 CallSiteEncoding = dwarf::DW_EH_PE_udata4;
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;
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;
256 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
257 TTypeEncoding = dwarf::DW_EH_PE_absptr;
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;
270 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
271 LSDAEncoding = dwarf::DW_EH_PE_absptr;
272 TTypeEncoding = dwarf::DW_EH_PE_absptr;
280 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
282 auto &C = getContext();
284 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
285 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
288 Streamer.SwitchSection(S);
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);
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, "");
304 Streamer.SwitchSection(S);
306 for (const auto *Operand : DependentLibraries->operands()) {
308 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
309 Streamer.emitInt8(0);
313 unsigned Version = 0;
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();
327 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
328 M.getModuleFlagsMetadata(ModuleFlags);
330 MDNode *CFGProfile = nullptr;
332 for (const auto &MFE : ModuleFlags) {
333 StringRef Key = MFE.Key->getString();
334 if (Key == "CG Profile") {
335 CFGProfile = cast<MDNode>(MFE.Val);
343 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
346 auto V = cast<ValueAsMetadata>(MDO);
347 const Function *F = cast<Function>(V->getValue());
348 return TM->getSymbol(F);
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.
359 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
363 Streamer.emitCGProfileEntry(
364 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
365 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
369 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!");
381 void TargetLoweringObjectFileELF::emitPersonalityValue(
382 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
383 SmallString<64> NameData("DW.ref.");
384 NameData += Sym->getName();
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 Size = DL.getPointerSize();
393 Streamer.SwitchSection(Sec);
394 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
395 Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
396 const MCExpr *E = MCConstantExpr::create(Size, getContext());
397 Streamer.emitELFSize(Label, E);
398 Streamer.emitLabel(Label);
400 Streamer.emitSymbolValue(Sym, Size);
403 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
404 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
405 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
406 if (Encoding & DW_EH_PE_indirect) {
407 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
409 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
411 // Add information about the stub reference to ELFMMI so that the stub
412 // gets emitted by the asmprinter.
413 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
414 if (!StubSym.getPointer()) {
415 MCSymbol *Sym = TM.getSymbol(GV);
416 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
419 return TargetLoweringObjectFile::
420 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
421 Encoding & ~DW_EH_PE_indirect, Streamer);
424 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
428 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
429 // N.B.: The defaults used in here are not the same ones used in MC.
430 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
431 // both gas and MC will produce a section with no flags. Given
432 // section(".eh_frame") gcc will produce:
434 // .section .eh_frame,"a",@progbits
436 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
437 /*AddSegmentInfo=*/false) ||
438 Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
439 /*AddSegmentInfo=*/false))
440 return SectionKind::getMetadata();
442 if (Name.empty() || Name[0] != '.') return K;
444 // Default implementation based on some magic section names.
445 if (Name == ".bss" ||
446 Name.startswith(".bss.") ||
447 Name.startswith(".gnu.linkonce.b.") ||
448 Name.startswith(".llvm.linkonce.b.") ||
450 Name.startswith(".sbss.") ||
451 Name.startswith(".gnu.linkonce.sb.") ||
452 Name.startswith(".llvm.linkonce.sb."))
453 return SectionKind::getBSS();
455 if (Name == ".tdata" ||
456 Name.startswith(".tdata.") ||
457 Name.startswith(".gnu.linkonce.td.") ||
458 Name.startswith(".llvm.linkonce.td."))
459 return SectionKind::getThreadData();
461 if (Name == ".tbss" ||
462 Name.startswith(".tbss.") ||
463 Name.startswith(".gnu.linkonce.tb.") ||
464 Name.startswith(".llvm.linkonce.tb."))
465 return SectionKind::getThreadBSS();
470 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
471 // Use SHT_NOTE for section whose name starts with ".note" to allow
472 // emitting ELF notes from C variable declaration.
473 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
474 if (Name.startswith(".note"))
475 return ELF::SHT_NOTE;
477 if (Name == ".init_array")
478 return ELF::SHT_INIT_ARRAY;
480 if (Name == ".fini_array")
481 return ELF::SHT_FINI_ARRAY;
483 if (Name == ".preinit_array")
484 return ELF::SHT_PREINIT_ARRAY;
486 if (K.isBSS() || K.isThreadBSS())
487 return ELF::SHT_NOBITS;
489 return ELF::SHT_PROGBITS;
492 static unsigned getELFSectionFlags(SectionKind K) {
496 Flags |= ELF::SHF_ALLOC;
499 Flags |= ELF::SHF_EXECINSTR;
501 if (K.isExecuteOnly())
502 Flags |= ELF::SHF_ARM_PURECODE;
505 Flags |= ELF::SHF_WRITE;
507 if (K.isThreadLocal())
508 Flags |= ELF::SHF_TLS;
510 if (K.isMergeableCString() || K.isMergeableConst())
511 Flags |= ELF::SHF_MERGE;
513 if (K.isMergeableCString())
514 Flags |= ELF::SHF_STRINGS;
519 static const Comdat *getELFComdat(const GlobalValue *GV) {
520 const Comdat *C = GV->getComdat();
524 if (C->getSelectionKind() != Comdat::Any)
525 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
526 C->getName() + "' cannot be lowered.");
531 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
532 const TargetMachine &TM) {
533 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
537 const MDOperand &Op = MD->getOperand(0);
541 auto *VM = dyn_cast<ValueAsMetadata>(Op);
543 report_fatal_error("MD_associated operand is not ValueAsMetadata");
545 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
546 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
549 static unsigned getEntrySizeForKind(SectionKind Kind) {
550 if (Kind.isMergeable1ByteCString())
552 else if (Kind.isMergeable2ByteCString())
554 else if (Kind.isMergeable4ByteCString())
556 else if (Kind.isMergeableConst4())
558 else if (Kind.isMergeableConst8())
560 else if (Kind.isMergeableConst16())
562 else if (Kind.isMergeableConst32())
565 // We shouldn't have mergeable C strings or mergeable constants that we
566 // didn't handle above.
567 assert(!Kind.isMergeableCString() && "unknown string width");
568 assert(!Kind.isMergeableConst() && "unknown data width");
573 /// Return the section prefix name used by options FunctionsSections and
575 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
578 if (Kind.isReadOnly())
582 if (Kind.isThreadData())
584 if (Kind.isThreadBSS())
588 if (Kind.isReadOnlyWithRel())
589 return ".data.rel.ro";
590 llvm_unreachable("Unknown section kind");
593 static SmallString<128>
594 getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
595 Mangler &Mang, const TargetMachine &TM,
596 unsigned EntrySize, bool UniqueSectionName) {
597 SmallString<128> Name;
598 if (Kind.isMergeableCString()) {
599 // We also need alignment here.
600 // FIXME: this is getting the alignment of the character, not the
601 // alignment of the global!
602 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
603 cast<GlobalVariable>(GO));
605 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
606 Name = SizeSpec + utostr(Alignment.value());
607 } else if (Kind.isMergeableConst()) {
608 Name = ".rodata.cst";
609 Name += utostr(EntrySize);
611 Name = getSectionPrefixForGlobal(Kind);
614 bool HasPrefix = false;
615 if (const auto *F = dyn_cast<Function>(GO)) {
616 if (Optional<StringRef> Prefix = F->getSectionPrefix()) {
622 if (UniqueSectionName) {
624 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
625 } else if (HasPrefix)
631 class LoweringDiagnosticInfo : public DiagnosticInfo {
635 LoweringDiagnosticInfo(const Twine &DiagMsg,
636 DiagnosticSeverity Severity = DS_Error)
637 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
638 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
642 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
643 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
644 StringRef SectionName = GO->getSection();
646 // Check if '#pragma clang section' name is applicable.
647 // Note that pragma directive overrides -ffunction-section, -fdata-section
648 // and so section name is exactly as user specified and not uniqued.
649 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
650 if (GV && GV->hasImplicitSection()) {
651 auto Attrs = GV->getAttributes();
652 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
653 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
654 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
655 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
656 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
657 SectionName = Attrs.getAttribute("relro-section").getValueAsString();
658 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
659 SectionName = Attrs.getAttribute("data-section").getValueAsString();
662 const Function *F = dyn_cast<Function>(GO);
663 if (F && F->hasFnAttribute("implicit-section-name")) {
664 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
667 // Infer section flags from the section name if we can.
668 Kind = getELFKindForNamedSection(SectionName, Kind);
670 StringRef Group = "";
671 unsigned Flags = getELFSectionFlags(Kind);
672 if (const Comdat *C = getELFComdat(GO)) {
673 Group = C->getName();
674 Flags |= ELF::SHF_GROUP;
677 unsigned EntrySize = getEntrySizeForKind(Kind);
679 // A section can have at most one associated section. Put each global with
680 // MD_associated in a unique section.
681 unsigned UniqueID = MCContext::GenericSectionID;
682 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
684 UniqueID = NextUniqueID++;
685 Flags |= ELF::SHF_LINK_ORDER;
687 if (getContext().getAsmInfo()->useIntegratedAssembler()) {
688 // Symbols must be placed into sections with compatible entry
689 // sizes. Generate unique sections for symbols that have not
690 // been assigned to compatible sections.
691 if (Flags & ELF::SHF_MERGE) {
692 auto maybeID = getContext().getELFUniqueIDForEntsize(SectionName, Flags,
697 // If the user has specified the same section name as would be created
698 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
699 // to unique the section as the entry size for this symbol will be
700 // compatible with implicitly created sections.
701 SmallString<128> ImplicitSectionNameStem = getELFSectionNameForGlobal(
702 GO, Kind, getMangler(), TM, EntrySize, false);
703 if (!(getContext().isELFImplicitMergeableSectionNamePrefix(
705 SectionName.startswith(ImplicitSectionNameStem)))
706 UniqueID = NextUniqueID++;
709 // We need to unique the section if the user has explicity
710 // assigned a non-mergeable symbol to a section name for
711 // a generic mergeable section.
712 if (getContext().isELFGenericMergeableSection(SectionName)) {
713 auto maybeID = getContext().getELFUniqueIDForEntsize(
714 SectionName, Flags, EntrySize);
715 UniqueID = maybeID ? *maybeID : NextUniqueID++;
719 // If two symbols with differing sizes end up in the same mergeable
720 // section that section can be assigned an incorrect entry size. To avoid
721 // this we usually put symbols of the same size into distinct mergeable
722 // sections with the same name. Doing so relies on the ",unique ,"
723 // assembly feature. This feature is not avalible until bintuils
724 // version 2.35 (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
725 Flags &= ~ELF::SHF_MERGE;
730 MCSectionELF *Section = getContext().getELFSection(
731 SectionName, getELFSectionType(SectionName, Kind), Flags,
732 EntrySize, Group, UniqueID, LinkedToSym);
733 // Make sure that we did not get some other section with incompatible sh_link.
734 // This should not be possible due to UniqueID code above.
735 assert(Section->getLinkedToSymbol() == LinkedToSym &&
736 "Associated symbol mismatch between sections");
738 if (!getContext().getAsmInfo()->useIntegratedAssembler()) {
739 // If we are not using the integrated assembler then this symbol might have
740 // been placed in an incompatible mergeable section. Emit an error if this
741 // is the case to avoid creating broken output.
742 if ((Section->getFlags() & ELF::SHF_MERGE) &&
743 (Section->getEntrySize() != getEntrySizeForKind(Kind)))
744 GO->getContext().diagnose(LoweringDiagnosticInfo(
745 "Symbol '" + GO->getName() + "' from module '" +
746 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
747 "' required a section with entry-size=" +
748 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
749 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
750 ": Explicit assignment by pragma or attribute of an incompatible "
751 "symbol to this section?"));
757 static MCSectionELF *selectELFSectionForGlobal(
758 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
759 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
760 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
762 StringRef Group = "";
763 if (const Comdat *C = getELFComdat(GO)) {
764 Flags |= ELF::SHF_GROUP;
765 Group = C->getName();
768 // Get the section entry size based on the kind.
769 unsigned EntrySize = getEntrySizeForKind(Kind);
771 bool UniqueSectionName = false;
772 unsigned UniqueID = MCContext::GenericSectionID;
773 if (EmitUniqueSection) {
774 if (TM.getUniqueSectionNames()) {
775 UniqueSectionName = true;
777 UniqueID = *NextUniqueID;
781 SmallString<128> Name = getELFSectionNameForGlobal(
782 GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
784 // Use 0 as the unique ID for execute-only text.
785 if (Kind.isExecuteOnly())
787 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
788 EntrySize, Group, UniqueID, AssociatedSymbol);
791 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
792 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
793 unsigned Flags = getELFSectionFlags(Kind);
795 // If we have -ffunction-section or -fdata-section then we should emit the
796 // global value to a uniqued section specifically for it.
797 bool EmitUniqueSection = false;
798 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
800 EmitUniqueSection = TM.getFunctionSections();
802 EmitUniqueSection = TM.getDataSections();
804 EmitUniqueSection |= GO->hasComdat();
806 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
808 EmitUniqueSection = true;
809 Flags |= ELF::SHF_LINK_ORDER;
812 MCSectionELF *Section = selectELFSectionForGlobal(
813 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
814 &NextUniqueID, LinkedToSym);
815 assert(Section->getLinkedToSymbol() == LinkedToSym);
819 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
820 const Function &F, const TargetMachine &TM) const {
821 // If the function can be removed, produce a unique section so that
822 // the table doesn't prevent the removal.
823 const Comdat *C = F.getComdat();
824 bool EmitUniqueSection = TM.getFunctionSections() || C;
825 if (!EmitUniqueSection)
826 return ReadOnlySection;
828 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
829 getMangler(), TM, EmitUniqueSection,
830 ELF::SHF_ALLOC, &NextUniqueID,
831 /* AssociatedSymbol */ nullptr);
834 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
835 bool UsesLabelDifference, const Function &F) const {
836 // We can always create relative relocations, so use another section
837 // that can be marked non-executable.
841 /// Given a mergeable constant with the specified size and relocation
842 /// information, return a section that it should be placed in.
843 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
844 const DataLayout &DL, SectionKind Kind, const Constant *C,
845 Align &Alignment) const {
846 if (Kind.isMergeableConst4() && MergeableConst4Section)
847 return MergeableConst4Section;
848 if (Kind.isMergeableConst8() && MergeableConst8Section)
849 return MergeableConst8Section;
850 if (Kind.isMergeableConst16() && MergeableConst16Section)
851 return MergeableConst16Section;
852 if (Kind.isMergeableConst32() && MergeableConst32Section)
853 return MergeableConst32Section;
854 if (Kind.isReadOnly())
855 return ReadOnlySection;
857 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
858 return DataRelROSection;
861 /// Returns a unique section for the given machine basic block.
862 MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
863 const Function &F, const MachineBasicBlock &MBB,
864 const TargetMachine &TM) const {
865 assert(MBB.isBeginSection() && "Basic block does not start a section!");
866 unsigned UniqueID = MCContext::GenericSectionID;
868 // For cold sections use the .text.unlikely prefix along with the parent
869 // function name. All cold blocks for the same function go to the same
870 // section. Similarly all exception blocks are grouped by symbol name
871 // under the .text.eh prefix. For regular sections, we either use a unique
872 // name, or a unique ID for the section.
873 SmallString<128> Name;
874 if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
875 Name += ".text.unlikely.";
876 Name += MBB.getParent()->getName();
877 } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
879 Name += MBB.getParent()->getName();
881 Name += MBB.getParent()->getSection()->getName();
882 if (TM.getUniqueBasicBlockSectionNames()) {
884 Name += MBB.getSymbol()->getName();
886 UniqueID = NextUniqueID++;
890 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
891 std::string GroupName = "";
893 Flags |= ELF::SHF_GROUP;
894 GroupName = F.getComdat()->getName().str();
896 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
897 0 /* Entry Size */, GroupName, UniqueID,
901 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
902 bool IsCtor, unsigned Priority,
903 const MCSymbol *KeySym) {
906 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
907 StringRef COMDAT = KeySym ? KeySym->getName() : "";
910 Flags |= ELF::SHF_GROUP;
914 Type = ELF::SHT_INIT_ARRAY;
915 Name = ".init_array";
917 Type = ELF::SHT_FINI_ARRAY;
918 Name = ".fini_array";
920 if (Priority != 65535) {
922 Name += utostr(Priority);
925 // The default scheme is .ctor / .dtor, so we have to invert the priority
931 if (Priority != 65535)
932 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
933 Type = ELF::SHT_PROGBITS;
936 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
939 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
940 unsigned Priority, const MCSymbol *KeySym) const {
941 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
945 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
946 unsigned Priority, const MCSymbol *KeySym) const {
947 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
951 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
952 const GlobalValue *LHS, const GlobalValue *RHS,
953 const TargetMachine &TM) const {
954 // We may only use a PLT-relative relocation to refer to unnamed_addr
956 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
959 // Basic sanity checks.
960 if (LHS->getType()->getPointerAddressSpace() != 0 ||
961 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
962 RHS->isThreadLocal())
965 return MCBinaryExpr::createSub(
966 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
968 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
971 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
972 // Use ".GCC.command.line" since this feature is to support clang's
973 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
975 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
976 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
980 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
981 UseInitArray = UseInitArray_;
982 MCContext &Ctx = getContext();
984 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
985 ELF::SHF_ALLOC | ELF::SHF_WRITE);
987 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
988 ELF::SHF_ALLOC | ELF::SHF_WRITE);
992 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
993 ELF::SHF_WRITE | ELF::SHF_ALLOC);
994 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
995 ELF::SHF_WRITE | ELF::SHF_ALLOC);
998 //===----------------------------------------------------------------------===//
1000 //===----------------------------------------------------------------------===//
1002 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
1003 : TargetLoweringObjectFile() {
1004 SupportIndirectSymViaGOTPCRel = true;
1007 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1008 const TargetMachine &TM) {
1009 TargetLoweringObjectFile::Initialize(Ctx, TM);
1010 if (TM.getRelocationModel() == Reloc::Static) {
1011 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1012 SectionKind::getData());
1013 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1014 SectionKind::getData());
1016 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1017 MachO::S_MOD_INIT_FUNC_POINTERS,
1018 SectionKind::getData());
1019 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1020 MachO::S_MOD_TERM_FUNC_POINTERS,
1021 SectionKind::getData());
1024 PersonalityEncoding =
1025 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1026 LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1028 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1031 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1033 // Emit the linker options if present.
1034 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1035 for (const auto *Option : LinkerOptions->operands()) {
1036 SmallVector<std::string, 4> StrOptions;
1037 for (const auto &Piece : cast<MDNode>(Option)->operands())
1038 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1039 Streamer.emitLinkerOptions(StrOptions);
1043 unsigned VersionVal = 0;
1044 unsigned ImageInfoFlags = 0;
1045 StringRef SectionVal;
1047 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1049 // The section is mandatory. If we don't have it, then we don't have GC info.
1050 if (SectionVal.empty())
1053 StringRef Segment, Section;
1054 unsigned TAA = 0, StubSize = 0;
1056 std::string ErrorCode =
1057 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
1058 TAA, TAAParsed, StubSize);
1059 if (!ErrorCode.empty())
1060 // If invalid, report the error with report_fatal_error.
1061 report_fatal_error("Invalid section specifier '" + Section + "': " +
1065 MCSectionMachO *S = getContext().getMachOSection(
1066 Segment, Section, TAA, StubSize, SectionKind::getData());
1067 Streamer.SwitchSection(S);
1068 Streamer.emitLabel(getContext().
1069 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1070 Streamer.emitInt32(VersionVal);
1071 Streamer.emitInt32(ImageInfoFlags);
1072 Streamer.AddBlankLine();
1075 static void checkMachOComdat(const GlobalValue *GV) {
1076 const Comdat *C = GV->getComdat();
1080 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1081 "' cannot be lowered.");
1084 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1085 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1086 // Parse the section specifier and create it if valid.
1087 StringRef Segment, Section;
1088 unsigned TAA = 0, StubSize = 0;
1091 checkMachOComdat(GO);
1093 std::string ErrorCode =
1094 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
1095 TAA, TAAParsed, StubSize);
1096 if (!ErrorCode.empty()) {
1097 // If invalid, report the error with report_fatal_error.
1098 report_fatal_error("Global variable '" + GO->getName() +
1099 "' has an invalid section specifier '" +
1100 GO->getSection() + "': " + ErrorCode + ".");
1105 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1107 // If TAA wasn't set by ParseSectionSpecifier() above,
1108 // use the value returned by getMachOSection() as a default.
1110 TAA = S->getTypeAndAttributes();
1112 // Okay, now that we got the section, verify that the TAA & StubSize agree.
1113 // If the user declared multiple globals with different section flags, we need
1114 // to reject it here.
1115 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1116 // If invalid, report the error with report_fatal_error.
1117 report_fatal_error("Global variable '" + GO->getName() +
1118 "' section type or attributes does not match previous"
1119 " section specifier");
1125 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1126 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1127 checkMachOComdat(GO);
1129 // Handle thread local data.
1130 if (Kind.isThreadBSS()) return TLSBSSSection;
1131 if (Kind.isThreadData()) return TLSDataSection;
1134 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
1136 // If this is weak/linkonce, put this in a coalescable section, either in text
1137 // or data depending on if it is writable.
1138 if (GO->isWeakForLinker()) {
1139 if (Kind.isReadOnly())
1140 return ConstTextCoalSection;
1141 if (Kind.isReadOnlyWithRel())
1142 return ConstDataCoalSection;
1143 return DataCoalSection;
1146 // FIXME: Alignment check should be handled by section classifier.
1147 if (Kind.isMergeable1ByteCString() &&
1148 GO->getParent()->getDataLayout().getPreferredAlign(
1149 cast<GlobalVariable>(GO)) < Align(32))
1150 return CStringSection;
1152 // Do not put 16-bit arrays in the UString section if they have an
1153 // externally visible label, this runs into issues with certain linker
1155 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1156 GO->getParent()->getDataLayout().getPreferredAlign(
1157 cast<GlobalVariable>(GO)) < Align(32))
1158 return UStringSection;
1160 // With MachO only variables whose corresponding symbol starts with 'l' or
1161 // 'L' can be merged, so we only try merging GVs with private linkage.
1162 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1163 if (Kind.isMergeableConst4())
1164 return FourByteConstantSection;
1165 if (Kind.isMergeableConst8())
1166 return EightByteConstantSection;
1167 if (Kind.isMergeableConst16())
1168 return SixteenByteConstantSection;
1171 // Otherwise, if it is readonly, but not something we can specially optimize,
1172 // just drop it in .const.
1173 if (Kind.isReadOnly())
1174 return ReadOnlySection;
1176 // If this is marked const, put it into a const section. But if the dynamic
1177 // linker needs to write to it, put it in the data segment.
1178 if (Kind.isReadOnlyWithRel())
1179 return ConstDataSection;
1181 // Put zero initialized globals with strong external linkage in the
1182 // DATA, __common section with the .zerofill directive.
1183 if (Kind.isBSSExtern())
1184 return DataCommonSection;
1186 // Put zero initialized globals with local linkage in __DATA,__bss directive
1187 // with the .zerofill directive (aka .lcomm).
1188 if (Kind.isBSSLocal())
1189 return DataBSSSection;
1191 // Otherwise, just drop the variable in the normal data section.
1195 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1196 const DataLayout &DL, SectionKind Kind, const Constant *C,
1197 Align &Alignment) const {
1198 // If this constant requires a relocation, we have to put it in the data
1199 // segment, not in the text segment.
1200 if (Kind.isData() || Kind.isReadOnlyWithRel())
1201 return ConstDataSection;
1203 if (Kind.isMergeableConst4())
1204 return FourByteConstantSection;
1205 if (Kind.isMergeableConst8())
1206 return EightByteConstantSection;
1207 if (Kind.isMergeableConst16())
1208 return SixteenByteConstantSection;
1209 return ReadOnlySection; // .const
1212 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1213 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1214 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1215 // The mach-o version of this method defaults to returning a stub reference.
1217 if (Encoding & DW_EH_PE_indirect) {
1218 MachineModuleInfoMachO &MachOMMI =
1219 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1221 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1223 // Add information about the stub reference to MachOMMI so that the stub
1224 // gets emitted by the asmprinter.
1225 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1226 if (!StubSym.getPointer()) {
1227 MCSymbol *Sym = TM.getSymbol(GV);
1228 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1231 return TargetLoweringObjectFile::
1232 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1233 Encoding & ~DW_EH_PE_indirect, Streamer);
1236 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1240 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1241 const GlobalValue *GV, const TargetMachine &TM,
1242 MachineModuleInfo *MMI) const {
1243 // The mach-o version of this method defaults to returning a stub reference.
1244 MachineModuleInfoMachO &MachOMMI =
1245 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1247 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1249 // Add information about the stub reference to MachOMMI so that the stub
1250 // gets emitted by the asmprinter.
1251 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1252 if (!StubSym.getPointer()) {
1253 MCSymbol *Sym = TM.getSymbol(GV);
1254 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1260 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1261 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1262 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1263 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1264 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1265 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1266 // computation of deltas to final external symbols. Example:
1272 // .long _extgotequiv-_delta
1274 // is transformed to:
1277 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1279 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1280 // L_extfoo$non_lazy_ptr:
1281 // .indirect_symbol _extfoo
1284 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1285 // may point to both local (same translation unit) and global (other
1286 // translation units) symbols. Example:
1288 // .section __DATA,__pointers,non_lazy_symbol_pointers
1290 // .indirect_symbol _myGlobal
1293 // .indirect_symbol _myLocal
1296 // If the symbol is local, instead of the symbol's index, the assembler
1297 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1298 // Then the linker will notice the constant in the table and will look at the
1299 // content of the symbol.
1300 MachineModuleInfoMachO &MachOMMI =
1301 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1302 MCContext &Ctx = getContext();
1304 // The offset must consider the original displacement from the base symbol
1305 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1306 Offset = -MV.getConstant();
1307 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1309 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1310 // non_lazy_ptr stubs.
1311 SmallString<128> Name;
1312 StringRef Suffix = "$non_lazy_ptr";
1313 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1314 Name += Sym->getName();
1316 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1318 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1320 if (!StubSym.getPointer())
1321 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1322 !GV->hasLocalLinkage());
1324 const MCExpr *BSymExpr =
1325 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1327 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1330 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1333 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1334 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1337 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1338 const MCSection &Section) {
1339 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1342 // If it is not dead stripped, it is safe to use private labels.
1343 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1344 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1350 void TargetLoweringObjectFileMachO::getNameWithPrefix(
1351 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1352 const TargetMachine &TM) const {
1353 bool CannotUsePrivateLabel = true;
1354 if (auto *GO = GV->getBaseObject()) {
1355 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1356 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1357 CannotUsePrivateLabel =
1358 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1360 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1363 //===----------------------------------------------------------------------===//
1365 //===----------------------------------------------------------------------===//
1368 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1370 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1374 COFF::IMAGE_SCN_MEM_DISCARDABLE;
1375 else if (K.isText())
1377 COFF::IMAGE_SCN_MEM_EXECUTE |
1378 COFF::IMAGE_SCN_MEM_READ |
1379 COFF::IMAGE_SCN_CNT_CODE |
1380 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1383 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1384 COFF::IMAGE_SCN_MEM_READ |
1385 COFF::IMAGE_SCN_MEM_WRITE;
1386 else if (K.isThreadLocal())
1388 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1389 COFF::IMAGE_SCN_MEM_READ |
1390 COFF::IMAGE_SCN_MEM_WRITE;
1391 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1393 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1394 COFF::IMAGE_SCN_MEM_READ;
1395 else if (K.isWriteable())
1397 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1398 COFF::IMAGE_SCN_MEM_READ |
1399 COFF::IMAGE_SCN_MEM_WRITE;
1404 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1405 const Comdat *C = GV->getComdat();
1406 assert(C && "expected GV to have a Comdat!");
1408 StringRef ComdatGVName = C->getName();
1409 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1411 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1412 "' does not exist.");
1414 if (ComdatGV->getComdat() != C)
1415 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1416 "' is not a key for its COMDAT.");
1421 static int getSelectionForCOFF(const GlobalValue *GV) {
1422 if (const Comdat *C = GV->getComdat()) {
1423 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1424 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1425 ComdatKey = GA->getBaseObject();
1426 if (ComdatKey == GV) {
1427 switch (C->getSelectionKind()) {
1429 return COFF::IMAGE_COMDAT_SELECT_ANY;
1430 case Comdat::ExactMatch:
1431 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1432 case Comdat::Largest:
1433 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1434 case Comdat::NoDuplicates:
1435 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1436 case Comdat::SameSize:
1437 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1440 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1446 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1447 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1449 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1450 StringRef Name = GO->getSection();
1451 StringRef COMDATSymName = "";
1452 if (GO->hasComdat()) {
1453 Selection = getSelectionForCOFF(GO);
1454 const GlobalValue *ComdatGV;
1455 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1456 ComdatGV = getComdatGVForCOFF(GO);
1460 if (!ComdatGV->hasPrivateLinkage()) {
1461 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1462 COMDATSymName = Sym->getName();
1463 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1469 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1473 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1478 if (Kind.isThreadLocal())
1480 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1485 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1486 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1487 // If we have -ffunction-sections then we should emit the global value to a
1488 // uniqued section specifically for it.
1489 bool EmitUniquedSection;
1491 EmitUniquedSection = TM.getFunctionSections();
1493 EmitUniquedSection = TM.getDataSections();
1495 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1496 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1498 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1500 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1501 int Selection = getSelectionForCOFF(GO);
1503 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1504 const GlobalValue *ComdatGV;
1505 if (GO->hasComdat())
1506 ComdatGV = getComdatGVForCOFF(GO);
1510 unsigned UniqueID = MCContext::GenericSectionID;
1511 if (EmitUniquedSection)
1512 UniqueID = NextUniqueID++;
1514 if (!ComdatGV->hasPrivateLinkage()) {
1515 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1516 StringRef COMDATSymName = Sym->getName();
1518 // Append "$symbol" to the section name *before* IR-level mangling is
1519 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1520 // COFF linker will not properly handle comdats otherwise.
1521 if (getTargetTriple().isWindowsGNUEnvironment())
1522 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1524 return getContext().getCOFFSection(Name, Characteristics, Kind,
1525 COMDATSymName, Selection, UniqueID);
1527 SmallString<256> TmpData;
1528 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1529 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1530 Selection, UniqueID);
1537 if (Kind.isThreadLocal())
1538 return TLSDataSection;
1540 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1541 return ReadOnlySection;
1543 // Note: we claim that common symbols are put in BSSSection, but they are
1544 // really emitted with the magic .comm directive, which creates a symbol table
1545 // entry but not a section.
1546 if (Kind.isBSS() || Kind.isCommon())
1552 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1553 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1554 const TargetMachine &TM) const {
1555 bool CannotUsePrivateLabel = false;
1556 if (GV->hasPrivateLinkage() &&
1557 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1558 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1559 CannotUsePrivateLabel = true;
1561 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1564 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1565 const Function &F, const TargetMachine &TM) const {
1566 // If the function can be removed, produce a unique section so that
1567 // the table doesn't prevent the removal.
1568 const Comdat *C = F.getComdat();
1569 bool EmitUniqueSection = TM.getFunctionSections() || C;
1570 if (!EmitUniqueSection)
1571 return ReadOnlySection;
1573 // FIXME: we should produce a symbol for F instead.
1574 if (F.hasPrivateLinkage())
1575 return ReadOnlySection;
1577 MCSymbol *Sym = TM.getSymbol(&F);
1578 StringRef COMDATSymName = Sym->getName();
1580 SectionKind Kind = SectionKind::getReadOnly();
1581 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1582 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1583 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1584 unsigned UniqueID = NextUniqueID++;
1586 return getContext().getCOFFSection(
1587 SecName, Characteristics, Kind, COMDATSymName,
1588 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1591 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1593 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1594 // Emit the linker options to the linker .drectve section. According to the
1595 // spec, this section is a space-separated string containing flags for
1597 MCSection *Sec = getDrectveSection();
1598 Streamer.SwitchSection(Sec);
1599 for (const auto *Option : LinkerOptions->operands()) {
1600 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1601 // Lead with a space for consistency with our dllexport implementation.
1602 std::string Directive(" ");
1603 Directive.append(std::string(cast<MDString>(Piece)->getString()));
1604 Streamer.emitBytes(Directive);
1609 unsigned Version = 0;
1613 GetObjCImageInfo(M, Version, Flags, Section);
1614 if (Section.empty())
1617 auto &C = getContext();
1618 auto *S = C.getCOFFSection(
1619 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1620 SectionKind::getReadOnly());
1621 Streamer.SwitchSection(S);
1622 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1623 Streamer.emitInt32(Version);
1624 Streamer.emitInt32(Flags);
1625 Streamer.AddBlankLine();
1628 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1629 const TargetMachine &TM) {
1630 TargetLoweringObjectFile::Initialize(Ctx, TM);
1631 const Triple &T = TM.getTargetTriple();
1632 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1634 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1635 COFF::IMAGE_SCN_MEM_READ,
1636 SectionKind::getReadOnly());
1638 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1639 COFF::IMAGE_SCN_MEM_READ,
1640 SectionKind::getReadOnly());
1642 StaticCtorSection = Ctx.getCOFFSection(
1643 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1644 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1645 SectionKind::getData());
1646 StaticDtorSection = Ctx.getCOFFSection(
1647 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1648 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1649 SectionKind::getData());
1653 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1654 const Triple &T, bool IsCtor,
1656 const MCSymbol *KeySym,
1657 MCSectionCOFF *Default) {
1658 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1659 // If the priority is the default, use .CRT$XCU, possibly associative.
1660 if (Priority == 65535)
1661 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1663 // Otherwise, we need to compute a new section name. Low priorities should
1664 // run earlier. The linker will sort sections ASCII-betically, and we need a
1665 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1666 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1667 // low priorities need to sort before 'L', since the CRT uses that
1668 // internally, so we use ".CRT$XCA00001" for them.
1669 SmallString<24> Name;
1670 raw_svector_ostream OS(Name);
1671 OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
1672 (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1673 MCSectionCOFF *Sec = Ctx.getCOFFSection(
1674 Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1675 SectionKind::getReadOnly());
1676 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1679 std::string Name = IsCtor ? ".ctors" : ".dtors";
1680 if (Priority != 65535)
1681 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1683 return Ctx.getAssociativeCOFFSection(
1684 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1685 COFF::IMAGE_SCN_MEM_READ |
1686 COFF::IMAGE_SCN_MEM_WRITE,
1687 SectionKind::getData()),
1691 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1692 unsigned Priority, const MCSymbol *KeySym) const {
1693 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1695 cast<MCSectionCOFF>(StaticCtorSection));
1698 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1699 unsigned Priority, const MCSymbol *KeySym) const {
1700 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1702 cast<MCSectionCOFF>(StaticDtorSection));
1705 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1706 raw_ostream &OS, const GlobalValue *GV) const {
1707 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1710 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1711 raw_ostream &OS, const GlobalValue *GV) const {
1712 emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1715 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1716 const GlobalValue *LHS, const GlobalValue *RHS,
1717 const TargetMachine &TM) const {
1718 const Triple &T = TM.getTargetTriple();
1719 if (T.isOSCygMing())
1722 // Our symbols should exist in address space zero, cowardly no-op if
1724 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1725 RHS->getType()->getPointerAddressSpace() != 0)
1728 // Both ptrtoint instructions must wrap global objects:
1729 // - Only global variables are eligible for image relative relocations.
1730 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1731 // We expect __ImageBase to be a global variable without a section, externally
1734 // It should look something like this: @__ImageBase = external constant i8
1735 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1736 LHS->isThreadLocal() || RHS->isThreadLocal() ||
1737 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1738 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1741 return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1742 MCSymbolRefExpr::VK_COFF_IMGREL32,
1746 static std::string APIntToHexString(const APInt &AI) {
1747 unsigned Width = (AI.getBitWidth() / 8) * 2;
1748 std::string HexString = AI.toString(16, /*Signed=*/false);
1749 llvm::transform(HexString, HexString.begin(), tolower);
1750 unsigned Size = HexString.size();
1751 assert(Width >= Size && "hex string is too large!");
1752 HexString.insert(HexString.begin(), Width - Size, '0');
1757 static std::string scalarConstantToHexString(const Constant *C) {
1758 Type *Ty = C->getType();
1759 if (isa<UndefValue>(C)) {
1760 return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1761 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1762 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1763 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1764 return APIntToHexString(CI->getValue());
1766 unsigned NumElements;
1767 if (auto *VTy = dyn_cast<VectorType>(Ty))
1768 NumElements = cast<FixedVectorType>(VTy)->getNumElements();
1770 NumElements = Ty->getArrayNumElements();
1771 std::string HexString;
1772 for (int I = NumElements - 1, E = -1; I != E; --I)
1773 HexString += scalarConstantToHexString(C->getAggregateElement(I));
1778 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1779 const DataLayout &DL, SectionKind Kind, const Constant *C,
1780 Align &Alignment) const {
1781 if (Kind.isMergeableConst() && C &&
1782 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1783 // This creates comdat sections with the given symbol name, but unless
1784 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1785 // will be created with a null storage class, which makes GNU binutils
1787 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1788 COFF::IMAGE_SCN_MEM_READ |
1789 COFF::IMAGE_SCN_LNK_COMDAT;
1790 std::string COMDATSymName;
1791 if (Kind.isMergeableConst4()) {
1792 if (Alignment <= 4) {
1793 COMDATSymName = "__real@" + scalarConstantToHexString(C);
1794 Alignment = Align(4);
1796 } else if (Kind.isMergeableConst8()) {
1797 if (Alignment <= 8) {
1798 COMDATSymName = "__real@" + scalarConstantToHexString(C);
1799 Alignment = Align(8);
1801 } else if (Kind.isMergeableConst16()) {
1802 // FIXME: These may not be appropriate for non-x86 architectures.
1803 if (Alignment <= 16) {
1804 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1805 Alignment = Align(16);
1807 } else if (Kind.isMergeableConst32()) {
1808 if (Alignment <= 32) {
1809 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1810 Alignment = Align(32);
1814 if (!COMDATSymName.empty())
1815 return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1817 COFF::IMAGE_COMDAT_SELECT_ANY);
1820 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
1824 //===----------------------------------------------------------------------===//
1826 //===----------------------------------------------------------------------===//
1828 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1829 const Comdat *C = GV->getComdat();
1833 if (C->getSelectionKind() != Comdat::Any)
1834 report_fatal_error("WebAssembly COMDATs only support "
1835 "SelectionKind::Any, '" + C->getName() + "' cannot be "
1841 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1842 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1843 // We don't support explict section names for functions in the wasm object
1844 // format. Each function has to be in its own unique section.
1845 if (isa<Function>(GO)) {
1846 return SelectSectionForGlobal(GO, Kind, TM);
1849 StringRef Name = GO->getSection();
1851 // Certain data sections we treat as named custom sections rather than
1852 // segments within the data section.
1853 // This could be avoided if all data segements (the wasm sense) were
1854 // represented as their own sections (in the llvm sense).
1855 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
1856 if (Name == ".llvmcmd" || Name == ".llvmbc")
1857 Kind = SectionKind::getMetadata();
1859 StringRef Group = "";
1860 if (const Comdat *C = getWasmComdat(GO)) {
1861 Group = C->getName();
1864 MCSectionWasm* Section =
1865 getContext().getWasmSection(Name, Kind, Group,
1866 MCContext::GenericSectionID);
1871 static MCSectionWasm *selectWasmSectionForGlobal(
1872 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1873 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1874 StringRef Group = "";
1875 if (const Comdat *C = getWasmComdat(GO)) {
1876 Group = C->getName();
1879 bool UniqueSectionNames = TM.getUniqueSectionNames();
1880 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1882 if (const auto *F = dyn_cast<Function>(GO)) {
1883 const auto &OptionalPrefix = F->getSectionPrefix();
1885 Name += *OptionalPrefix;
1888 if (EmitUniqueSection && UniqueSectionNames) {
1889 Name.push_back('.');
1890 TM.getNameWithPrefix(Name, GO, Mang, true);
1892 unsigned UniqueID = MCContext::GenericSectionID;
1893 if (EmitUniqueSection && !UniqueSectionNames) {
1894 UniqueID = *NextUniqueID;
1898 return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1901 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1902 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1904 if (Kind.isCommon())
1905 report_fatal_error("mergable sections not supported yet on wasm");
1907 // If we have -ffunction-section or -fdata-section then we should emit the
1908 // global value to a uniqued section specifically for it.
1909 bool EmitUniqueSection = false;
1911 EmitUniqueSection = TM.getFunctionSections();
1913 EmitUniqueSection = TM.getDataSections();
1914 EmitUniqueSection |= GO->hasComdat();
1916 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1917 EmitUniqueSection, &NextUniqueID);
1920 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1921 bool UsesLabelDifference, const Function &F) const {
1922 // We can always create relative relocations, so use another section
1923 // that can be marked non-executable.
1927 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1928 const GlobalValue *LHS, const GlobalValue *RHS,
1929 const TargetMachine &TM) const {
1930 // We may only use a PLT-relative relocation to refer to unnamed_addr
1932 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1935 // Basic sanity checks.
1936 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1937 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1938 RHS->isThreadLocal())
1941 return MCBinaryExpr::createSub(
1942 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1944 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1947 void TargetLoweringObjectFileWasm::InitializeWasm() {
1949 getContext().getWasmSection(".init_array", SectionKind::getData());
1951 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
1952 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
1953 TTypeEncoding = dwarf::DW_EH_PE_absptr;
1956 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1957 unsigned Priority, const MCSymbol *KeySym) const {
1958 return Priority == UINT16_MAX ?
1960 getContext().getWasmSection(".init_array." + utostr(Priority),
1961 SectionKind::getData());
1964 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1965 unsigned Priority, const MCSymbol *KeySym) const {
1966 llvm_unreachable("@llvm.global_dtors should have been lowered already");
1970 //===----------------------------------------------------------------------===//
1972 //===----------------------------------------------------------------------===//
1974 TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
1975 const TargetMachine &TM) const {
1976 if (TM.getDataSections())
1977 report_fatal_error("XCOFF unique data sections not yet implemented");
1979 // We always use a qualname symbol for a GV that represents
1980 // a declaration, a function descriptor, or a common symbol.
1981 // It is inherently ambiguous when the GO represents the address of a
1982 // function, as the GO could either represent a function descriptor or a
1983 // function entry point. We choose to always return a function descriptor
1985 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
1986 if (GO->isDeclarationForLinker())
1987 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
1988 ->getQualNameSymbol();
1990 SectionKind GOKind = getKindForGlobal(GO, TM);
1991 if (GOKind.isText())
1992 return cast<MCSectionXCOFF>(
1993 getSectionForFunctionDescriptor(cast<Function>(GO), TM))
1994 ->getQualNameSymbol();
1995 if (GOKind.isCommon() || GOKind.isBSSLocal())
1996 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
1997 ->getQualNameSymbol();
2000 // For all other cases, fall back to getSymbol to return the unqualified name.
2001 // This could change for a GV that is a GlobalVariable when we decide to
2002 // support -fdata-sections since we could avoid having label symbols if the
2003 // linkage name is applied to the csect symbol.
2007 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
2008 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2009 report_fatal_error("XCOFF explicit sections not yet implemented.");
2012 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
2013 const GlobalObject *GO, const TargetMachine &TM) const {
2014 assert(GO->isDeclarationForLinker() &&
2015 "Tried to get ER section for a defined global.");
2017 SmallString<128> Name;
2018 getNameWithPrefix(Name, GO, TM);
2019 XCOFF::StorageClass SC =
2020 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
2022 // Externals go into a csect of type ER.
2023 return getContext().getXCOFFSection(
2024 Name, isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA, XCOFF::XTY_ER,
2025 SC, SectionKind::getMetadata());
2028 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
2029 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2030 assert(!TM.getFunctionSections() && !TM.getDataSections() &&
2031 "XCOFF unique sections not yet implemented.");
2033 // Common symbols go into a csect with matching name which will get mapped
2034 // into the .bss section.
2035 if (Kind.isBSSLocal() || Kind.isCommon()) {
2036 SmallString<128> Name;
2037 getNameWithPrefix(Name, GO, TM);
2038 XCOFF::StorageClass SC =
2039 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
2040 return getContext().getXCOFFSection(
2041 Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM,
2042 SC, Kind, /* BeginSymbolName */ nullptr);
2045 if (Kind.isMergeableCString()) {
2046 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
2047 cast<GlobalVariable>(GO));
2049 unsigned EntrySize = getEntrySizeForKind(Kind);
2050 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
2051 SmallString<128> Name;
2052 Name = SizeSpec + utostr(Alignment.value());
2054 return getContext().getXCOFFSection(
2055 Name, XCOFF::XMC_RO, XCOFF::XTY_SD,
2056 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO),
2057 Kind, /* BeginSymbolName */ nullptr);
2063 if (Kind.isData() || Kind.isReadOnlyWithRel())
2064 // TODO: We may put this under option control, because user may want to
2065 // have read-only data with relocations placed into a read-only section by
2069 // Zero initialized data must be emitted to the .data section because external
2070 // linkage control sections that get mapped to the .bss section will be linked
2071 // as tentative defintions, which is only appropriate for SectionKind::Common.
2075 if (Kind.isReadOnly())
2076 return ReadOnlySection;
2078 report_fatal_error("XCOFF other section types not yet implemented.");
2081 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2082 const Function &F, const TargetMachine &TM) const {
2083 assert (!TM.getFunctionSections() && "Unique sections not supported on XCOFF"
2085 assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2086 //TODO: Enable emiting jump table to unique sections when we support it.
2087 return ReadOnlySection;
2090 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
2091 bool UsesLabelDifference, const Function &F) const {
2095 /// Given a mergeable constant with the specified size and relocation
2096 /// information, return a section that it should be placed in.
2097 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2098 const DataLayout &DL, SectionKind Kind, const Constant *C,
2099 Align &Alignment) const {
2100 //TODO: Enable emiting constant pool to unique sections when we support it.
2101 return ReadOnlySection;
2104 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
2105 const TargetMachine &TgtM) {
2106 TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2108 PersonalityEncoding = 0;
2112 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
2113 unsigned Priority, const MCSymbol *KeySym) const {
2114 report_fatal_error("XCOFF ctor section not yet implemented.");
2117 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
2118 unsigned Priority, const MCSymbol *KeySym) const {
2119 report_fatal_error("XCOFF dtor section not yet implemented.");
2122 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
2123 const GlobalValue *LHS, const GlobalValue *RHS,
2124 const TargetMachine &TM) const {
2125 report_fatal_error("XCOFF not yet implemented.");
2128 XCOFF::StorageClass TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(
2129 const GlobalObject *GO) {
2130 switch (GO->getLinkage()) {
2131 case GlobalValue::InternalLinkage:
2132 case GlobalValue::PrivateLinkage:
2133 return XCOFF::C_HIDEXT;
2134 case GlobalValue::ExternalLinkage:
2135 case GlobalValue::CommonLinkage:
2136 case GlobalValue::AvailableExternallyLinkage:
2137 return XCOFF::C_EXT;
2138 case GlobalValue::ExternalWeakLinkage:
2139 case GlobalValue::LinkOnceAnyLinkage:
2140 case GlobalValue::LinkOnceODRLinkage:
2141 case GlobalValue::WeakAnyLinkage:
2142 case GlobalValue::WeakODRLinkage:
2143 return XCOFF::C_WEAKEXT;
2144 case GlobalValue::AppendingLinkage:
2146 "There is no mapping that implements AppendingLinkage for XCOFF.");
2148 llvm_unreachable("Unknown linkage type!");
2151 MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2152 const Function *F, const TargetMachine &TM) const {
2153 SmallString<128> NameStr;
2154 NameStr.push_back('.');
2155 getNameWithPrefix(NameStr, F, TM);
2156 return getContext().getOrCreateSymbol(NameStr);
2159 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
2160 const Function *F, const TargetMachine &TM) const {
2161 SmallString<128> NameStr;
2162 getNameWithPrefix(NameStr, F, TM);
2163 return getContext().getXCOFFSection(NameStr, XCOFF::XMC_DS, XCOFF::XTY_SD,
2164 getStorageClassForGlobal(F),
2165 SectionKind::getData());
2168 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2169 const MCSymbol *Sym) const {
2170 return getContext().getXCOFFSection(
2171 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), XCOFF::XMC_TC,
2172 XCOFF::XTY_SD, XCOFF::C_HIDEXT, SectionKind::getData());