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/TargetMachine.h" 39 using namespace llvm; 40 using namespace dwarf; 41 42 //===----------------------------------------------------------------------===// 43 // ELF 44 //===----------------------------------------------------------------------===// 45 46 MCSymbol * 47 TargetLoweringObjectFileELF::getCFIPersonalitySymbol(const GlobalValue *GV, 48 Mangler *Mang, 49 MachineModuleInfo *MMI) const { 50 unsigned Encoding = getPersonalityEncoding(); 51 switch (Encoding & 0x70) { 52 default: 53 report_fatal_error("We do not support this DWARF encoding yet!"); 54 case dwarf::DW_EH_PE_absptr: 55 return getSymbol(*Mang, GV); 56 case dwarf::DW_EH_PE_pcrel: { 57 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") + 58 getSymbol(*Mang, GV)->getName()); 59 } 60 } 61 } 62 63 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer, 64 const TargetMachine &TM, 65 const MCSymbol *Sym) const { 66 SmallString<64> NameData("DW.ref."); 67 NameData += Sym->getName(); 68 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData); 69 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 70 Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 71 StringRef Prefix = ".data."; 72 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end()); 73 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 74 const MCSection *Sec = getContext().getELFSection(NameData, 75 ELF::SHT_PROGBITS, 76 Flags, 77 SectionKind::getDataRel(), 78 0, Label->getName()); 79 unsigned Size = TM.getDataLayout()->getPointerSize(); 80 Streamer.SwitchSection(Sec); 81 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment()); 82 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); 83 const MCExpr *E = MCConstantExpr::Create(Size, getContext()); 84 Streamer.EmitELFSize(Label, E); 85 Streamer.EmitLabel(Label); 86 87 Streamer.EmitSymbolValue(Sym, Size); 88 } 89 90 const MCExpr *TargetLoweringObjectFileELF:: 91 getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, 92 MachineModuleInfo *MMI, unsigned Encoding, 93 MCStreamer &Streamer) const { 94 95 if (Encoding & dwarf::DW_EH_PE_indirect) { 96 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 97 98 MCSymbol *SSym = getSymbolWithGlobalValueBase(*Mang, GV, ".DW.stub"); 99 100 // Add information about the stub reference to ELFMMI so that the stub 101 // gets emitted by the asmprinter. 102 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 103 if (StubSym.getPointer() == 0) { 104 MCSymbol *Sym = getSymbol(*Mang, GV); 105 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 106 } 107 108 return TargetLoweringObjectFile:: 109 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 110 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 111 } 112 113 return TargetLoweringObjectFile:: 114 getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer); 115 } 116 117 static SectionKind 118 getELFKindForNamedSection(StringRef Name, SectionKind K) { 119 // N.B.: The defaults used in here are no the same ones used in MC. 120 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 121 // both gas and MC will produce a section with no flags. Given 122 // section(".eh_frame") gcc will produce: 123 // 124 // .section .eh_frame,"a",@progbits 125 if (Name.empty() || Name[0] != '.') return K; 126 127 // Some lame default implementation based on some magic section names. 128 if (Name == ".bss" || 129 Name.startswith(".bss.") || 130 Name.startswith(".gnu.linkonce.b.") || 131 Name.startswith(".llvm.linkonce.b.") || 132 Name == ".sbss" || 133 Name.startswith(".sbss.") || 134 Name.startswith(".gnu.linkonce.sb.") || 135 Name.startswith(".llvm.linkonce.sb.")) 136 return SectionKind::getBSS(); 137 138 if (Name == ".tdata" || 139 Name.startswith(".tdata.") || 140 Name.startswith(".gnu.linkonce.td.") || 141 Name.startswith(".llvm.linkonce.td.")) 142 return SectionKind::getThreadData(); 143 144 if (Name == ".tbss" || 145 Name.startswith(".tbss.") || 146 Name.startswith(".gnu.linkonce.tb.") || 147 Name.startswith(".llvm.linkonce.tb.")) 148 return SectionKind::getThreadBSS(); 149 150 return K; 151 } 152 153 154 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 155 156 if (Name == ".init_array") 157 return ELF::SHT_INIT_ARRAY; 158 159 if (Name == ".fini_array") 160 return ELF::SHT_FINI_ARRAY; 161 162 if (Name == ".preinit_array") 163 return ELF::SHT_PREINIT_ARRAY; 164 165 if (K.isBSS() || K.isThreadBSS()) 166 return ELF::SHT_NOBITS; 167 168 return ELF::SHT_PROGBITS; 169 } 170 171 172 static unsigned 173 getELFSectionFlags(SectionKind K) { 174 unsigned Flags = 0; 175 176 if (!K.isMetadata()) 177 Flags |= ELF::SHF_ALLOC; 178 179 if (K.isText()) 180 Flags |= ELF::SHF_EXECINSTR; 181 182 if (K.isWriteable()) 183 Flags |= ELF::SHF_WRITE; 184 185 if (K.isThreadLocal()) 186 Flags |= ELF::SHF_TLS; 187 188 // K.isMergeableConst() is left out to honour PR4650 189 if (K.isMergeableCString() || K.isMergeableConst4() || 190 K.isMergeableConst8() || K.isMergeableConst16()) 191 Flags |= ELF::SHF_MERGE; 192 193 if (K.isMergeableCString()) 194 Flags |= ELF::SHF_STRINGS; 195 196 return Flags; 197 } 198 199 200 const MCSection *TargetLoweringObjectFileELF:: 201 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 202 Mangler *Mang, const TargetMachine &TM) const { 203 StringRef SectionName = GV->getSection(); 204 205 // Infer section flags from the section name if we can. 206 Kind = getELFKindForNamedSection(SectionName, Kind); 207 208 return getContext().getELFSection(SectionName, 209 getELFSectionType(SectionName, Kind), 210 getELFSectionFlags(Kind), Kind); 211 } 212 213 /// getSectionPrefixForGlobal - Return the section prefix name used by options 214 /// FunctionsSections and DataSections. 215 static const char *getSectionPrefixForGlobal(SectionKind Kind) { 216 if (Kind.isText()) return ".text."; 217 if (Kind.isReadOnly()) return ".rodata."; 218 if (Kind.isBSS()) return ".bss."; 219 220 if (Kind.isThreadData()) return ".tdata."; 221 if (Kind.isThreadBSS()) return ".tbss."; 222 223 if (Kind.isDataNoRel()) return ".data."; 224 if (Kind.isDataRelLocal()) return ".data.rel.local."; 225 if (Kind.isDataRel()) return ".data.rel."; 226 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local."; 227 228 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 229 return ".data.rel.ro."; 230 } 231 232 233 const MCSection *TargetLoweringObjectFileELF:: 234 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 235 Mangler *Mang, TargetMachine &TM) const { 236 // If we have -ffunction-section or -fdata-section then we should emit the 237 // global value to a uniqued section specifically for it. 238 bool EmitUniquedSection; 239 if (Kind.isText()) 240 EmitUniquedSection = TM.getFunctionSections(); 241 else 242 EmitUniquedSection = TM.getDataSections(); 243 244 // If this global is linkonce/weak and the target handles this by emitting it 245 // into a 'uniqued' section name, create and return the section now. 246 if ((GV->isWeakForLinker() || EmitUniquedSection) && 247 !Kind.isCommon()) { 248 const char *Prefix; 249 Prefix = getSectionPrefixForGlobal(Kind); 250 251 SmallString<128> Name(Prefix, Prefix+strlen(Prefix)); 252 MCSymbol *Sym = getSymbol(*Mang, GV); 253 Name.append(Sym->getName().begin(), Sym->getName().end()); 254 StringRef Group = ""; 255 unsigned Flags = getELFSectionFlags(Kind); 256 if (GV->isWeakForLinker()) { 257 Group = Sym->getName(); 258 Flags |= ELF::SHF_GROUP; 259 } 260 261 // Set that we've used a unique section name in the target machine. 262 TM.setDebugUseUniqueSections(true); 263 return getContext().getELFSection(Name.str(), 264 getELFSectionType(Name.str(), Kind), 265 Flags, Kind, 0, Group); 266 } 267 268 if (Kind.isText()) return TextSection; 269 270 if (Kind.isMergeable1ByteCString() || 271 Kind.isMergeable2ByteCString() || 272 Kind.isMergeable4ByteCString()) { 273 274 // We also need alignment here. 275 // FIXME: this is getting the alignment of the character, not the 276 // alignment of the global! 277 unsigned Align = 278 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)); 279 280 const char *SizeSpec = ".rodata.str1."; 281 if (Kind.isMergeable2ByteCString()) 282 SizeSpec = ".rodata.str2."; 283 else if (Kind.isMergeable4ByteCString()) 284 SizeSpec = ".rodata.str4."; 285 else 286 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 287 288 289 std::string Name = SizeSpec + utostr(Align); 290 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 291 ELF::SHF_ALLOC | 292 ELF::SHF_MERGE | 293 ELF::SHF_STRINGS, 294 Kind); 295 } 296 297 if (Kind.isMergeableConst()) { 298 if (Kind.isMergeableConst4() && MergeableConst4Section) 299 return MergeableConst4Section; 300 if (Kind.isMergeableConst8() && MergeableConst8Section) 301 return MergeableConst8Section; 302 if (Kind.isMergeableConst16() && MergeableConst16Section) 303 return MergeableConst16Section; 304 return ReadOnlySection; // .const 305 } 306 307 if (Kind.isReadOnly()) return ReadOnlySection; 308 309 if (Kind.isThreadData()) return TLSDataSection; 310 if (Kind.isThreadBSS()) return TLSBSSSection; 311 312 // Note: we claim that common symbols are put in BSSSection, but they are 313 // really emitted with the magic .comm directive, which creates a symbol table 314 // entry but not a section. 315 if (Kind.isBSS() || Kind.isCommon()) return BSSSection; 316 317 if (Kind.isDataNoRel()) return DataSection; 318 if (Kind.isDataRelLocal()) return DataRelLocalSection; 319 if (Kind.isDataRel()) return DataRelSection; 320 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 321 322 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 323 return DataRelROSection; 324 } 325 326 /// getSectionForConstant - Given a mergeable constant with the 327 /// specified size and relocation information, return a section that it 328 /// should be placed in. 329 const MCSection *TargetLoweringObjectFileELF:: 330 getSectionForConstant(SectionKind Kind) const { 331 if (Kind.isMergeableConst4() && MergeableConst4Section) 332 return MergeableConst4Section; 333 if (Kind.isMergeableConst8() && MergeableConst8Section) 334 return MergeableConst8Section; 335 if (Kind.isMergeableConst16() && MergeableConst16Section) 336 return MergeableConst16Section; 337 if (Kind.isReadOnly()) 338 return ReadOnlySection; 339 340 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 341 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 342 return DataRelROSection; 343 } 344 345 const MCSection * 346 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const { 347 // The default scheme is .ctor / .dtor, so we have to invert the priority 348 // numbering. 349 if (Priority == 65535) 350 return StaticCtorSection; 351 352 if (UseInitArray) { 353 std::string Name = std::string(".init_array.") + utostr(Priority); 354 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY, 355 ELF::SHF_ALLOC | ELF::SHF_WRITE, 356 SectionKind::getDataRel()); 357 } else { 358 std::string Name = std::string(".ctors.") + utostr(65535 - Priority); 359 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 360 ELF::SHF_ALLOC |ELF::SHF_WRITE, 361 SectionKind::getDataRel()); 362 } 363 } 364 365 const MCSection * 366 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const { 367 // The default scheme is .ctor / .dtor, so we have to invert the priority 368 // numbering. 369 if (Priority == 65535) 370 return StaticDtorSection; 371 372 if (UseInitArray) { 373 std::string Name = std::string(".fini_array.") + utostr(Priority); 374 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY, 375 ELF::SHF_ALLOC | ELF::SHF_WRITE, 376 SectionKind::getDataRel()); 377 } else { 378 std::string Name = std::string(".dtors.") + utostr(65535 - Priority); 379 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, 380 ELF::SHF_ALLOC |ELF::SHF_WRITE, 381 SectionKind::getDataRel()); 382 } 383 } 384 385 void 386 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 387 UseInitArray = UseInitArray_; 388 if (!UseInitArray) 389 return; 390 391 StaticCtorSection = 392 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 393 ELF::SHF_WRITE | 394 ELF::SHF_ALLOC, 395 SectionKind::getDataRel()); 396 StaticDtorSection = 397 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 398 ELF::SHF_WRITE | 399 ELF::SHF_ALLOC, 400 SectionKind::getDataRel()); 401 } 402 403 //===----------------------------------------------------------------------===// 404 // MachO 405 //===----------------------------------------------------------------------===// 406 407 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker 408 /// option string. Returns StringRef() if the option does not specify a library. 409 StringRef TargetLoweringObjectFileMachO:: 410 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 411 const char *LibCmd = "-l"; 412 if (LinkerOption.startswith(LibCmd)) 413 return LinkerOption.substr(strlen(LibCmd)); 414 return StringRef(); 415 } 416 417 /// emitModuleFlags - Perform code emission for module flags. 418 void TargetLoweringObjectFileMachO:: 419 emitModuleFlags(MCStreamer &Streamer, 420 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 421 Mangler *Mang, const TargetMachine &TM) const { 422 unsigned VersionVal = 0; 423 unsigned ImageInfoFlags = 0; 424 MDNode *LinkerOptions = 0; 425 StringRef SectionVal; 426 427 for (ArrayRef<Module::ModuleFlagEntry>::iterator 428 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 429 const Module::ModuleFlagEntry &MFE = *i; 430 431 // Ignore flags with 'Require' behavior. 432 if (MFE.Behavior == Module::Require) 433 continue; 434 435 StringRef Key = MFE.Key->getString(); 436 Value *Val = MFE.Val; 437 438 if (Key == "Objective-C Image Info Version") { 439 VersionVal = cast<ConstantInt>(Val)->getZExtValue(); 440 } else if (Key == "Objective-C Garbage Collection" || 441 Key == "Objective-C GC Only" || 442 Key == "Objective-C Is Simulated") { 443 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue(); 444 } else if (Key == "Objective-C Image Info Section") { 445 SectionVal = cast<MDString>(Val)->getString(); 446 } else if (Key == "Linker Options") { 447 LinkerOptions = cast<MDNode>(Val); 448 } 449 } 450 451 // Emit the linker options if present. 452 if (LinkerOptions) { 453 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 454 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 455 SmallVector<std::string, 4> StrOptions; 456 457 // Convert to strings. 458 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 459 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 460 StrOptions.push_back(MDOption->getString()); 461 } 462 463 Streamer.EmitLinkerOptions(StrOptions); 464 } 465 } 466 467 // The section is mandatory. If we don't have it, then we don't have GC info. 468 if (SectionVal.empty()) return; 469 470 StringRef Segment, Section; 471 unsigned TAA = 0, StubSize = 0; 472 bool TAAParsed; 473 std::string ErrorCode = 474 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 475 TAA, TAAParsed, StubSize); 476 if (!ErrorCode.empty()) 477 // If invalid, report the error with report_fatal_error. 478 report_fatal_error("Invalid section specifier '" + Section + "': " + 479 ErrorCode + "."); 480 481 // Get the section. 482 const MCSectionMachO *S = 483 getContext().getMachOSection(Segment, Section, TAA, StubSize, 484 SectionKind::getDataNoRel()); 485 Streamer.SwitchSection(S); 486 Streamer.EmitLabel(getContext(). 487 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 488 Streamer.EmitIntValue(VersionVal, 4); 489 Streamer.EmitIntValue(ImageInfoFlags, 4); 490 Streamer.AddBlankLine(); 491 } 492 493 const MCSection *TargetLoweringObjectFileMachO:: 494 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 495 Mangler *Mang, const TargetMachine &TM) const { 496 // Parse the section specifier and create it if valid. 497 StringRef Segment, Section; 498 unsigned TAA = 0, StubSize = 0; 499 bool TAAParsed; 500 std::string ErrorCode = 501 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 502 TAA, TAAParsed, StubSize); 503 if (!ErrorCode.empty()) { 504 // If invalid, report the error with report_fatal_error. 505 report_fatal_error("Global variable '" + GV->getName() + 506 "' has an invalid section specifier '" + 507 GV->getSection() + "': " + ErrorCode + "."); 508 } 509 510 // Get the section. 511 const MCSectionMachO *S = 512 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 513 514 // If TAA wasn't set by ParseSectionSpecifier() above, 515 // use the value returned by getMachOSection() as a default. 516 if (!TAAParsed) 517 TAA = S->getTypeAndAttributes(); 518 519 // Okay, now that we got the section, verify that the TAA & StubSize agree. 520 // If the user declared multiple globals with different section flags, we need 521 // to reject it here. 522 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 523 // If invalid, report the error with report_fatal_error. 524 report_fatal_error("Global variable '" + GV->getName() + 525 "' section type or attributes does not match previous" 526 " section specifier"); 527 } 528 529 return S; 530 } 531 532 const MCSection *TargetLoweringObjectFileMachO:: 533 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 534 Mangler *Mang, TargetMachine &TM) const { 535 536 // Handle thread local data. 537 if (Kind.isThreadBSS()) return TLSBSSSection; 538 if (Kind.isThreadData()) return TLSDataSection; 539 540 if (Kind.isText()) 541 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 542 543 // If this is weak/linkonce, put this in a coalescable section, either in text 544 // or data depending on if it is writable. 545 if (GV->isWeakForLinker()) { 546 if (Kind.isReadOnly()) 547 return ConstTextCoalSection; 548 return DataCoalSection; 549 } 550 551 // FIXME: Alignment check should be handled by section classifier. 552 if (Kind.isMergeable1ByteCString() && 553 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 554 return CStringSection; 555 556 // Do not put 16-bit arrays in the UString section if they have an 557 // externally visible label, this runs into issues with certain linker 558 // versions. 559 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() && 560 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32) 561 return UStringSection; 562 563 if (Kind.isMergeableConst()) { 564 if (Kind.isMergeableConst4()) 565 return FourByteConstantSection; 566 if (Kind.isMergeableConst8()) 567 return EightByteConstantSection; 568 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 569 return SixteenByteConstantSection; 570 } 571 572 // Otherwise, if it is readonly, but not something we can specially optimize, 573 // just drop it in .const. 574 if (Kind.isReadOnly()) 575 return ReadOnlySection; 576 577 // If this is marked const, put it into a const section. But if the dynamic 578 // linker needs to write to it, put it in the data segment. 579 if (Kind.isReadOnlyWithRel()) 580 return ConstDataSection; 581 582 // Put zero initialized globals with strong external linkage in the 583 // DATA, __common section with the .zerofill directive. 584 if (Kind.isBSSExtern()) 585 return DataCommonSection; 586 587 // Put zero initialized globals with local linkage in __DATA,__bss directive 588 // with the .zerofill directive (aka .lcomm). 589 if (Kind.isBSSLocal()) 590 return DataBSSSection; 591 592 // Otherwise, just drop the variable in the normal data section. 593 return DataSection; 594 } 595 596 const MCSection * 597 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const { 598 // If this constant requires a relocation, we have to put it in the data 599 // segment, not in the text segment. 600 if (Kind.isDataRel() || Kind.isReadOnlyWithRel()) 601 return ConstDataSection; 602 603 if (Kind.isMergeableConst4()) 604 return FourByteConstantSection; 605 if (Kind.isMergeableConst8()) 606 return EightByteConstantSection; 607 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 608 return SixteenByteConstantSection; 609 return ReadOnlySection; // .const 610 } 611 612 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide 613 /// not to emit the UsedDirective for some symbols in llvm.used. 614 // FIXME: REMOVE this (rdar://7071300) 615 bool TargetLoweringObjectFileMachO:: 616 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const { 617 /// On Darwin, internally linked data beginning with "L" or "l" does not have 618 /// the directive emitted (this occurs in ObjC metadata). 619 if (!GV) return false; 620 621 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix. 622 if (GV->hasLocalLinkage() && !isa<Function>(GV)) { 623 // FIXME: ObjC metadata is currently emitted as internal symbols that have 624 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and 625 // this horrible hack can go away. 626 MCSymbol *Sym = getSymbol(*Mang, GV); 627 if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l') 628 return false; 629 } 630 631 return true; 632 } 633 634 const MCExpr *TargetLoweringObjectFileMachO:: 635 getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, 636 MachineModuleInfo *MMI, unsigned Encoding, 637 MCStreamer &Streamer) const { 638 // The mach-o version of this method defaults to returning a stub reference. 639 640 if (Encoding & DW_EH_PE_indirect) { 641 MachineModuleInfoMachO &MachOMMI = 642 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 643 644 MCSymbol *SSym = getSymbolWithGlobalValueBase(*Mang, GV, "$non_lazy_ptr"); 645 646 // Add information about the stub reference to MachOMMI so that the stub 647 // gets emitted by the asmprinter. 648 MachineModuleInfoImpl::StubValueTy &StubSym = 649 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) : 650 MachOMMI.getGVStubEntry(SSym); 651 if (StubSym.getPointer() == 0) { 652 MCSymbol *Sym = getSymbol(*Mang, GV); 653 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 654 } 655 656 return TargetLoweringObjectFile:: 657 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()), 658 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer); 659 } 660 661 return TargetLoweringObjectFile:: 662 getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer); 663 } 664 665 MCSymbol *TargetLoweringObjectFileMachO:: 666 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang, 667 MachineModuleInfo *MMI) const { 668 // The mach-o version of this method defaults to returning a stub reference. 669 MachineModuleInfoMachO &MachOMMI = 670 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 671 672 MCSymbol *SSym = getSymbolWithGlobalValueBase(*Mang, GV, "$non_lazy_ptr"); 673 674 // Add information about the stub reference to MachOMMI so that the stub 675 // gets emitted by the asmprinter. 676 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 677 if (StubSym.getPointer() == 0) { 678 MCSymbol *Sym = getSymbol(*Mang, GV); 679 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 680 } 681 682 return SSym; 683 } 684 685 //===----------------------------------------------------------------------===// 686 // COFF 687 //===----------------------------------------------------------------------===// 688 689 static unsigned 690 getCOFFSectionFlags(SectionKind K) { 691 unsigned Flags = 0; 692 693 if (K.isMetadata()) 694 Flags |= 695 COFF::IMAGE_SCN_MEM_DISCARDABLE; 696 else if (K.isText()) 697 Flags |= 698 COFF::IMAGE_SCN_MEM_EXECUTE | 699 COFF::IMAGE_SCN_MEM_READ | 700 COFF::IMAGE_SCN_CNT_CODE; 701 else if (K.isBSS ()) 702 Flags |= 703 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 704 COFF::IMAGE_SCN_MEM_READ | 705 COFF::IMAGE_SCN_MEM_WRITE; 706 else if (K.isThreadLocal()) 707 Flags |= 708 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 709 COFF::IMAGE_SCN_MEM_READ | 710 COFF::IMAGE_SCN_MEM_WRITE; 711 else if (K.isReadOnly()) 712 Flags |= 713 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 714 COFF::IMAGE_SCN_MEM_READ; 715 else if (K.isWriteable()) 716 Flags |= 717 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 718 COFF::IMAGE_SCN_MEM_READ | 719 COFF::IMAGE_SCN_MEM_WRITE; 720 721 return Flags; 722 } 723 724 const MCSection *TargetLoweringObjectFileCOFF:: 725 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 726 Mangler *Mang, const TargetMachine &TM) const { 727 int Selection = 0; 728 unsigned Characteristics = getCOFFSectionFlags(Kind); 729 StringRef Name = GV->getSection(); 730 StringRef COMDATSymName = ""; 731 if (GV->isWeakForLinker()) { 732 Selection = COFF::IMAGE_COMDAT_SELECT_ANY; 733 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 734 MCSymbol *Sym = getSymbol(*Mang, GV); 735 COMDATSymName = Sym->getName(); 736 } 737 return getContext().getCOFFSection(Name, 738 Characteristics, 739 Kind, 740 COMDATSymName, 741 Selection); 742 } 743 744 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 745 if (Kind.isText()) 746 return ".text"; 747 if (Kind.isBSS ()) 748 return ".bss"; 749 if (Kind.isThreadLocal()) 750 return ".tls$"; 751 if (Kind.isWriteable()) 752 return ".data"; 753 return ".rdata"; 754 } 755 756 757 const MCSection *TargetLoweringObjectFileCOFF:: 758 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 759 Mangler *Mang, TargetMachine &TM) const { 760 761 // If this global is linkonce/weak and the target handles this by emitting it 762 // into a 'uniqued' section name, create and return the section now. 763 if (GV->isWeakForLinker()) { 764 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); 765 unsigned Characteristics = getCOFFSectionFlags(Kind); 766 767 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 768 MCSymbol *Sym = getSymbol(*Mang, GV); 769 return getContext().getCOFFSection(Name, Characteristics, 770 Kind, Sym->getName(), 771 COFF::IMAGE_COMDAT_SELECT_ANY); 772 } 773 774 if (Kind.isText()) 775 return TextSection; 776 777 if (Kind.isThreadLocal()) 778 return TLSDataSection; 779 780 if (Kind.isReadOnly()) 781 return ReadOnlySection; 782 783 if (Kind.isBSS()) 784 return BSSSection; 785 786 return DataSection; 787 } 788 789 StringRef TargetLoweringObjectFileCOFF:: 790 getDepLibFromLinkerOpt(StringRef LinkerOption) const { 791 const char *LibCmd = "/DEFAULTLIB:"; 792 if (LinkerOption.startswith(LibCmd)) 793 return LinkerOption.substr(strlen(LibCmd)); 794 return StringRef(); 795 } 796 797 void TargetLoweringObjectFileCOFF:: 798 emitModuleFlags(MCStreamer &Streamer, 799 ArrayRef<Module::ModuleFlagEntry> ModuleFlags, 800 Mangler *Mang, const TargetMachine &TM) const { 801 MDNode *LinkerOptions = 0; 802 803 // Look for the "Linker Options" flag, since it's the only one we support. 804 for (ArrayRef<Module::ModuleFlagEntry>::iterator 805 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { 806 const Module::ModuleFlagEntry &MFE = *i; 807 StringRef Key = MFE.Key->getString(); 808 Value *Val = MFE.Val; 809 if (Key == "Linker Options") { 810 LinkerOptions = cast<MDNode>(Val); 811 break; 812 } 813 } 814 if (!LinkerOptions) 815 return; 816 817 // Emit the linker options to the linker .drectve section. According to the 818 // spec, this section is a space-separated string containing flags for linker. 819 const MCSection *Sec = getDrectveSection(); 820 Streamer.SwitchSection(Sec); 821 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 822 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 823 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 824 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 825 StringRef Op = MDOption->getString(); 826 // Lead with a space for consistency with our dllexport implementation. 827 std::string Escaped(" "); 828 if (Op.find(" ") != StringRef::npos) { 829 // The PE-COFF spec says args with spaces must be quoted. It doesn't say 830 // how to escape quotes, but it probably uses this algorithm: 831 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx 832 // FIXME: Reuse escaping code from Support/Windows/Program.inc 833 Escaped.push_back('\"'); 834 Escaped.append(Op); 835 Escaped.push_back('\"'); 836 } else { 837 Escaped.append(Op); 838 } 839 Streamer.EmitBytes(Escaped); 840 } 841 } 842 } 843