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

source code of llvm/lib/MC/MCContext.cpp