1 //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h" 16 #include "llvm/Constants.h" 17 #include "llvm/DerivedTypes.h" 18 #include "llvm/Function.h" 19 #include "llvm/GlobalVariable.h" 20 #include "llvm/MC/MCContext.h" 21 #include "llvm/MC/MCExpr.h" 22 #include "llvm/MC/MCSectionMachO.h" 23 #include "llvm/MC/MCSectionELF.h" 24 #include "llvm/Target/TargetData.h" 25 #include "llvm/Target/TargetMachine.h" 26 #include "llvm/Target/TargetOptions.h" 27 #include "llvm/Support/Mangler.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/ADT/StringExtras.h" 30 using namespace llvm; 31 32 //===----------------------------------------------------------------------===// 33 // Generic Code 34 //===----------------------------------------------------------------------===// 35 36 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) { 37 TextSection = 0; 38 DataSection = 0; 39 BSSSection = 0; 40 ReadOnlySection = 0; 41 StaticCtorSection = 0; 42 StaticDtorSection = 0; 43 LSDASection = 0; 44 EHFrameSection = 0; 45 46 DwarfAbbrevSection = 0; 47 DwarfInfoSection = 0; 48 DwarfLineSection = 0; 49 DwarfFrameSection = 0; 50 DwarfPubNamesSection = 0; 51 DwarfPubTypesSection = 0; 52 DwarfDebugInlineSection = 0; 53 DwarfStrSection = 0; 54 DwarfLocSection = 0; 55 DwarfARangesSection = 0; 56 DwarfRangesSection = 0; 57 DwarfMacroInfoSection = 0; 58 } 59 60 TargetLoweringObjectFile::~TargetLoweringObjectFile() { 61 } 62 63 static bool isSuitableForBSS(const GlobalVariable *GV) { 64 Constant *C = GV->getInitializer(); 65 66 // Must have zero initializer. 67 if (!C->isNullValue()) 68 return false; 69 70 // Leave constant zeros in readonly constant sections, so they can be shared. 71 if (GV->isConstant()) 72 return false; 73 74 // If the global has an explicit section specified, don't put it in BSS. 75 if (!GV->getSection().empty()) 76 return false; 77 78 // If -nozero-initialized-in-bss is specified, don't ever use BSS. 79 if (NoZerosInBSS) 80 return false; 81 82 // Otherwise, put it in BSS! 83 return true; 84 } 85 86 /// IsNullTerminatedString - Return true if the specified constant (which is 87 /// known to have a type that is an array of 1/2/4 byte elements) ends with a 88 /// nul value and contains no other nuls in it. 89 static bool IsNullTerminatedString(const Constant *C) { 90 const ArrayType *ATy = cast<ArrayType>(C->getType()); 91 92 // First check: is we have constant array of i8 terminated with zero 93 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) { 94 if (ATy->getNumElements() == 0) return false; 95 96 ConstantInt *Null = 97 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1)); 98 if (Null == 0 || Null->getZExtValue() != 0) 99 return false; // Not null terminated. 100 101 // Verify that the null doesn't occur anywhere else in the string. 102 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i) 103 // Reject constantexpr elements etc. 104 if (!isa<ConstantInt>(CVA->getOperand(i)) || 105 CVA->getOperand(i) == Null) 106 return false; 107 return true; 108 } 109 110 // Another possibility: [1 x i8] zeroinitializer 111 if (isa<ConstantAggregateZero>(C)) 112 return ATy->getNumElements() == 1; 113 114 return false; 115 } 116 117 /// getKindForGlobal - This is a top-level target-independent classifier for 118 /// a global variable. Given an global variable and information from TM, it 119 /// classifies the global in a variety of ways that make various target 120 /// implementations simpler. The target implementation is free to ignore this 121 /// extra info of course. 122 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV, 123 const TargetMachine &TM){ 124 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() && 125 "Can only be used for global definitions"); 126 127 Reloc::Model ReloModel = TM.getRelocationModel(); 128 129 // Early exit - functions should be always in text sections. 130 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV); 131 if (GVar == 0) 132 return SectionKind::getText(); 133 134 // Handle thread-local data first. 135 if (GVar->isThreadLocal()) { 136 if (isSuitableForBSS(GVar)) 137 return SectionKind::getThreadBSS(); 138 return SectionKind::getThreadData(); 139 } 140 141 // Variable can be easily put to BSS section. 142 if (isSuitableForBSS(GVar)) 143 return SectionKind::getBSS(); 144 145 Constant *C = GVar->getInitializer(); 146 147 // If the global is marked constant, we can put it into a mergable section, 148 // a mergable string section, or general .data if it contains relocations. 149 if (GVar->isConstant()) { 150 // If the initializer for the global contains something that requires a 151 // relocation, then we may have to drop this into a wriable data section 152 // even though it is marked const. 153 switch (C->getRelocationInfo()) { 154 default: llvm_unreachable("unknown relocation info kind"); 155 case Constant::NoRelocation: 156 // If initializer is a null-terminated string, put it in a "cstring" 157 // section of the right width. 158 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) { 159 if (const IntegerType *ITy = 160 dyn_cast<IntegerType>(ATy->getElementType())) { 161 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 || 162 ITy->getBitWidth() == 32) && 163 IsNullTerminatedString(C)) { 164 if (ITy->getBitWidth() == 8) 165 return SectionKind::getMergeable1ByteCString(); 166 if (ITy->getBitWidth() == 16) 167 return SectionKind::getMergeable2ByteCString(); 168 169 assert(ITy->getBitWidth() == 32 && "Unknown width"); 170 return SectionKind::getMergeable4ByteCString(); 171 } 172 } 173 } 174 175 // Otherwise, just drop it into a mergable constant section. If we have 176 // a section for this size, use it, otherwise use the arbitrary sized 177 // mergable section. 178 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) { 179 case 4: return SectionKind::getMergeableConst4(); 180 case 8: return SectionKind::getMergeableConst8(); 181 case 16: return SectionKind::getMergeableConst16(); 182 default: return SectionKind::getMergeableConst(); 183 } 184 185 case Constant::LocalRelocation: 186 // In static relocation model, the linker will resolve all addresses, so 187 // the relocation entries will actually be constants by the time the app 188 // starts up. However, we can't put this into a mergable section, because 189 // the linker doesn't take relocations into consideration when it tries to 190 // merge entries in the section. 191 if (ReloModel == Reloc::Static) 192 return SectionKind::getReadOnly(); 193 194 // Otherwise, the dynamic linker needs to fix it up, put it in the 195 // writable data.rel.local section. 196 return SectionKind::getReadOnlyWithRelLocal(); 197 198 case Constant::GlobalRelocations: 199 // In static relocation model, the linker will resolve all addresses, so 200 // the relocation entries will actually be constants by the time the app 201 // starts up. However, we can't put this into a mergable section, because 202 // the linker doesn't take relocations into consideration when it tries to 203 // merge entries in the section. 204 if (ReloModel == Reloc::Static) 205 return SectionKind::getReadOnly(); 206 207 // Otherwise, the dynamic linker needs to fix it up, put it in the 208 // writable data.rel section. 209 return SectionKind::getReadOnlyWithRel(); 210 } 211 } 212 213 // Okay, this isn't a constant. If the initializer for the global is going 214 // to require a runtime relocation by the dynamic linker, put it into a more 215 // specific section to improve startup time of the app. This coalesces these 216 // globals together onto fewer pages, improving the locality of the dynamic 217 // linker. 218 if (ReloModel == Reloc::Static) 219 return SectionKind::getDataNoRel(); 220 221 switch (C->getRelocationInfo()) { 222 default: llvm_unreachable("unknown relocation info kind"); 223 case Constant::NoRelocation: 224 return SectionKind::getDataNoRel(); 225 case Constant::LocalRelocation: 226 return SectionKind::getDataRelLocal(); 227 case Constant::GlobalRelocations: 228 return SectionKind::getDataRel(); 229 } 230 } 231 232 /// SectionForGlobal - This method computes the appropriate section to emit 233 /// the specified global variable or function definition. This should not 234 /// be passed external (or available externally) globals. 235 const MCSection *TargetLoweringObjectFile:: 236 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, 237 const TargetMachine &TM) const { 238 // Select section name. 239 if (GV->hasSection()) 240 return getExplicitSectionGlobal(GV, Kind, Mang, TM); 241 242 243 // Use default section depending on the 'type' of global 244 return SelectSectionForGlobal(GV, Kind, Mang, TM); 245 } 246 247 248 // Lame default implementation. Calculate the section name for global. 249 const MCSection * 250 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV, 251 SectionKind Kind, 252 Mangler *Mang, 253 const TargetMachine &TM) const{ 254 assert(!Kind.isThreadLocal() && "Doesn't support TLS"); 255 256 if (Kind.isText()) 257 return getTextSection(); 258 259 if (Kind.isBSS() && BSSSection != 0) 260 return BSSSection; 261 262 if (Kind.isReadOnly() && ReadOnlySection != 0) 263 return ReadOnlySection; 264 265 return getDataSection(); 266 } 267 268 /// getSectionForConstant - Given a mergable constant with the 269 /// specified size and relocation information, return a section that it 270 /// should be placed in. 271 const MCSection * 272 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const { 273 if (Kind.isReadOnly() && ReadOnlySection != 0) 274 return ReadOnlySection; 275 276 return DataSection; 277 } 278 279 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a 280 /// pc-relative reference to the specified global variable from exception 281 /// handling information. In addition to the symbol, this returns 282 /// by-reference: 283 /// 284 /// IsIndirect - True if the returned symbol is actually a stub that contains 285 /// the address of the symbol, false if the symbol is the global itself. 286 /// 287 /// IsPCRel - True if the symbol reference is already pc-relative, false if 288 /// the caller needs to subtract off the address of the reference from the 289 /// symbol. 290 /// 291 const MCExpr *TargetLoweringObjectFile:: 292 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang, 293 bool &IsIndirect, bool &IsPCRel) const { 294 // The generic implementation of this just returns a direct reference to the 295 // symbol. 296 IsIndirect = false; 297 IsPCRel = false; 298 299 SmallString<128> Name; 300 Mang->getNameWithPrefix(Name, GV, false); 301 return MCSymbolRefExpr::Create(Name.str(), getContext()); 302 } 303 304 305 //===----------------------------------------------------------------------===// 306 // ELF 307 //===----------------------------------------------------------------------===// 308 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy; 309 310 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() { 311 // If we have the section uniquing map, free it. 312 delete (ELFUniqueMapTy*)UniquingMap; 313 } 314 315 const MCSection *TargetLoweringObjectFileELF:: 316 getELFSection(StringRef Section, unsigned Type, unsigned Flags, 317 SectionKind Kind, bool IsExplicit) const { 318 if (UniquingMap == 0) 319 UniquingMap = new ELFUniqueMapTy(); 320 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap; 321 322 // Do the lookup, if we have a hit, return it. 323 const MCSectionELF *&Entry = Map[Section]; 324 if (Entry) return Entry; 325 326 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit, 327 getContext()); 328 } 329 330 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 331 const TargetMachine &TM) { 332 if (UniquingMap != 0) 333 ((ELFUniqueMapTy*)UniquingMap)->clear(); 334 TargetLoweringObjectFile::Initialize(Ctx, TM); 335 336 BSSSection = 337 getELFSection(".bss", MCSectionELF::SHT_NOBITS, 338 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC, 339 SectionKind::getBSS()); 340 341 TextSection = 342 getELFSection(".text", MCSectionELF::SHT_PROGBITS, 343 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC, 344 SectionKind::getText()); 345 346 DataSection = 347 getELFSection(".data", MCSectionELF::SHT_PROGBITS, 348 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC, 349 SectionKind::getDataRel()); 350 351 ReadOnlySection = 352 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS, 353 MCSectionELF::SHF_ALLOC, 354 SectionKind::getReadOnly()); 355 356 TLSDataSection = 357 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS, 358 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 359 MCSectionELF::SHF_WRITE, SectionKind::getThreadData()); 360 361 TLSBSSSection = 362 getELFSection(".tbss", MCSectionELF::SHT_NOBITS, 363 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 364 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS()); 365 366 DataRelSection = 367 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS, 368 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 369 SectionKind::getDataRel()); 370 371 DataRelLocalSection = 372 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS, 373 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 374 SectionKind::getDataRelLocal()); 375 376 DataRelROSection = 377 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS, 378 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 379 SectionKind::getReadOnlyWithRel()); 380 381 DataRelROLocalSection = 382 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS, 383 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 384 SectionKind::getReadOnlyWithRelLocal()); 385 386 MergeableConst4Section = 387 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS, 388 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 389 SectionKind::getMergeableConst4()); 390 391 MergeableConst8Section = 392 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS, 393 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 394 SectionKind::getMergeableConst8()); 395 396 MergeableConst16Section = 397 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS, 398 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 399 SectionKind::getMergeableConst16()); 400 401 StaticCtorSection = 402 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS, 403 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 404 SectionKind::getDataRel()); 405 406 StaticDtorSection = 407 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS, 408 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 409 SectionKind::getDataRel()); 410 411 // Exception Handling Sections. 412 413 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though 414 // it contains relocatable pointers. In PIC mode, this is probably a big 415 // runtime hit for C++ apps. Either the contents of the LSDA need to be 416 // adjusted or this should be a data section. 417 LSDASection = 418 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS, 419 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly()); 420 EHFrameSection = 421 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS, 422 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 423 SectionKind::getDataRel()); 424 425 // Debug Info Sections. 426 DwarfAbbrevSection = 427 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0, 428 SectionKind::getMetadata()); 429 DwarfInfoSection = 430 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0, 431 SectionKind::getMetadata()); 432 DwarfLineSection = 433 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0, 434 SectionKind::getMetadata()); 435 DwarfFrameSection = 436 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0, 437 SectionKind::getMetadata()); 438 DwarfPubNamesSection = 439 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0, 440 SectionKind::getMetadata()); 441 DwarfPubTypesSection = 442 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0, 443 SectionKind::getMetadata()); 444 DwarfStrSection = 445 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0, 446 SectionKind::getMetadata()); 447 DwarfLocSection = 448 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0, 449 SectionKind::getMetadata()); 450 DwarfARangesSection = 451 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0, 452 SectionKind::getMetadata()); 453 DwarfRangesSection = 454 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0, 455 SectionKind::getMetadata()); 456 DwarfMacroInfoSection = 457 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0, 458 SectionKind::getMetadata()); 459 } 460 461 462 static SectionKind 463 getELFKindForNamedSection(const char *Name, SectionKind K) { 464 if (Name[0] != '.') return K; 465 466 // Some lame default implementation based on some magic section names. 467 if (strcmp(Name, ".bss") == 0 || 468 strncmp(Name, ".bss.", 5) == 0 || 469 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 || 470 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 || 471 strcmp(Name, ".sbss") == 0 || 472 strncmp(Name, ".sbss.", 6) == 0 || 473 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 || 474 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0) 475 return SectionKind::getBSS(); 476 477 if (strcmp(Name, ".tdata") == 0 || 478 strncmp(Name, ".tdata.", 7) == 0 || 479 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 || 480 strncmp(Name, ".llvm.linkonce.td.", 18) == 0) 481 return SectionKind::getThreadData(); 482 483 if (strcmp(Name, ".tbss") == 0 || 484 strncmp(Name, ".tbss.", 6) == 0 || 485 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 || 486 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0) 487 return SectionKind::getThreadBSS(); 488 489 return K; 490 } 491 492 493 static unsigned 494 getELFSectionType(const char *Name, SectionKind K) { 495 496 if (strcmp(Name, ".init_array") == 0) 497 return MCSectionELF::SHT_INIT_ARRAY; 498 499 if (strcmp(Name, ".fini_array") == 0) 500 return MCSectionELF::SHT_FINI_ARRAY; 501 502 if (strcmp(Name, ".preinit_array") == 0) 503 return MCSectionELF::SHT_PREINIT_ARRAY; 504 505 if (K.isBSS() || K.isThreadBSS()) 506 return MCSectionELF::SHT_NOBITS; 507 508 return MCSectionELF::SHT_PROGBITS; 509 } 510 511 512 static unsigned 513 getELFSectionFlags(SectionKind K) { 514 unsigned Flags = 0; 515 516 if (!K.isMetadata()) 517 Flags |= MCSectionELF::SHF_ALLOC; 518 519 if (K.isText()) 520 Flags |= MCSectionELF::SHF_EXECINSTR; 521 522 if (K.isWriteable()) 523 Flags |= MCSectionELF::SHF_WRITE; 524 525 if (K.isThreadLocal()) 526 Flags |= MCSectionELF::SHF_TLS; 527 528 // K.isMergeableConst() is left out to honour PR4650 529 if (K.isMergeableCString() || K.isMergeableConst4() || 530 K.isMergeableConst8() || K.isMergeableConst16()) 531 Flags |= MCSectionELF::SHF_MERGE; 532 533 if (K.isMergeableCString()) 534 Flags |= MCSectionELF::SHF_STRINGS; 535 536 return Flags; 537 } 538 539 540 const MCSection *TargetLoweringObjectFileELF:: 541 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 542 Mangler *Mang, const TargetMachine &TM) const { 543 const char *SectionName = GV->getSection().c_str(); 544 545 // Infer section flags from the section name if we can. 546 Kind = getELFKindForNamedSection(SectionName, Kind); 547 548 return getELFSection(SectionName, 549 getELFSectionType(SectionName, Kind), 550 getELFSectionFlags(Kind), Kind, true); 551 } 552 553 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) { 554 if (Kind.isText()) return ".gnu.linkonce.t."; 555 if (Kind.isReadOnly()) return ".gnu.linkonce.r."; 556 557 if (Kind.isThreadData()) return ".gnu.linkonce.td."; 558 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb."; 559 560 if (Kind.isBSS()) return ".gnu.linkonce.b."; 561 if (Kind.isDataNoRel()) return ".gnu.linkonce.d."; 562 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local."; 563 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel."; 564 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local."; 565 566 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 567 return ".gnu.linkonce.d.rel.ro."; 568 } 569 570 const MCSection *TargetLoweringObjectFileELF:: 571 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 572 Mangler *Mang, const TargetMachine &TM) const { 573 574 // If this global is linkonce/weak and the target handles this by emitting it 575 // into a 'uniqued' section name, create and return the section now. 576 if (GV->isWeakForLinker()) { 577 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind); 578 std::string Name = Mang->makeNameProper(GV->getNameStr()); 579 580 return getELFSection((Prefix+Name).c_str(), 581 getELFSectionType((Prefix+Name).c_str(), Kind), 582 getELFSectionFlags(Kind), 583 Kind); 584 } 585 586 if (Kind.isText()) return TextSection; 587 588 if (Kind.isMergeable1ByteCString() || 589 Kind.isMergeable2ByteCString() || 590 Kind.isMergeable4ByteCString()) { 591 592 // We also need alignment here. 593 // FIXME: this is getting the alignment of the character, not the 594 // alignment of the global! 595 unsigned Align = 596 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)); 597 598 const char *SizeSpec = ".rodata.str1."; 599 if (Kind.isMergeable2ByteCString()) 600 SizeSpec = ".rodata.str2."; 601 else if (Kind.isMergeable4ByteCString()) 602 SizeSpec = ".rodata.str4."; 603 else 604 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 605 606 607 std::string Name = SizeSpec + utostr(Align); 608 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS, 609 MCSectionELF::SHF_ALLOC | 610 MCSectionELF::SHF_MERGE | 611 MCSectionELF::SHF_STRINGS, 612 Kind); 613 } 614 615 if (Kind.isMergeableConst()) { 616 if (Kind.isMergeableConst4() && MergeableConst4Section) 617 return MergeableConst4Section; 618 if (Kind.isMergeableConst8() && MergeableConst8Section) 619 return MergeableConst8Section; 620 if (Kind.isMergeableConst16() && MergeableConst16Section) 621 return MergeableConst16Section; 622 return ReadOnlySection; // .const 623 } 624 625 if (Kind.isReadOnly()) return ReadOnlySection; 626 627 if (Kind.isThreadData()) return TLSDataSection; 628 if (Kind.isThreadBSS()) return TLSBSSSection; 629 630 if (Kind.isBSS()) return BSSSection; 631 632 if (Kind.isDataNoRel()) return DataSection; 633 if (Kind.isDataRelLocal()) return DataRelLocalSection; 634 if (Kind.isDataRel()) return DataRelSection; 635 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 636 637 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 638 return DataRelROSection; 639 } 640 641 /// getSectionForConstant - Given a mergeable constant with the 642 /// specified size and relocation information, return a section that it 643 /// should be placed in. 644 const MCSection *TargetLoweringObjectFileELF:: 645 getSectionForConstant(SectionKind Kind) const { 646 if (Kind.isMergeableConst4() && MergeableConst4Section) 647 return MergeableConst4Section; 648 if (Kind.isMergeableConst8() && MergeableConst8Section) 649 return MergeableConst8Section; 650 if (Kind.isMergeableConst16() && MergeableConst16Section) 651 return MergeableConst16Section; 652 if (Kind.isReadOnly()) 653 return ReadOnlySection; 654 655 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 656 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 657 return DataRelROSection; 658 } 659 660 //===----------------------------------------------------------------------===// 661 // MachO 662 //===----------------------------------------------------------------------===// 663 664 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy; 665 666 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() { 667 // If we have the MachO uniquing map, free it. 668 delete (MachOUniqueMapTy*)UniquingMap; 669 } 670 671 672 const MCSectionMachO *TargetLoweringObjectFileMachO:: 673 getMachOSection(const StringRef &Segment, const StringRef &Section, 674 unsigned TypeAndAttributes, 675 unsigned Reserved2, SectionKind Kind) const { 676 // We unique sections by their segment/section pair. The returned section 677 // may not have the same flags as the requested section, if so this should be 678 // diagnosed by the client as an error. 679 680 // Create the map if it doesn't already exist. 681 if (UniquingMap == 0) 682 UniquingMap = new MachOUniqueMapTy(); 683 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap; 684 685 // Form the name to look up. 686 SmallString<64> Name; 687 Name += Segment; 688 Name.push_back(','); 689 Name += Section; 690 691 // Do the lookup, if we have a hit, return it. 692 const MCSectionMachO *&Entry = Map[Name.str()]; 693 if (Entry) return Entry; 694 695 // Otherwise, return a new section. 696 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes, 697 Reserved2, Kind, getContext()); 698 } 699 700 701 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 702 const TargetMachine &TM) { 703 if (UniquingMap != 0) 704 ((MachOUniqueMapTy*)UniquingMap)->clear(); 705 TargetLoweringObjectFile::Initialize(Ctx, TM); 706 707 TextSection // .text 708 = getMachOSection("__TEXT", "__text", 709 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 710 SectionKind::getText()); 711 DataSection // .data 712 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel()); 713 714 CStringSection // .cstring 715 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS, 716 SectionKind::getMergeable1ByteCString()); 717 UStringSection 718 = getMachOSection("__TEXT","__ustring", 0, 719 SectionKind::getMergeable2ByteCString()); 720 FourByteConstantSection // .literal4 721 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS, 722 SectionKind::getMergeableConst4()); 723 EightByteConstantSection // .literal8 724 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS, 725 SectionKind::getMergeableConst8()); 726 727 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back 728 // to using it in -static mode. 729 SixteenByteConstantSection = 0; 730 if (TM.getRelocationModel() != Reloc::Static && 731 TM.getTargetData()->getPointerSize() == 32) 732 SixteenByteConstantSection = // .literal16 733 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS, 734 SectionKind::getMergeableConst16()); 735 736 ReadOnlySection // .const 737 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly()); 738 739 TextCoalSection 740 = getMachOSection("__TEXT", "__textcoal_nt", 741 MCSectionMachO::S_COALESCED | 742 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 743 SectionKind::getText()); 744 ConstTextCoalSection 745 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED, 746 SectionKind::getText()); 747 ConstDataCoalSection 748 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED, 749 SectionKind::getText()); 750 ConstDataSection // .const_data 751 = getMachOSection("__DATA", "__const", 0, 752 SectionKind::getReadOnlyWithRel()); 753 DataCoalSection 754 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED, 755 SectionKind::getDataRel()); 756 757 758 LazySymbolPointerSection 759 = getMachOSection("__DATA", "__la_symbol_ptr", 760 MCSectionMachO::S_LAZY_SYMBOL_POINTERS, 761 SectionKind::getMetadata()); 762 NonLazySymbolPointerSection 763 = getMachOSection("__DATA", "__nl_symbol_ptr", 764 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS, 765 SectionKind::getMetadata()); 766 767 if (TM.getRelocationModel() == Reloc::Static) { 768 StaticCtorSection 769 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel()); 770 StaticDtorSection 771 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel()); 772 } else { 773 StaticCtorSection 774 = getMachOSection("__DATA", "__mod_init_func", 775 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS, 776 SectionKind::getDataRel()); 777 StaticDtorSection 778 = getMachOSection("__DATA", "__mod_term_func", 779 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS, 780 SectionKind::getDataRel()); 781 } 782 783 // Exception Handling. 784 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0, 785 SectionKind::getDataRel()); 786 EHFrameSection = 787 getMachOSection("__TEXT", "__eh_frame", 788 MCSectionMachO::S_COALESCED | 789 MCSectionMachO::S_ATTR_NO_TOC | 790 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS | 791 MCSectionMachO::S_ATTR_LIVE_SUPPORT, 792 SectionKind::getReadOnly()); 793 794 // Debug Information. 795 DwarfAbbrevSection = 796 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG, 797 SectionKind::getMetadata()); 798 DwarfInfoSection = 799 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG, 800 SectionKind::getMetadata()); 801 DwarfLineSection = 802 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG, 803 SectionKind::getMetadata()); 804 DwarfFrameSection = 805 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG, 806 SectionKind::getMetadata()); 807 DwarfPubNamesSection = 808 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG, 809 SectionKind::getMetadata()); 810 DwarfPubTypesSection = 811 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG, 812 SectionKind::getMetadata()); 813 DwarfStrSection = 814 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG, 815 SectionKind::getMetadata()); 816 DwarfLocSection = 817 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG, 818 SectionKind::getMetadata()); 819 DwarfARangesSection = 820 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG, 821 SectionKind::getMetadata()); 822 DwarfRangesSection = 823 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG, 824 SectionKind::getMetadata()); 825 DwarfMacroInfoSection = 826 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG, 827 SectionKind::getMetadata()); 828 DwarfDebugInlineSection = 829 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG, 830 SectionKind::getMetadata()); 831 } 832 833 const MCSection *TargetLoweringObjectFileMachO:: 834 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 835 Mangler *Mang, const TargetMachine &TM) const { 836 // Parse the section specifier and create it if valid. 837 StringRef Segment, Section; 838 unsigned TAA, StubSize; 839 std::string ErrorCode = 840 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 841 TAA, StubSize); 842 if (!ErrorCode.empty()) { 843 // If invalid, report the error with llvm_report_error. 844 llvm_report_error("Global variable '" + GV->getNameStr() + 845 "' has an invalid section specifier '" + GV->getSection()+ 846 "': " + ErrorCode + "."); 847 // Fall back to dropping it into the data section. 848 return DataSection; 849 } 850 851 // Get the section. 852 const MCSectionMachO *S = 853 getMachOSection(Segment, Section, TAA, StubSize, Kind); 854 855 // Okay, now that we got the section, verify that the TAA & StubSize agree. 856 // If the user declared multiple globals with different section flags, we need 857 // to reject it here. 858 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 859 // If invalid, report the error with llvm_report_error. 860 llvm_report_error("Global variable '" + GV->getNameStr() + 861 "' section type or attributes does not match previous" 862 " section specifier"); 863 } 864 865 return S; 866 } 867 868 const MCSection *TargetLoweringObjectFileMachO:: 869 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 870 Mangler *Mang, const TargetMachine &TM) const { 871 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS"); 872 873 if (Kind.isText()) 874 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 875 876 // If this is weak/linkonce, put this in a coalescable section, either in text 877 // or data depending on if it is writable. 878 if (GV->isWeakForLinker()) { 879 if (Kind.isReadOnly()) 880 return ConstTextCoalSection; 881 return DataCoalSection; 882 } 883 884 // FIXME: Alignment check should be handled by section classifier. 885 if (Kind.isMergeable1ByteCString() || 886 Kind.isMergeable2ByteCString()) { 887 if (TM.getTargetData()->getPreferredAlignment( 888 cast<GlobalVariable>(GV)) < 32) { 889 if (Kind.isMergeable1ByteCString()) 890 return CStringSection; 891 assert(Kind.isMergeable2ByteCString()); 892 return UStringSection; 893 } 894 } 895 896 if (Kind.isMergeableConst()) { 897 if (Kind.isMergeableConst4()) 898 return FourByteConstantSection; 899 if (Kind.isMergeableConst8()) 900 return EightByteConstantSection; 901 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 902 return SixteenByteConstantSection; 903 } 904 905 // Otherwise, if it is readonly, but not something we can specially optimize, 906 // just drop it in .const. 907 if (Kind.isReadOnly()) 908 return ReadOnlySection; 909 910 // If this is marked const, put it into a const section. But if the dynamic 911 // linker needs to write to it, put it in the data segment. 912 if (Kind.isReadOnlyWithRel()) 913 return ConstDataSection; 914 915 // Otherwise, just drop the variable in the normal data section. 916 return DataSection; 917 } 918 919 const MCSection * 920 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const { 921 // If this constant requires a relocation, we have to put it in the data 922 // segment, not in the text segment. 923 if (Kind.isDataRel()) 924 return ConstDataSection; 925 926 if (Kind.isMergeableConst4()) 927 return FourByteConstantSection; 928 if (Kind.isMergeableConst8()) 929 return EightByteConstantSection; 930 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 931 return SixteenByteConstantSection; 932 return ReadOnlySection; // .const 933 } 934 935 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide 936 /// not to emit the UsedDirective for some symbols in llvm.used. 937 // FIXME: REMOVE this (rdar://7071300) 938 bool TargetLoweringObjectFileMachO:: 939 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const { 940 /// On Darwin, internally linked data beginning with "L" or "l" does not have 941 /// the directive emitted (this occurs in ObjC metadata). 942 if (!GV) return false; 943 944 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix. 945 if (GV->hasLocalLinkage() && !isa<Function>(GV)) { 946 // FIXME: ObjC metadata is currently emitted as internal symbols that have 947 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and 948 // this horrible hack can go away. 949 const std::string &Name = Mang->getMangledName(GV); 950 if (Name[0] == 'L' || Name[0] == 'l') 951 return false; 952 } 953 954 return true; 955 } 956 957 const MCExpr *TargetLoweringObjectFileMachO:: 958 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang, 959 bool &IsIndirect, bool &IsPCRel) const { 960 // The mach-o version of this method defaults to returning a stub reference. 961 IsIndirect = true; 962 IsPCRel = false; 963 964 SmallString<128> Name; 965 Mang->getNameWithPrefix(Name, GV, true); 966 Name += "$non_lazy_ptr"; 967 return MCSymbolRefExpr::Create(Name.str(), getContext()); 968 } 969 970 971 //===----------------------------------------------------------------------===// 972 // COFF 973 //===----------------------------------------------------------------------===// 974 975 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy; 976 977 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() { 978 delete (COFFUniqueMapTy*)UniquingMap; 979 } 980 981 982 const MCSection *TargetLoweringObjectFileCOFF:: 983 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const { 984 // Create the map if it doesn't already exist. 985 if (UniquingMap == 0) 986 UniquingMap = new MachOUniqueMapTy(); 987 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap; 988 989 // Do the lookup, if we have a hit, return it. 990 const MCSectionCOFF *&Entry = Map[Name]; 991 if (Entry) return Entry; 992 993 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext()); 994 } 995 996 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 997 const TargetMachine &TM) { 998 if (UniquingMap != 0) 999 ((COFFUniqueMapTy*)UniquingMap)->clear(); 1000 TargetLoweringObjectFile::Initialize(Ctx, TM); 1001 TextSection = getCOFFSection("\t.text", true, SectionKind::getText()); 1002 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel()); 1003 StaticCtorSection = 1004 getCOFFSection(".ctors", false, SectionKind::getDataRel()); 1005 StaticDtorSection = 1006 getCOFFSection(".dtors", false, SectionKind::getDataRel()); 1007 1008 // FIXME: We're emitting LSDA info into a readonly section on COFF, even 1009 // though it contains relocatable pointers. In PIC mode, this is probably a 1010 // big runtime hit for C++ apps. Either the contents of the LSDA need to be 1011 // adjusted or this should be a data section. 1012 LSDASection = 1013 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly()); 1014 EHFrameSection = 1015 getCOFFSection(".eh_frame", false, SectionKind::getDataRel()); 1016 1017 // Debug info. 1018 // FIXME: Don't use 'directive' mode here. 1019 DwarfAbbrevSection = 1020 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"", 1021 true, SectionKind::getMetadata()); 1022 DwarfInfoSection = 1023 getCOFFSection("\t.section\t.debug_info,\"dr\"", 1024 true, SectionKind::getMetadata()); 1025 DwarfLineSection = 1026 getCOFFSection("\t.section\t.debug_line,\"dr\"", 1027 true, SectionKind::getMetadata()); 1028 DwarfFrameSection = 1029 getCOFFSection("\t.section\t.debug_frame,\"dr\"", 1030 true, SectionKind::getMetadata()); 1031 DwarfPubNamesSection = 1032 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"", 1033 true, SectionKind::getMetadata()); 1034 DwarfPubTypesSection = 1035 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"", 1036 true, SectionKind::getMetadata()); 1037 DwarfStrSection = 1038 getCOFFSection("\t.section\t.debug_str,\"dr\"", 1039 true, SectionKind::getMetadata()); 1040 DwarfLocSection = 1041 getCOFFSection("\t.section\t.debug_loc,\"dr\"", 1042 true, SectionKind::getMetadata()); 1043 DwarfARangesSection = 1044 getCOFFSection("\t.section\t.debug_aranges,\"dr\"", 1045 true, SectionKind::getMetadata()); 1046 DwarfRangesSection = 1047 getCOFFSection("\t.section\t.debug_ranges,\"dr\"", 1048 true, SectionKind::getMetadata()); 1049 DwarfMacroInfoSection = 1050 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"", 1051 true, SectionKind::getMetadata()); 1052 } 1053 1054 const MCSection *TargetLoweringObjectFileCOFF:: 1055 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 1056 Mangler *Mang, const TargetMachine &TM) const { 1057 return getCOFFSection(GV->getSection().c_str(), false, Kind); 1058 } 1059 1060 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) { 1061 if (Kind.isText()) 1062 return ".text$linkonce"; 1063 if (Kind.isWriteable()) 1064 return ".data$linkonce"; 1065 return ".rdata$linkonce"; 1066 } 1067 1068 1069 const MCSection *TargetLoweringObjectFileCOFF:: 1070 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 1071 Mangler *Mang, const TargetMachine &TM) const { 1072 assert(!Kind.isThreadLocal() && "Doesn't support TLS"); 1073 1074 // If this global is linkonce/weak and the target handles this by emitting it 1075 // into a 'uniqued' section name, create and return the section now. 1076 if (GV->isWeakForLinker()) { 1077 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind); 1078 std::string Name = Mang->makeNameProper(GV->getNameStr()); 1079 return getCOFFSection((Prefix+Name).c_str(), false, Kind); 1080 } 1081 1082 if (Kind.isText()) 1083 return getTextSection(); 1084 1085 return getDataSection(); 1086 } 1087 1088