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