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/MC/MCAsmInfo.h" 19 #include "llvm/MC/MCCodeView.h" 20 #include "llvm/MC/MCDwarf.h" 21 #include "llvm/MC/MCExpr.h" 22 #include "llvm/MC/MCFragment.h" 23 #include "llvm/MC/MCLabel.h" 24 #include "llvm/MC/MCObjectFileInfo.h" 25 #include "llvm/MC/MCSectionCOFF.h" 26 #include "llvm/MC/MCSectionELF.h" 27 #include "llvm/MC/MCSectionMachO.h" 28 #include "llvm/MC/MCSectionWasm.h" 29 #include "llvm/MC/MCSectionXCOFF.h" 30 #include "llvm/MC/MCStreamer.h" 31 #include "llvm/MC/MCSymbol.h" 32 #include "llvm/MC/MCSymbolCOFF.h" 33 #include "llvm/MC/MCSymbolELF.h" 34 #include "llvm/MC/MCSymbolMachO.h" 35 #include "llvm/MC/MCSymbolWasm.h" 36 #include "llvm/MC/MCSymbolXCOFF.h" 37 #include "llvm/MC/SectionKind.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/MemoryBuffer.h" 42 #include "llvm/Support/Path.h" 43 #include "llvm/Support/Signals.h" 44 #include "llvm/Support/SourceMgr.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include <cassert> 47 #include <cstdlib> 48 #include <tuple> 49 #include <utility> 50 51 using namespace llvm; 52 53 static cl::opt<char*> 54 AsSecureLogFileName("as-secure-log-file-name", 55 cl::desc("As secure log file name (initialized from " 56 "AS_SECURE_LOG_FILE env variable)"), 57 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden); 58 59 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri, 60 const MCObjectFileInfo *mofi, const SourceMgr *mgr, 61 bool DoAutoReset) 62 : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi), 63 Symbols(Allocator), UsedNames(Allocator), 64 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), 65 AutoReset(DoAutoReset) { 66 SecureLogFile = AsSecureLogFileName; 67 68 if (SrcMgr && SrcMgr->getNumBuffers()) 69 MainFileName = 70 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier(); 71 } 72 73 MCContext::~MCContext() { 74 if (AutoReset) 75 reset(); 76 77 // NOTE: The symbols are all allocated out of a bump pointer allocator, 78 // we don't need to free them here. 79 } 80 81 //===----------------------------------------------------------------------===// 82 // Module Lifetime Management 83 //===----------------------------------------------------------------------===// 84 85 void MCContext::reset() { 86 // Call the destructors so the fragments are freed 87 COFFAllocator.DestroyAll(); 88 ELFAllocator.DestroyAll(); 89 MachOAllocator.DestroyAll(); 90 XCOFFAllocator.DestroyAll(); 91 92 MCSubtargetAllocator.DestroyAll(); 93 UsedNames.clear(); 94 Symbols.clear(); 95 Allocator.Reset(); 96 Instances.clear(); 97 CompilationDir.clear(); 98 MainFileName.clear(); 99 MCDwarfLineTablesCUMap.clear(); 100 SectionsForRanges.clear(); 101 MCGenDwarfLabelEntries.clear(); 102 DwarfDebugFlags = StringRef(); 103 DwarfCompileUnitID = 0; 104 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); 105 106 CVContext.reset(); 107 108 MachOUniquingMap.clear(); 109 ELFUniquingMap.clear(); 110 COFFUniquingMap.clear(); 111 WasmUniquingMap.clear(); 112 XCOFFUniquingMap.clear(); 113 114 NextID.clear(); 115 AllowTemporaryLabels = true; 116 DwarfLocSeen = false; 117 GenDwarfForAssembly = false; 118 GenDwarfFileNumber = 0; 119 120 HadError = false; 121 } 122 123 //===----------------------------------------------------------------------===// 124 // Symbol Manipulation 125 //===----------------------------------------------------------------------===// 126 127 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) { 128 SmallString<128> NameSV; 129 StringRef NameRef = Name.toStringRef(NameSV); 130 131 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!"); 132 133 MCSymbol *&Sym = Symbols[NameRef]; 134 if (!Sym) 135 Sym = createSymbol(NameRef, false, false); 136 137 return Sym; 138 } 139 140 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName, 141 unsigned Idx) { 142 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 143 "$frame_escape_" + Twine(Idx)); 144 } 145 146 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) { 147 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 148 "$parent_frame_offset"); 149 } 150 151 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) { 152 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" + 153 FuncName); 154 } 155 156 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name, 157 bool IsTemporary) { 158 if (MOFI) { 159 switch (MOFI->getObjectFileType()) { 160 case MCObjectFileInfo::IsCOFF: 161 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary); 162 case MCObjectFileInfo::IsELF: 163 return new (Name, *this) MCSymbolELF(Name, IsTemporary); 164 case MCObjectFileInfo::IsMachO: 165 return new (Name, *this) MCSymbolMachO(Name, IsTemporary); 166 case MCObjectFileInfo::IsWasm: 167 return new (Name, *this) MCSymbolWasm(Name, IsTemporary); 168 case MCObjectFileInfo::IsXCOFF: 169 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary); 170 } 171 } 172 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name, 173 IsTemporary); 174 } 175 176 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix, 177 bool CanBeUnnamed) { 178 if (CanBeUnnamed && !UseNamesOnTempLabels) 179 return createSymbolImpl(nullptr, true); 180 181 // Determine whether this is a user written assembler temporary or normal 182 // label, if used. 183 bool IsTemporary = CanBeUnnamed; 184 if (AllowTemporaryLabels && !IsTemporary) 185 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); 186 187 SmallString<128> NewName = Name; 188 bool AddSuffix = AlwaysAddSuffix; 189 unsigned &NextUniqueID = NextID[Name]; 190 while (true) { 191 if (AddSuffix) { 192 NewName.resize(Name.size()); 193 raw_svector_ostream(NewName) << NextUniqueID++; 194 } 195 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true)); 196 if (NameEntry.second || !NameEntry.first->second) { 197 // Ok, we found a name. 198 // Mark it as used for a non-section symbol. 199 NameEntry.first->second = true; 200 // Have the MCSymbol object itself refer to the copy of the string that is 201 // embedded in the UsedNames entry. 202 return createSymbolImpl(&*NameEntry.first, IsTemporary); 203 } 204 assert(IsTemporary && "Cannot rename non-temporary symbols"); 205 AddSuffix = true; 206 } 207 llvm_unreachable("Infinite loop"); 208 } 209 210 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix, 211 bool CanBeUnnamed) { 212 SmallString<128> NameSV; 213 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; 214 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed); 215 } 216 217 MCSymbol *MCContext::createLinkerPrivateTempSymbol() { 218 SmallString<128> NameSV; 219 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp"; 220 return createSymbol(NameSV, true, false); 221 } 222 223 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) { 224 return createTempSymbol("tmp", true, CanBeUnnamed); 225 } 226 227 unsigned MCContext::NextInstance(unsigned LocalLabelVal) { 228 MCLabel *&Label = Instances[LocalLabelVal]; 229 if (!Label) 230 Label = new (*this) MCLabel(0); 231 return Label->incInstance(); 232 } 233 234 unsigned MCContext::GetInstance(unsigned LocalLabelVal) { 235 MCLabel *&Label = Instances[LocalLabelVal]; 236 if (!Label) 237 Label = new (*this) MCLabel(0); 238 return Label->getInstance(); 239 } 240 241 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, 242 unsigned Instance) { 243 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; 244 if (!Sym) 245 Sym = createTempSymbol(false); 246 return Sym; 247 } 248 249 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) { 250 unsigned Instance = NextInstance(LocalLabelVal); 251 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 252 } 253 254 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal, 255 bool Before) { 256 unsigned Instance = GetInstance(LocalLabelVal); 257 if (!Before) 258 ++Instance; 259 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 260 } 261 262 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { 263 SmallString<128> NameSV; 264 StringRef NameRef = Name.toStringRef(NameSV); 265 return Symbols.lookup(NameRef); 266 } 267 268 void MCContext::setSymbolValue(MCStreamer &Streamer, 269 StringRef Sym, 270 uint64_t Val) { 271 auto Symbol = getOrCreateSymbol(Sym); 272 Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this)); 273 } 274 275 //===----------------------------------------------------------------------===// 276 // Section Management 277 //===----------------------------------------------------------------------===// 278 279 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section, 280 unsigned TypeAndAttributes, 281 unsigned Reserved2, SectionKind Kind, 282 const char *BeginSymName) { 283 // We unique sections by their segment/section pair. The returned section 284 // may not have the same flags as the requested section, if so this should be 285 // diagnosed by the client as an error. 286 287 // Form the name to look up. 288 SmallString<64> Name; 289 Name += Segment; 290 Name.push_back(','); 291 Name += Section; 292 293 // Do the lookup, if we have a hit, return it. 294 MCSectionMachO *&Entry = MachOUniquingMap[Name]; 295 if (Entry) 296 return Entry; 297 298 MCSymbol *Begin = nullptr; 299 if (BeginSymName) 300 Begin = createTempSymbol(BeginSymName, false); 301 302 // Otherwise, return a new section. 303 return Entry = new (MachOAllocator.Allocate()) MCSectionMachO( 304 Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin); 305 } 306 307 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) { 308 StringRef GroupName; 309 if (const MCSymbol *Group = Section->getGroup()) 310 GroupName = Group->getName(); 311 312 unsigned UniqueID = Section->getUniqueID(); 313 ELFUniquingMap.erase( 314 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID}); 315 auto I = ELFUniquingMap.insert(std::make_pair( 316 ELFSectionKey{Name, GroupName, UniqueID}, 317 Section)) 318 .first; 319 StringRef CachedName = I->first.SectionName; 320 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName); 321 } 322 323 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type, 324 unsigned Flags, SectionKind K, 325 unsigned EntrySize, 326 const MCSymbolELF *Group, 327 unsigned UniqueID, 328 const MCSymbolELF *Associated) { 329 MCSymbolELF *R; 330 MCSymbol *&Sym = Symbols[Section]; 331 // A section symbol can not redefine regular symbols. There may be multiple 332 // sections with the same name, in which case the first such section wins. 333 if (Sym && Sym->isDefined() && 334 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym)) 335 reportError(SMLoc(), "invalid symbol redefinition"); 336 if (Sym && Sym->isUndefined()) { 337 R = cast<MCSymbolELF>(Sym); 338 } else { 339 auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first; 340 R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false); 341 if (!Sym) 342 Sym = R; 343 } 344 R->setBinding(ELF::STB_LOCAL); 345 R->setType(ELF::STT_SECTION); 346 347 auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF( 348 Section, Type, Flags, K, EntrySize, Group, UniqueID, R, Associated); 349 350 auto *F = new MCDataFragment(); 351 Ret->getFragmentList().insert(Ret->begin(), F); 352 F->setParent(Ret); 353 R->setFragment(F); 354 355 return Ret; 356 } 357 358 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type, 359 unsigned Flags, unsigned EntrySize, 360 const MCSymbolELF *Group, 361 const MCSectionELF *RelInfoSection) { 362 StringMap<bool>::iterator I; 363 bool Inserted; 364 std::tie(I, Inserted) = 365 RelSecNames.insert(std::make_pair(Name.str(), true)); 366 367 return createELFSectionImpl( 368 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group, 369 true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol())); 370 } 371 372 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix, 373 const Twine &Suffix, unsigned Type, 374 unsigned Flags, 375 unsigned EntrySize) { 376 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix); 377 } 378 379 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, 380 unsigned Flags, unsigned EntrySize, 381 const Twine &Group, unsigned UniqueID, 382 const MCSymbolELF *Associated) { 383 MCSymbolELF *GroupSym = nullptr; 384 if (!Group.isTriviallyEmpty() && !Group.str().empty()) 385 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group)); 386 387 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID, 388 Associated); 389 } 390 391 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, 392 unsigned Flags, unsigned EntrySize, 393 const MCSymbolELF *GroupSym, 394 unsigned UniqueID, 395 const MCSymbolELF *Associated) { 396 StringRef Group = ""; 397 if (GroupSym) 398 Group = GroupSym->getName(); 399 // Do the lookup, if we have a hit, return it. 400 auto IterBool = ELFUniquingMap.insert( 401 std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr)); 402 auto &Entry = *IterBool.first; 403 if (!IterBool.second) 404 return Entry.second; 405 406 StringRef CachedName = Entry.first.SectionName; 407 408 SectionKind Kind; 409 if (Flags & ELF::SHF_ARM_PURECODE) 410 Kind = SectionKind::getExecuteOnly(); 411 else if (Flags & ELF::SHF_EXECINSTR) 412 Kind = SectionKind::getText(); 413 else 414 Kind = SectionKind::getReadOnly(); 415 416 MCSectionELF *Result = createELFSectionImpl( 417 CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Associated); 418 Entry.second = Result; 419 return Result; 420 } 421 422 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) { 423 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 424 SectionKind::getReadOnly(), 4, Group, ~0, 425 nullptr); 426 } 427 428 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 429 unsigned Characteristics, 430 SectionKind Kind, 431 StringRef COMDATSymName, int Selection, 432 unsigned UniqueID, 433 const char *BeginSymName) { 434 MCSymbol *COMDATSymbol = nullptr; 435 if (!COMDATSymName.empty()) { 436 COMDATSymbol = getOrCreateSymbol(COMDATSymName); 437 COMDATSymName = COMDATSymbol->getName(); 438 } 439 440 441 // Do the lookup, if we have a hit, return it. 442 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID}; 443 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr)); 444 auto Iter = IterBool.first; 445 if (!IterBool.second) 446 return Iter->second; 447 448 MCSymbol *Begin = nullptr; 449 if (BeginSymName) 450 Begin = createTempSymbol(BeginSymName, false); 451 452 StringRef CachedName = Iter->first.SectionName; 453 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( 454 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin); 455 456 Iter->second = Result; 457 return Result; 458 } 459 460 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 461 unsigned Characteristics, 462 SectionKind Kind, 463 const char *BeginSymName) { 464 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID, 465 BeginSymName); 466 } 467 468 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, 469 const MCSymbol *KeySym, 470 unsigned UniqueID) { 471 // Return the normal section if we don't have to be associative or unique. 472 if (!KeySym && UniqueID == GenericSectionID) 473 return Sec; 474 475 // If we have a key symbol, make an associative section with the same name and 476 // kind as the normal section. 477 unsigned Characteristics = Sec->getCharacteristics(); 478 if (KeySym) { 479 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 480 return getCOFFSection(Sec->getSectionName(), Characteristics, 481 Sec->getKind(), KeySym->getName(), 482 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 483 } 484 485 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(), 486 "", 0, UniqueID); 487 } 488 489 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K, 490 const Twine &Group, unsigned UniqueID, 491 const char *BeginSymName) { 492 MCSymbolWasm *GroupSym = nullptr; 493 if (!Group.isTriviallyEmpty() && !Group.str().empty()) { 494 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group)); 495 GroupSym->setComdat(true); 496 } 497 498 return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName); 499 } 500 501 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind, 502 const MCSymbolWasm *GroupSym, 503 unsigned UniqueID, 504 const char *BeginSymName) { 505 StringRef Group = ""; 506 if (GroupSym) 507 Group = GroupSym->getName(); 508 // Do the lookup, if we have a hit, return it. 509 auto IterBool = WasmUniquingMap.insert( 510 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr)); 511 auto &Entry = *IterBool.first; 512 if (!IterBool.second) 513 return Entry.second; 514 515 StringRef CachedName = Entry.first.SectionName; 516 517 MCSymbol *Begin = createSymbol(CachedName, false, false); 518 cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION); 519 520 MCSectionWasm *Result = new (WasmAllocator.Allocate()) 521 MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin); 522 Entry.second = Result; 523 524 auto *F = new MCDataFragment(); 525 Result->getFragmentList().insert(Result->begin(), F); 526 F->setParent(Result); 527 Begin->setFragment(F); 528 529 return Result; 530 } 531 532 MCSectionXCOFF *MCContext::getXCOFFSection(StringRef Section, 533 XCOFF::StorageMappingClass SMC, 534 SectionKind Kind, 535 const char *BeginSymName) { 536 // Do the lookup. If we have a hit, return it. 537 auto IterBool = XCOFFUniquingMap.insert( 538 std::make_pair(XCOFFSectionKey{Section.str(), SMC}, nullptr)); 539 auto &Entry = *IterBool.first; 540 if (!IterBool.second) 541 return Entry.second; 542 543 // Otherwise, return a new section. 544 StringRef CachedName = Entry.first.SectionName; 545 546 MCSymbol *Begin = nullptr; 547 if (BeginSymName) 548 Begin = createTempSymbol(BeginSymName, false); 549 550 MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate()) 551 MCSectionXCOFF(CachedName, SMC, Kind, Begin); 552 Entry.second = Result; 553 554 auto *F = new MCDataFragment(); 555 Result->getFragmentList().insert(Result->begin(), F); 556 F->setParent(Result); 557 558 if (Begin) 559 Begin->setFragment(F); 560 561 return Result; 562 } 563 564 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { 565 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); 566 } 567 568 void MCContext::addDebugPrefixMapEntry(const std::string &From, 569 const std::string &To) { 570 DebugPrefixMap.insert(std::make_pair(From, To)); 571 } 572 573 void MCContext::RemapDebugPaths() { 574 const auto &DebugPrefixMap = this->DebugPrefixMap; 575 const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) { 576 for (const auto &Entry : DebugPrefixMap) 577 if (StringRef(Path).startswith(Entry.first)) { 578 std::string RemappedPath = 579 (Twine(Entry.second) + Path.substr(Entry.first.size())).str(); 580 Path.swap(RemappedPath); 581 } 582 }; 583 584 // Remap compilation directory. 585 std::string CompDir = CompilationDir.str(); 586 RemapDebugPath(CompDir); 587 CompilationDir = CompDir; 588 589 // Remap MCDwarfDirs in all compilation units. 590 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) 591 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) 592 RemapDebugPath(Dir); 593 } 594 595 //===----------------------------------------------------------------------===// 596 // Dwarf Management 597 //===----------------------------------------------------------------------===// 598 599 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) { 600 // MCDwarf needs the root file as well as the compilation directory. 601 // If we find a '.file 0' directive that will supersede these values. 602 Optional<MD5::MD5Result> Cksum; 603 if (getDwarfVersion() >= 5) { 604 MD5 Hash; 605 MD5::MD5Result Sum; 606 Hash.update(Buffer); 607 Hash.final(Sum); 608 Cksum = Sum; 609 } 610 // Canonicalize the root filename. It cannot be empty, and should not 611 // repeat the compilation dir. 612 // The MCContext ctor initializes MainFileName to the name associated with 613 // the SrcMgr's main file ID, which might be the same as InputFileName (and 614 // possibly include directory components). 615 // Or, MainFileName might have been overridden by a -main-file-name option, 616 // which is supposed to be just a base filename with no directory component. 617 // So, if the InputFileName and MainFileName are not equal, assume 618 // MainFileName is a substitute basename and replace the last component. 619 SmallString<1024> FileNameBuf = InputFileName; 620 if (FileNameBuf.empty() || FileNameBuf == "-") 621 FileNameBuf = "<stdin>"; 622 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) { 623 llvm::sys::path::remove_filename(FileNameBuf); 624 llvm::sys::path::append(FileNameBuf, getMainFileName()); 625 } 626 StringRef FileName = FileNameBuf; 627 if (FileName.consume_front(getCompilationDir())) 628 if (llvm::sys::path::is_separator(FileName.front())) 629 FileName = FileName.drop_front(); 630 assert(!FileName.empty()); 631 setMCLineTableRootFile( 632 /*CUID=*/0, getCompilationDir(), FileName, Cksum, None); 633 } 634 635 /// getDwarfFile - takes a file name and number to place in the dwarf file and 636 /// directory tables. If the file number has already been allocated it is an 637 /// error and zero is returned and the client reports the error, else the 638 /// allocated file number is returned. The file numbers may be in any order. 639 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory, 640 StringRef FileName, 641 unsigned FileNumber, 642 Optional<MD5::MD5Result> Checksum, 643 Optional<StringRef> Source, 644 unsigned CUID) { 645 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; 646 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, 647 FileNumber); 648 } 649 650 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it 651 /// currently is assigned and false otherwise. 652 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { 653 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID); 654 if (FileNumber == 0) 655 return getDwarfVersion() >= 5; 656 if (FileNumber >= LineTable.getMCDwarfFiles().size()) 657 return false; 658 659 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty(); 660 } 661 662 /// Remove empty sections from SectionsForRanges, to avoid generating 663 /// useless debug info for them. 664 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) { 665 SectionsForRanges.remove_if( 666 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); }); 667 } 668 669 CodeViewContext &MCContext::getCVContext() { 670 if (!CVContext.get()) 671 CVContext.reset(new CodeViewContext); 672 return *CVContext.get(); 673 } 674 675 //===----------------------------------------------------------------------===// 676 // Error Reporting 677 //===----------------------------------------------------------------------===// 678 679 void MCContext::reportError(SMLoc Loc, const Twine &Msg) { 680 HadError = true; 681 682 // If we have a source manager use it. Otherwise, try using the inline source 683 // manager. 684 // If that fails, use the generic report_fatal_error(). 685 if (SrcMgr) 686 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); 687 else if (InlineSrcMgr) 688 InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); 689 else 690 report_fatal_error(Msg, false); 691 } 692 693 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) { 694 reportError(Loc, Msg); 695 696 // If we reached here, we are failing ungracefully. Run the interrupt handlers 697 // to make sure any special cleanups get done, in particular that we remove 698 // files registered with RemoveFileOnSignal. 699 sys::RunInterruptHandlers(); 700 exit(1); 701 } 702