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