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