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