Revert " [LoongArch][ISel] Check the number of sign bits in `PatGprGpr_32` (#107432)"
[llvm-project.git] / llvm / lib / MC / MCContext.cpp
blob228c4fb03a276ed72320a281736897f7b78b3185
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 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCContext.h"
10 #include "llvm/ADT/SmallString.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/StringMap.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/BinaryFormat/COFF.h"
16 #include "llvm/BinaryFormat/ELF.h"
17 #include "llvm/BinaryFormat/Wasm.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/MCInst.h"
25 #include "llvm/MC/MCLabel.h"
26 #include "llvm/MC/MCSectionCOFF.h"
27 #include "llvm/MC/MCSectionDXContainer.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCSectionGOFF.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCSectionSPIRV.h"
32 #include "llvm/MC/MCSectionWasm.h"
33 #include "llvm/MC/MCSectionXCOFF.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/MC/MCSymbolCOFF.h"
38 #include "llvm/MC/MCSymbolELF.h"
39 #include "llvm/MC/MCSymbolGOFF.h"
40 #include "llvm/MC/MCSymbolMachO.h"
41 #include "llvm/MC/MCSymbolWasm.h"
42 #include "llvm/MC/MCSymbolXCOFF.h"
43 #include "llvm/MC/MCTargetOptions.h"
44 #include "llvm/MC/SectionKind.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/EndianStream.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 <optional>
57 #include <tuple>
58 #include <utility>
60 using namespace llvm;
62 static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
63 std::vector<const MDNode *> &) {
64 SMD.print(nullptr, errs());
67 MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
68 const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
69 const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
70 bool DoAutoReset, StringRef Swift5ReflSegmentName)
71 : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
72 SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
73 MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator),
74 InlineAsmUsedLabelNames(Allocator),
75 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
76 AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
77 SaveTempLabels = TargetOptions && TargetOptions->MCSaveTempLabels;
78 SecureLogFile = TargetOptions ? TargetOptions->AsSecureLogFile : "";
80 if (SrcMgr && SrcMgr->getNumBuffers())
81 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
82 ->getBufferIdentifier());
84 switch (TheTriple.getObjectFormat()) {
85 case Triple::MachO:
86 Env = IsMachO;
87 break;
88 case Triple::COFF:
89 if (!TheTriple.isOSWindows() && !TheTriple.isUEFI())
90 report_fatal_error(
91 "Cannot initialize MC for non-Windows COFF object files.");
93 Env = IsCOFF;
94 break;
95 case Triple::ELF:
96 Env = IsELF;
97 break;
98 case Triple::Wasm:
99 Env = IsWasm;
100 break;
101 case Triple::XCOFF:
102 Env = IsXCOFF;
103 break;
104 case Triple::GOFF:
105 Env = IsGOFF;
106 break;
107 case Triple::DXContainer:
108 Env = IsDXContainer;
109 break;
110 case Triple::SPIRV:
111 Env = IsSPIRV;
112 break;
113 case Triple::UnknownObjectFormat:
114 report_fatal_error("Cannot initialize MC for unknown object file format.");
115 break;
119 MCContext::~MCContext() {
120 if (AutoReset)
121 reset();
123 // NOTE: The symbols are all allocated out of a bump pointer allocator,
124 // we don't need to free them here.
127 void MCContext::initInlineSourceManager() {
128 if (!InlineSrcMgr)
129 InlineSrcMgr.reset(new SourceMgr());
132 //===----------------------------------------------------------------------===//
133 // Module Lifetime Management
134 //===----------------------------------------------------------------------===//
136 void MCContext::reset() {
137 SrcMgr = nullptr;
138 InlineSrcMgr.reset();
139 LocInfos.clear();
140 DiagHandler = defaultDiagHandler;
142 // Call the destructors so the fragments are freed
143 COFFAllocator.DestroyAll();
144 DXCAllocator.DestroyAll();
145 ELFAllocator.DestroyAll();
146 GOFFAllocator.DestroyAll();
147 MachOAllocator.DestroyAll();
148 WasmAllocator.DestroyAll();
149 XCOFFAllocator.DestroyAll();
150 MCInstAllocator.DestroyAll();
151 SPIRVAllocator.DestroyAll();
152 WasmSignatureAllocator.DestroyAll();
154 // ~CodeViewContext may destroy a MCFragment outside of sections and need to
155 // be reset before FragmentAllocator.
156 CVContext.reset();
158 MCSubtargetAllocator.DestroyAll();
159 InlineAsmUsedLabelNames.clear();
160 Symbols.clear();
161 Allocator.Reset();
162 FragmentAllocator.Reset();
163 Instances.clear();
164 CompilationDir.clear();
165 MainFileName.clear();
166 MCDwarfLineTablesCUMap.clear();
167 SectionsForRanges.clear();
168 MCGenDwarfLabelEntries.clear();
169 DwarfDebugFlags = StringRef();
170 DwarfCompileUnitID = 0;
171 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
173 MachOUniquingMap.clear();
174 ELFUniquingMap.clear();
175 GOFFUniquingMap.clear();
176 COFFUniquingMap.clear();
177 WasmUniquingMap.clear();
178 XCOFFUniquingMap.clear();
179 DXCUniquingMap.clear();
181 ELFEntrySizeMap.clear();
182 ELFSeenGenericMergeableSections.clear();
184 DwarfLocSeen = false;
185 GenDwarfForAssembly = false;
186 GenDwarfFileNumber = 0;
188 HadError = false;
191 //===----------------------------------------------------------------------===//
192 // MCInst Management
193 //===----------------------------------------------------------------------===//
195 MCInst *MCContext::createMCInst() {
196 return new (MCInstAllocator.Allocate()) MCInst;
199 // Allocate the initial MCDataFragment for the begin symbol.
200 MCDataFragment *MCContext::allocInitialFragment(MCSection &Sec) {
201 assert(!Sec.curFragList()->Head);
202 auto *F = allocFragment<MCDataFragment>();
203 F->setParent(&Sec);
204 Sec.curFragList()->Head = F;
205 Sec.curFragList()->Tail = F;
206 return F;
209 //===----------------------------------------------------------------------===//
210 // Symbol Manipulation
211 //===----------------------------------------------------------------------===//
213 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
214 SmallString<128> NameSV;
215 StringRef NameRef = Name.toStringRef(NameSV);
217 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
219 MCSymbolTableEntry &Entry = getSymbolTableEntry(NameRef);
220 if (!Entry.second.Symbol) {
221 bool IsRenamable = NameRef.starts_with(MAI->getPrivateGlobalPrefix());
222 bool IsTemporary = IsRenamable && !SaveTempLabels;
223 if (!Entry.second.Used) {
224 Entry.second.Used = true;
225 Entry.second.Symbol = createSymbolImpl(&Entry, IsTemporary);
226 } else {
227 assert(IsRenamable && "cannot rename non-private symbol");
228 // Slow path: we need to rename a temp symbol from the user.
229 Entry.second.Symbol = createRenamableSymbol(NameRef, false, IsTemporary);
233 return Entry.second.Symbol;
236 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(const Twine &FuncName,
237 unsigned Idx) {
238 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +
239 "$frame_escape_" + Twine(Idx));
242 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(const Twine &FuncName) {
243 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +
244 "$parent_frame_offset");
247 MCSymbol *MCContext::getOrCreateLSDASymbol(const Twine &FuncName) {
248 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + "__ehtable$" +
249 FuncName);
252 MCSymbolTableEntry &MCContext::getSymbolTableEntry(StringRef Name) {
253 return *Symbols.try_emplace(Name, MCSymbolTableValue{}).first;
256 MCSymbol *MCContext::createSymbolImpl(const MCSymbolTableEntry *Name,
257 bool IsTemporary) {
258 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
259 "MCSymbol classes must be trivially destructible");
260 static_assert(std::is_trivially_destructible<MCSymbolELF>(),
261 "MCSymbol classes must be trivially destructible");
262 static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
263 "MCSymbol classes must be trivially destructible");
264 static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
265 "MCSymbol classes must be trivially destructible");
266 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
267 "MCSymbol classes must be trivially destructible");
269 switch (getObjectFileType()) {
270 case MCContext::IsCOFF:
271 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
272 case MCContext::IsELF:
273 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
274 case MCContext::IsGOFF:
275 return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
276 case MCContext::IsMachO:
277 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
278 case MCContext::IsWasm:
279 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
280 case MCContext::IsXCOFF:
281 return createXCOFFSymbolImpl(Name, IsTemporary);
282 case MCContext::IsDXContainer:
283 break;
284 case MCContext::IsSPIRV:
285 return new (Name, *this)
286 MCSymbol(MCSymbol::SymbolKindUnset, Name, IsTemporary);
288 return new (Name, *this)
289 MCSymbol(MCSymbol::SymbolKindUnset, Name, IsTemporary);
292 MCSymbol *MCContext::createRenamableSymbol(const Twine &Name,
293 bool AlwaysAddSuffix,
294 bool IsTemporary) {
295 SmallString<128> NewName;
296 Name.toVector(NewName);
297 size_t NameLen = NewName.size();
299 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(NewName.str());
300 MCSymbolTableEntry *EntryPtr = &NameEntry;
301 while (AlwaysAddSuffix || EntryPtr->second.Used) {
302 AlwaysAddSuffix = false;
304 NewName.resize(NameLen);
305 raw_svector_ostream(NewName) << NameEntry.second.NextUniqueID++;
306 EntryPtr = &getSymbolTableEntry(NewName.str());
309 EntryPtr->second.Used = true;
310 return createSymbolImpl(EntryPtr, IsTemporary);
313 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
314 if (!UseNamesOnTempLabels)
315 return createSymbolImpl(nullptr, /*IsTemporary=*/true);
316 return createRenamableSymbol(MAI->getPrivateGlobalPrefix() + Name,
317 AlwaysAddSuffix, /*IsTemporary=*/true);
320 MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
321 return createRenamableSymbol(MAI->getPrivateGlobalPrefix() + Name, true,
322 /*IsTemporary=*/!SaveTempLabels);
325 MCSymbol *MCContext::createBlockSymbol(const Twine &Name, bool AlwaysEmit) {
326 if (AlwaysEmit)
327 return getOrCreateSymbol(MAI->getPrivateLabelPrefix() + Name);
329 bool IsTemporary = !SaveTempLabels;
330 if (IsTemporary && !UseNamesOnTempLabels)
331 return createSymbolImpl(nullptr, IsTemporary);
332 return createRenamableSymbol(MAI->getPrivateLabelPrefix() + Name,
333 /*AlwaysAddSuffix=*/false, IsTemporary);
336 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
337 return createLinkerPrivateSymbol("tmp");
340 MCSymbol *MCContext::createLinkerPrivateSymbol(const Twine &Name) {
341 return createRenamableSymbol(MAI->getLinkerPrivateGlobalPrefix() + Name,
342 /*AlwaysAddSuffix=*/true,
343 /*IsTemporary=*/false);
346 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
348 MCSymbol *MCContext::createNamedTempSymbol() {
349 return createNamedTempSymbol("tmp");
352 MCSymbol *MCContext::createLocalSymbol(StringRef Name) {
353 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name);
354 return createSymbolImpl(&NameEntry, /*IsTemporary=*/false);
357 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
358 MCLabel *&Label = Instances[LocalLabelVal];
359 if (!Label)
360 Label = new (*this) MCLabel(0);
361 return Label->incInstance();
364 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
365 MCLabel *&Label = Instances[LocalLabelVal];
366 if (!Label)
367 Label = new (*this) MCLabel(0);
368 return Label->getInstance();
371 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
372 unsigned Instance) {
373 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
374 if (!Sym)
375 Sym = createNamedTempSymbol();
376 return Sym;
379 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
380 unsigned Instance = NextInstance(LocalLabelVal);
381 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
384 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
385 bool Before) {
386 unsigned Instance = GetInstance(LocalLabelVal);
387 if (!Before)
388 ++Instance;
389 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
392 template <typename Symbol>
393 Symbol *MCContext::getOrCreateSectionSymbol(StringRef Section) {
394 Symbol *R;
395 auto &SymEntry = getSymbolTableEntry(Section);
396 MCSymbol *Sym = SymEntry.second.Symbol;
397 // A section symbol can not redefine regular symbols. There may be multiple
398 // sections with the same name, in which case the first such section wins.
399 if (Sym && Sym->isDefined() &&
400 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
401 reportError(SMLoc(), "invalid symbol redefinition");
402 if (Sym && Sym->isUndefined()) {
403 R = cast<Symbol>(Sym);
404 } else {
405 SymEntry.second.Used = true;
406 R = new (&SymEntry, *this) Symbol(&SymEntry, /*isTemporary=*/false);
407 if (!Sym)
408 SymEntry.second.Symbol = R;
410 return R;
413 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
414 SmallString<128> NameSV;
415 StringRef NameRef = Name.toStringRef(NameSV);
416 return Symbols.lookup(NameRef).Symbol;
419 void MCContext::setSymbolValue(MCStreamer &Streamer, const Twine &Sym,
420 uint64_t Val) {
421 auto Symbol = getOrCreateSymbol(Sym);
422 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
425 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
426 InlineAsmUsedLabelNames[Sym->getName()] = Sym;
429 wasm::WasmSignature *MCContext::createWasmSignature() {
430 return new (WasmSignatureAllocator.Allocate()) wasm::WasmSignature;
433 MCSymbolXCOFF *MCContext::createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
434 bool IsTemporary) {
435 if (!Name)
436 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
438 StringRef OriginalName = Name->first();
439 if (OriginalName.starts_with("._Renamed..") ||
440 OriginalName.starts_with("_Renamed.."))
441 reportError(SMLoc(), "invalid symbol name from source");
443 if (MAI->isValidUnquotedName(OriginalName))
444 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
446 // Now we have a name that contains invalid character(s) for XCOFF symbol.
447 // Let's replace with something valid, but save the original name so that
448 // we could still use the original name in the symbol table.
449 SmallString<128> InvalidName(OriginalName);
451 // If it's an entry point symbol, we will keep the '.'
452 // in front for the convention purpose. Otherwise, add "_Renamed.."
453 // as prefix to signal this is an renamed symbol.
454 const bool IsEntryPoint = InvalidName.starts_with(".");
455 SmallString<128> ValidName =
456 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
458 // Append the hex values of '_' and invalid characters with "_Renamed..";
459 // at the same time replace invalid characters with '_'.
460 for (size_t I = 0; I < InvalidName.size(); ++I) {
461 if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
462 raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
463 InvalidName[I] = '_';
467 // Skip entry point symbol's '.' as we already have a '.' in front of
468 // "_Renamed".
469 if (IsEntryPoint)
470 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
471 else
472 ValidName.append(InvalidName);
474 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(ValidName.str());
475 assert(!NameEntry.second.Used && "This name is used somewhere else.");
476 NameEntry.second.Used = true;
477 // Have the MCSymbol object itself refer to the copy of the string
478 // that is embedded in the symbol table entry.
479 MCSymbolXCOFF *XSym =
480 new (&NameEntry, *this) MCSymbolXCOFF(&NameEntry, IsTemporary);
481 XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
482 return XSym;
485 //===----------------------------------------------------------------------===//
486 // Section Management
487 //===----------------------------------------------------------------------===//
489 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
490 unsigned TypeAndAttributes,
491 unsigned Reserved2, SectionKind Kind,
492 const char *BeginSymName) {
493 // We unique sections by their segment/section pair. The returned section
494 // may not have the same flags as the requested section, if so this should be
495 // diagnosed by the client as an error.
497 // Form the name to look up.
498 assert(Section.size() <= 16 && "section name is too long");
499 assert(!memchr(Section.data(), '\0', Section.size()) &&
500 "section name cannot contain NUL");
502 // Do the lookup, if we have a hit, return it.
503 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
504 if (!R.second)
505 return R.first->second;
507 MCSymbol *Begin = nullptr;
508 if (BeginSymName)
509 Begin = createTempSymbol(BeginSymName, false);
511 // Otherwise, return a new section.
512 StringRef Name = R.first->first();
513 auto *Ret = new (MachOAllocator.Allocate())
514 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
515 TypeAndAttributes, Reserved2, Kind, Begin);
516 R.first->second = Ret;
517 allocInitialFragment(*Ret);
518 return Ret;
521 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
522 unsigned Flags,
523 unsigned EntrySize,
524 const MCSymbolELF *Group,
525 bool Comdat, unsigned UniqueID,
526 const MCSymbolELF *LinkedToSym) {
527 auto *R = getOrCreateSectionSymbol<MCSymbolELF>(Section);
528 R->setBinding(ELF::STB_LOCAL);
529 R->setType(ELF::STT_SECTION);
531 auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
532 Section, Type, Flags, EntrySize, Group, Comdat, UniqueID, R, LinkedToSym);
534 auto *F = allocInitialFragment(*Ret);
535 R->setFragment(F);
536 return Ret;
539 MCSectionELF *
540 MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
541 unsigned EntrySize, const MCSymbolELF *Group,
542 const MCSectionELF *RelInfoSection) {
543 StringMap<bool>::iterator I;
544 bool Inserted;
545 std::tie(I, Inserted) = RelSecNames.insert(std::make_pair(Name.str(), true));
547 return createELFSectionImpl(
548 I->getKey(), Type, Flags, EntrySize, Group, true, true,
549 cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
552 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
553 const Twine &Suffix, unsigned Type,
554 unsigned Flags,
555 unsigned EntrySize) {
556 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
557 /*IsComdat=*/true);
560 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
561 unsigned Flags, unsigned EntrySize,
562 const Twine &Group, bool IsComdat,
563 unsigned UniqueID,
564 const MCSymbolELF *LinkedToSym) {
565 MCSymbolELF *GroupSym = nullptr;
566 if (!Group.isTriviallyEmpty() && !Group.str().empty())
567 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
569 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
570 UniqueID, LinkedToSym);
573 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
574 unsigned Flags, unsigned EntrySize,
575 const MCSymbolELF *GroupSym,
576 bool IsComdat, unsigned UniqueID,
577 const MCSymbolELF *LinkedToSym) {
578 StringRef Group = "";
579 if (GroupSym)
580 Group = GroupSym->getName();
581 assert(!(LinkedToSym && LinkedToSym->getName().empty()));
583 // Sections are differentiated by the quadruple (section_name, group_name,
584 // unique_id, link_to_symbol_name). Sections sharing the same quadruple are
585 // combined into one section. As an optimization, non-unique sections without
586 // group or linked-to symbol have a shorter unique-ing key.
587 std::pair<StringMap<MCSectionELF *>::iterator, bool> EntryNewPair;
588 // Length of the section name, which are the first SectionLen bytes of the key
589 unsigned SectionLen;
590 if (GroupSym || LinkedToSym || UniqueID != MCSection::NonUniqueID) {
591 SmallString<128> Buffer;
592 Section.toVector(Buffer);
593 SectionLen = Buffer.size();
594 Buffer.push_back(0); // separator which cannot occur in the name
595 if (GroupSym)
596 Buffer.append(GroupSym->getName());
597 Buffer.push_back(0); // separator which cannot occur in the name
598 if (LinkedToSym)
599 Buffer.append(LinkedToSym->getName());
600 support::endian::write(Buffer, UniqueID, endianness::native);
601 StringRef UniqueMapKey = StringRef(Buffer);
602 EntryNewPair = ELFUniquingMap.insert(std::make_pair(UniqueMapKey, nullptr));
603 } else if (!Section.isSingleStringRef()) {
604 SmallString<128> Buffer;
605 StringRef UniqueMapKey = Section.toStringRef(Buffer);
606 SectionLen = UniqueMapKey.size();
607 EntryNewPair = ELFUniquingMap.insert(std::make_pair(UniqueMapKey, nullptr));
608 } else {
609 StringRef UniqueMapKey = Section.getSingleStringRef();
610 SectionLen = UniqueMapKey.size();
611 EntryNewPair = ELFUniquingMap.insert(std::make_pair(UniqueMapKey, nullptr));
614 if (!EntryNewPair.second)
615 return EntryNewPair.first->second;
617 StringRef CachedName = EntryNewPair.first->getKey().take_front(SectionLen);
619 MCSectionELF *Result =
620 createELFSectionImpl(CachedName, Type, Flags, EntrySize, GroupSym,
621 IsComdat, UniqueID, LinkedToSym);
622 EntryNewPair.first->second = Result;
624 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
625 Result->getUniqueID(), Result->getEntrySize());
627 return Result;
630 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
631 bool IsComdat) {
632 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 4, Group, IsComdat,
633 MCSection::NonUniqueID, nullptr);
636 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
637 unsigned Flags, unsigned UniqueID,
638 unsigned EntrySize) {
639 bool IsMergeable = Flags & ELF::SHF_MERGE;
640 if (UniqueID == GenericSectionID) {
641 ELFSeenGenericMergeableSections.insert(SectionName);
642 // Minor performance optimization: avoid hash map lookup in
643 // isELFGenericMergeableSection, which will return true for SectionName.
644 IsMergeable = true;
647 // For mergeable sections or non-mergeable sections with a generic mergeable
648 // section name we enter their Unique ID into the ELFEntrySizeMap so that
649 // compatible globals can be assigned to the same section.
651 if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
652 ELFEntrySizeMap.insert(std::make_pair(
653 std::make_tuple(SectionName, Flags, EntrySize), UniqueID));
657 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
658 return SectionName.starts_with(".rodata.str") ||
659 SectionName.starts_with(".rodata.cst");
662 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
663 return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
664 ELFSeenGenericMergeableSections.count(SectionName);
667 std::optional<unsigned>
668 MCContext::getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags,
669 unsigned EntrySize) {
670 auto I = ELFEntrySizeMap.find(std::make_tuple(SectionName, Flags, EntrySize));
671 return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)
672 : std::nullopt;
675 MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind,
676 MCSection *Parent,
677 uint32_t Subsection) {
678 // Do the lookup. If we don't have a hit, return a new section.
679 auto IterBool =
680 GOFFUniquingMap.insert(std::make_pair(Section.str(), nullptr));
681 auto Iter = IterBool.first;
682 if (!IterBool.second)
683 return Iter->second;
685 StringRef CachedName = Iter->first;
686 MCSectionGOFF *GOFFSection = new (GOFFAllocator.Allocate())
687 MCSectionGOFF(CachedName, Kind, Parent, Subsection);
688 Iter->second = GOFFSection;
689 allocInitialFragment(*GOFFSection);
690 return GOFFSection;
693 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
694 unsigned Characteristics,
695 StringRef COMDATSymName, int Selection,
696 unsigned UniqueID) {
697 MCSymbol *COMDATSymbol = nullptr;
698 if (!COMDATSymName.empty()) {
699 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
700 COMDATSymName = COMDATSymbol->getName();
701 // A non-associative COMDAT is considered to define the COMDAT symbol. Check
702 // the redefinition error.
703 if (Selection != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE && COMDATSymbol &&
704 COMDATSymbol->isDefined() &&
705 (!COMDATSymbol->isInSection() ||
706 cast<MCSectionCOFF>(COMDATSymbol->getSection()).getCOMDATSymbol() !=
707 COMDATSymbol))
708 reportError(SMLoc(), "invalid symbol redefinition");
711 // Do the lookup, if we have a hit, return it.
712 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
713 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
714 auto Iter = IterBool.first;
715 if (!IterBool.second)
716 return Iter->second;
718 StringRef CachedName = Iter->first.SectionName;
719 MCSymbol *Begin = getOrCreateSectionSymbol<MCSymbolCOFF>(Section);
720 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
721 CachedName, Characteristics, COMDATSymbol, Selection, Begin);
722 Iter->second = Result;
723 auto *F = allocInitialFragment(*Result);
724 Begin->setFragment(F);
725 return Result;
728 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
729 unsigned Characteristics) {
730 return getCOFFSection(Section, Characteristics, "", 0, GenericSectionID);
733 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
734 const MCSymbol *KeySym,
735 unsigned UniqueID) {
736 // Return the normal section if we don't have to be associative or unique.
737 if (!KeySym && UniqueID == GenericSectionID)
738 return Sec;
740 // If we have a key symbol, make an associative section with the same name and
741 // kind as the normal section.
742 unsigned Characteristics = Sec->getCharacteristics();
743 if (KeySym) {
744 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
745 return getCOFFSection(Sec->getName(), Characteristics, KeySym->getName(),
746 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
749 return getCOFFSection(Sec->getName(), Characteristics, "", 0, UniqueID);
752 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
753 unsigned Flags, const Twine &Group,
754 unsigned UniqueID) {
755 MCSymbolWasm *GroupSym = nullptr;
756 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
757 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
758 GroupSym->setComdat(true);
761 return getWasmSection(Section, K, Flags, GroupSym, UniqueID);
764 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
765 unsigned Flags,
766 const MCSymbolWasm *GroupSym,
767 unsigned UniqueID) {
768 StringRef Group = "";
769 if (GroupSym)
770 Group = GroupSym->getName();
771 // Do the lookup, if we have a hit, return it.
772 auto IterBool = WasmUniquingMap.insert(
773 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
774 auto &Entry = *IterBool.first;
775 if (!IterBool.second)
776 return Entry.second;
778 StringRef CachedName = Entry.first.SectionName;
780 MCSymbol *Begin = createRenamableSymbol(CachedName, true, false);
781 // Begin always has a different name than CachedName... see #48596.
782 getSymbolTableEntry(Begin->getName()).second.Symbol = Begin;
783 cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
785 MCSectionWasm *Result = new (WasmAllocator.Allocate())
786 MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
787 Entry.second = Result;
789 auto *F = allocInitialFragment(*Result);
790 Begin->setFragment(F);
791 return Result;
794 bool MCContext::hasXCOFFSection(StringRef Section,
795 XCOFF::CsectProperties CsectProp) const {
796 return XCOFFUniquingMap.count(
797 XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
800 MCSectionXCOFF *MCContext::getXCOFFSection(
801 StringRef Section, SectionKind Kind,
802 std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
803 std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
804 bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
805 assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
807 // Do the lookup. If we have a hit, return it.
808 auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
809 IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
810 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
811 nullptr));
812 auto &Entry = *IterBool.first;
813 if (!IterBool.second) {
814 MCSectionXCOFF *ExistedEntry = Entry.second;
815 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
816 report_fatal_error("section's multiply symbols policy does not match");
818 return ExistedEntry;
821 // Otherwise, return a new section.
822 StringRef CachedName = Entry.first.SectionName;
823 MCSymbolXCOFF *QualName = nullptr;
824 // Debug section don't have storage class attribute.
825 if (IsDwarfSec)
826 QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
827 else
828 QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
829 CachedName + "[" +
830 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
832 // QualName->getUnqualifiedName() and CachedName are the same except when
833 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
834 MCSectionXCOFF *Result = nullptr;
835 if (IsDwarfSec)
836 Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
837 QualName->getUnqualifiedName(), Kind, QualName,
838 *DwarfSectionSubtypeFlags, QualName, CachedName, MultiSymbolsAllowed);
839 else
840 Result = new (XCOFFAllocator.Allocate())
841 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
842 CsectProp->Type, Kind, QualName, nullptr, CachedName,
843 MultiSymbolsAllowed);
845 Entry.second = Result;
847 auto *F = allocInitialFragment(*Result);
849 // We might miss calculating the symbols difference as absolute value before
850 // adding fixups when symbol_A without the fragment set is the csect itself
851 // and symbol_B is in it.
852 // TODO: Currently we only set the fragment for XMC_PR csects and DWARF
853 // sections because we don't have other cases that hit this problem yet.
854 if (IsDwarfSec || CsectProp->MappingClass == XCOFF::XMC_PR)
855 QualName->setFragment(F);
857 return Result;
860 MCSectionSPIRV *MCContext::getSPIRVSection() {
861 MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate()) MCSectionSPIRV();
863 allocInitialFragment(*Result);
864 return Result;
867 MCSectionDXContainer *MCContext::getDXContainerSection(StringRef Section,
868 SectionKind K) {
869 // Do the lookup, if we have a hit, return it.
870 auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
871 if (!ItInsertedPair.second)
872 return ItInsertedPair.first->second;
874 auto MapIt = ItInsertedPair.first;
875 // Grab the name from the StringMap. Since the Section is going to keep a
876 // copy of this StringRef we need to make sure the underlying string stays
877 // alive as long as we need it.
878 StringRef Name = MapIt->first();
879 MapIt->second =
880 new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
882 // The first fragment will store the header
883 allocInitialFragment(*MapIt->second);
884 return MapIt->second;
887 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
888 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
891 void MCContext::addDebugPrefixMapEntry(const std::string &From,
892 const std::string &To) {
893 DebugPrefixMap.emplace_back(From, To);
896 void MCContext::remapDebugPath(SmallVectorImpl<char> &Path) {
897 for (const auto &[From, To] : llvm::reverse(DebugPrefixMap))
898 if (llvm::sys::path::replace_path_prefix(Path, From, To))
899 break;
902 void MCContext::RemapDebugPaths() {
903 const auto &DebugPrefixMap = this->DebugPrefixMap;
904 if (DebugPrefixMap.empty())
905 return;
907 // Remap compilation directory.
908 remapDebugPath(CompilationDir);
910 // Remap MCDwarfDirs and RootFile.Name in all compilation units.
911 SmallString<256> P;
912 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
913 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
914 P = Dir;
915 remapDebugPath(P);
916 Dir = std::string(P);
919 // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
920 // DW_AT_decl_file for DWARF v5 generated for assembly source.
921 P = CUIDTablePair.second.getRootFile().Name;
922 remapDebugPath(P);
923 CUIDTablePair.second.getRootFile().Name = std::string(P);
927 //===----------------------------------------------------------------------===//
928 // Dwarf Management
929 //===----------------------------------------------------------------------===//
931 EmitDwarfUnwindType MCContext::emitDwarfUnwindInfo() const {
932 if (!TargetOptions)
933 return EmitDwarfUnwindType::Default;
934 return TargetOptions->EmitDwarfUnwind;
937 bool MCContext::emitCompactUnwindNonCanonical() const {
938 if (TargetOptions)
939 return TargetOptions->EmitCompactUnwindNonCanonical;
940 return false;
943 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
944 // MCDwarf needs the root file as well as the compilation directory.
945 // If we find a '.file 0' directive that will supersede these values.
946 std::optional<MD5::MD5Result> Cksum;
947 if (getDwarfVersion() >= 5) {
948 MD5 Hash;
949 MD5::MD5Result Sum;
950 Hash.update(Buffer);
951 Hash.final(Sum);
952 Cksum = Sum;
954 // Canonicalize the root filename. It cannot be empty, and should not
955 // repeat the compilation dir.
956 // The MCContext ctor initializes MainFileName to the name associated with
957 // the SrcMgr's main file ID, which might be the same as InputFileName (and
958 // possibly include directory components).
959 // Or, MainFileName might have been overridden by a -main-file-name option,
960 // which is supposed to be just a base filename with no directory component.
961 // So, if the InputFileName and MainFileName are not equal, assume
962 // MainFileName is a substitute basename and replace the last component.
963 SmallString<1024> FileNameBuf = InputFileName;
964 if (FileNameBuf.empty() || FileNameBuf == "-")
965 FileNameBuf = "<stdin>";
966 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
967 llvm::sys::path::remove_filename(FileNameBuf);
968 llvm::sys::path::append(FileNameBuf, getMainFileName());
970 StringRef FileName = FileNameBuf;
971 if (FileName.consume_front(getCompilationDir()))
972 if (llvm::sys::path::is_separator(FileName.front()))
973 FileName = FileName.drop_front();
974 assert(!FileName.empty());
975 setMCLineTableRootFile(
976 /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);
979 /// getDwarfFile - takes a file name and number to place in the dwarf file and
980 /// directory tables. If the file number has already been allocated it is an
981 /// error and zero is returned and the client reports the error, else the
982 /// allocated file number is returned. The file numbers may be in any order.
983 Expected<unsigned>
984 MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
985 unsigned FileNumber,
986 std::optional<MD5::MD5Result> Checksum,
987 std::optional<StringRef> Source, unsigned CUID) {
988 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
989 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
990 FileNumber);
993 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
994 /// currently is assigned and false otherwise.
995 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
996 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
997 if (FileNumber == 0)
998 return getDwarfVersion() >= 5;
999 if (FileNumber >= LineTable.getMCDwarfFiles().size())
1000 return false;
1002 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
1005 /// Remove empty sections from SectionsForRanges, to avoid generating
1006 /// useless debug info for them.
1007 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
1008 SectionsForRanges.remove_if(
1009 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
1012 CodeViewContext &MCContext::getCVContext() {
1013 if (!CVContext)
1014 CVContext.reset(new CodeViewContext(this));
1015 return *CVContext;
1018 //===----------------------------------------------------------------------===//
1019 // Error Reporting
1020 //===----------------------------------------------------------------------===//
1022 void MCContext::diagnose(const SMDiagnostic &SMD) {
1023 assert(DiagHandler && "MCContext::DiagHandler is not set");
1024 bool UseInlineSrcMgr = false;
1025 const SourceMgr *SMP = nullptr;
1026 if (SrcMgr) {
1027 SMP = SrcMgr;
1028 } else if (InlineSrcMgr) {
1029 SMP = InlineSrcMgr.get();
1030 UseInlineSrcMgr = true;
1031 } else
1032 llvm_unreachable("Either SourceMgr should be available");
1033 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
1036 void MCContext::reportCommon(
1037 SMLoc Loc,
1038 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
1039 // * MCContext::SrcMgr is null when the MC layer emits machine code for input
1040 // other than assembly file, say, for .c/.cpp/.ll/.bc.
1041 // * MCContext::InlineSrcMgr is null when the inline asm is not used.
1042 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1043 // and MCContext::InlineSrcMgr are null.
1044 SourceMgr SM;
1045 const SourceMgr *SMP = &SM;
1046 bool UseInlineSrcMgr = false;
1048 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1049 // For MC-only execution, only SrcMgr is used;
1050 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1051 // inline asm in the IR.
1052 if (Loc.isValid()) {
1053 if (SrcMgr) {
1054 SMP = SrcMgr;
1055 } else if (InlineSrcMgr) {
1056 SMP = InlineSrcMgr.get();
1057 UseInlineSrcMgr = true;
1058 } else
1059 llvm_unreachable("Either SourceMgr should be available");
1062 SMDiagnostic D;
1063 GetMessage(D, SMP);
1064 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1067 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
1068 HadError = true;
1069 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1070 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1074 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
1075 if (TargetOptions && TargetOptions->MCNoWarn)
1076 return;
1077 if (TargetOptions && TargetOptions->MCFatalWarnings) {
1078 reportError(Loc, Msg);
1079 } else {
1080 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1081 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);