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