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