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