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