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