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