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