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