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