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