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