LLVM 22.0.0git
MCContext.cpp
Go to the documentation of this file.
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"
12#include "llvm/ADT/StringMap.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCCodeView.h"
22#include "llvm/MC/MCDwarf.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCLabel.h"
34#include "llvm/MC/MCStreamer.h"
36#include "llvm/MC/MCSymbol.h"
38#include "llvm/MC/MCSymbolELF.h"
44#include "llvm/MC/SectionKind.h"
48#include "llvm/Support/Path.h"
49#include "llvm/Support/SMLoc.h"
52#include <cassert>
53#include <cstdlib>
54#include <optional>
55#include <tuple>
56#include <utility>
57
58using namespace llvm;
59
60static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
61 std::vector<const MDNode *> &) {
62 SMD.print(nullptr, errs());
63}
64
65MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
66 const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
67 const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
68 bool DoAutoReset, StringRef Swift5ReflSegmentName)
69 : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
70 SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
71 MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator),
72 InlineAsmUsedLabelNames(Allocator),
73 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
74 AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
75 SaveTempLabels = TargetOptions && TargetOptions->MCSaveTempLabels;
76 if (SaveTempLabels)
78 SecureLogFile = TargetOptions ? TargetOptions->AsSecureLogFile : "";
79
80 if (SrcMgr && SrcMgr->getNumBuffers())
81 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
83
84 switch (TheTriple.getObjectFormat()) {
85 case Triple::MachO:
86 Env = IsMachO;
87 break;
88 case Triple::COFF:
89 if (!TheTriple.isOSWindows() && !TheTriple.isUEFI()) {
91 "cannot initialize MC for non-Windows COFF object files");
92 }
93
94 Env = IsCOFF;
95 break;
96 case Triple::ELF:
97 Env = IsELF;
98 break;
99 case Triple::Wasm:
100 Env = IsWasm;
101 break;
102 case Triple::XCOFF:
103 Env = IsXCOFF;
104 break;
105 case Triple::GOFF:
106 Env = IsGOFF;
107 break;
109 Env = IsDXContainer;
110 break;
111 case Triple::SPIRV:
112 Env = IsSPIRV;
113 break;
115 report_fatal_error("Cannot initialize MC for unknown object file format.");
116 break;
117 }
118}
119
121 if (AutoReset)
122 reset();
123
124 // NOTE: The symbols are all allocated out of a bump pointer allocator,
125 // we don't need to free them here.
126}
127
129 if (!InlineSrcMgr)
130 InlineSrcMgr.reset(new SourceMgr());
131}
132
133//===----------------------------------------------------------------------===//
134// Module Lifetime Management
135//===----------------------------------------------------------------------===//
136
138 SrcMgr = nullptr;
139 InlineSrcMgr.reset();
140 LocInfos.clear();
141 DiagHandler = defaultDiagHandler;
142
143 // Call the destructors so the fragments are freed
144 COFFAllocator.DestroyAll();
145 DXCAllocator.DestroyAll();
146 ELFAllocator.DestroyAll();
147 GOFFAllocator.DestroyAll();
148 MachOAllocator.DestroyAll();
149 WasmAllocator.DestroyAll();
150 XCOFFAllocator.DestroyAll();
151 MCInstAllocator.DestroyAll();
152 SPIRVAllocator.DestroyAll();
153 WasmSignatureAllocator.DestroyAll();
154
155 CVContext.reset();
156
157 MCSubtargetAllocator.DestroyAll();
158 InlineAsmUsedLabelNames.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 MachOUniquingMap.clear();
172 ELFUniquingMap.clear();
173 GOFFUniquingMap.clear();
174 COFFUniquingMap.clear();
175 WasmUniquingMap.clear();
176 XCOFFUniquingMap.clear();
177 DXCUniquingMap.clear();
178
179 RelSecNames.clear();
180 MacroMap.clear();
181 ELFEntrySizeMap.clear();
182 ELFSeenGenericMergeableSections.clear();
183
184 DwarfLocSeen = false;
185 GenDwarfForAssembly = false;
186 GenDwarfFileNumber = 0;
187
188 HadError = false;
189}
190
191//===----------------------------------------------------------------------===//
192// MCInst Management
193//===----------------------------------------------------------------------===//
194
196 return new (MCInstAllocator.Allocate()) MCInst;
197}
198
199//===----------------------------------------------------------------------===//
200// Symbol Manipulation
201//===----------------------------------------------------------------------===//
202
204 SmallString<128> NameSV;
205 StringRef NameRef = Name.toStringRef(NameSV);
206 if (NameRef.contains('\\')) {
207 NameSV = NameRef;
208 size_t S = 0;
209 // Support escaped \\ and \" as in GNU Assembler. GAS issues a warning for
210 // other characters following \\, which we do not implement due to code
211 // structure.
212 for (size_t I = 0, E = NameSV.size(); I != E; ++I) {
213 char C = NameSV[I];
214 if (C == '\\' && I + 1 != E) {
215 switch (NameSV[I + 1]) {
216 case '"':
217 case '\\':
218 C = NameSV[++I];
219 break;
220 }
221 }
222 NameSV[S++] = C;
223 }
224 NameSV.resize(S);
225 NameRef = NameSV;
226 }
227
228 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
229
230 MCSymbolTableEntry &Entry = getSymbolTableEntry(NameRef);
231 if (!Entry.second.Symbol) {
232 bool IsRenamable = NameRef.starts_with(MAI->getPrivateGlobalPrefix());
233 bool IsTemporary = IsRenamable && !SaveTempLabels;
234 if (!Entry.second.Used) {
235 Entry.second.Used = true;
236 Entry.second.Symbol = createSymbolImpl(&Entry, IsTemporary);
237 } else {
238 assert(IsRenamable && "cannot rename non-private symbol");
239 // Slow path: we need to rename a temp symbol from the user.
240 Entry.second.Symbol = createRenamableSymbol(NameRef, false, IsTemporary);
241 }
242 }
243
244 return Entry.second.Symbol;
245}
246
248 unsigned Idx) {
249 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +
250 "$frame_escape_" + Twine(Idx));
251}
252
254 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +
255 "$parent_frame_offset");
256}
257
259 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + "__ehtable$" +
260 FuncName);
261}
262
263MCSymbolTableEntry &MCContext::getSymbolTableEntry(StringRef Name) {
264 return *Symbols.try_emplace(Name, MCSymbolTableValue{}).first;
265}
266
267MCSymbol *MCContext::createSymbolImpl(const MCSymbolTableEntry *Name,
268 bool IsTemporary) {
269 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
270 "MCSymbol classes must be trivially destructible");
271 static_assert(std::is_trivially_destructible<MCSymbolELF>(),
272 "MCSymbol classes must be trivially destructible");
273 static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
274 "MCSymbol classes must be trivially destructible");
275 static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
276 "MCSymbol classes must be trivially destructible");
277 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
278 "MCSymbol classes must be trivially destructible");
279
280 switch (getObjectFileType()) {
282 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
283 case MCContext::IsELF:
284 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
286 return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
288 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
290 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
292 return createXCOFFSymbolImpl(Name, IsTemporary);
294 break;
296 return new (Name, *this) MCSymbol(Name, IsTemporary);
297 }
298 return new (Name, *this) MCSymbol(Name, IsTemporary);
299}
300
302 MCSymbol *NewSym = nullptr;
303 auto Name = Sym.getNameEntryPtr();
304 switch (getObjectFileType()) {
306 NewSym =
307 new (Name, *this) MCSymbolCOFF(static_cast<const MCSymbolCOFF &>(Sym));
308 break;
309 case MCContext::IsELF:
310 NewSym =
311 new (Name, *this) MCSymbolELF(static_cast<const MCSymbolELF &>(Sym));
312 break;
314 NewSym = new (Name, *this)
315 MCSymbolMachO(static_cast<const MCSymbolMachO &>(Sym));
316 break;
317 default:
318 reportFatalUsageError(".set redefinition is not supported");
319 break;
320 }
321 // Set the name and redirect the `Symbols` entry to `NewSym`.
322 NewSym->getNameEntryPtr() = Name;
323 const_cast<MCSymbolTableEntry *>(Name)->second.Symbol = NewSym;
324 // Ensure the next `registerSymbol` call will add the new symbol to `Symbols`.
325 NewSym->setIsRegistered(false);
326
327 // Ensure the original symbol is not emitted to the symbol table.
328 Sym.IsTemporary = true;
329 return NewSym;
330}
331
332MCSymbol *MCContext::createRenamableSymbol(const Twine &Name,
333 bool AlwaysAddSuffix,
334 bool IsTemporary) {
335 SmallString<128> NewName;
336 Name.toVector(NewName);
337 size_t NameLen = NewName.size();
338
339 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(NewName.str());
340 MCSymbolTableEntry *EntryPtr = &NameEntry;
341 while (AlwaysAddSuffix || EntryPtr->second.Used) {
342 AlwaysAddSuffix = false;
343
344 NewName.resize(NameLen);
345 raw_svector_ostream(NewName) << NameEntry.second.NextUniqueID++;
346 EntryPtr = &getSymbolTableEntry(NewName.str());
347 }
348
349 EntryPtr->second.Used = true;
350 return createSymbolImpl(EntryPtr, IsTemporary);
351}
352
353MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
354 if (!UseNamesOnTempLabels)
355 return createSymbolImpl(nullptr, /*IsTemporary=*/true);
356 return createRenamableSymbol(MAI->getPrivateGlobalPrefix() + Name,
357 AlwaysAddSuffix, /*IsTemporary=*/true);
358}
359
361 return createRenamableSymbol(MAI->getPrivateGlobalPrefix() + Name, true,
362 /*IsTemporary=*/!SaveTempLabels);
363}
364
366 if (AlwaysEmit)
368
369 bool IsTemporary = !SaveTempLabels;
370 if (IsTemporary && !UseNamesOnTempLabels)
371 return createSymbolImpl(nullptr, IsTemporary);
372 return createRenamableSymbol(MAI->getPrivateLabelPrefix() + Name,
373 /*AlwaysAddSuffix=*/false, IsTemporary);
374}
375
377 return createLinkerPrivateSymbol("tmp");
378}
379
381 return createRenamableSymbol(MAI->getLinkerPrivateGlobalPrefix() + Name,
382 /*AlwaysAddSuffix=*/true,
383 /*IsTemporary=*/false);
384}
385
387
389 return createNamedTempSymbol("tmp");
390}
391
393 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name);
394 return createSymbolImpl(&NameEntry, /*IsTemporary=*/false);
395}
396
397unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
398 MCLabel *&Label = Instances[LocalLabelVal];
399 if (!Label)
400 Label = new (*this) MCLabel(0);
401 return Label->incInstance();
402}
403
404unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
405 MCLabel *&Label = Instances[LocalLabelVal];
406 if (!Label)
407 Label = new (*this) MCLabel(0);
408 return Label->getInstance();
409}
410
411MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
412 unsigned Instance) {
413 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
414 if (!Sym)
416 return Sym;
417}
418
420 unsigned Instance = NextInstance(LocalLabelVal);
421 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
422}
423
425 bool Before) {
426 unsigned Instance = GetInstance(LocalLabelVal);
427 if (!Before)
428 ++Instance;
429 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
430}
431
432// Create a section symbol, with a distinct one for each section of the same.
433// The first symbol is used for assembly code references.
434template <typename Symbol>
435Symbol *MCContext::getOrCreateSectionSymbol(StringRef Section) {
436 Symbol *R;
437 auto &SymEntry = getSymbolTableEntry(Section);
438 MCSymbol *Sym = SymEntry.second.Symbol;
439 if (Sym && Sym->isDefined() &&
440 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
441 reportError(SMLoc(), "invalid symbol redefinition");
442 // Use the symbol's index to track if it has been used as a section symbol.
443 // Set to -1 to catch potential bugs if misused as a symbol index.
444 if (Sym && Sym->getIndex() != -1u) {
445 R = static_cast<Symbol *>(Sym);
446 } else {
447 SymEntry.second.Used = true;
448 R = new (&SymEntry, *this) Symbol(&SymEntry, /*isTemporary=*/false);
449 if (!Sym)
450 SymEntry.second.Symbol = R;
451 }
452 // Mark as section symbol.
453 R->setIndex(-1u);
454 return R;
455}
456
458 SmallString<128> NameSV;
459 StringRef NameRef = Name.toStringRef(NameSV);
460 return Symbols.lookup(NameRef).Symbol;
461}
462
464 uint64_t Val) {
465 auto Symbol = getOrCreateSymbol(Sym);
466 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
467}
468
470 InlineAsmUsedLabelNames[Sym->getName()] = Sym;
471}
472
474 return new (WasmSignatureAllocator.Allocate()) wasm::WasmSignature;
475}
476
477MCSymbolXCOFF *MCContext::createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
478 bool IsTemporary) {
479 if (!Name)
480 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
481
482 StringRef OriginalName = Name->first();
483 if (OriginalName.starts_with("._Renamed..") ||
484 OriginalName.starts_with("_Renamed.."))
485 reportError(SMLoc(), "invalid symbol name from source");
486
487 if (MAI->isValidUnquotedName(OriginalName))
488 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
489
490 // Now we have a name that contains invalid character(s) for XCOFF symbol.
491 // Let's replace with something valid, but save the original name so that
492 // we could still use the original name in the symbol table.
493 SmallString<128> InvalidName(OriginalName);
494
495 // If it's an entry point symbol, we will keep the '.'
496 // in front for the convention purpose. Otherwise, add "_Renamed.."
497 // as prefix to signal this is an renamed symbol.
498 const bool IsEntryPoint = InvalidName.starts_with(".");
499 SmallString<128> ValidName =
500 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
501
502 // Append the hex values of '_' and invalid characters with "_Renamed..";
503 // at the same time replace invalid characters with '_'.
504 for (char &C : InvalidName) {
505 if (!MAI->isAcceptableChar(C) || C == '_') {
506 raw_svector_ostream(ValidName).write_hex(C);
507 C = '_';
508 }
509 }
510
511 // Skip entry point symbol's '.' as we already have a '.' in front of
512 // "_Renamed".
513 if (IsEntryPoint)
514 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
515 else
516 ValidName.append(InvalidName);
517
518 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(ValidName.str());
519 assert(!NameEntry.second.Used && "This name is used somewhere else.");
520 NameEntry.second.Used = true;
521 // Have the MCSymbol object itself refer to the copy of the string
522 // that is embedded in the symbol table entry.
523 MCSymbolXCOFF *XSym =
524 new (&NameEntry, *this) MCSymbolXCOFF(&NameEntry, IsTemporary);
526 return XSym;
527}
528
529//===----------------------------------------------------------------------===//
530// Section Management
531//===----------------------------------------------------------------------===//
532
534 unsigned TypeAndAttributes,
535 unsigned Reserved2, SectionKind Kind,
536 const char *BeginSymName) {
537 // We unique sections by their segment/section pair. The returned section
538 // may not have the same flags as the requested section, if so this should be
539 // diagnosed by the client as an error.
540
541 // Form the name to look up.
542 assert(Section.size() <= 16 && "section name is too long");
543 assert(!memchr(Section.data(), '\0', Section.size()) &&
544 "section name cannot contain NUL");
545
546 // Do the lookup, if we have a hit, return it.
547 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
548 if (!R.second)
549 return R.first->second;
550
551 MCSymbol *Begin = nullptr;
552 if (BeginSymName)
553 Begin = createTempSymbol(BeginSymName, false);
554
555 // Otherwise, return a new section.
556 StringRef Name = R.first->first();
557 auto *Ret = new (MachOAllocator.Allocate())
558 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
559 TypeAndAttributes, Reserved2, Kind, Begin);
560 R.first->second = Ret;
561 return Ret;
562}
563
564MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
565 unsigned Flags,
566 unsigned EntrySize,
567 const MCSymbolELF *Group,
568 bool Comdat, unsigned UniqueID,
569 const MCSymbolELF *LinkedToSym) {
570 auto *R = getOrCreateSectionSymbol<MCSymbolELF>(Section);
571 return new (ELFAllocator.Allocate()) MCSectionELF(
572 Section, Type, Flags, EntrySize, Group, Comdat, UniqueID, R, LinkedToSym);
573}
574
576MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
577 unsigned EntrySize, const MCSymbolELF *Group,
578 const MCSectionELF *RelInfoSection) {
580 bool Inserted;
581 std::tie(I, Inserted) = RelSecNames.insert(std::make_pair(Name.str(), true));
582
583 return createELFSectionImpl(
584 I->getKey(), Type, Flags, EntrySize, Group, true, true,
585 static_cast<const MCSymbolELF *>(RelInfoSection->getBeginSymbol()));
586}
587
589 const Twine &Suffix, unsigned Type,
590 unsigned Flags,
591 unsigned EntrySize) {
592 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
593 /*IsComdat=*/true);
594}
595
597 unsigned Flags, unsigned EntrySize,
598 const Twine &Group, bool IsComdat,
599 unsigned UniqueID,
600 const MCSymbolELF *LinkedToSym) {
601 MCSymbolELF *GroupSym = nullptr;
602 if (!Group.isTriviallyEmpty() && !Group.str().empty())
603 GroupSym = static_cast<MCSymbolELF *>(getOrCreateSymbol(Group));
604
605 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
606 UniqueID, LinkedToSym);
607}
608
610 unsigned Flags, unsigned EntrySize,
611 const MCSymbolELF *GroupSym,
612 bool IsComdat, unsigned UniqueID,
613 const MCSymbolELF *LinkedToSym) {
614 assert(!(LinkedToSym && LinkedToSym->getName().empty()));
615
616 // Sections are differentiated by the quadruple (section_name, group_name,
617 // unique_id, link_to_symbol_name). Sections sharing the same quadruple are
618 // combined into one section. As an optimization, non-unique sections without
619 // group or linked-to symbol have a shorter unique-ing key.
620 std::pair<StringMap<MCSectionELF *>::iterator, bool> EntryNewPair;
621 // Length of the section name, which are the first SectionLen bytes of the key
622 unsigned SectionLen;
623 if (GroupSym || LinkedToSym || UniqueID != MCSection::NonUniqueID) {
624 SmallString<128> Buffer;
625 Section.toVector(Buffer);
626 SectionLen = Buffer.size();
627 Buffer.push_back(0); // separator which cannot occur in the name
628 if (GroupSym)
629 Buffer.append(GroupSym->getName());
630 Buffer.push_back(0); // separator which cannot occur in the name
631 if (LinkedToSym)
632 Buffer.append(LinkedToSym->getName());
634 StringRef UniqueMapKey = StringRef(Buffer);
635 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
636 } else if (!Section.isSingleStringRef()) {
637 SmallString<128> Buffer;
638 StringRef UniqueMapKey = Section.toStringRef(Buffer);
639 SectionLen = UniqueMapKey.size();
640 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
641 } else {
642 StringRef UniqueMapKey = Section.getSingleStringRef();
643 SectionLen = UniqueMapKey.size();
644 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
645 }
646
647 if (!EntryNewPair.second)
648 return EntryNewPair.first->second;
649
650 StringRef CachedName = EntryNewPair.first->getKey().take_front(SectionLen);
651
652 MCSectionELF *Result =
653 createELFSectionImpl(CachedName, Type, Flags, EntrySize, GroupSym,
654 IsComdat, UniqueID, LinkedToSym);
655 EntryNewPair.first->second = Result;
656
657 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
658 Result->getUniqueID(), Result->getEntrySize());
659
660 return Result;
661}
662
664 bool IsComdat) {
665 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 4, Group, IsComdat,
666 MCSection::NonUniqueID, nullptr);
667}
668
670 unsigned Flags, unsigned UniqueID,
671 unsigned EntrySize) {
672 bool IsMergeable = Flags & ELF::SHF_MERGE;
673 if (UniqueID == MCSection::NonUniqueID) {
674 ELFSeenGenericMergeableSections.insert(SectionName);
675 // Minor performance optimization: avoid hash map lookup in
676 // isELFGenericMergeableSection, which will return true for SectionName.
677 IsMergeable = true;
678 }
679
680 // For mergeable sections or non-mergeable sections with a generic mergeable
681 // section name we enter their Unique ID into the ELFEntrySizeMap so that
682 // compatible globals can be assigned to the same section.
683
684 if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
685 ELFEntrySizeMap.insert(std::make_pair(
686 std::make_tuple(SectionName, Flags, EntrySize), UniqueID));
687 }
688}
689
691 return SectionName.starts_with(".rodata.str") ||
692 SectionName.starts_with(".rodata.cst");
693}
694
697 ELFSeenGenericMergeableSections.count(SectionName);
698}
699
700std::optional<unsigned>
702 unsigned EntrySize) {
703 auto I = ELFEntrySizeMap.find(std::make_tuple(SectionName, Flags, EntrySize));
704 return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)
705 : std::nullopt;
706}
707
708template <typename TAttr>
709MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
710 TAttr Attributes, MCSection *Parent,
711 bool IsVirtual) {
712 std::string UniqueName(Name);
713 if (Parent) {
714 UniqueName.append("/").append(Parent->getName());
715 if (auto *P = static_cast<MCSectionGOFF *>(Parent)->getParent())
716 UniqueName.append("/").append(P->getName());
717 }
718 // Do the lookup. If we don't have a hit, return a new section.
719 auto [Iter, Inserted] = GOFFUniquingMap.try_emplace(UniqueName);
720 if (!Inserted)
721 return Iter->second;
722
723 StringRef CachedName = StringRef(Iter->first.c_str(), Name.size());
724 MCSectionGOFF *GOFFSection = new (GOFFAllocator.Allocate())
725 MCSectionGOFF(CachedName, Kind, IsVirtual, Attributes,
726 static_cast<MCSectionGOFF *>(Parent));
727 Iter->second = GOFFSection;
728 return GOFFSection;
729}
730
731MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
732 GOFF::SDAttr SDAttributes) {
733 return getGOFFSection<GOFF::SDAttr>(Kind, Name, SDAttributes, nullptr,
734 /*IsVirtual=*/true);
735}
736
737MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
738 GOFF::EDAttr EDAttributes,
739 MCSection *Parent) {
740 return getGOFFSection<GOFF::EDAttr>(
741 Kind, Name, EDAttributes, Parent,
742 /*IsVirtual=*/EDAttributes.BindAlgorithm == GOFF::ESD_BA_Merge);
743}
744
745MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
746 GOFF::PRAttr PRAttributes,
747 MCSection *Parent) {
748 return getGOFFSection<GOFF::PRAttr>(Kind, Name, PRAttributes, Parent,
749 /*IsVirtual=*/false);
750}
751
753 unsigned Characteristics,
754 StringRef COMDATSymName, int Selection,
755 unsigned UniqueID) {
756 MCSymbol *COMDATSymbol = nullptr;
757 if (!COMDATSymName.empty()) {
758 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
759 assert(COMDATSymbol && "COMDATSymbol is null");
760 COMDATSymName = COMDATSymbol->getName();
761 // A non-associative COMDAT is considered to define the COMDAT symbol. Check
762 // the redefinition error.
764 COMDATSymbol->isDefined() &&
765 (!COMDATSymbol->isInSection() ||
766 static_cast<const MCSectionCOFF &>(COMDATSymbol->getSection())
767 .getCOMDATSymbol() != COMDATSymbol))
768 reportError(SMLoc(), "invalid symbol redefinition");
769 }
770
771 // Do the lookup, if we have a hit, return it.
772 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
773 auto [Iter, Inserted] = COFFUniquingMap.try_emplace(T);
774 if (!Inserted)
775 return Iter->second;
776
777 StringRef CachedName = Iter->first.SectionName;
778 MCSymbol *Begin = getOrCreateSectionSymbol<MCSymbolCOFF>(Section);
779 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
780 CachedName, Characteristics, COMDATSymbol, Selection, UniqueID, Begin);
781 Iter->second = Result;
782 Begin->setFragment(&Result->getDummyFragment());
783 return Result;
784}
785
787 unsigned Characteristics) {
788 return getCOFFSection(Section, Characteristics, "", 0,
790}
791
793 const MCSymbol *KeySym,
794 unsigned UniqueID) {
795 // Return the normal section if we don't have to be associative or unique.
796 if (!KeySym && UniqueID == MCSection::NonUniqueID)
797 return Sec;
798
799 // If we have a key symbol, make an associative section with the same name and
800 // kind as the normal section.
801 unsigned Characteristics = Sec->getCharacteristics();
802 if (KeySym) {
804 return getCOFFSection(Sec->getName(), Characteristics, KeySym->getName(),
806 }
807
808 return getCOFFSection(Sec->getName(), Characteristics, "", 0, UniqueID);
809}
810
812 unsigned Flags, const Twine &Group,
813 unsigned UniqueID) {
814 MCSymbolWasm *GroupSym = nullptr;
815 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
816 GroupSym = static_cast<MCSymbolWasm *>(getOrCreateSymbol(Group));
817 GroupSym->setComdat(true);
818 if (K.isMetadata() && !GroupSym->getType().has_value()) {
819 // Comdat group symbol associated with a custom section is a section
820 // symbol (not a data symbol).
822 }
823 }
824
825 return getWasmSection(Section, K, Flags, GroupSym, UniqueID);
826}
827
829 unsigned Flags,
830 const MCSymbolWasm *GroupSym,
831 unsigned UniqueID) {
832 StringRef Group = "";
833 if (GroupSym)
834 Group = GroupSym->getName();
835 // Do the lookup, if we have a hit, return it.
836 auto IterBool = WasmUniquingMap.insert(
837 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
838 auto &Entry = *IterBool.first;
839 if (!IterBool.second)
840 return Entry.second;
841
842 StringRef CachedName = Entry.first.SectionName;
843
844 MCSymbol *Begin = createRenamableSymbol(CachedName, true, false);
845 // Begin always has a different name than CachedName... see #48596.
846 getSymbolTableEntry(Begin->getName()).second.Symbol = Begin;
847 static_cast<MCSymbolWasm *>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
848
849 MCSectionWasm *Result = new (WasmAllocator.Allocate())
850 MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
851 Entry.second = Result;
852
853 return Result;
854}
855
857 XCOFF::CsectProperties CsectProp) const {
858 return XCOFFUniquingMap.count(
859 XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
860}
861
863 StringRef Section, SectionKind Kind,
864 std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
865 std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
866 bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
867 assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
868
869 // Do the lookup. If we have a hit, return it.
870 auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
871 IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
872 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
873 nullptr));
874 auto &Entry = *IterBool.first;
875 if (!IterBool.second) {
876 MCSectionXCOFF *ExistedEntry = Entry.second;
877 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
878 report_fatal_error("section's multiply symbols policy does not match");
879
880 return ExistedEntry;
881 }
882
883 // Otherwise, return a new section.
884 StringRef CachedName = Entry.first.SectionName;
885 MCSymbolXCOFF *QualName = nullptr;
886 // Debug section don't have storage class attribute.
887 if (IsDwarfSec)
888 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(CachedName));
889 else
890 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(
891 CachedName + "[" +
892 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
893
894 // QualName->getUnqualifiedName() and CachedName are the same except when
895 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
896 MCSectionXCOFF *Result = nullptr;
897 if (IsDwarfSec)
898 Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
899 QualName->getUnqualifiedName(), Kind, QualName,
900 *DwarfSectionSubtypeFlags, QualName, CachedName, MultiSymbolsAllowed);
901 else
902 Result = new (XCOFFAllocator.Allocate())
903 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
904 CsectProp->Type, Kind, QualName, nullptr, CachedName,
905 MultiSymbolsAllowed);
906
907 Entry.second = Result;
908 return Result;
909}
910
912 MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate()) MCSectionSPIRV();
913 return Result;
914}
915
917 SectionKind K) {
918 // Do the lookup, if we have a hit, return it.
919 auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
920 if (!ItInsertedPair.second)
921 return ItInsertedPair.first->second;
922
923 auto MapIt = ItInsertedPair.first;
924 // Grab the name from the StringMap. Since the Section is going to keep a
925 // copy of this StringRef we need to make sure the underlying string stays
926 // alive as long as we need it.
927 StringRef Name = MapIt->first();
928 MapIt->second =
929 new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
930
931 // The first fragment will store the header
932 return MapIt->second;
933}
934
936 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
937}
938
940 const std::string &To) {
941 DebugPrefixMap.emplace_back(From, To);
942}
943
945 for (const auto &[From, To] : llvm::reverse(DebugPrefixMap))
947 break;
948}
949
951 const auto &DebugPrefixMap = this->DebugPrefixMap;
952 if (DebugPrefixMap.empty())
953 return;
954
955 // Remap compilation directory.
956 remapDebugPath(CompilationDir);
957
958 // Remap MCDwarfDirs and RootFile.Name in all compilation units.
960 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
961 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
962 P = Dir;
964 Dir = std::string(P);
965 }
966
967 // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
968 // DW_AT_decl_file for DWARF v5 generated for assembly source.
969 P = CUIDTablePair.second.getRootFile().Name;
971 CUIDTablePair.second.getRootFile().Name = std::string(P);
972 }
973}
974
975//===----------------------------------------------------------------------===//
976// Dwarf Management
977//===----------------------------------------------------------------------===//
978
980 if (!TargetOptions)
982 return TargetOptions->EmitDwarfUnwind;
983}
984
986 if (TargetOptions)
987 return TargetOptions->EmitCompactUnwindNonCanonical;
988 return false;
989}
990
992 // MCDwarf needs the root file as well as the compilation directory.
993 // If we find a '.file 0' directive that will supersede these values.
994 std::optional<MD5::MD5Result> Cksum;
995 if (getDwarfVersion() >= 5) {
996 MD5 Hash;
997 MD5::MD5Result Sum;
998 Hash.update(Buffer);
999 Hash.final(Sum);
1000 Cksum = Sum;
1001 }
1002 // Canonicalize the root filename. It cannot be empty, and should not
1003 // repeat the compilation dir.
1004 // The MCContext ctor initializes MainFileName to the name associated with
1005 // the SrcMgr's main file ID, which might be the same as InputFileName (and
1006 // possibly include directory components).
1007 // Or, MainFileName might have been overridden by a -main-file-name option,
1008 // which is supposed to be just a base filename with no directory component.
1009 // So, if the InputFileName and MainFileName are not equal, assume
1010 // MainFileName is a substitute basename and replace the last component.
1011 SmallString<1024> FileNameBuf = InputFileName;
1012 if (FileNameBuf.empty() || FileNameBuf == "-")
1013 FileNameBuf = "<stdin>";
1014 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
1017 }
1018 StringRef FileName = FileNameBuf;
1019 if (FileName.consume_front(getCompilationDir()))
1020 if (llvm::sys::path::is_separator(FileName.front()))
1021 FileName = FileName.drop_front();
1022 assert(!FileName.empty());
1024 /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);
1025}
1026
1027/// getDwarfFile - takes a file name and number to place in the dwarf file and
1028/// directory tables. If the file number has already been allocated it is an
1029/// error and zero is returned and the client reports the error, else the
1030/// allocated file number is returned. The file numbers may be in any order.
1033 unsigned FileNumber,
1034 std::optional<MD5::MD5Result> Checksum,
1035 std::optional<StringRef> Source, unsigned CUID) {
1036 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
1037 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
1038 FileNumber);
1039}
1040
1041/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
1042/// currently is assigned and false otherwise.
1043bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
1044 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
1045 if (FileNumber == 0)
1046 return getDwarfVersion() >= 5;
1047 if (FileNumber >= LineTable.getMCDwarfFiles().size())
1048 return false;
1049
1050 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
1051}
1052
1053/// Remove empty sections from SectionsForRanges, to avoid generating
1054/// useless debug info for them.
1056 SectionsForRanges.remove_if(
1057 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
1058}
1059
1061 if (!CVContext)
1062 CVContext.reset(new CodeViewContext(this));
1063 return *CVContext;
1064}
1065
1066//===----------------------------------------------------------------------===//
1067// Error Reporting
1068//===----------------------------------------------------------------------===//
1069
1071 assert(DiagHandler && "MCContext::DiagHandler is not set");
1072 bool UseInlineSrcMgr = false;
1073 const SourceMgr *SMP = nullptr;
1074 if (SrcMgr) {
1075 SMP = SrcMgr;
1076 } else if (InlineSrcMgr) {
1077 SMP = InlineSrcMgr.get();
1078 UseInlineSrcMgr = true;
1079 } else
1080 llvm_unreachable("Either SourceMgr should be available");
1081 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
1082}
1083
1084void MCContext::reportCommon(
1085 SMLoc Loc,
1086 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
1087 // * MCContext::SrcMgr is null when the MC layer emits machine code for input
1088 // other than assembly file, say, for .c/.cpp/.ll/.bc.
1089 // * MCContext::InlineSrcMgr is null when the inline asm is not used.
1090 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1091 // and MCContext::InlineSrcMgr are null.
1092 SourceMgr SM;
1093 const SourceMgr *SMP = &SM;
1094 bool UseInlineSrcMgr = false;
1095
1096 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1097 // For MC-only execution, only SrcMgr is used;
1098 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1099 // inline asm in the IR.
1100 if (Loc.isValid()) {
1101 if (SrcMgr) {
1102 SMP = SrcMgr;
1103 } else if (InlineSrcMgr) {
1104 SMP = InlineSrcMgr.get();
1105 UseInlineSrcMgr = true;
1106 } else
1107 llvm_unreachable("Either SourceMgr should be available");
1108 }
1109
1111 GetMessage(D, SMP);
1112 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1113}
1114
1115void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
1116 HadError = true;
1117 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1118 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1119 });
1120}
1121
1122void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
1123 if (TargetOptions && TargetOptions->MCNoWarn)
1124 return;
1125 if (TargetOptions && TargetOptions->MCFatalWarnings) {
1126 reportError(Loc, Msg);
1127 } else {
1128 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1129 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
1130 });
1131 }
1132}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
amdgpu AMDGPU DAG DAG Pattern Instruction Selection
static const Function * getParent(const Value *V)
BlockVerifier::State From
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:350
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &, std::vector< const MDNode * > &)
Definition: MCContext.cpp:60
#define DWARF2_FLAG_IS_STMT
Definition: MCDwarf.h:118
This file declares the MCSectionGOFF class, which contains all of the necessary machine code sections...
This file contains the MCSymbolGOFF class.
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
Basic Register Allocator
This file defines the SmallString class.
This file defines the SmallVector class.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Definition: TextStub.cpp:1059
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
Definition: Allocator.h:124
Holds state from .cv_file and .cv_loc directives for later emission.
Definition: MCCodeView.h:144
Tagged union holding either a T or a Error.
Definition: Error.h:485
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:64
StringRef getPrivateGlobalPrefix() const
Definition: MCAsmInfo.h:545
StringRef getLinkerPrivateGlobalPrefix() const
Definition: MCAsmInfo.h:552
StringRef getPrivateLabelPrefix() const
Definition: MCAsmInfo.h:546
virtual bool isAcceptableChar(char C) const
Return true if C is an acceptable character inside a symbol name.
Definition: MCAsmInfo.cpp:100
virtual bool isValidUnquotedName(StringRef Name) const
Return true if the identifier Name does not need quotes to be syntactically correct.
Definition: MCAsmInfo.cpp:107
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:212
LLVM_ABI void remapDebugPath(SmallVectorImpl< char > &Path)
Remap one path in-place as per the debug prefix map.
Definition: MCContext.cpp:944
LLVM_ABI MCSymbol * createBlockSymbol(const Twine &Name, bool AlwaysEmit=false)
Get or create a symbol for a basic block.
Definition: MCContext.cpp:365
LLVM_ABI MCSubtargetInfo & getSubtargetCopy(const MCSubtargetInfo &STI)
Definition: MCContext.cpp:935
LLVM_ABI MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:533
Environment getObjectFileType() const
Definition: MCContext.h:392
LLVM_ABI void setSymbolValue(MCStreamer &Streamer, const Twine &Sym, uint64_t Val)
Set value for a symbol.
Definition: MCContext.cpp:463
const std::string & getMainFileName() const
Get the main file name for use in error messages and debug info.
Definition: MCContext.h:696
LLVM_ABI MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, StringRef COMDATSymName, int Selection, unsigned UniqueID=MCSection::NonUniqueID)
Definition: MCContext.cpp:752
LLVM_ABI void addDebugPrefixMapEntry(const std::string &From, const std::string &To)
Add an entry to the debug prefix map.
Definition: MCContext.cpp:939
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
Definition: MCContext.cpp:386
StringRef getCompilationDir() const
Get the compilation directory for DW_AT_comp_dir The compilation directory should be set with setComp...
Definition: MCContext.h:678
LLVM_ABI void RemapDebugPaths()
Definition: MCContext.cpp:950
LLVM_ABI MCInst * createMCInst()
Create and return a new MC instruction.
Definition: MCContext.cpp:195
LLVM_ABI MCSymbol * getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen.
Definition: MCContext.cpp:247
LLVM_ABI MCSectionELF * createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, const MCSectionELF *RelInfoSection)
Definition: MCContext.cpp:576
LLVM_ABI MCSymbol * createLinkerPrivateTempSymbol()
Create a new linker temporary symbol with the specified prefix (Name) or "tmp".
Definition: MCContext.cpp:376
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition: MCContext.h:637
LLVM_ABI void recordELFMergeableSectionInfo(StringRef SectionName, unsigned Flags, unsigned UniqueID, unsigned EntrySize)
Definition: MCContext.cpp:669
LLVM_ABI Expected< unsigned > getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source, unsigned CUID)
Creates an entry in the dwarf file and directory tables.
Definition: MCContext.cpp:1032
LLVM_ABI wasm::WasmSignature * createWasmSignature()
Allocates and returns a new WasmSignature instance (with empty parameter and return type lists).
Definition: MCContext.cpp:473
LLVM_ABI MCSectionELF * getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize=0)
Get a section with the provided group identifier.
Definition: MCContext.cpp:588
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:549
LLVM_ABI MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
Definition: MCContext.cpp:862
LLVM_ABI void diagnose(const SMDiagnostic &SMD)
Definition: MCContext.cpp:1070
LLVM_ABI bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID=0)
isValidDwarfFileNumber - takes a dwarf file number and returns true if it currently is assigned and f...
Definition: MCContext.cpp:1043
LLVM_ABI void registerInlineAsmLabel(MCSymbol *Sym)
registerInlineAsmLabel - Records that the name is a label referenced in inline assembly.
Definition: MCContext.cpp:469
LLVM_ABI MCSymbol * createLocalSymbol(StringRef Name)
Create a local, non-temporary symbol like an ELF mapping symbol.
Definition: MCContext.cpp:392
MCDwarfLineTable & getMCDwarfLineTable(unsigned CUID)
Definition: MCContext.h:713
LLVM_ABI void initInlineSourceManager()
Definition: MCContext.cpp:128
LLVM_ABI MCSymbol * getOrCreateParentFrameOffsetSymbol(const Twine &FuncName)
Definition: MCContext.cpp:253
LLVM_ABI MCSymbol * lookupSymbol(const Twine &Name) const
Get the symbol for Name, or null.
Definition: MCContext.cpp:457
LLVM_ABI bool emitCompactUnwindNonCanonical() const
Definition: MCContext.cpp:985
LLVM_ABI ~MCContext()
Definition: MCContext.cpp:120
LLVM_ABI CodeViewContext & getCVContext()
Definition: MCContext.cpp:1060
LLVM_ABI void reset()
reset - return object to right after construction state to prepare to process a new module
Definition: MCContext.cpp:137
LLVM_ABI bool isELFGenericMergeableSection(StringRef Name)
Definition: MCContext.cpp:695
LLVM_ABI MCContext(const Triple &TheTriple, const MCAsmInfo *MAI, const MCRegisterInfo *MRI, const MCSubtargetInfo *MSTI, const SourceMgr *Mgr=nullptr, MCTargetOptions const *TargetOpts=nullptr, bool DoAutoReset=true, StringRef Swift5ReflSegmentName={})
Definition: MCContext.cpp:65
LLVM_ABI std::optional< unsigned > getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags, unsigned EntrySize)
Return the unique ID of the section with the given name, flags and entry size, if it exists.
Definition: MCContext.cpp:701
LLVM_ABI MCSymbol * createDirectionalLocalSymbol(unsigned LocalLabelVal)
Create the definition of a directional local symbol for numbered label (used for "1:" definitions).
Definition: MCContext.cpp:419
LLVM_ABI void reportWarning(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1122
uint16_t getDwarfVersion() const
Definition: MCContext.h:813
LLVM_ABI void finalizeDwarfSections(MCStreamer &MCOS)
Remove empty sections from SectionsForRanges, to avoid generating useless debug info for them.
Definition: MCContext.cpp:1055
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1115
LLVM_ABI MCSymbol * getOrCreateLSDASymbol(const Twine &FuncName)
Definition: MCContext.cpp:258
LLVM_ABI MCSectionDXContainer * getDXContainerSection(StringRef Section, SectionKind K)
Get the section for the provided Section name.
Definition: MCContext.cpp:916
LLVM_ABI bool hasXCOFFSection(StringRef Section, XCOFF::CsectProperties CsectProp) const
Definition: MCContext.cpp:856
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:203
LLVM_ABI MCSymbol * createLinkerPrivateSymbol(const Twine &Name)
Definition: MCContext.cpp:380
LLVM_ABI MCSectionSPIRV * getSPIRVSection()
Definition: MCContext.cpp:911
LLVM_ABI MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=MCSection::NonUniqueID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym.
Definition: MCContext.cpp:792
LLVM_ABI MCSymbol * cloneSymbol(MCSymbol &Sym)
Clone a symbol for the .set directive, replacing it in the symbol table.
Definition: MCContext.cpp:301
LLVM_ABI EmitDwarfUnwindType emitDwarfUnwindInfo() const
Definition: MCContext.cpp:979
LLVM_ABI bool isELFImplicitMergeableSectionNamePrefix(StringRef Name)
Definition: MCContext.cpp:690
LLVM_ABI MCSectionELF * createELFGroupSection(const MCSymbolELF *Group, bool IsComdat)
Definition: MCContext.cpp:663
void setUseNamesOnTempLabels(bool Value)
Definition: MCContext.h:424
LLVM_ABI void setGenDwarfRootFile(StringRef FileName, StringRef Buffer)
Specifies information about the "root file" for assembler clients (e.g., llvm-mc).
Definition: MCContext.cpp:991
void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir, StringRef Filename, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source)
Specifies the "root" file and directory of the compilation unit.
Definition: MCContext.h:737
LLVM_ABI MCSymbol * getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before)
Create and return a directional local symbol for numbered label (used for "1b" or 1f" references).
Definition: MCContext.cpp:424
LLVM_ABI MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
Definition: MCContext.cpp:388
LLVM_ABI Expected< unsigned > tryGetFile(StringRef &Directory, StringRef &FileName, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source, uint16_t DwarfVersion, unsigned FileNumber=0)
Definition: MCDwarf.cpp:621
const SmallVectorImpl< MCDwarfFile > & getMCDwarfFiles() const
Definition: MCDwarf.h:442
Instances of this class represent the information from a dwarf .loc directive.
Definition: MCDwarf.h:106
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:188
Instances of this class represent a label name in the MC file, and MCLabel are created and uniqued by...
Definition: MCLabel.h:23
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This represents a section on Windows.
Definition: MCSectionCOFF.h:27
MCSymbol * getCOMDATSymbol() const
Definition: MCSectionCOFF.h:74
unsigned getCharacteristics() const
Definition: MCSectionCOFF.h:73
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
This represents a section on a Mach-O system (used by Mac OS X).
This represents a section on wasm.
Definition: MCSectionWasm.h:26
bool isMultiSymbolsAllowed() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:496
static constexpr unsigned NonUniqueID
Definition: MCSection.h:501
StringRef getName() const
Definition: MCSection.h:565
MCSymbol * getBeginSymbol()
Definition: MCSection.h:568
Streaming machine code generation interface.
Definition: MCStreamer.h:220
virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value)
Emit an assignment of Value to Symbol.
virtual bool mayHaveInstructions(MCSection &Sec) const
Definition: MCStreamer.h:1086
Generic base class for all target subtargets.
void setComdat(bool isComdat)
Definition: MCSymbolWasm.h:83
void setType(wasm::WasmSymbolType type)
Definition: MCSymbolWasm.h:55
std::optional< wasm::WasmSymbolType > getType() const
Definition: MCSymbolWasm.h:53
static StringRef getUnqualifiedName(StringRef Name)
Definition: MCSymbolXCOFF.h:30
void setSymbolTableName(StringRef STN)
Definition: MCSymbolXCOFF.h:63
StringRef getUnqualifiedName() const
Definition: MCSymbolXCOFF.h:51
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:233
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:237
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:188
void setFragment(MCFragment *F) const
Mark the symbol as defined in the fragment F.
Definition: MCSymbol.h:257
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:251
void setIsRegistered(bool Value) const
Definition: MCSymbol.h:196
Definition: MD5.h:42
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition: MD5.cpp:189
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:77
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:282
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
Definition: SourceMgr.cpp:484
Represents a location in source code.
Definition: SMLoc.h:23
constexpr bool isValid() const
Definition: SMLoc.h:29
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:254
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void resize(size_type N)
Definition: SmallVector.h:639
void push_back(const T &Elt)
Definition: SmallVector.h:414
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:32
unsigned getMainFileID() const
Definition: SourceMgr.h:133
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:126
unsigned getNumBuffers() const
Definition: SourceMgr.h:131
LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
Definition: SourceMgr.cpp:274
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: StringMap.h:257
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition: StringMap.h:372
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:312
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:269
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:619
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
char front() const
front - Get the first character in the string.
Definition: StringRef.h:157
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:434
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:645
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition: StringRef.h:590
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition: Triple.h:434
bool isUEFI() const
Tests whether the OS is UEFI.
Definition: Triple.h:671
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:676
@ DXContainer
Definition: Triple.h:318
@ UnknownObjectFormat
Definition: Triple.h:315
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition: Twine.h:431
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_SCN_LNK_COMDAT
Definition: COFF.h:309
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition: COFF.h:459
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHT_GROUP
Definition: ELF.h:1154
@ SHF_MERGE
Definition: ELF.h:1246
@ ESD_BA_Merge
Definition: GOFF.h:99
DwarfSectionSubtypeFlags
Values for defining the section subtype of sections of type STYP_DWARF as they would appear in the (s...
Definition: XCOFF.h:155
LLVM_ABI StringRef getMappingClassString(XCOFF::StorageMappingClass SMC)
Definition: XCOFF.cpp:22
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:92
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:474
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition: Path.cpp:518
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:456
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition: Path.cpp:601
@ WASM_SYMBOL_TYPE_SECTION
Definition: Wasm.h:223
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
SourceMgr SrcMgr
Definition: Error.cpp:24
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
EmitDwarfUnwindType
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition: Error.cpp:180
GOFF::ESDBindingAlgorithm BindAlgorithm
The value for an entry in the symbol table of an MCContext.
MCSymbol * Symbol
The symbol associated with the name, if any.
StorageMappingClass MappingClass
Definition: XCOFF.h:502