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