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