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