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/Mangler.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Target/TargetMachine.h" 28 #include "llvm/Target/TargetOptions.h" 29 #include "llvm/Support/ErrorHandling.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 // FIXME: Use GetGlobalValueSymbol. 304 SmallString<128> Name; 305 Mang->getNameWithPrefix(Name, GV, false); 306 return MCSymbolRefExpr::Create(Name.str(), getContext()); 307 } 308 309 310 //===----------------------------------------------------------------------===// 311 // ELF 312 //===----------------------------------------------------------------------===// 313 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy; 314 315 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() { 316 // If we have the section uniquing map, free it. 317 delete (ELFUniqueMapTy*)UniquingMap; 318 } 319 320 const MCSection *TargetLoweringObjectFileELF:: 321 getELFSection(StringRef Section, unsigned Type, unsigned Flags, 322 SectionKind Kind, bool IsExplicit) const { 323 if (UniquingMap == 0) 324 UniquingMap = new ELFUniqueMapTy(); 325 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap; 326 327 // Do the lookup, if we have a hit, return it. 328 const MCSectionELF *&Entry = Map[Section]; 329 if (Entry) return Entry; 330 331 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit, 332 getContext()); 333 } 334 335 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 336 const TargetMachine &TM) { 337 if (UniquingMap != 0) 338 ((ELFUniqueMapTy*)UniquingMap)->clear(); 339 TargetLoweringObjectFile::Initialize(Ctx, TM); 340 341 BSSSection = 342 getELFSection(".bss", MCSectionELF::SHT_NOBITS, 343 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC, 344 SectionKind::getBSS()); 345 346 TextSection = 347 getELFSection(".text", MCSectionELF::SHT_PROGBITS, 348 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC, 349 SectionKind::getText()); 350 351 DataSection = 352 getELFSection(".data", MCSectionELF::SHT_PROGBITS, 353 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC, 354 SectionKind::getDataRel()); 355 356 ReadOnlySection = 357 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS, 358 MCSectionELF::SHF_ALLOC, 359 SectionKind::getReadOnly()); 360 361 TLSDataSection = 362 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS, 363 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 364 MCSectionELF::SHF_WRITE, SectionKind::getThreadData()); 365 366 TLSBSSSection = 367 getELFSection(".tbss", MCSectionELF::SHT_NOBITS, 368 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 369 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS()); 370 371 DataRelSection = 372 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS, 373 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 374 SectionKind::getDataRel()); 375 376 DataRelLocalSection = 377 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS, 378 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 379 SectionKind::getDataRelLocal()); 380 381 DataRelROSection = 382 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS, 383 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 384 SectionKind::getReadOnlyWithRel()); 385 386 DataRelROLocalSection = 387 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS, 388 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 389 SectionKind::getReadOnlyWithRelLocal()); 390 391 MergeableConst4Section = 392 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS, 393 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 394 SectionKind::getMergeableConst4()); 395 396 MergeableConst8Section = 397 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS, 398 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 399 SectionKind::getMergeableConst8()); 400 401 MergeableConst16Section = 402 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS, 403 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 404 SectionKind::getMergeableConst16()); 405 406 StaticCtorSection = 407 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS, 408 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 409 SectionKind::getDataRel()); 410 411 StaticDtorSection = 412 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS, 413 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 414 SectionKind::getDataRel()); 415 416 // Exception Handling Sections. 417 418 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though 419 // it contains relocatable pointers. In PIC mode, this is probably a big 420 // runtime hit for C++ apps. Either the contents of the LSDA need to be 421 // adjusted or this should be a data section. 422 LSDASection = 423 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS, 424 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly()); 425 EHFrameSection = 426 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS, 427 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 428 SectionKind::getDataRel()); 429 430 // Debug Info Sections. 431 DwarfAbbrevSection = 432 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0, 433 SectionKind::getMetadata()); 434 DwarfInfoSection = 435 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0, 436 SectionKind::getMetadata()); 437 DwarfLineSection = 438 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0, 439 SectionKind::getMetadata()); 440 DwarfFrameSection = 441 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0, 442 SectionKind::getMetadata()); 443 DwarfPubNamesSection = 444 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0, 445 SectionKind::getMetadata()); 446 DwarfPubTypesSection = 447 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0, 448 SectionKind::getMetadata()); 449 DwarfStrSection = 450 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0, 451 SectionKind::getMetadata()); 452 DwarfLocSection = 453 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0, 454 SectionKind::getMetadata()); 455 DwarfARangesSection = 456 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0, 457 SectionKind::getMetadata()); 458 DwarfRangesSection = 459 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0, 460 SectionKind::getMetadata()); 461 DwarfMacroInfoSection = 462 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0, 463 SectionKind::getMetadata()); 464 } 465 466 467 static SectionKind 468 getELFKindForNamedSection(const char *Name, SectionKind K) { 469 if (Name[0] != '.') return K; 470 471 // Some lame default implementation based on some magic section names. 472 if (strcmp(Name, ".bss") == 0 || 473 strncmp(Name, ".bss.", 5) == 0 || 474 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 || 475 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 || 476 strcmp(Name, ".sbss") == 0 || 477 strncmp(Name, ".sbss.", 6) == 0 || 478 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 || 479 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0) 480 return SectionKind::getBSS(); 481 482 if (strcmp(Name, ".tdata") == 0 || 483 strncmp(Name, ".tdata.", 7) == 0 || 484 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 || 485 strncmp(Name, ".llvm.linkonce.td.", 18) == 0) 486 return SectionKind::getThreadData(); 487 488 if (strcmp(Name, ".tbss") == 0 || 489 strncmp(Name, ".tbss.", 6) == 0 || 490 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 || 491 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0) 492 return SectionKind::getThreadBSS(); 493 494 return K; 495 } 496 497 498 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 499 500 if (Name == ".init_array") 501 return MCSectionELF::SHT_INIT_ARRAY; 502 503 if (Name == ".fini_array") 504 return MCSectionELF::SHT_FINI_ARRAY; 505 506 if (Name == ".preinit_array") 507 return MCSectionELF::SHT_PREINIT_ARRAY; 508 509 if (K.isBSS() || K.isThreadBSS()) 510 return MCSectionELF::SHT_NOBITS; 511 512 return MCSectionELF::SHT_PROGBITS; 513 } 514 515 516 static unsigned 517 getELFSectionFlags(SectionKind K) { 518 unsigned Flags = 0; 519 520 if (!K.isMetadata()) 521 Flags |= MCSectionELF::SHF_ALLOC; 522 523 if (K.isText()) 524 Flags |= MCSectionELF::SHF_EXECINSTR; 525 526 if (K.isWriteable()) 527 Flags |= MCSectionELF::SHF_WRITE; 528 529 if (K.isThreadLocal()) 530 Flags |= MCSectionELF::SHF_TLS; 531 532 // K.isMergeableConst() is left out to honour PR4650 533 if (K.isMergeableCString() || K.isMergeableConst4() || 534 K.isMergeableConst8() || K.isMergeableConst16()) 535 Flags |= MCSectionELF::SHF_MERGE; 536 537 if (K.isMergeableCString()) 538 Flags |= MCSectionELF::SHF_STRINGS; 539 540 return Flags; 541 } 542 543 544 const MCSection *TargetLoweringObjectFileELF:: 545 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 546 Mangler *Mang, const TargetMachine &TM) const { 547 const char *SectionName = GV->getSection().c_str(); 548 549 // Infer section flags from the section name if we can. 550 Kind = getELFKindForNamedSection(SectionName, Kind); 551 552 return getELFSection(SectionName, 553 getELFSectionType(SectionName, Kind), 554 getELFSectionFlags(Kind), Kind, true); 555 } 556 557 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) { 558 if (Kind.isText()) return ".gnu.linkonce.t."; 559 if (Kind.isReadOnly()) return ".gnu.linkonce.r."; 560 561 if (Kind.isThreadData()) return ".gnu.linkonce.td."; 562 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb."; 563 564 if (Kind.isBSS()) return ".gnu.linkonce.b."; 565 if (Kind.isDataNoRel()) return ".gnu.linkonce.d."; 566 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local."; 567 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel."; 568 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local."; 569 570 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 571 return ".gnu.linkonce.d.rel.ro."; 572 } 573 574 const MCSection *TargetLoweringObjectFileELF:: 575 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 576 Mangler *Mang, const TargetMachine &TM) const { 577 578 // If this global is linkonce/weak and the target handles this by emitting it 579 // into a 'uniqued' section name, create and return the section now. 580 if (GV->isWeakForLinker()) { 581 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind); 582 SmallString<128> Name, MangledName; 583 Name.append(Prefix, Prefix+strlen(Prefix)); 584 Mang->getNameWithPrefix(Name, GV, false); 585 586 raw_svector_ostream OS(MangledName); 587 MCSymbol::printMangledName(Name, OS, 0); 588 OS.flush(); 589 590 return getELFSection(MangledName.str(), 591 getELFSectionType(MangledName.str(), Kind), 592 getELFSectionFlags(Kind), 593 Kind); 594 } 595 596 if (Kind.isText()) return TextSection; 597 598 if (Kind.isMergeable1ByteCString() || 599 Kind.isMergeable2ByteCString() || 600 Kind.isMergeable4ByteCString()) { 601 602 // We also need alignment here. 603 // FIXME: this is getting the alignment of the character, not the 604 // alignment of the global! 605 unsigned Align = 606 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)); 607 608 const char *SizeSpec = ".rodata.str1."; 609 if (Kind.isMergeable2ByteCString()) 610 SizeSpec = ".rodata.str2."; 611 else if (Kind.isMergeable4ByteCString()) 612 SizeSpec = ".rodata.str4."; 613 else 614 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 615 616 617 std::string Name = SizeSpec + utostr(Align); 618 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS, 619 MCSectionELF::SHF_ALLOC | 620 MCSectionELF::SHF_MERGE | 621 MCSectionELF::SHF_STRINGS, 622 Kind); 623 } 624 625 if (Kind.isMergeableConst()) { 626 if (Kind.isMergeableConst4() && MergeableConst4Section) 627 return MergeableConst4Section; 628 if (Kind.isMergeableConst8() && MergeableConst8Section) 629 return MergeableConst8Section; 630 if (Kind.isMergeableConst16() && MergeableConst16Section) 631 return MergeableConst16Section; 632 return ReadOnlySection; // .const 633 } 634 635 if (Kind.isReadOnly()) return ReadOnlySection; 636 637 if (Kind.isThreadData()) return TLSDataSection; 638 if (Kind.isThreadBSS()) return TLSBSSSection; 639 640 if (Kind.isBSS()) return BSSSection; 641 642 if (Kind.isDataNoRel()) return DataSection; 643 if (Kind.isDataRelLocal()) return DataRelLocalSection; 644 if (Kind.isDataRel()) return DataRelSection; 645 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 646 647 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 648 return DataRelROSection; 649 } 650 651 /// getSectionForConstant - Given a mergeable constant with the 652 /// specified size and relocation information, return a section that it 653 /// should be placed in. 654 const MCSection *TargetLoweringObjectFileELF:: 655 getSectionForConstant(SectionKind Kind) const { 656 if (Kind.isMergeableConst4() && MergeableConst4Section) 657 return MergeableConst4Section; 658 if (Kind.isMergeableConst8() && MergeableConst8Section) 659 return MergeableConst8Section; 660 if (Kind.isMergeableConst16() && MergeableConst16Section) 661 return MergeableConst16Section; 662 if (Kind.isReadOnly()) 663 return ReadOnlySection; 664 665 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 666 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 667 return DataRelROSection; 668 } 669 670 //===----------------------------------------------------------------------===// 671 // MachO 672 //===----------------------------------------------------------------------===// 673 674 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy; 675 676 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() { 677 // If we have the MachO uniquing map, free it. 678 delete (MachOUniqueMapTy*)UniquingMap; 679 } 680 681 682 const MCSectionMachO *TargetLoweringObjectFileMachO:: 683 getMachOSection(StringRef Segment, StringRef Section, 684 unsigned TypeAndAttributes, 685 unsigned Reserved2, SectionKind Kind) const { 686 // We unique sections by their segment/section pair. The returned section 687 // may not have the same flags as the requested section, if so this should be 688 // diagnosed by the client as an error. 689 690 // Create the map if it doesn't already exist. 691 if (UniquingMap == 0) 692 UniquingMap = new MachOUniqueMapTy(); 693 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap; 694 695 // Form the name to look up. 696 SmallString<64> Name; 697 Name += Segment; 698 Name.push_back(','); 699 Name += Section; 700 701 // Do the lookup, if we have a hit, return it. 702 const MCSectionMachO *&Entry = Map[Name.str()]; 703 if (Entry) return Entry; 704 705 // Otherwise, return a new section. 706 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes, 707 Reserved2, Kind, getContext()); 708 } 709 710 711 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 712 const TargetMachine &TM) { 713 if (UniquingMap != 0) 714 ((MachOUniqueMapTy*)UniquingMap)->clear(); 715 TargetLoweringObjectFile::Initialize(Ctx, TM); 716 717 TextSection // .text 718 = getMachOSection("__TEXT", "__text", 719 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 720 SectionKind::getText()); 721 DataSection // .data 722 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel()); 723 724 CStringSection // .cstring 725 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS, 726 SectionKind::getMergeable1ByteCString()); 727 UStringSection 728 = getMachOSection("__TEXT","__ustring", 0, 729 SectionKind::getMergeable2ByteCString()); 730 FourByteConstantSection // .literal4 731 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS, 732 SectionKind::getMergeableConst4()); 733 EightByteConstantSection // .literal8 734 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS, 735 SectionKind::getMergeableConst8()); 736 737 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back 738 // to using it in -static mode. 739 SixteenByteConstantSection = 0; 740 if (TM.getRelocationModel() != Reloc::Static && 741 TM.getTargetData()->getPointerSize() == 32) 742 SixteenByteConstantSection = // .literal16 743 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS, 744 SectionKind::getMergeableConst16()); 745 746 ReadOnlySection // .const 747 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly()); 748 749 TextCoalSection 750 = getMachOSection("__TEXT", "__textcoal_nt", 751 MCSectionMachO::S_COALESCED | 752 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 753 SectionKind::getText()); 754 ConstTextCoalSection 755 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED, 756 SectionKind::getText()); 757 ConstDataCoalSection 758 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED, 759 SectionKind::getText()); 760 ConstDataSection // .const_data 761 = getMachOSection("__DATA", "__const", 0, 762 SectionKind::getReadOnlyWithRel()); 763 DataCoalSection 764 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED, 765 SectionKind::getDataRel()); 766 767 768 LazySymbolPointerSection 769 = getMachOSection("__DATA", "__la_symbol_ptr", 770 MCSectionMachO::S_LAZY_SYMBOL_POINTERS, 771 SectionKind::getMetadata()); 772 NonLazySymbolPointerSection 773 = getMachOSection("__DATA", "__nl_symbol_ptr", 774 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS, 775 SectionKind::getMetadata()); 776 777 if (TM.getRelocationModel() == Reloc::Static) { 778 StaticCtorSection 779 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel()); 780 StaticDtorSection 781 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel()); 782 } else { 783 StaticCtorSection 784 = getMachOSection("__DATA", "__mod_init_func", 785 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS, 786 SectionKind::getDataRel()); 787 StaticDtorSection 788 = getMachOSection("__DATA", "__mod_term_func", 789 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS, 790 SectionKind::getDataRel()); 791 } 792 793 // Exception Handling. 794 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0, 795 SectionKind::getDataRel()); 796 EHFrameSection = 797 getMachOSection("__TEXT", "__eh_frame", 798 MCSectionMachO::S_COALESCED | 799 MCSectionMachO::S_ATTR_NO_TOC | 800 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS | 801 MCSectionMachO::S_ATTR_LIVE_SUPPORT, 802 SectionKind::getReadOnly()); 803 804 // Debug Information. 805 DwarfAbbrevSection = 806 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG, 807 SectionKind::getMetadata()); 808 DwarfInfoSection = 809 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG, 810 SectionKind::getMetadata()); 811 DwarfLineSection = 812 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG, 813 SectionKind::getMetadata()); 814 DwarfFrameSection = 815 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG, 816 SectionKind::getMetadata()); 817 DwarfPubNamesSection = 818 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG, 819 SectionKind::getMetadata()); 820 DwarfPubTypesSection = 821 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG, 822 SectionKind::getMetadata()); 823 DwarfStrSection = 824 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG, 825 SectionKind::getMetadata()); 826 DwarfLocSection = 827 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG, 828 SectionKind::getMetadata()); 829 DwarfARangesSection = 830 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG, 831 SectionKind::getMetadata()); 832 DwarfRangesSection = 833 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG, 834 SectionKind::getMetadata()); 835 DwarfMacroInfoSection = 836 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG, 837 SectionKind::getMetadata()); 838 DwarfDebugInlineSection = 839 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG, 840 SectionKind::getMetadata()); 841 } 842 843 const MCSection *TargetLoweringObjectFileMachO:: 844 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 845 Mangler *Mang, const TargetMachine &TM) const { 846 // Parse the section specifier and create it if valid. 847 StringRef Segment, Section; 848 unsigned TAA, StubSize; 849 std::string ErrorCode = 850 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 851 TAA, StubSize); 852 if (!ErrorCode.empty()) { 853 // If invalid, report the error with llvm_report_error. 854 llvm_report_error("Global variable '" + GV->getNameStr() + 855 "' has an invalid section specifier '" + GV->getSection()+ 856 "': " + ErrorCode + "."); 857 // Fall back to dropping it into the data section. 858 return DataSection; 859 } 860 861 // Get the section. 862 const MCSectionMachO *S = 863 getMachOSection(Segment, Section, TAA, StubSize, Kind); 864 865 // Okay, now that we got the section, verify that the TAA & StubSize agree. 866 // If the user declared multiple globals with different section flags, we need 867 // to reject it here. 868 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 869 // If invalid, report the error with llvm_report_error. 870 llvm_report_error("Global variable '" + GV->getNameStr() + 871 "' section type or attributes does not match previous" 872 " section specifier"); 873 } 874 875 return S; 876 } 877 878 const MCSection *TargetLoweringObjectFileMachO:: 879 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 880 Mangler *Mang, const TargetMachine &TM) const { 881 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS"); 882 883 if (Kind.isText()) 884 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 885 886 // If this is weak/linkonce, put this in a coalescable section, either in text 887 // or data depending on if it is writable. 888 if (GV->isWeakForLinker()) { 889 if (Kind.isReadOnly()) 890 return ConstTextCoalSection; 891 return DataCoalSection; 892 } 893 894 // FIXME: Alignment check should be handled by section classifier. 895 if (Kind.isMergeable1ByteCString() || 896 Kind.isMergeable2ByteCString()) { 897 if (TM.getTargetData()->getPreferredAlignment( 898 cast<GlobalVariable>(GV)) < 32) { 899 if (Kind.isMergeable1ByteCString()) 900 return CStringSection; 901 assert(Kind.isMergeable2ByteCString()); 902 return UStringSection; 903 } 904 } 905 906 if (Kind.isMergeableConst()) { 907 if (Kind.isMergeableConst4()) 908 return FourByteConstantSection; 909 if (Kind.isMergeableConst8()) 910 return EightByteConstantSection; 911 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 912 return SixteenByteConstantSection; 913 } 914 915 // Otherwise, if it is readonly, but not something we can specially optimize, 916 // just drop it in .const. 917 if (Kind.isReadOnly()) 918 return ReadOnlySection; 919 920 // If this is marked const, put it into a const section. But if the dynamic 921 // linker needs to write to it, put it in the data segment. 922 if (Kind.isReadOnlyWithRel()) 923 return ConstDataSection; 924 925 // Otherwise, just drop the variable in the normal data section. 926 return DataSection; 927 } 928 929 const MCSection * 930 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const { 931 // If this constant requires a relocation, we have to put it in the data 932 // segment, not in the text segment. 933 if (Kind.isDataRel() || Kind.isReadOnlyWithRel()) 934 return ConstDataSection; 935 936 if (Kind.isMergeableConst4()) 937 return FourByteConstantSection; 938 if (Kind.isMergeableConst8()) 939 return EightByteConstantSection; 940 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 941 return SixteenByteConstantSection; 942 return ReadOnlySection; // .const 943 } 944 945 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide 946 /// not to emit the UsedDirective for some symbols in llvm.used. 947 // FIXME: REMOVE this (rdar://7071300) 948 bool TargetLoweringObjectFileMachO:: 949 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const { 950 /// On Darwin, internally linked data beginning with "L" or "l" does not have 951 /// the directive emitted (this occurs in ObjC metadata). 952 if (!GV) return false; 953 954 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix. 955 if (GV->hasLocalLinkage() && !isa<Function>(GV)) { 956 // FIXME: ObjC metadata is currently emitted as internal symbols that have 957 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and 958 // this horrible hack can go away. 959 SmallString<64> Name; 960 Mang->getNameWithPrefix(Name, GV, false); 961 if (Name[0] == 'L' || Name[0] == 'l') 962 return false; 963 } 964 965 return true; 966 } 967 968 const MCExpr *TargetLoweringObjectFileMachO:: 969 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang, 970 MachineModuleInfo *MMI, 971 bool &IsIndirect, bool &IsPCRel) const { 972 // The mach-o version of this method defaults to returning a stub reference. 973 IsIndirect = true; 974 IsPCRel = false; 975 976 SmallString<128> Name; 977 Mang->getNameWithPrefix(Name, GV, true); 978 Name += "$non_lazy_ptr"; 979 return MCSymbolRefExpr::Create(Name.str(), getContext()); 980 } 981 982 983 //===----------------------------------------------------------------------===// 984 // COFF 985 //===----------------------------------------------------------------------===// 986 987 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy; 988 989 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() { 990 delete (COFFUniqueMapTy*)UniquingMap; 991 } 992 993 994 const MCSection *TargetLoweringObjectFileCOFF:: 995 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const { 996 // Create the map if it doesn't already exist. 997 if (UniquingMap == 0) 998 UniquingMap = new MachOUniqueMapTy(); 999 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap; 1000 1001 // Do the lookup, if we have a hit, return it. 1002 const MCSectionCOFF *&Entry = Map[Name]; 1003 if (Entry) return Entry; 1004 1005 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext()); 1006 } 1007 1008 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1009 const TargetMachine &TM) { 1010 if (UniquingMap != 0) 1011 ((COFFUniqueMapTy*)UniquingMap)->clear(); 1012 TargetLoweringObjectFile::Initialize(Ctx, TM); 1013 TextSection = getCOFFSection("\t.text", true, SectionKind::getText()); 1014 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel()); 1015 StaticCtorSection = 1016 getCOFFSection(".ctors", false, SectionKind::getDataRel()); 1017 StaticDtorSection = 1018 getCOFFSection(".dtors", false, SectionKind::getDataRel()); 1019 1020 // FIXME: We're emitting LSDA info into a readonly section on COFF, even 1021 // though it contains relocatable pointers. In PIC mode, this is probably a 1022 // big runtime hit for C++ apps. Either the contents of the LSDA need to be 1023 // adjusted or this should be a data section. 1024 LSDASection = 1025 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly()); 1026 EHFrameSection = 1027 getCOFFSection(".eh_frame", false, SectionKind::getDataRel()); 1028 1029 // Debug info. 1030 // FIXME: Don't use 'directive' mode here. 1031 DwarfAbbrevSection = 1032 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"", 1033 true, SectionKind::getMetadata()); 1034 DwarfInfoSection = 1035 getCOFFSection("\t.section\t.debug_info,\"dr\"", 1036 true, SectionKind::getMetadata()); 1037 DwarfLineSection = 1038 getCOFFSection("\t.section\t.debug_line,\"dr\"", 1039 true, SectionKind::getMetadata()); 1040 DwarfFrameSection = 1041 getCOFFSection("\t.section\t.debug_frame,\"dr\"", 1042 true, SectionKind::getMetadata()); 1043 DwarfPubNamesSection = 1044 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"", 1045 true, SectionKind::getMetadata()); 1046 DwarfPubTypesSection = 1047 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"", 1048 true, SectionKind::getMetadata()); 1049 DwarfStrSection = 1050 getCOFFSection("\t.section\t.debug_str,\"dr\"", 1051 true, SectionKind::getMetadata()); 1052 DwarfLocSection = 1053 getCOFFSection("\t.section\t.debug_loc,\"dr\"", 1054 true, SectionKind::getMetadata()); 1055 DwarfARangesSection = 1056 getCOFFSection("\t.section\t.debug_aranges,\"dr\"", 1057 true, SectionKind::getMetadata()); 1058 DwarfRangesSection = 1059 getCOFFSection("\t.section\t.debug_ranges,\"dr\"", 1060 true, SectionKind::getMetadata()); 1061 DwarfMacroInfoSection = 1062 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"", 1063 true, SectionKind::getMetadata()); 1064 } 1065 1066 const MCSection *TargetLoweringObjectFileCOFF:: 1067 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 1068 Mangler *Mang, const TargetMachine &TM) const { 1069 return getCOFFSection(GV->getSection().c_str(), false, Kind); 1070 } 1071 1072 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) { 1073 if (Kind.isText()) 1074 return ".text$linkonce"; 1075 if (Kind.isWriteable()) 1076 return ".data$linkonce"; 1077 return ".rdata$linkonce"; 1078 } 1079 1080 1081 const MCSection *TargetLoweringObjectFileCOFF:: 1082 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 1083 Mangler *Mang, const TargetMachine &TM) const { 1084 assert(!Kind.isThreadLocal() && "Doesn't support TLS"); 1085 1086 // If this global is linkonce/weak and the target handles this by emitting it 1087 // into a 'uniqued' section name, create and return the section now. 1088 if (GV->isWeakForLinker()) { 1089 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind); 1090 SmallString<128> Name(Prefix, Prefix+strlen(Prefix)); 1091 Mang->getNameWithPrefix(Name, GV, false); 1092 return getCOFFSection(Name.str(), false, Kind); 1093 } 1094 1095 if (Kind.isText()) 1096 return getTextSection(); 1097 1098 return getDataSection(); 1099 } 1100 1101