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 using namespace llvm; 41 using namespace dwarf; 42 43 //===----------------------------------------------------------------------===// 44 // ELF 45 //===----------------------------------------------------------------------===// 46 47 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 48 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM, 49 MachineModuleInfo *MMI) const { 50 unsigned Encoding = getPersonalityEncoding(); 51 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect) 52 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") + 53 TM.getSymbol(GV, Mang)->getName()); 54 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr) 55 return TM.getSymbol(GV, Mang); 56 report_fatal_error("We do not support this DWARF encoding yet!"); 57 } 58 59 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer, 60 const TargetMachine &TM, 61 const MCSymbol *Sym) const { 62 SmallString<64> NameData("DW.ref."); 63 NameData += Sym->getName(); 64 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData); 65 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 66 Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 67 StringRef Prefix = ".data."; 68 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end()); 69 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 70 const MCSection *Sec = getContext().getELFSection(NameData, 71 ELF::SHT_PROGBITS, 72 Flags, 73 SectionKind::getDataRel(), 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 // K.isMergeableConst() is left out to honour PR4650 185 if (K.isMergeableCString() || K.isMergeableConst4() || 186 K.isMergeableConst8() || K.isMergeableConst16()) 187 Flags |= ELF::SHF_MERGE; 188 189 if (K.isMergeableCString()) 190 Flags |= ELF::SHF_STRINGS; 191 192 return Flags; 193 } 194 195 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 196 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 197 const TargetMachine &TM) const { 198 StringRef SectionName = GV->getSection(); 199 200 // Infer section flags from the section name if we can. 201 Kind = getELFKindForNamedSection(SectionName, Kind); 202 203 return getContext().getELFSection(SectionName, 204 getELFSectionType(SectionName, Kind), 205 getELFSectionFlags(Kind), Kind); 206 } 207 208 /// getSectionPrefixForGlobal - Return the section prefix name used by options 209 /// FunctionsSections and DataSections. 210 static const char *getSectionPrefixForGlobal(SectionKind Kind) { 211 if (Kind.isText()) return ".text."; 212 if (Kind.isReadOnly()) return ".rodata."; 213 if (Kind.isBSS()) return ".bss."; 214 215 if (Kind.isThreadData()) return ".tdata."; 216 if (Kind.isThreadBSS()) return ".tbss."; 217 218 if (Kind.isDataNoRel()) return ".data."; 219 if (Kind.isDataRelLocal()) return ".data.rel.local."; 220 if (Kind.isDataRel()) return ".data.rel."; 221 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local."; 222 223 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 224 return ".data.rel.ro."; 225 } 226 227 228 const MCSection *TargetLoweringObjectFileELF:: 229 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 230 Mangler &Mang, const TargetMachine &TM) const { 231 // If we have -ffunction-section or -fdata-section then we should emit the 232 // global value to a uniqued section specifically for it. 233 bool EmitUniquedSection; 234 if (Kind.isText()) 235 EmitUniquedSection = TM.getFunctionSections(); 236 else 237 EmitUniquedSection = TM.getDataSections(); 238 239 // If this global is linkonce/weak and the target handles this by emitting it 240 // into a 'uniqued' section name, create and return the section now. 241 if ((GV->isWeakForLinker() || EmitUniquedSection) && 242 !Kind.isCommon()) { 243 const char *Prefix; 244 Prefix = getSectionPrefixForGlobal(Kind); 245 246 SmallString<128> Name(Prefix, Prefix+strlen(Prefix)); 247 TM.getNameWithPrefix(Name, GV, Mang, true); 248 249 StringRef Group = ""; 250 unsigned Flags = getELFSectionFlags(Kind); 251 if (GV->isWeakForLinker()) { 252 Group = Name.substr(strlen(Prefix)); 253 Flags |= ELF::SHF_GROUP; 254 } 255 256 return getContext().getELFSection(Name.str(), 257 getELFSectionType(Name.str(), Kind), 258 Flags, Kind, 0, Group); 259 } 260 261 if (Kind.isText()) return TextSection; 262 263 if (Kind.isMergeable1ByteCString() || 264 Kind.isMergeable2ByteCString() || 265 Kind.isMergeable4ByteCString()) { 266 267 // We also need alignment here. 268 // FIXME: this is getting the alignment of the character, not the 269 // alignment of the global! 270 unsigned Align = 271 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)); 272 273 const char *SizeSpec = ".rodata.str1."; 274 if (Kind.isMergeable2ByteCString()) 275 SizeSpec = ".rodata.str2."; 276 else if (Kind.isMergeable4ByteCString()) 277 SizeSpec = ".rodata.str4."; 278 else 279 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 280 281 282 std::string Name = SizeSpec + utostr(Align); 283 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 284 ELF::SHF_ALLOC | 285 ELF::SHF_MERGE | 286 ELF::SHF_STRINGS, 287 Kind); 288 } 289 290 if (Kind.isMergeableConst()) { 291 if (Kind.isMergeableConst4() && MergeableConst4Section) 292 return MergeableConst4Section; 293 if (Kind.isMergeableConst8() && MergeableConst8Section) 294 return MergeableConst8Section; 295 if (Kind.isMergeableConst16() && MergeableConst16Section) 296 return MergeableConst16Section; 297 return ReadOnlySection; // .const 298 } 299 300 if (Kind.isReadOnly()) return ReadOnlySection; 301 302 if (Kind.isThreadData()) return TLSDataSection; 303 if (Kind.isThreadBSS()) return TLSBSSSection; 304 305 // Note: we claim that common symbols are put in BSSSection, but they are 306 // really emitted with the magic .comm directive, which creates a symbol table 307 // entry but not a section. 308 if (Kind.isBSS() || Kind.isCommon()) return BSSSection; 309 310 if (Kind.isDataNoRel()) return DataSection; 311 if (Kind.isDataRelLocal()) return DataRelLocalSection; 312 if (Kind.isDataRel()) return DataRelSection; 313 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 314 315 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 316 return DataRelROSection; 317 } 318 319 /// getSectionForConstant - Given a mergeable constant with the 320 /// specified size and relocation information, return a section that it 321 /// should be placed in. 322 const MCSection *TargetLoweringObjectFileELF:: 323 getSectionForConstant(SectionKind Kind) const { 324 if (Kind.isMergeableConst4() && MergeableConst4Section) 325 return MergeableConst4Section; 326 if (Kind.isMergeableConst8() && MergeableConst8Section) 327 return MergeableConst8Section; 328 if (Kind.isMergeableConst16() && MergeableConst16Section) 329 return MergeableConst16Section; 330 if (Kind.isReadOnly()) 331 return ReadOnlySection; 332 333 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 334 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 335 return DataRelROSection; 336 } 337 338 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 339 unsigned Priority, const MCSymbol *KeySym) const { 340 // The default scheme is .ctor / .dtor, so we have to invert the priority 341 // numbering. 342 if (Priority == 65535) 343 return StaticCtorSection; 344 345 if (UseInitArray) { 346 std::string Name = std::string(".init_array.") + utostr(Priority); 347 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY, 348 ELF::SHF_ALLOC | ELF::SHF_WRITE, 349 SectionKind::getDataRel()); 350 } else { 351 std::string Name = std::string(".ctors.") + utostr(65535 - Priority); 352 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 353 ELF::SHF_ALLOC |ELF::SHF_WRITE, 354 SectionKind::getDataRel()); 355 } 356 } 357 358 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 359 unsigned Priority, const MCSymbol *KeySym) const { 360 // The default scheme is .ctor / .dtor, so we have to invert the priority 361 // numbering. 362 if (Priority == 65535) 363 return StaticDtorSection; 364 365 if (UseInitArray) { 366 std::string Name = std::string(".fini_array.") + utostr(Priority); 367 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY, 368 ELF::SHF_ALLOC | ELF::SHF_WRITE, 369 SectionKind::getDataRel()); 370 } else { 371 std::string Name = std::string(".dtors.") + utostr(65535 - Priority); 372 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 373 ELF::SHF_ALLOC |ELF::SHF_WRITE, 374 SectionKind::getDataRel()); 375 } 376 } 377 378 void 379 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 380 UseInitArray = UseInitArray_; 381 if (!UseInitArray) 382 return; 383 384 StaticCtorSection = 385 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 386 ELF::SHF_WRITE | 387 ELF::SHF_ALLOC, 388 SectionKind::getDataRel()); 389 StaticDtorSection = 390 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 391 ELF::SHF_WRITE | 392 ELF::SHF_ALLOC, 393 SectionKind::getDataRel()); 394 } 395 396 //===----------------------------------------------------------------------===// 397 // MachO 398 //===----------------------------------------------------------------------===// 399 400 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker 401 /// option string. Returns StringRef() if the option does not specify a library. 402 StringRef TargetLoweringObjectFileMachO:: 403 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 404 const char *LibCmd = "-l"; 405 if (LinkerOption.startswith(LibCmd)) 406 return LinkerOption.substr(strlen(LibCmd)); 407 return StringRef(); 408 } 409 410 /// emitModuleFlags - Perform code emission for module flags. 411 void TargetLoweringObjectFileMachO:: 412 emitModuleFlags(MCStreamer &Streamer, 413 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 414 Mangler &Mang, const TargetMachine &TM) const { 415 unsigned VersionVal = 0; 416 unsigned ImageInfoFlags = 0; 417 MDNode *LinkerOptions = nullptr; 418 StringRef SectionVal; 419 420 for (ArrayRef<Module::ModuleFlagEntry>::iterator 421 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 422 const Module::ModuleFlagEntry &MFE = *i; 423 424 // Ignore flags with 'Require' behavior. 425 if (MFE.Behavior == Module::Require) 426 continue; 427 428 StringRef Key = MFE.Key->getString(); 429 Value *Val = MFE.Val; 430 431 if (Key == "Objective-C Image Info Version") { 432 VersionVal = cast<ConstantInt>(Val)->getZExtValue(); 433 } else if (Key == "Objective-C Garbage Collection" || 434 Key == "Objective-C GC Only" || 435 Key == "Objective-C Is Simulated") { 436 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue(); 437 } else if (Key == "Objective-C Image Info Section") { 438 SectionVal = cast<MDString>(Val)->getString(); 439 } else if (Key == "Linker Options") { 440 LinkerOptions = cast<MDNode>(Val); 441 } 442 } 443 444 // Emit the linker options if present. 445 if (LinkerOptions) { 446 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 447 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 448 SmallVector<std::string, 4> StrOptions; 449 450 // Convert to strings. 451 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 452 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 453 StrOptions.push_back(MDOption->getString()); 454 } 455 456 Streamer.EmitLinkerOptions(StrOptions); 457 } 458 } 459 460 // The section is mandatory. If we don't have it, then we don't have GC info. 461 if (SectionVal.empty()) return; 462 463 StringRef Segment, Section; 464 unsigned TAA = 0, StubSize = 0; 465 bool TAAParsed; 466 std::string ErrorCode = 467 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 468 TAA, TAAParsed, StubSize); 469 if (!ErrorCode.empty()) 470 // If invalid, report the error with report_fatal_error. 471 report_fatal_error("Invalid section specifier '" + Section + "': " + 472 ErrorCode + "."); 473 474 // Get the section. 475 const MCSectionMachO *S = 476 getContext().getMachOSection(Segment, Section, TAA, StubSize, 477 SectionKind::getDataNoRel()); 478 Streamer.SwitchSection(S); 479 Streamer.EmitLabel(getContext(). 480 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 481 Streamer.EmitIntValue(VersionVal, 4); 482 Streamer.EmitIntValue(ImageInfoFlags, 4); 483 Streamer.AddBlankLine(); 484 } 485 486 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 487 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 488 const TargetMachine &TM) const { 489 // Parse the section specifier and create it if valid. 490 StringRef Segment, Section; 491 unsigned TAA = 0, StubSize = 0; 492 bool TAAParsed; 493 std::string ErrorCode = 494 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 495 TAA, TAAParsed, StubSize); 496 if (!ErrorCode.empty()) { 497 // If invalid, report the error with report_fatal_error. 498 report_fatal_error("Global variable '" + GV->getName() + 499 "' has an invalid section specifier '" + 500 GV->getSection() + "': " + ErrorCode + "."); 501 } 502 503 // Get the section. 504 const MCSectionMachO *S = 505 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 506 507 // If TAA wasn't set by ParseSectionSpecifier() above, 508 // use the value returned by getMachOSection() as a default. 509 if (!TAAParsed) 510 TAA = S->getTypeAndAttributes(); 511 512 // Okay, now that we got the section, verify that the TAA & StubSize agree. 513 // If the user declared multiple globals with different section flags, we need 514 // to reject it here. 515 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 516 // If invalid, report the error with report_fatal_error. 517 report_fatal_error("Global variable '" + GV->getName() + 518 "' section type or attributes does not match previous" 519 " section specifier"); 520 } 521 522 return S; 523 } 524 525 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols( 526 const MCSection &Section) const { 527 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section); 528 529 // Sections holding 1 byte strings are atomized based on the data 530 // they contain. 531 // Sections holding 2 byte strings require symbols in order to be 532 // atomized. 533 // There is no dedicated section for 4 byte strings. 534 if (SMO.getKind().isMergeable1ByteCString()) 535 return false; 536 537 if (SMO.getSegmentName() == "__DATA" && 538 SMO.getSectionName() == "__cfstring") 539 return false; 540 541 switch (SMO.getType()) { 542 default: 543 return true; 544 545 // These sections are atomized at the element boundaries without using 546 // symbols. 547 case MachO::S_4BYTE_LITERALS: 548 case MachO::S_8BYTE_LITERALS: 549 case MachO::S_16BYTE_LITERALS: 550 case MachO::S_LITERAL_POINTERS: 551 case MachO::S_NON_LAZY_SYMBOL_POINTERS: 552 case MachO::S_LAZY_SYMBOL_POINTERS: 553 case MachO::S_MOD_INIT_FUNC_POINTERS: 554 case MachO::S_MOD_TERM_FUNC_POINTERS: 555 case MachO::S_INTERPOSING: 556 return false; 557 } 558 } 559 560 const MCSection *TargetLoweringObjectFileMachO:: 561 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 562 Mangler &Mang, const TargetMachine &TM) const { 563 564 // Handle thread local data. 565 if (Kind.isThreadBSS()) return TLSBSSSection; 566 if (Kind.isThreadData()) return TLSDataSection; 567 568 if (Kind.isText()) 569 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 570 571 // If this is weak/linkonce, put this in a coalescable section, either in text 572 // or data depending on if it is writable. 573 if (GV->isWeakForLinker()) { 574 if (Kind.isReadOnly()) 575 return ConstTextCoalSection; 576 return DataCoalSection; 577 } 578 579 // FIXME: Alignment check should be handled by section classifier. 580 if (Kind.isMergeable1ByteCString() && 581 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 582 return CStringSection; 583 584 // Do not put 16-bit arrays in the UString section if they have an 585 // externally visible label, this runs into issues with certain linker 586 // versions. 587 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() && 588 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 589 return UStringSection; 590 591 if (Kind.isMergeableConst()) { 592 if (Kind.isMergeableConst4()) 593 return FourByteConstantSection; 594 if (Kind.isMergeableConst8()) 595 return EightByteConstantSection; 596 if (Kind.isMergeableConst16()) 597 return SixteenByteConstantSection; 598 } 599 600 // Otherwise, if it is readonly, but not something we can specially optimize, 601 // just drop it in .const. 602 if (Kind.isReadOnly()) 603 return ReadOnlySection; 604 605 // If this is marked const, put it into a const section. But if the dynamic 606 // linker needs to write to it, put it in the data segment. 607 if (Kind.isReadOnlyWithRel()) 608 return ConstDataSection; 609 610 // Put zero initialized globals with strong external linkage in the 611 // DATA, __common section with the .zerofill directive. 612 if (Kind.isBSSExtern()) 613 return DataCommonSection; 614 615 // Put zero initialized globals with local linkage in __DATA,__bss directive 616 // with the .zerofill directive (aka .lcomm). 617 if (Kind.isBSSLocal()) 618 return DataBSSSection; 619 620 // Otherwise, just drop the variable in the normal data section. 621 return DataSection; 622 } 623 624 const MCSection * 625 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) 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()) 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 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 732 const GlobalValue *GV, SectionKind Kind, Mangler &Mang, 733 const TargetMachine &TM) const { 734 int Selection = 0; 735 unsigned Characteristics = getCOFFSectionFlags(Kind); 736 StringRef Name = GV->getSection(); 737 StringRef COMDATSymName = ""; 738 if (GV->isWeakForLinker()) { 739 Selection = COFF::IMAGE_COMDAT_SELECT_ANY; 740 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 741 MCSymbol *Sym = TM.getSymbol(GV, Mang); 742 COMDATSymName = Sym->getName(); 743 } 744 return getContext().getCOFFSection(Name, 745 Characteristics, 746 Kind, 747 COMDATSymName, 748 Selection); 749 } 750 751 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 752 if (Kind.isText()) 753 return ".text"; 754 if (Kind.isBSS()) 755 return ".bss"; 756 if (Kind.isThreadLocal()) 757 return ".tls$"; 758 if (Kind.isWriteable()) 759 return ".data"; 760 return ".rdata"; 761 } 762 763 764 const MCSection *TargetLoweringObjectFileCOFF:: 765 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 766 Mangler &Mang, const TargetMachine &TM) const { 767 // If we have -ffunction-sections then we should emit the global value to a 768 // uniqued section specifically for it. 769 bool EmitUniquedSection; 770 if (Kind.isText()) 771 EmitUniquedSection = TM.getFunctionSections(); 772 else 773 EmitUniquedSection = TM.getDataSections(); 774 775 // If this global is linkonce/weak and the target handles this by emitting it 776 // into a 'uniqued' section name, create and return the section now. 777 // Section names depend on the name of the symbol which is not feasible if the 778 // symbol has private linkage. 779 if ((GV->isWeakForLinker() || EmitUniquedSection) && 780 !GV->hasPrivateLinkage() && !Kind.isCommon()) { 781 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 782 unsigned Characteristics = getCOFFSectionFlags(Kind); 783 784 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 785 MCSymbol *Sym = TM.getSymbol(GV, Mang); 786 return getContext().getCOFFSection( 787 Name, Characteristics, Kind, Sym->getName(), 788 GV->isWeakForLinker() ? COFF::IMAGE_COMDAT_SELECT_ANY 789 : COFF::IMAGE_COMDAT_SELECT_NODUPLICATES); 790 } 791 792 if (Kind.isText()) 793 return TextSection; 794 795 if (Kind.isThreadLocal()) 796 return TLSDataSection; 797 798 if (Kind.isReadOnly()) 799 return ReadOnlySection; 800 801 // Note: we claim that common symbols are put in BSSSection, but they are 802 // really emitted with the magic .comm directive, which creates a symbol table 803 // entry but not a section. 804 if (Kind.isBSS() || Kind.isCommon()) 805 return BSSSection; 806 807 return DataSection; 808 } 809 810 StringRef TargetLoweringObjectFileCOFF:: 811 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 812 const char *LibCmd = "/DEFAULTLIB:"; 813 if (LinkerOption.startswith(LibCmd)) 814 return LinkerOption.substr(strlen(LibCmd)); 815 return StringRef(); 816 } 817 818 void TargetLoweringObjectFileCOFF:: 819 emitModuleFlags(MCStreamer &Streamer, 820 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 821 Mangler &Mang, const TargetMachine &TM) const { 822 MDNode *LinkerOptions = nullptr; 823 824 // Look for the "Linker Options" flag, since it's the only one we support. 825 for (ArrayRef<Module::ModuleFlagEntry>::iterator 826 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 827 const Module::ModuleFlagEntry &MFE = *i; 828 StringRef Key = MFE.Key->getString(); 829 Value *Val = MFE.Val; 830 if (Key == "Linker Options") { 831 LinkerOptions = cast<MDNode>(Val); 832 break; 833 } 834 } 835 if (!LinkerOptions) 836 return; 837 838 // Emit the linker options to the linker .drectve section. According to the 839 // spec, this section is a space-separated string containing flags for linker. 840 const MCSection *Sec = getDrectveSection(); 841 Streamer.SwitchSection(Sec); 842 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 843 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 844 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 845 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 846 StringRef Op = MDOption->getString(); 847 // Lead with a space for consistency with our dllexport implementation. 848 std::string Escaped(" "); 849 if (Op.find(" ") != StringRef::npos) { 850 // The PE-COFF spec says args with spaces must be quoted. It doesn't say 851 // how to escape quotes, but it probably uses this algorithm: 852 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx 853 // FIXME: Reuse escaping code from Support/Windows/Program.inc 854 Escaped.push_back('\"'); 855 Escaped.append(Op); 856 Escaped.push_back('\"'); 857 } else { 858 Escaped.append(Op); 859 } 860 Streamer.EmitBytes(Escaped); 861 } 862 } 863 } 864 865 static const MCSection *getAssociativeCOFFSection(MCContext &Ctx, 866 const MCSection *Sec, 867 const MCSymbol *KeySym) { 868 // Return the normal section if we don't have to be associative. 869 if (!KeySym) 870 return Sec; 871 872 // Make an associative section with the same name and kind as the normal 873 // section. 874 const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec); 875 unsigned Characteristics = 876 SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT; 877 return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics, 878 SecCOFF->getKind(), KeySym->getName(), 879 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE); 880 } 881 882 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 883 unsigned Priority, const MCSymbol *KeySym) const { 884 return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym); 885 } 886 887 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 888 unsigned Priority, const MCSymbol *KeySym) const { 889 return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym); 890 } 891