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