1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/MC/MCContext.h" 10 #include "llvm/ADT/Optional.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/SmallVector.h" 13 #include "llvm/ADT/StringMap.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/Twine.h" 16 #include "llvm/BinaryFormat/COFF.h" 17 #include "llvm/BinaryFormat/ELF.h" 18 #include "llvm/BinaryFormat/XCOFF.h" 19 #include "llvm/MC/MCAsmInfo.h" 20 #include "llvm/MC/MCCodeView.h" 21 #include "llvm/MC/MCDwarf.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCFragment.h" 24 #include "llvm/MC/MCLabel.h" 25 #include "llvm/MC/MCObjectFileInfo.h" 26 #include "llvm/MC/MCSectionCOFF.h" 27 #include "llvm/MC/MCSectionELF.h" 28 #include "llvm/MC/MCSectionMachO.h" 29 #include "llvm/MC/MCSectionWasm.h" 30 #include "llvm/MC/MCSectionXCOFF.h" 31 #include "llvm/MC/MCStreamer.h" 32 #include "llvm/MC/MCSymbol.h" 33 #include "llvm/MC/MCSymbolCOFF.h" 34 #include "llvm/MC/MCSymbolELF.h" 35 #include "llvm/MC/MCSymbolMachO.h" 36 #include "llvm/MC/MCSymbolWasm.h" 37 #include "llvm/MC/MCSymbolXCOFF.h" 38 #include "llvm/MC/SectionKind.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/MemoryBuffer.h" 43 #include "llvm/Support/Path.h" 44 #include "llvm/Support/Signals.h" 45 #include "llvm/Support/SourceMgr.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <cassert> 48 #include <cstdlib> 49 #include <tuple> 50 #include <utility> 51 52 using namespace llvm; 53 54 static cl::opt<char*> 55 AsSecureLogFileName("as-secure-log-file-name", 56 cl::desc("As secure log file name (initialized from " 57 "AS_SECURE_LOG_FILE env variable)"), 58 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden); 59 60 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri, 61 const MCObjectFileInfo *mofi, const SourceMgr *mgr, 62 MCTargetOptions const *TargetOpts, bool DoAutoReset) 63 : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi), 64 Symbols(Allocator), UsedNames(Allocator), 65 InlineAsmUsedLabelNames(Allocator), 66 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), 67 AutoReset(DoAutoReset), TargetOptions(TargetOpts) { 68 SecureLogFile = AsSecureLogFileName; 69 70 if (SrcMgr && SrcMgr->getNumBuffers()) 71 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID()) 72 ->getBufferIdentifier()); 73 } 74 75 MCContext::~MCContext() { 76 if (AutoReset) 77 reset(); 78 79 // NOTE: The symbols are all allocated out of a bump pointer allocator, 80 // we don't need to free them here. 81 } 82 83 //===----------------------------------------------------------------------===// 84 // Module Lifetime Management 85 //===----------------------------------------------------------------------===// 86 87 void MCContext::reset() { 88 // Call the destructors so the fragments are freed 89 COFFAllocator.DestroyAll(); 90 ELFAllocator.DestroyAll(); 91 MachOAllocator.DestroyAll(); 92 XCOFFAllocator.DestroyAll(); 93 MCInstAllocator.DestroyAll(); 94 95 MCSubtargetAllocator.DestroyAll(); 96 InlineAsmUsedLabelNames.clear(); 97 UsedNames.clear(); 98 Symbols.clear(); 99 Allocator.Reset(); 100 Instances.clear(); 101 CompilationDir.clear(); 102 MainFileName.clear(); 103 MCDwarfLineTablesCUMap.clear(); 104 SectionsForRanges.clear(); 105 MCGenDwarfLabelEntries.clear(); 106 DwarfDebugFlags = StringRef(); 107 DwarfCompileUnitID = 0; 108 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); 109 110 CVContext.reset(); 111 112 MachOUniquingMap.clear(); 113 ELFUniquingMap.clear(); 114 COFFUniquingMap.clear(); 115 WasmUniquingMap.clear(); 116 XCOFFUniquingMap.clear(); 117 118 ELFEntrySizeMap.clear(); 119 ELFSeenGenericMergeableSections.clear(); 120 121 NextID.clear(); 122 AllowTemporaryLabels = true; 123 DwarfLocSeen = false; 124 GenDwarfForAssembly = false; 125 GenDwarfFileNumber = 0; 126 127 HadError = false; 128 } 129 130 //===----------------------------------------------------------------------===// 131 // MCInst Management 132 //===----------------------------------------------------------------------===// 133 134 MCInst *MCContext::createMCInst() { 135 return new (MCInstAllocator.Allocate()) MCInst; 136 } 137 138 //===----------------------------------------------------------------------===// 139 // Symbol Manipulation 140 //===----------------------------------------------------------------------===// 141 142 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) { 143 SmallString<128> NameSV; 144 StringRef NameRef = Name.toStringRef(NameSV); 145 146 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!"); 147 148 MCSymbol *&Sym = Symbols[NameRef]; 149 if (!Sym) 150 Sym = createSymbol(NameRef, false, false); 151 152 return Sym; 153 } 154 155 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName, 156 unsigned Idx) { 157 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 158 "$frame_escape_" + Twine(Idx)); 159 } 160 161 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) { 162 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 163 "$parent_frame_offset"); 164 } 165 166 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) { 167 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" + 168 FuncName); 169 } 170 171 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name, 172 bool IsTemporary) { 173 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(), 174 "MCSymbol classes must be trivially destructible"); 175 static_assert(std::is_trivially_destructible<MCSymbolELF>(), 176 "MCSymbol classes must be trivially destructible"); 177 static_assert(std::is_trivially_destructible<MCSymbolMachO>(), 178 "MCSymbol classes must be trivially destructible"); 179 static_assert(std::is_trivially_destructible<MCSymbolWasm>(), 180 "MCSymbol classes must be trivially destructible"); 181 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(), 182 "MCSymbol classes must be trivially destructible"); 183 if (MOFI) { 184 switch (MOFI->getObjectFileType()) { 185 case MCObjectFileInfo::IsCOFF: 186 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary); 187 case MCObjectFileInfo::IsELF: 188 return new (Name, *this) MCSymbolELF(Name, IsTemporary); 189 case MCObjectFileInfo::IsMachO: 190 return new (Name, *this) MCSymbolMachO(Name, IsTemporary); 191 case MCObjectFileInfo::IsWasm: 192 return new (Name, *this) MCSymbolWasm(Name, IsTemporary); 193 case MCObjectFileInfo::IsXCOFF: 194 return createXCOFFSymbolImpl(Name, IsTemporary); 195 } 196 } 197 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name, 198 IsTemporary); 199 } 200 201 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix, 202 bool CanBeUnnamed) { 203 if (CanBeUnnamed && !UseNamesOnTempLabels) 204 return createSymbolImpl(nullptr, true); 205 206 // Determine whether this is a user written assembler temporary or normal 207 // label, if used. 208 bool IsTemporary = CanBeUnnamed; 209 if (AllowTemporaryLabels && !IsTemporary) 210 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); 211 212 SmallString<128> NewName = Name; 213 bool AddSuffix = AlwaysAddSuffix; 214 unsigned &NextUniqueID = NextID[Name]; 215 while (true) { 216 if (AddSuffix) { 217 NewName.resize(Name.size()); 218 raw_svector_ostream(NewName) << NextUniqueID++; 219 } 220 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true)); 221 if (NameEntry.second || !NameEntry.first->second) { 222 // Ok, we found a name. 223 // Mark it as used for a non-section symbol. 224 NameEntry.first->second = true; 225 // Have the MCSymbol object itself refer to the copy of the string that is 226 // embedded in the UsedNames entry. 227 return createSymbolImpl(&*NameEntry.first, IsTemporary); 228 } 229 assert(IsTemporary && "Cannot rename non-temporary symbols"); 230 AddSuffix = true; 231 } 232 llvm_unreachable("Infinite loop"); 233 } 234 235 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) { 236 SmallString<128> NameSV; 237 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; 238 return createSymbol(NameSV, AlwaysAddSuffix, true); 239 } 240 241 MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) { 242 SmallString<128> NameSV; 243 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; 244 return createSymbol(NameSV, true, false); 245 } 246 247 MCSymbol *MCContext::createLinkerPrivateTempSymbol() { 248 SmallString<128> NameSV; 249 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp"; 250 return createSymbol(NameSV, true, false); 251 } 252 253 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); } 254 255 MCSymbol *MCContext::createNamedTempSymbol() { 256 return createNamedTempSymbol("tmp"); 257 } 258 259 unsigned MCContext::NextInstance(unsigned LocalLabelVal) { 260 MCLabel *&Label = Instances[LocalLabelVal]; 261 if (!Label) 262 Label = new (*this) MCLabel(0); 263 return Label->incInstance(); 264 } 265 266 unsigned MCContext::GetInstance(unsigned LocalLabelVal) { 267 MCLabel *&Label = Instances[LocalLabelVal]; 268 if (!Label) 269 Label = new (*this) MCLabel(0); 270 return Label->getInstance(); 271 } 272 273 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, 274 unsigned Instance) { 275 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; 276 if (!Sym) 277 Sym = createNamedTempSymbol(); 278 return Sym; 279 } 280 281 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) { 282 unsigned Instance = NextInstance(LocalLabelVal); 283 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 284 } 285 286 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal, 287 bool Before) { 288 unsigned Instance = GetInstance(LocalLabelVal); 289 if (!Before) 290 ++Instance; 291 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 292 } 293 294 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { 295 SmallString<128> NameSV; 296 StringRef NameRef = Name.toStringRef(NameSV); 297 return Symbols.lookup(NameRef); 298 } 299 300 void MCContext::setSymbolValue(MCStreamer &Streamer, 301 StringRef Sym, 302 uint64_t Val) { 303 auto Symbol = getOrCreateSymbol(Sym); 304 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this)); 305 } 306 307 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) { 308 InlineAsmUsedLabelNames[Sym->getName()] = Sym; 309 } 310 311 MCSymbolXCOFF * 312 MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name, 313 bool IsTemporary) { 314 if (!Name) 315 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary); 316 317 StringRef OriginalName = Name->first(); 318 if (OriginalName.startswith("._Renamed..") || 319 OriginalName.startswith("_Renamed..")) 320 reportError(SMLoc(), "invalid symbol name from source"); 321 322 if (MAI->isValidUnquotedName(OriginalName)) 323 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary); 324 325 // Now we have a name that contains invalid character(s) for XCOFF symbol. 326 // Let's replace with something valid, but save the original name so that 327 // we could still use the original name in the symbol table. 328 SmallString<128> InvalidName(OriginalName); 329 330 // If it's an entry point symbol, we will keep the '.' 331 // in front for the convention purpose. Otherwise, add "_Renamed.." 332 // as prefix to signal this is an renamed symbol. 333 const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.'; 334 SmallString<128> ValidName = 335 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed.."); 336 337 // Append the hex values of '_' and invalid characters with "_Renamed.."; 338 // at the same time replace invalid characters with '_'. 339 for (size_t I = 0; I < InvalidName.size(); ++I) { 340 if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') { 341 raw_svector_ostream(ValidName).write_hex(InvalidName[I]); 342 InvalidName[I] = '_'; 343 } 344 } 345 346 // Skip entry point symbol's '.' as we already have a '.' in front of 347 // "_Renamed". 348 if (IsEntryPoint) 349 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1)); 350 else 351 ValidName.append(InvalidName); 352 353 auto NameEntry = UsedNames.insert(std::make_pair(ValidName, true)); 354 assert((NameEntry.second || !NameEntry.first->second) && 355 "This name is used somewhere else."); 356 // Mark the name as used for a non-section symbol. 357 NameEntry.first->second = true; 358 // Have the MCSymbol object itself refer to the copy of the string 359 // that is embedded in the UsedNames entry. 360 MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this) 361 MCSymbolXCOFF(&*NameEntry.first, IsTemporary); 362 XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName)); 363 return XSym; 364 } 365 366 //===----------------------------------------------------------------------===// 367 // Section Management 368 //===----------------------------------------------------------------------===// 369 370 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section, 371 unsigned TypeAndAttributes, 372 unsigned Reserved2, SectionKind Kind, 373 const char *BeginSymName) { 374 // We unique sections by their segment/section pair. The returned section 375 // may not have the same flags as the requested section, if so this should be 376 // diagnosed by the client as an error. 377 378 // Form the name to look up. 379 assert(Section.size() <= 16 && "section name is too long"); 380 assert(!memchr(Section.data(), '\0', Section.size()) && 381 "section name cannot contain NUL"); 382 383 // Do the lookup, if we have a hit, return it. 384 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str()); 385 if (!R.second) 386 return R.first->second; 387 388 MCSymbol *Begin = nullptr; 389 if (BeginSymName) 390 Begin = createTempSymbol(BeginSymName, false); 391 392 // Otherwise, return a new section. 393 StringRef Name = R.first->first(); 394 R.first->second = new (MachOAllocator.Allocate()) 395 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()), 396 TypeAndAttributes, Reserved2, Kind, Begin); 397 return R.first->second; 398 } 399 400 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) { 401 StringRef GroupName; 402 if (const MCSymbol *Group = Section->getGroup()) 403 GroupName = Group->getName(); 404 405 // This function is only used by .debug*, which should not have the 406 // SHF_LINK_ORDER flag. 407 unsigned UniqueID = Section->getUniqueID(); 408 ELFUniquingMap.erase( 409 ELFSectionKey{Section->getName(), GroupName, "", UniqueID}); 410 auto I = ELFUniquingMap 411 .insert(std::make_pair( 412 ELFSectionKey{Name, GroupName, "", UniqueID}, Section)) 413 .first; 414 StringRef CachedName = I->first.SectionName; 415 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName); 416 } 417 418 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type, 419 unsigned Flags, SectionKind K, 420 unsigned EntrySize, 421 const MCSymbolELF *Group, 422 bool Comdat, unsigned UniqueID, 423 const MCSymbolELF *LinkedToSym) { 424 MCSymbolELF *R; 425 MCSymbol *&Sym = Symbols[Section]; 426 // A section symbol can not redefine regular symbols. There may be multiple 427 // sections with the same name, in which case the first such section wins. 428 if (Sym && Sym->isDefined() && 429 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym)) 430 reportError(SMLoc(), "invalid symbol redefinition"); 431 if (Sym && Sym->isUndefined()) { 432 R = cast<MCSymbolELF>(Sym); 433 } else { 434 auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first; 435 R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false); 436 if (!Sym) 437 Sym = R; 438 } 439 R->setBinding(ELF::STB_LOCAL); 440 R->setType(ELF::STT_SECTION); 441 442 auto *Ret = new (ELFAllocator.Allocate()) 443 MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID, 444 R, LinkedToSym); 445 446 auto *F = new MCDataFragment(); 447 Ret->getFragmentList().insert(Ret->begin(), F); 448 F->setParent(Ret); 449 R->setFragment(F); 450 451 return Ret; 452 } 453 454 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type, 455 unsigned Flags, unsigned EntrySize, 456 const MCSymbolELF *Group, 457 const MCSectionELF *RelInfoSection) { 458 StringMap<bool>::iterator I; 459 bool Inserted; 460 std::tie(I, Inserted) = 461 RelSecNames.insert(std::make_pair(Name.str(), true)); 462 463 return createELFSectionImpl( 464 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group, 465 true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol())); 466 } 467 468 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix, 469 const Twine &Suffix, unsigned Type, 470 unsigned Flags, 471 unsigned EntrySize) { 472 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix, 473 /*IsComdat=*/true); 474 } 475 476 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, 477 unsigned Flags, unsigned EntrySize, 478 const Twine &Group, bool IsComdat, 479 unsigned UniqueID, 480 const MCSymbolELF *LinkedToSym) { 481 MCSymbolELF *GroupSym = nullptr; 482 if (!Group.isTriviallyEmpty() && !Group.str().empty()) 483 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group)); 484 485 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat, 486 UniqueID, LinkedToSym); 487 } 488 489 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, 490 unsigned Flags, unsigned EntrySize, 491 const MCSymbolELF *GroupSym, 492 bool IsComdat, unsigned UniqueID, 493 const MCSymbolELF *LinkedToSym) { 494 StringRef Group = ""; 495 if (GroupSym) 496 Group = GroupSym->getName(); 497 assert(!(LinkedToSym && LinkedToSym->getName().empty())); 498 // Do the lookup, if we have a hit, return it. 499 auto IterBool = ELFUniquingMap.insert(std::make_pair( 500 ELFSectionKey{Section.str(), Group, 501 LinkedToSym ? LinkedToSym->getName() : "", UniqueID}, 502 nullptr)); 503 auto &Entry = *IterBool.first; 504 if (!IterBool.second) 505 return Entry.second; 506 507 StringRef CachedName = Entry.first.SectionName; 508 509 SectionKind Kind; 510 if (Flags & ELF::SHF_ARM_PURECODE) 511 Kind = SectionKind::getExecuteOnly(); 512 else if (Flags & ELF::SHF_EXECINSTR) 513 Kind = SectionKind::getText(); 514 else 515 Kind = SectionKind::getReadOnly(); 516 517 MCSectionELF *Result = 518 createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym, 519 IsComdat, UniqueID, LinkedToSym); 520 Entry.second = Result; 521 522 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(), 523 Result->getUniqueID(), Result->getEntrySize()); 524 525 return Result; 526 } 527 528 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group, 529 bool IsComdat) { 530 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 531 SectionKind::getReadOnly(), 4, Group, IsComdat, 532 MCSection::NonUniqueID, nullptr); 533 } 534 535 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName, 536 unsigned Flags, unsigned UniqueID, 537 unsigned EntrySize) { 538 bool IsMergeable = Flags & ELF::SHF_MERGE; 539 if (IsMergeable && (UniqueID == GenericSectionID)) 540 ELFSeenGenericMergeableSections.insert(SectionName); 541 542 // For mergeable sections or non-mergeable sections with a generic mergeable 543 // section name we enter their Unique ID into the ELFEntrySizeMap so that 544 // compatible globals can be assigned to the same section. 545 if (IsMergeable || isELFGenericMergeableSection(SectionName)) { 546 ELFEntrySizeMap.insert(std::make_pair( 547 ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID)); 548 } 549 } 550 551 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) { 552 return SectionName.startswith(".rodata.str") || 553 SectionName.startswith(".rodata.cst"); 554 } 555 556 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) { 557 return isELFImplicitMergeableSectionNamePrefix(SectionName) || 558 ELFSeenGenericMergeableSections.count(SectionName); 559 } 560 561 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName, 562 unsigned Flags, 563 unsigned EntrySize) { 564 auto I = ELFEntrySizeMap.find( 565 MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize}); 566 return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None; 567 } 568 569 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 570 unsigned Characteristics, 571 SectionKind Kind, 572 StringRef COMDATSymName, int Selection, 573 unsigned UniqueID, 574 const char *BeginSymName) { 575 MCSymbol *COMDATSymbol = nullptr; 576 if (!COMDATSymName.empty()) { 577 COMDATSymbol = getOrCreateSymbol(COMDATSymName); 578 COMDATSymName = COMDATSymbol->getName(); 579 } 580 581 582 // Do the lookup, if we have a hit, return it. 583 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID}; 584 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr)); 585 auto Iter = IterBool.first; 586 if (!IterBool.second) 587 return Iter->second; 588 589 MCSymbol *Begin = nullptr; 590 if (BeginSymName) 591 Begin = createTempSymbol(BeginSymName, false); 592 593 StringRef CachedName = Iter->first.SectionName; 594 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( 595 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin); 596 597 Iter->second = Result; 598 return Result; 599 } 600 601 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 602 unsigned Characteristics, 603 SectionKind Kind, 604 const char *BeginSymName) { 605 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID, 606 BeginSymName); 607 } 608 609 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, 610 const MCSymbol *KeySym, 611 unsigned UniqueID) { 612 // Return the normal section if we don't have to be associative or unique. 613 if (!KeySym && UniqueID == GenericSectionID) 614 return Sec; 615 616 // If we have a key symbol, make an associative section with the same name and 617 // kind as the normal section. 618 unsigned Characteristics = Sec->getCharacteristics(); 619 if (KeySym) { 620 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 621 return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), 622 KeySym->getName(), 623 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 624 } 625 626 return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0, 627 UniqueID); 628 } 629 630 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K, 631 const Twine &Group, unsigned UniqueID, 632 const char *BeginSymName) { 633 MCSymbolWasm *GroupSym = nullptr; 634 if (!Group.isTriviallyEmpty() && !Group.str().empty()) { 635 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group)); 636 GroupSym->setComdat(true); 637 } 638 639 return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName); 640 } 641 642 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind, 643 const MCSymbolWasm *GroupSym, 644 unsigned UniqueID, 645 const char *BeginSymName) { 646 StringRef Group = ""; 647 if (GroupSym) 648 Group = GroupSym->getName(); 649 // Do the lookup, if we have a hit, return it. 650 auto IterBool = WasmUniquingMap.insert( 651 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr)); 652 auto &Entry = *IterBool.first; 653 if (!IterBool.second) 654 return Entry.second; 655 656 StringRef CachedName = Entry.first.SectionName; 657 658 MCSymbol *Begin = createSymbol(CachedName, true, false); 659 cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION); 660 661 MCSectionWasm *Result = new (WasmAllocator.Allocate()) 662 MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin); 663 Entry.second = Result; 664 665 auto *F = new MCDataFragment(); 666 Result->getFragmentList().insert(Result->begin(), F); 667 F->setParent(Result); 668 Begin->setFragment(F); 669 670 return Result; 671 } 672 673 MCSectionXCOFF * 674 MCContext::getXCOFFSection(StringRef Section, SectionKind Kind, 675 Optional<XCOFF::CsectProperties> CsectProp, 676 bool MultiSymbolsAllowed, const char *BeginSymName) { 677 // Do the lookup. If we have a hit, return it. 678 // FIXME: handle the case for non-csect sections. Non-csect section has None 679 // CsectProp. 680 auto IterBool = XCOFFUniquingMap.insert(std::make_pair( 681 XCOFFSectionKey{Section.str(), CsectProp->MappingClass}, nullptr)); 682 auto &Entry = *IterBool.first; 683 if (!IterBool.second) { 684 MCSectionXCOFF *ExistedEntry = Entry.second; 685 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed) 686 report_fatal_error("section's multiply symbols policy does not match"); 687 688 return ExistedEntry; 689 } 690 691 // Otherwise, return a new section. 692 StringRef CachedName = Entry.first.SectionName; 693 MCSymbolXCOFF *QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol( 694 CachedName + "[" + XCOFF::getMappingClassString(CsectProp->MappingClass) + 695 "]")); 696 697 MCSymbol *Begin = nullptr; 698 if (BeginSymName) 699 Begin = createTempSymbol(BeginSymName, false); 700 701 // QualName->getUnqualifiedName() and CachedName are the same except when 702 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol. 703 MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF( 704 QualName->getUnqualifiedName(), CsectProp->MappingClass, CsectProp->Type, 705 Kind, QualName, Begin, CachedName, MultiSymbolsAllowed); 706 Entry.second = Result; 707 708 auto *F = new MCDataFragment(); 709 Result->getFragmentList().insert(Result->begin(), F); 710 F->setParent(Result); 711 712 if (Begin) 713 Begin->setFragment(F); 714 715 return Result; 716 } 717 718 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { 719 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); 720 } 721 722 void MCContext::addDebugPrefixMapEntry(const std::string &From, 723 const std::string &To) { 724 DebugPrefixMap.insert(std::make_pair(From, To)); 725 } 726 727 void MCContext::RemapDebugPaths() { 728 const auto &DebugPrefixMap = this->DebugPrefixMap; 729 if (DebugPrefixMap.empty()) 730 return; 731 732 const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) { 733 SmallString<256> P(Path); 734 for (const auto &Entry : DebugPrefixMap) { 735 if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) { 736 Path = P.str().str(); 737 break; 738 } 739 } 740 }; 741 742 // Remap compilation directory. 743 std::string CompDir = std::string(CompilationDir.str()); 744 RemapDebugPath(CompDir); 745 CompilationDir = CompDir; 746 747 // Remap MCDwarfDirs in all compilation units. 748 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) 749 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) 750 RemapDebugPath(Dir); 751 } 752 753 //===----------------------------------------------------------------------===// 754 // Dwarf Management 755 //===----------------------------------------------------------------------===// 756 757 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) { 758 // MCDwarf needs the root file as well as the compilation directory. 759 // If we find a '.file 0' directive that will supersede these values. 760 Optional<MD5::MD5Result> Cksum; 761 if (getDwarfVersion() >= 5) { 762 MD5 Hash; 763 MD5::MD5Result Sum; 764 Hash.update(Buffer); 765 Hash.final(Sum); 766 Cksum = Sum; 767 } 768 // Canonicalize the root filename. It cannot be empty, and should not 769 // repeat the compilation dir. 770 // The MCContext ctor initializes MainFileName to the name associated with 771 // the SrcMgr's main file ID, which might be the same as InputFileName (and 772 // possibly include directory components). 773 // Or, MainFileName might have been overridden by a -main-file-name option, 774 // which is supposed to be just a base filename with no directory component. 775 // So, if the InputFileName and MainFileName are not equal, assume 776 // MainFileName is a substitute basename and replace the last component. 777 SmallString<1024> FileNameBuf = InputFileName; 778 if (FileNameBuf.empty() || FileNameBuf == "-") 779 FileNameBuf = "<stdin>"; 780 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) { 781 llvm::sys::path::remove_filename(FileNameBuf); 782 llvm::sys::path::append(FileNameBuf, getMainFileName()); 783 } 784 StringRef FileName = FileNameBuf; 785 if (FileName.consume_front(getCompilationDir())) 786 if (llvm::sys::path::is_separator(FileName.front())) 787 FileName = FileName.drop_front(); 788 assert(!FileName.empty()); 789 setMCLineTableRootFile( 790 /*CUID=*/0, getCompilationDir(), FileName, Cksum, None); 791 } 792 793 /// getDwarfFile - takes a file name and number to place in the dwarf file and 794 /// directory tables. If the file number has already been allocated it is an 795 /// error and zero is returned and the client reports the error, else the 796 /// allocated file number is returned. The file numbers may be in any order. 797 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory, 798 StringRef FileName, 799 unsigned FileNumber, 800 Optional<MD5::MD5Result> Checksum, 801 Optional<StringRef> Source, 802 unsigned CUID) { 803 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; 804 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, 805 FileNumber); 806 } 807 808 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it 809 /// currently is assigned and false otherwise. 810 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { 811 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID); 812 if (FileNumber == 0) 813 return getDwarfVersion() >= 5; 814 if (FileNumber >= LineTable.getMCDwarfFiles().size()) 815 return false; 816 817 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty(); 818 } 819 820 /// Remove empty sections from SectionsForRanges, to avoid generating 821 /// useless debug info for them. 822 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) { 823 SectionsForRanges.remove_if( 824 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); }); 825 } 826 827 CodeViewContext &MCContext::getCVContext() { 828 if (!CVContext.get()) 829 CVContext.reset(new CodeViewContext); 830 return *CVContext.get(); 831 } 832 833 //===----------------------------------------------------------------------===// 834 // Error Reporting 835 //===----------------------------------------------------------------------===// 836 837 void MCContext::reportError(SMLoc Loc, const Twine &Msg) { 838 HadError = true; 839 840 // If we have a source manager use it. Otherwise, try using the inline source 841 // manager. 842 // If that fails, construct a temporary SourceMgr. 843 if (SrcMgr) 844 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); 845 else if (InlineSrcMgr) 846 InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); 847 else 848 SourceMgr().PrintMessage(Loc, SourceMgr::DK_Error, Msg); 849 } 850 851 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) { 852 if (TargetOptions && TargetOptions->MCNoWarn) 853 return; 854 if (TargetOptions && TargetOptions->MCFatalWarnings) 855 reportError(Loc, Msg); 856 else { 857 // If we have a source manager use it. Otherwise, try using the inline 858 // source manager. 859 if (SrcMgr) 860 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg); 861 else if (InlineSrcMgr) 862 InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg); 863 } 864 } 865 866 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) { 867 reportError(Loc, Msg); 868 869 // If we reached here, we are failing ungracefully. Run the interrupt handlers 870 // to make sure any special cleanups get done, in particular that we remove 871 // files registered with RemoveFileOnSignal. 872 sys::RunInterruptHandlers(); 873 exit(1); 874 } 875