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