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