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