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