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