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