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