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