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