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 std::string Name; 364 unsigned Type; 365 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 366 SectionKind Kind = SectionKind::getDataRel(); 367 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 368 369 if (KeySym) 370 Flags |= ELF::SHF_GROUP; 371 372 if (UseInitArray) { 373 Name = ".init_array"; 374 if (Priority != 65535) { 375 Name += '.'; 376 Name += utostr(Priority); 377 } 378 Type = ELF::SHT_INIT_ARRAY; 379 } else { 380 // The default scheme is .ctor / .dtor, so we have to invert the priority 381 // numbering. 382 Name = std::string(".ctors"); 383 if (Priority != 65535) { 384 Name += '.'; 385 Name += utostr(65535 - Priority); 386 } 387 Type = ELF::SHT_PROGBITS; 388 } 389 390 return getContext().getELFSection(Name, Type, Flags, Kind, 0, COMDAT); 391 } 392 393 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 394 unsigned Priority, const MCSymbol *KeySym) const { 395 std::string Name; 396 unsigned Type; 397 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 398 SectionKind Kind = SectionKind::getDataRel(); 399 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 400 401 if (KeySym) 402 Flags |= ELF::SHF_GROUP; 403 404 if (UseInitArray) { 405 Name = ".fini_array"; 406 if (Priority != 65535) { 407 Name += '.'; 408 Name += utostr(Priority); 409 } 410 Type = ELF::SHT_FINI_ARRAY; 411 } else { 412 // The default scheme is .ctor / .dtor, so we have to invert the priority 413 // numbering. 414 Name = ".dtors"; 415 if (Priority != 65535) { 416 Name += '.'; 417 Name += utostr(65535 - Priority); 418 } 419 Type = ELF::SHT_PROGBITS; 420 } 421 422 return getContext().getELFSection(Name, Type, Flags, Kind, 0, COMDAT); 423 } 424 425 void 426 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 427 UseInitArray = UseInitArray_; 428 if (!UseInitArray) 429 return; 430 431 StaticCtorSection = 432 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 433 ELF::SHF_WRITE | 434 ELF::SHF_ALLOC, 435 SectionKind::getDataRel()); 436 StaticDtorSection = 437 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 438 ELF::SHF_WRITE | 439 ELF::SHF_ALLOC, 440 SectionKind::getDataRel()); 441 } 442 443 //===----------------------------------------------------------------------===// 444 // MachO 445 //===----------------------------------------------------------------------===// 446 447 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker 448 /// option string. Returns StringRef() if the option does not specify a library. 449 StringRef TargetLoweringObjectFileMachO:: 450 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 451 const char *LibCmd = "-l"; 452 if (LinkerOption.startswith(LibCmd)) 453 return LinkerOption.substr(strlen(LibCmd)); 454 return StringRef(); 455 } 456 457 /// emitModuleFlags - Perform code emission for module flags. 458 void TargetLoweringObjectFileMachO:: 459 emitModuleFlags(MCStreamer &Streamer, 460 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 461 Mangler &Mang, const TargetMachine &TM) const { 462 unsigned VersionVal = 0; 463 unsigned ImageInfoFlags = 0; 464 MDNode *LinkerOptions = nullptr; 465 StringRef SectionVal; 466 467 for (ArrayRef<Module::ModuleFlagEntry>::iterator 468 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 469 const Module::ModuleFlagEntry &MFE = *i; 470 471 // Ignore flags with 'Require' behavior. 472 if (MFE.Behavior == Module::Require) 473 continue; 474 475 StringRef Key = MFE.Key->getString(); 476 Value *Val = MFE.Val; 477 478 if (Key == "Objective-C Image Info Version") { 479 VersionVal = cast<ConstantInt>(Val)->getZExtValue(); 480 } else if (Key == "Objective-C Garbage Collection" || 481 Key == "Objective-C GC Only" || 482 Key == "Objective-C Is Simulated") { 483 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue(); 484 } else if (Key == "Objective-C Image Info Section") { 485 SectionVal = cast<MDString>(Val)->getString(); 486 } else if (Key == "Linker Options") { 487 LinkerOptions = cast<MDNode>(Val); 488 } 489 } 490 491 // Emit the linker options if present. 492 if (LinkerOptions) { 493 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 494 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 495 SmallVector<std::string, 4> StrOptions; 496 497 // Convert to strings. 498 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 499 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 500 StrOptions.push_back(MDOption->getString()); 501 } 502 503 Streamer.EmitLinkerOptions(StrOptions); 504 } 505 } 506 507 // The section is mandatory. If we don't have it, then we don't have GC info. 508 if (SectionVal.empty()) return; 509 510 StringRef Segment, Section; 511 unsigned TAA = 0, StubSize = 0; 512 bool TAAParsed; 513 std::string ErrorCode = 514 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 515 TAA, TAAParsed, StubSize); 516 if (!ErrorCode.empty()) 517 // If invalid, report the error with report_fatal_error. 518 report_fatal_error("Invalid section specifier '" + Section + "': " + 519 ErrorCode + "."); 520 521 // Get the section. 522 const MCSectionMachO *S = 523 getContext().getMachOSection(Segment, Section, TAA, StubSize, 524 SectionKind::getDataNoRel()); 525 Streamer.SwitchSection(S); 526 Streamer.EmitLabel(getContext(). 527 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 528 Streamer.EmitIntValue(VersionVal, 4); 529 Streamer.EmitIntValue(ImageInfoFlags, 4); 530 Streamer.AddBlankLine(); 531 } 532 533 static void checkMachOComdat(const GlobalValue *GV) { 534 const Comdat *C = GV->getComdat(); 535 if (!C) 536 return; 537 538 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 539 "' cannot be lowered."); 540 } 541 542 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 543 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 544 const TargetMachine &TM) const { 545 // Parse the section specifier and create it if valid. 546 StringRef Segment, Section; 547 unsigned TAA = 0, StubSize = 0; 548 bool TAAParsed; 549 550 checkMachOComdat(GV); 551 552 std::string ErrorCode = 553 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 554 TAA, TAAParsed, StubSize); 555 if (!ErrorCode.empty()) { 556 // If invalid, report the error with report_fatal_error. 557 report_fatal_error("Global variable '" + GV->getName() + 558 "' has an invalid section specifier '" + 559 GV->getSection() + "': " + ErrorCode + "."); 560 } 561 562 // Get the section. 563 const MCSectionMachO *S = 564 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 565 566 // If TAA wasn't set by ParseSectionSpecifier() above, 567 // use the value returned by getMachOSection() as a default. 568 if (!TAAParsed) 569 TAA = S->getTypeAndAttributes(); 570 571 // Okay, now that we got the section, verify that the TAA & StubSize agree. 572 // If the user declared multiple globals with different section flags, we need 573 // to reject it here. 574 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 575 // If invalid, report the error with report_fatal_error. 576 report_fatal_error("Global variable '" + GV->getName() + 577 "' section type or attributes does not match previous" 578 " section specifier"); 579 } 580 581 return S; 582 } 583 584 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols( 585 const MCSection &Section) const { 586 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section); 587 588 // Sections holding 1 byte strings are atomized based on the data 589 // they contain. 590 // Sections holding 2 byte strings require symbols in order to be 591 // atomized. 592 // There is no dedicated section for 4 byte strings. 593 if (SMO.getKind().isMergeable1ByteCString()) 594 return false; 595 596 if (SMO.getSegmentName() == "__DATA" && 597 SMO.getSectionName() == "__cfstring") 598 return false; 599 600 switch (SMO.getType()) { 601 default: 602 return true; 603 604 // These sections are atomized at the element boundaries without using 605 // symbols. 606 case MachO::S_4BYTE_LITERALS: 607 case MachO::S_8BYTE_LITERALS: 608 case MachO::S_16BYTE_LITERALS: 609 case MachO::S_LITERAL_POINTERS: 610 case MachO::S_NON_LAZY_SYMBOL_POINTERS: 611 case MachO::S_LAZY_SYMBOL_POINTERS: 612 case MachO::S_MOD_INIT_FUNC_POINTERS: 613 case MachO::S_MOD_TERM_FUNC_POINTERS: 614 case MachO::S_INTERPOSING: 615 return false; 616 } 617 } 618 619 const MCSection *TargetLoweringObjectFileMachO:: 620 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 621 Mangler &Mang, const TargetMachine &TM) const { 622 checkMachOComdat(GV); 623 624 // Handle thread local data. 625 if (Kind.isThreadBSS()) return TLSBSSSection; 626 if (Kind.isThreadData()) return TLSDataSection; 627 628 if (Kind.isText()) 629 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 630 631 // If this is weak/linkonce, put this in a coalescable section, either in text 632 // or data depending on if it is writable. 633 if (GV->isWeakForLinker()) { 634 if (Kind.isReadOnly()) 635 return ConstTextCoalSection; 636 return DataCoalSection; 637 } 638 639 // FIXME: Alignment check should be handled by section classifier. 640 if (Kind.isMergeable1ByteCString() && 641 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment( 642 cast<GlobalVariable>(GV)) < 32) 643 return CStringSection; 644 645 // Do not put 16-bit arrays in the UString section if they have an 646 // externally visible label, this runs into issues with certain linker 647 // versions. 648 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() && 649 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment( 650 cast<GlobalVariable>(GV)) < 32) 651 return UStringSection; 652 653 // With MachO only variables whose corresponding symbol starts with 'l' or 654 // 'L' can be merged, so we only try merging GVs with private linkage. 655 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) { 656 if (Kind.isMergeableConst4()) 657 return FourByteConstantSection; 658 if (Kind.isMergeableConst8()) 659 return EightByteConstantSection; 660 if (Kind.isMergeableConst16()) 661 return SixteenByteConstantSection; 662 } 663 664 // Otherwise, if it is readonly, but not something we can specially optimize, 665 // just drop it in .const. 666 if (Kind.isReadOnly()) 667 return ReadOnlySection; 668 669 // If this is marked const, put it into a const section. But if the dynamic 670 // linker needs to write to it, put it in the data segment. 671 if (Kind.isReadOnlyWithRel()) 672 return ConstDataSection; 673 674 // Put zero initialized globals with strong external linkage in the 675 // DATA, __common section with the .zerofill directive. 676 if (Kind.isBSSExtern()) 677 return DataCommonSection; 678 679 // Put zero initialized globals with local linkage in __DATA,__bss directive 680 // with the .zerofill directive (aka .lcomm). 681 if (Kind.isBSSLocal()) 682 return DataBSSSection; 683 684 // Otherwise, just drop the variable in the normal data section. 685 return DataSection; 686 } 687 688 const MCSection * 689 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind, 690 const Constant *C) const { 691 // If this constant requires a relocation, we have to put it in the data 692 // segment, not in the text segment. 693 if (Kind.isDataRel() || Kind.isReadOnlyWithRel()) 694 return ConstDataSection; 695 696 if (Kind.isMergeableConst4()) 697 return FourByteConstantSection; 698 if (Kind.isMergeableConst8()) 699 return EightByteConstantSection; 700 if (Kind.isMergeableConst16()) 701 return SixteenByteConstantSection; 702 return ReadOnlySection; // .const 703 } 704 705 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 706 const GlobalValue *GV, unsigned Encoding, Mangler &Mang, 707 const TargetMachine &TM, MachineModuleInfo *MMI, 708 MCStreamer &Streamer) const { 709 // The mach-o version of this method defaults to returning a stub reference. 710 711 if (Encoding & DW_EH_PE_indirect) { 712 MachineModuleInfoMachO &MachOMMI = 713 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 714 715 MCSymbol *SSym = 716 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM); 717 718 // Add information about the stub reference to MachOMMI so that the stub 719 // gets emitted by the asmprinter. 720 MachineModuleInfoImpl::StubValueTy &StubSym = 721 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) : 722 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 TargetLoweringObjectFile:: 729 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 730 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 731 } 732 733 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang, 734 TM, MMI, Streamer); 735 } 736 737 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 738 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM, 739 MachineModuleInfo *MMI) const { 740 // The mach-o version of this method defaults to returning a stub reference. 741 MachineModuleInfoMachO &MachOMMI = 742 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 743 744 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM); 745 746 // Add information about the stub reference to MachOMMI so that the stub 747 // gets emitted by the asmprinter. 748 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 749 if (!StubSym.getPointer()) { 750 MCSymbol *Sym = TM.getSymbol(GV, Mang); 751 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 752 } 753 754 return SSym; 755 } 756 757 //===----------------------------------------------------------------------===// 758 // COFF 759 //===----------------------------------------------------------------------===// 760 761 static unsigned 762 getCOFFSectionFlags(SectionKind K) { 763 unsigned Flags = 0; 764 765 if (K.isMetadata()) 766 Flags |= 767 COFF::IMAGE_SCN_MEM_DISCARDABLE; 768 else if (K.isText()) 769 Flags |= 770 COFF::IMAGE_SCN_MEM_EXECUTE | 771 COFF::IMAGE_SCN_MEM_READ | 772 COFF::IMAGE_SCN_CNT_CODE; 773 else if (K.isBSS ()) 774 Flags |= 775 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 776 COFF::IMAGE_SCN_MEM_READ | 777 COFF::IMAGE_SCN_MEM_WRITE; 778 else if (K.isThreadLocal()) 779 Flags |= 780 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 781 COFF::IMAGE_SCN_MEM_READ | 782 COFF::IMAGE_SCN_MEM_WRITE; 783 else if (K.isReadOnly()) 784 Flags |= 785 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 786 COFF::IMAGE_SCN_MEM_READ; 787 else if (K.isWriteable()) 788 Flags |= 789 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 790 COFF::IMAGE_SCN_MEM_READ | 791 COFF::IMAGE_SCN_MEM_WRITE; 792 793 return Flags; 794 } 795 796 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 797 const Comdat *C = GV->getComdat(); 798 assert(C && "expected GV to have a Comdat!"); 799 800 StringRef ComdatGVName = C->getName(); 801 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 802 if (!ComdatGV) 803 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 804 "' does not exist."); 805 806 if (ComdatGV->getComdat() != C) 807 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 808 "' is not a key for it's COMDAT."); 809 810 return ComdatGV; 811 } 812 813 static int getSelectionForCOFF(const GlobalValue *GV) { 814 if (const Comdat *C = GV->getComdat()) { 815 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 816 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 817 ComdatKey = GA->getBaseObject(); 818 if (ComdatKey == GV) { 819 switch (C->getSelectionKind()) { 820 case Comdat::Any: 821 return COFF::IMAGE_COMDAT_SELECT_ANY; 822 case Comdat::ExactMatch: 823 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 824 case Comdat::Largest: 825 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 826 case Comdat::NoDuplicates: 827 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 828 case Comdat::SameSize: 829 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 830 } 831 } else { 832 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 833 } 834 } else if (GV->isWeakForLinker()) { 835 return COFF::IMAGE_COMDAT_SELECT_ANY; 836 } 837 return 0; 838 } 839 840 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 841 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 842 const TargetMachine &TM) const { 843 int Selection = 0; 844 unsigned Characteristics = getCOFFSectionFlags(Kind); 845 StringRef Name = GV->getSection(); 846 StringRef COMDATSymName = ""; 847 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) { 848 Selection = getSelectionForCOFF(GV); 849 const GlobalValue *ComdatGV; 850 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 851 ComdatGV = getComdatGVForCOFF(GV); 852 else 853 ComdatGV = GV; 854 855 if (!ComdatGV->hasPrivateLinkage()) { 856 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang); 857 COMDATSymName = Sym->getName(); 858 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 859 } else { 860 Selection = 0; 861 } 862 } 863 return getContext().getCOFFSection(Name, 864 Characteristics, 865 Kind, 866 COMDATSymName, 867 Selection); 868 } 869 870 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 871 if (Kind.isText()) 872 return ".text"; 873 if (Kind.isBSS()) 874 return ".bss"; 875 if (Kind.isThreadLocal()) 876 return ".tls$"; 877 if (Kind.isWriteable()) 878 return ".data"; 879 return ".rdata"; 880 } 881 882 883 const MCSection *TargetLoweringObjectFileCOFF:: 884 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 885 Mangler &Mang, const TargetMachine &TM) const { 886 // If we have -ffunction-sections then we should emit the global value to a 887 // uniqued section specifically for it. 888 bool EmitUniquedSection; 889 if (Kind.isText()) 890 EmitUniquedSection = TM.getFunctionSections(); 891 else 892 EmitUniquedSection = TM.getDataSections(); 893 894 // If this global is linkonce/weak and the target handles this by emitting it 895 // into a 'uniqued' section name, create and return the section now. 896 // Section names depend on the name of the symbol which is not feasible if the 897 // symbol has private linkage. 898 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) && 899 !Kind.isCommon()) { 900 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 901 unsigned Characteristics = getCOFFSectionFlags(Kind); 902 903 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 904 int Selection = getSelectionForCOFF(GV); 905 if (!Selection) 906 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 907 const GlobalValue *ComdatGV; 908 if (GV->hasComdat()) 909 ComdatGV = getComdatGVForCOFF(GV); 910 else 911 ComdatGV = GV; 912 913 if (!ComdatGV->hasPrivateLinkage()) { 914 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang); 915 StringRef COMDATSymName = Sym->getName(); 916 return getContext().getCOFFSection(Name, Characteristics, Kind, 917 COMDATSymName, Selection); 918 } 919 } 920 921 if (Kind.isText()) 922 return TextSection; 923 924 if (Kind.isThreadLocal()) 925 return TLSDataSection; 926 927 if (Kind.isReadOnly()) 928 return ReadOnlySection; 929 930 // Note: we claim that common symbols are put in BSSSection, but they are 931 // really emitted with the magic .comm directive, which creates a symbol table 932 // entry but not a section. 933 if (Kind.isBSS() || Kind.isCommon()) 934 return BSSSection; 935 936 return DataSection; 937 } 938 939 StringRef TargetLoweringObjectFileCOFF:: 940 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 941 const char *LibCmd = "/DEFAULTLIB:"; 942 if (LinkerOption.startswith(LibCmd)) 943 return LinkerOption.substr(strlen(LibCmd)); 944 return StringRef(); 945 } 946 947 void TargetLoweringObjectFileCOFF:: 948 emitModuleFlags(MCStreamer &Streamer, 949 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 950 Mangler &Mang, const TargetMachine &TM) const { 951 MDNode *LinkerOptions = nullptr; 952 953 // Look for the "Linker Options" flag, since it's the only one we support. 954 for (ArrayRef<Module::ModuleFlagEntry>::iterator 955 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 956 const Module::ModuleFlagEntry &MFE = *i; 957 StringRef Key = MFE.Key->getString(); 958 Value *Val = MFE.Val; 959 if (Key == "Linker Options") { 960 LinkerOptions = cast<MDNode>(Val); 961 break; 962 } 963 } 964 if (!LinkerOptions) 965 return; 966 967 // Emit the linker options to the linker .drectve section. According to the 968 // spec, this section is a space-separated string containing flags for linker. 969 const MCSection *Sec = getDrectveSection(); 970 Streamer.SwitchSection(Sec); 971 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 972 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 973 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 974 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 975 StringRef Op = MDOption->getString(); 976 // Lead with a space for consistency with our dllexport implementation. 977 std::string Escaped(" "); 978 if (Op.find(" ") != StringRef::npos) { 979 // The PE-COFF spec says args with spaces must be quoted. It doesn't say 980 // how to escape quotes, but it probably uses this algorithm: 981 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx 982 // FIXME: Reuse escaping code from Support/Windows/Program.inc 983 Escaped.push_back('\"'); 984 Escaped.append(Op); 985 Escaped.push_back('\"'); 986 } else { 987 Escaped.append(Op); 988 } 989 Streamer.EmitBytes(Escaped); 990 } 991 } 992 } 993 994 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 995 unsigned Priority, const MCSymbol *KeySym) const { 996 return getContext().getAssociativeCOFFSection( 997 cast<MCSectionCOFF>(StaticCtorSection), KeySym); 998 } 999 1000 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1001 unsigned Priority, const MCSymbol *KeySym) const { 1002 return getContext().getAssociativeCOFFSection( 1003 cast<MCSectionCOFF>(StaticDtorSection), KeySym); 1004 } 1005