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