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