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/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"
61 static void defaultDiagHandler(const SMDiagnostic
&SMD
, bool, const SourceMgr
&,
62 std::vector
<const MDNode
*> &) {
63 SMD
.print(nullptr, errs());
66 MCContext::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
: "";
78 if (SrcMgr
&& SrcMgr
->getNumBuffers())
79 MainFileName
= std::string(SrcMgr
->getMemoryBuffer(SrcMgr
->getMainFileID())
80 ->getBufferIdentifier());
82 switch (TheTriple
.getObjectFormat()) {
87 if (!TheTriple
.isOSWindows() && !TheTriple
.isUEFI())
89 "Cannot initialize MC for non-Windows COFF object files.");
105 case Triple::DXContainer
:
111 case Triple::UnknownObjectFormat
:
112 report_fatal_error("Cannot initialize MC for unknown object file format.");
117 MCContext::~MCContext() {
121 // NOTE: The symbols are all allocated out of a bump pointer allocator,
122 // we don't need to free them here.
125 void MCContext::initInlineSourceManager() {
127 InlineSrcMgr
.reset(new SourceMgr());
130 //===----------------------------------------------------------------------===//
131 // Module Lifetime Management
132 //===----------------------------------------------------------------------===//
134 void MCContext::reset() {
136 InlineSrcMgr
.reset();
138 DiagHandler
= defaultDiagHandler
;
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();
151 MCSubtargetAllocator
.DestroyAll();
152 InlineAsmUsedLabelNames
.clear();
157 CompilationDir
.clear();
158 MainFileName
.clear();
159 MCDwarfLineTablesCUMap
.clear();
160 SectionsForRanges
.clear();
161 MCGenDwarfLabelEntries
.clear();
162 DwarfDebugFlags
= StringRef();
163 DwarfCompileUnitID
= 0;
164 CurrentDwarfLoc
= MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT
, 0, 0);
168 MachOUniquingMap
.clear();
169 ELFUniquingMap
.clear();
170 GOFFUniquingMap
.clear();
171 COFFUniquingMap
.clear();
172 WasmUniquingMap
.clear();
173 XCOFFUniquingMap
.clear();
174 DXCUniquingMap
.clear();
176 ELFEntrySizeMap
.clear();
177 ELFSeenGenericMergeableSections
.clear();
180 AllowTemporaryLabels
= true;
181 DwarfLocSeen
= false;
182 GenDwarfForAssembly
= false;
183 GenDwarfFileNumber
= 0;
188 //===----------------------------------------------------------------------===//
190 //===----------------------------------------------------------------------===//
192 MCInst
*MCContext::createMCInst() {
193 return new (MCInstAllocator
.Allocate()) MCInst
;
196 //===----------------------------------------------------------------------===//
197 // Symbol Manipulation
198 //===----------------------------------------------------------------------===//
200 MCSymbol
*MCContext::getOrCreateSymbol(const Twine
&Name
) {
201 SmallString
<128> NameSV
;
202 StringRef NameRef
= Name
.toStringRef(NameSV
);
204 assert(!NameRef
.empty() && "Normal symbols cannot be unnamed!");
206 MCSymbol
*&Sym
= Symbols
[NameRef
];
208 Sym
= createSymbol(NameRef
, false, false);
213 MCSymbol
*MCContext::getOrCreateFrameAllocSymbol(const Twine
&FuncName
,
215 return getOrCreateSymbol(MAI
->getPrivateGlobalPrefix() + FuncName
+
216 "$frame_escape_" + Twine(Idx
));
219 MCSymbol
*MCContext::getOrCreateParentFrameOffsetSymbol(const Twine
&FuncName
) {
220 return getOrCreateSymbol(MAI
->getPrivateGlobalPrefix() + FuncName
+
221 "$parent_frame_offset");
224 MCSymbol
*MCContext::getOrCreateLSDASymbol(const Twine
&FuncName
) {
225 return getOrCreateSymbol(MAI
->getPrivateGlobalPrefix() + "__ehtable$" +
229 MCSymbol
*MCContext::createSymbolImpl(const StringMapEntry
<bool> *Name
,
231 static_assert(std::is_trivially_destructible
<MCSymbolCOFF
>(),
232 "MCSymbol classes must be trivially destructible");
233 static_assert(std::is_trivially_destructible
<MCSymbolELF
>(),
234 "MCSymbol classes must be trivially destructible");
235 static_assert(std::is_trivially_destructible
<MCSymbolMachO
>(),
236 "MCSymbol classes must be trivially destructible");
237 static_assert(std::is_trivially_destructible
<MCSymbolWasm
>(),
238 "MCSymbol classes must be trivially destructible");
239 static_assert(std::is_trivially_destructible
<MCSymbolXCOFF
>(),
240 "MCSymbol classes must be trivially destructible");
242 switch (getObjectFileType()) {
243 case MCContext::IsCOFF
:
244 return new (Name
, *this) MCSymbolCOFF(Name
, IsTemporary
);
245 case MCContext::IsELF
:
246 return new (Name
, *this) MCSymbolELF(Name
, IsTemporary
);
247 case MCContext::IsGOFF
:
248 return new (Name
, *this) MCSymbolGOFF(Name
, IsTemporary
);
249 case MCContext::IsMachO
:
250 return new (Name
, *this) MCSymbolMachO(Name
, IsTemporary
);
251 case MCContext::IsWasm
:
252 return new (Name
, *this) MCSymbolWasm(Name
, IsTemporary
);
253 case MCContext::IsXCOFF
:
254 return createXCOFFSymbolImpl(Name
, IsTemporary
);
255 case MCContext::IsDXContainer
:
257 case MCContext::IsSPIRV
:
258 return new (Name
, *this)
259 MCSymbol(MCSymbol::SymbolKindUnset
, Name
, IsTemporary
);
261 return new (Name
, *this)
262 MCSymbol(MCSymbol::SymbolKindUnset
, Name
, IsTemporary
);
265 MCSymbol
*MCContext::createSymbol(StringRef Name
, bool AlwaysAddSuffix
,
267 if (CanBeUnnamed
&& !UseNamesOnTempLabels
)
268 return createSymbolImpl(nullptr, true);
270 // Determine whether this is a user written assembler temporary or normal
272 bool IsTemporary
= CanBeUnnamed
;
273 if (AllowTemporaryLabels
&& !IsTemporary
)
274 IsTemporary
= Name
.starts_with(MAI
->getPrivateGlobalPrefix());
276 SmallString
<128> NewName
= Name
;
277 bool AddSuffix
= AlwaysAddSuffix
;
278 unsigned &NextUniqueID
= NextID
[Name
];
281 NewName
.resize(Name
.size());
282 raw_svector_ostream(NewName
) << NextUniqueID
++;
284 auto NameEntry
= UsedNames
.insert(std::make_pair(NewName
.str(), true));
285 if (NameEntry
.second
|| !NameEntry
.first
->second
) {
286 // Ok, we found a name.
287 // Mark it as used for a non-section symbol.
288 NameEntry
.first
->second
= true;
289 // Have the MCSymbol object itself refer to the copy of the string that is
290 // embedded in the UsedNames entry.
291 return createSymbolImpl(&*NameEntry
.first
, IsTemporary
);
293 assert(IsTemporary
&& "Cannot rename non-temporary symbols");
296 llvm_unreachable("Infinite loop");
299 MCSymbol
*MCContext::createTempSymbol(const Twine
&Name
, bool AlwaysAddSuffix
) {
300 SmallString
<128> NameSV
;
301 raw_svector_ostream(NameSV
) << MAI
->getPrivateGlobalPrefix() << Name
;
302 return createSymbol(NameSV
, AlwaysAddSuffix
, true);
305 MCSymbol
*MCContext::createNamedTempSymbol(const Twine
&Name
) {
306 SmallString
<128> NameSV
;
307 raw_svector_ostream(NameSV
) << MAI
->getPrivateGlobalPrefix() << Name
;
308 return createSymbol(NameSV
, true, false);
311 MCSymbol
*MCContext::createLinkerPrivateTempSymbol() {
312 return createLinkerPrivateSymbol("tmp");
315 MCSymbol
*MCContext::createLinkerPrivateSymbol(const Twine
&Name
) {
316 SmallString
<128> NameSV
;
317 raw_svector_ostream(NameSV
) << MAI
->getLinkerPrivateGlobalPrefix() << Name
;
318 return createSymbol(NameSV
, true, false);
321 MCSymbol
*MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
323 MCSymbol
*MCContext::createNamedTempSymbol() {
324 return createNamedTempSymbol("tmp");
327 unsigned MCContext::NextInstance(unsigned LocalLabelVal
) {
328 MCLabel
*&Label
= Instances
[LocalLabelVal
];
330 Label
= new (*this) MCLabel(0);
331 return Label
->incInstance();
334 unsigned MCContext::GetInstance(unsigned LocalLabelVal
) {
335 MCLabel
*&Label
= Instances
[LocalLabelVal
];
337 Label
= new (*this) MCLabel(0);
338 return Label
->getInstance();
341 MCSymbol
*MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal
,
343 MCSymbol
*&Sym
= LocalSymbols
[std::make_pair(LocalLabelVal
, Instance
)];
345 Sym
= createNamedTempSymbol();
349 MCSymbol
*MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal
) {
350 unsigned Instance
= NextInstance(LocalLabelVal
);
351 return getOrCreateDirectionalLocalSymbol(LocalLabelVal
, Instance
);
354 MCSymbol
*MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal
,
356 unsigned Instance
= GetInstance(LocalLabelVal
);
359 return getOrCreateDirectionalLocalSymbol(LocalLabelVal
, Instance
);
362 MCSymbol
*MCContext::lookupSymbol(const Twine
&Name
) const {
363 SmallString
<128> NameSV
;
364 StringRef NameRef
= Name
.toStringRef(NameSV
);
365 return Symbols
.lookup(NameRef
);
368 void MCContext::setSymbolValue(MCStreamer
&Streamer
, const Twine
&Sym
,
370 auto Symbol
= getOrCreateSymbol(Sym
);
371 Streamer
.emitAssignment(Symbol
, MCConstantExpr::create(Val
, *this));
374 void MCContext::registerInlineAsmLabel(MCSymbol
*Sym
) {
375 InlineAsmUsedLabelNames
[Sym
->getName()] = Sym
;
379 MCContext::createXCOFFSymbolImpl(const StringMapEntry
<bool> *Name
,
382 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary
);
384 StringRef OriginalName
= Name
->first();
385 if (OriginalName
.starts_with("._Renamed..") ||
386 OriginalName
.starts_with("_Renamed.."))
387 reportError(SMLoc(), "invalid symbol name from source");
389 if (MAI
->isValidUnquotedName(OriginalName
))
390 return new (Name
, *this) MCSymbolXCOFF(Name
, IsTemporary
);
392 // Now we have a name that contains invalid character(s) for XCOFF symbol.
393 // Let's replace with something valid, but save the original name so that
394 // we could still use the original name in the symbol table.
395 SmallString
<128> InvalidName(OriginalName
);
397 // If it's an entry point symbol, we will keep the '.'
398 // in front for the convention purpose. Otherwise, add "_Renamed.."
399 // as prefix to signal this is an renamed symbol.
400 const bool IsEntryPoint
= !InvalidName
.empty() && InvalidName
[0] == '.';
401 SmallString
<128> ValidName
=
402 StringRef(IsEntryPoint
? "._Renamed.." : "_Renamed..");
404 // Append the hex values of '_' and invalid characters with "_Renamed..";
405 // at the same time replace invalid characters with '_'.
406 for (size_t I
= 0; I
< InvalidName
.size(); ++I
) {
407 if (!MAI
->isAcceptableChar(InvalidName
[I
]) || InvalidName
[I
] == '_') {
408 raw_svector_ostream(ValidName
).write_hex(InvalidName
[I
]);
409 InvalidName
[I
] = '_';
413 // Skip entry point symbol's '.' as we already have a '.' in front of
416 ValidName
.append(InvalidName
.substr(1, InvalidName
.size() - 1));
418 ValidName
.append(InvalidName
);
420 auto NameEntry
= UsedNames
.insert(std::make_pair(ValidName
.str(), true));
421 assert((NameEntry
.second
|| !NameEntry
.first
->second
) &&
422 "This name is used somewhere else.");
423 // Mark the name as used for a non-section symbol.
424 NameEntry
.first
->second
= true;
425 // Have the MCSymbol object itself refer to the copy of the string
426 // that is embedded in the UsedNames entry.
427 MCSymbolXCOFF
*XSym
= new (&*NameEntry
.first
, *this)
428 MCSymbolXCOFF(&*NameEntry
.first
, IsTemporary
);
429 XSym
->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName
));
433 //===----------------------------------------------------------------------===//
434 // Section Management
435 //===----------------------------------------------------------------------===//
437 MCSectionMachO
*MCContext::getMachOSection(StringRef Segment
, StringRef Section
,
438 unsigned TypeAndAttributes
,
439 unsigned Reserved2
, SectionKind Kind
,
440 const char *BeginSymName
) {
441 // We unique sections by their segment/section pair. The returned section
442 // may not have the same flags as the requested section, if so this should be
443 // diagnosed by the client as an error.
445 // Form the name to look up.
446 assert(Section
.size() <= 16 && "section name is too long");
447 assert(!memchr(Section
.data(), '\0', Section
.size()) &&
448 "section name cannot contain NUL");
450 // Do the lookup, if we have a hit, return it.
451 auto R
= MachOUniquingMap
.try_emplace((Segment
+ Twine(',') + Section
).str());
453 return R
.first
->second
;
455 MCSymbol
*Begin
= nullptr;
457 Begin
= createTempSymbol(BeginSymName
, false);
459 // Otherwise, return a new section.
460 StringRef Name
= R
.first
->first();
461 R
.first
->second
= new (MachOAllocator
.Allocate())
462 MCSectionMachO(Segment
, Name
.substr(Name
.size() - Section
.size()),
463 TypeAndAttributes
, Reserved2
, Kind
, Begin
);
464 return R
.first
->second
;
467 MCSectionELF
*MCContext::createELFSectionImpl(StringRef Section
, unsigned Type
,
468 unsigned Flags
, SectionKind K
,
470 const MCSymbolELF
*Group
,
471 bool Comdat
, unsigned UniqueID
,
472 const MCSymbolELF
*LinkedToSym
) {
474 MCSymbol
*&Sym
= Symbols
[Section
];
475 // A section symbol can not redefine regular symbols. There may be multiple
476 // sections with the same name, in which case the first such section wins.
477 if (Sym
&& Sym
->isDefined() &&
478 (!Sym
->isInSection() || Sym
->getSection().getBeginSymbol() != Sym
))
479 reportError(SMLoc(), "invalid symbol redefinition");
480 if (Sym
&& Sym
->isUndefined()) {
481 R
= cast
<MCSymbolELF
>(Sym
);
483 auto NameIter
= UsedNames
.insert(std::make_pair(Section
, false)).first
;
484 R
= new (&*NameIter
, *this) MCSymbolELF(&*NameIter
, /*isTemporary*/ false);
488 R
->setBinding(ELF::STB_LOCAL
);
489 R
->setType(ELF::STT_SECTION
);
491 auto *Ret
= new (ELFAllocator
.Allocate())
492 MCSectionELF(Section
, Type
, Flags
, K
, EntrySize
, Group
, Comdat
, UniqueID
,
495 auto *F
= new MCDataFragment();
496 Ret
->getFragmentList().insert(Ret
->begin(), F
);
504 MCContext::createELFRelSection(const Twine
&Name
, unsigned Type
, unsigned Flags
,
505 unsigned EntrySize
, const MCSymbolELF
*Group
,
506 const MCSectionELF
*RelInfoSection
) {
507 StringMap
<bool>::iterator I
;
509 std::tie(I
, Inserted
) = RelSecNames
.insert(std::make_pair(Name
.str(), true));
511 return createELFSectionImpl(
512 I
->getKey(), Type
, Flags
, SectionKind::getReadOnly(), EntrySize
, Group
,
513 true, true, cast
<MCSymbolELF
>(RelInfoSection
->getBeginSymbol()));
516 MCSectionELF
*MCContext::getELFNamedSection(const Twine
&Prefix
,
517 const Twine
&Suffix
, unsigned Type
,
519 unsigned EntrySize
) {
520 return getELFSection(Prefix
+ "." + Suffix
, Type
, Flags
, EntrySize
, Suffix
,
524 MCSectionELF
*MCContext::getELFSection(const Twine
&Section
, unsigned Type
,
525 unsigned Flags
, unsigned EntrySize
,
526 const Twine
&Group
, bool IsComdat
,
528 const MCSymbolELF
*LinkedToSym
) {
529 MCSymbolELF
*GroupSym
= nullptr;
530 if (!Group
.isTriviallyEmpty() && !Group
.str().empty())
531 GroupSym
= cast
<MCSymbolELF
>(getOrCreateSymbol(Group
));
533 return getELFSection(Section
, Type
, Flags
, EntrySize
, GroupSym
, IsComdat
,
534 UniqueID
, LinkedToSym
);
537 MCSectionELF
*MCContext::getELFSection(const Twine
&Section
, unsigned Type
,
538 unsigned Flags
, unsigned EntrySize
,
539 const MCSymbolELF
*GroupSym
,
540 bool IsComdat
, unsigned UniqueID
,
541 const MCSymbolELF
*LinkedToSym
) {
542 StringRef Group
= "";
544 Group
= GroupSym
->getName();
545 assert(!(LinkedToSym
&& LinkedToSym
->getName().empty()));
546 // Do the lookup, if we have a hit, return it.
547 auto IterBool
= ELFUniquingMap
.insert(std::make_pair(
548 ELFSectionKey
{Section
.str(), Group
,
549 LinkedToSym
? LinkedToSym
->getName() : "", UniqueID
},
551 auto &Entry
= *IterBool
.first
;
552 if (!IterBool
.second
)
555 StringRef CachedName
= Entry
.first
.SectionName
;
558 if (Flags
& ELF::SHF_ARM_PURECODE
)
559 Kind
= SectionKind::getExecuteOnly();
560 else if (Flags
& ELF::SHF_EXECINSTR
)
561 Kind
= SectionKind::getText();
562 else if (~Flags
& ELF::SHF_WRITE
)
563 Kind
= SectionKind::getReadOnly();
564 else if (Flags
& ELF::SHF_TLS
)
565 Kind
= (Type
& ELF::SHT_NOBITS
) ? SectionKind::getThreadBSS()
566 : SectionKind::getThreadData();
568 // Default to `SectionKind::getText()`. This is the default for gas as
569 // well. The condition that falls into this case is where we do not have any
570 // section flags and must infer a classification rather than where we have
571 // section flags (i.e. this is not that SHF_EXECINSTR is unset bur rather it
573 Kind
= llvm::StringSwitch
<SectionKind
>(CachedName
)
574 .Case(".bss", SectionKind::getBSS())
575 .StartsWith(".bss.", SectionKind::getBSS())
576 .StartsWith(".gnu.linkonce.b.", SectionKind::getBSS())
577 .StartsWith(".llvm.linkonce.b.", SectionKind::getBSS())
578 .Case(".data", SectionKind::getData())
579 .Case(".data1", SectionKind::getData())
580 .Case(".data.rel.ro", SectionKind::getReadOnlyWithRel())
581 .StartsWith(".data.", SectionKind::getData())
582 .Case(".rodata", SectionKind::getReadOnly())
583 .Case(".rodata1", SectionKind::getReadOnly())
584 .StartsWith(".rodata.", SectionKind::getReadOnly())
585 .Case(".tbss", SectionKind::getThreadBSS())
586 .StartsWith(".tbss.", SectionKind::getThreadData())
587 .StartsWith(".gnu.linkonce.tb.", SectionKind::getThreadData())
588 .StartsWith(".llvm.linkonce.tb.", SectionKind::getThreadData())
589 .Case(".tdata", SectionKind::getThreadData())
590 .StartsWith(".tdata.", SectionKind::getThreadData())
591 .StartsWith(".gnu.linkonce.td.", SectionKind::getThreadData())
592 .StartsWith(".llvm.linkonce.td.", SectionKind::getThreadData())
593 .StartsWith(".debug_", SectionKind::getMetadata())
594 .Default(SectionKind::getReadOnly());
596 MCSectionELF
*Result
=
597 createELFSectionImpl(CachedName
, Type
, Flags
, Kind
, EntrySize
, GroupSym
,
598 IsComdat
, UniqueID
, LinkedToSym
);
599 Entry
.second
= Result
;
601 recordELFMergeableSectionInfo(Result
->getName(), Result
->getFlags(),
602 Result
->getUniqueID(), Result
->getEntrySize());
607 MCSectionELF
*MCContext::createELFGroupSection(const MCSymbolELF
*Group
,
609 return createELFSectionImpl(".group", ELF::SHT_GROUP
, 0,
610 SectionKind::getReadOnly(), 4, Group
, IsComdat
,
611 MCSection::NonUniqueID
, nullptr);
614 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName
,
615 unsigned Flags
, unsigned UniqueID
,
616 unsigned EntrySize
) {
617 bool IsMergeable
= Flags
& ELF::SHF_MERGE
;
618 if (UniqueID
== GenericSectionID
)
619 ELFSeenGenericMergeableSections
.insert(SectionName
);
621 // For mergeable sections or non-mergeable sections with a generic mergeable
622 // section name we enter their Unique ID into the ELFEntrySizeMap so that
623 // compatible globals can be assigned to the same section.
624 if (IsMergeable
|| isELFGenericMergeableSection(SectionName
)) {
625 ELFEntrySizeMap
.insert(std::make_pair(
626 ELFEntrySizeKey
{SectionName
, Flags
, EntrySize
}, UniqueID
));
630 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName
) {
631 return SectionName
.starts_with(".rodata.str") ||
632 SectionName
.starts_with(".rodata.cst");
635 bool MCContext::isELFGenericMergeableSection(StringRef SectionName
) {
636 return isELFImplicitMergeableSectionNamePrefix(SectionName
) ||
637 ELFSeenGenericMergeableSections
.count(SectionName
);
640 std::optional
<unsigned>
641 MCContext::getELFUniqueIDForEntsize(StringRef SectionName
, unsigned Flags
,
642 unsigned EntrySize
) {
643 auto I
= ELFEntrySizeMap
.find(
644 MCContext::ELFEntrySizeKey
{SectionName
, Flags
, EntrySize
});
645 return (I
!= ELFEntrySizeMap
.end()) ? std::optional
<unsigned>(I
->second
)
649 MCSectionGOFF
*MCContext::getGOFFSection(StringRef Section
, SectionKind Kind
,
651 const MCExpr
*SubsectionId
) {
652 // Do the lookup. If we don't have a hit, return a new section.
654 GOFFUniquingMap
.insert(std::make_pair(Section
.str(), nullptr));
655 auto Iter
= IterBool
.first
;
656 if (!IterBool
.second
)
659 StringRef CachedName
= Iter
->first
;
660 MCSectionGOFF
*GOFFSection
= new (GOFFAllocator
.Allocate())
661 MCSectionGOFF(CachedName
, Kind
, Parent
, SubsectionId
);
662 Iter
->second
= GOFFSection
;
667 MCSectionCOFF
*MCContext::getCOFFSection(StringRef Section
,
668 unsigned Characteristics
,
670 StringRef COMDATSymName
, int Selection
,
672 const char *BeginSymName
) {
673 MCSymbol
*COMDATSymbol
= nullptr;
674 if (!COMDATSymName
.empty()) {
675 COMDATSymbol
= getOrCreateSymbol(COMDATSymName
);
676 COMDATSymName
= COMDATSymbol
->getName();
679 // Do the lookup, if we have a hit, return it.
680 COFFSectionKey T
{Section
, COMDATSymName
, Selection
, UniqueID
};
681 auto IterBool
= COFFUniquingMap
.insert(std::make_pair(T
, nullptr));
682 auto Iter
= IterBool
.first
;
683 if (!IterBool
.second
)
686 MCSymbol
*Begin
= nullptr;
688 Begin
= createTempSymbol(BeginSymName
, false);
690 StringRef CachedName
= Iter
->first
.SectionName
;
691 MCSectionCOFF
*Result
= new (COFFAllocator
.Allocate()) MCSectionCOFF(
692 CachedName
, Characteristics
, COMDATSymbol
, Selection
, Kind
, Begin
);
694 Iter
->second
= Result
;
698 MCSectionCOFF
*MCContext::getCOFFSection(StringRef Section
,
699 unsigned Characteristics
,
701 const char *BeginSymName
) {
702 return getCOFFSection(Section
, Characteristics
, Kind
, "", 0, GenericSectionID
,
706 MCSectionCOFF
*MCContext::getAssociativeCOFFSection(MCSectionCOFF
*Sec
,
707 const MCSymbol
*KeySym
,
709 // Return the normal section if we don't have to be associative or unique.
710 if (!KeySym
&& UniqueID
== GenericSectionID
)
713 // If we have a key symbol, make an associative section with the same name and
714 // kind as the normal section.
715 unsigned Characteristics
= Sec
->getCharacteristics();
717 Characteristics
|= COFF::IMAGE_SCN_LNK_COMDAT
;
718 return getCOFFSection(Sec
->getName(), Characteristics
, Sec
->getKind(),
720 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
, UniqueID
);
723 return getCOFFSection(Sec
->getName(), Characteristics
, Sec
->getKind(), "", 0,
727 MCSectionWasm
*MCContext::getWasmSection(const Twine
&Section
, SectionKind K
,
728 unsigned Flags
, const Twine
&Group
,
730 const char *BeginSymName
) {
731 MCSymbolWasm
*GroupSym
= nullptr;
732 if (!Group
.isTriviallyEmpty() && !Group
.str().empty()) {
733 GroupSym
= cast
<MCSymbolWasm
>(getOrCreateSymbol(Group
));
734 GroupSym
->setComdat(true);
737 return getWasmSection(Section
, K
, Flags
, GroupSym
, UniqueID
, BeginSymName
);
740 MCSectionWasm
*MCContext::getWasmSection(const Twine
&Section
, SectionKind Kind
,
742 const MCSymbolWasm
*GroupSym
,
744 const char *BeginSymName
) {
745 StringRef Group
= "";
747 Group
= GroupSym
->getName();
748 // Do the lookup, if we have a hit, return it.
749 auto IterBool
= WasmUniquingMap
.insert(
750 std::make_pair(WasmSectionKey
{Section
.str(), Group
, UniqueID
}, nullptr));
751 auto &Entry
= *IterBool
.first
;
752 if (!IterBool
.second
)
755 StringRef CachedName
= Entry
.first
.SectionName
;
757 MCSymbol
*Begin
= createSymbol(CachedName
, true, false);
758 Symbols
[Begin
->getName()] = Begin
;
759 cast
<MCSymbolWasm
>(Begin
)->setType(wasm::WASM_SYMBOL_TYPE_SECTION
);
761 MCSectionWasm
*Result
= new (WasmAllocator
.Allocate())
762 MCSectionWasm(CachedName
, Kind
, Flags
, GroupSym
, UniqueID
, Begin
);
763 Entry
.second
= Result
;
765 auto *F
= new MCDataFragment();
766 Result
->getFragmentList().insert(Result
->begin(), F
);
767 F
->setParent(Result
);
768 Begin
->setFragment(F
);
773 bool MCContext::hasXCOFFSection(StringRef Section
,
774 XCOFF::CsectProperties CsectProp
) const {
775 return XCOFFUniquingMap
.count(
776 XCOFFSectionKey(Section
.str(), CsectProp
.MappingClass
)) != 0;
779 MCSectionXCOFF
*MCContext::getXCOFFSection(
780 StringRef Section
, SectionKind Kind
,
781 std::optional
<XCOFF::CsectProperties
> CsectProp
, bool MultiSymbolsAllowed
,
782 const char *BeginSymName
,
783 std::optional
<XCOFF::DwarfSectionSubtypeFlags
> DwarfSectionSubtypeFlags
) {
784 bool IsDwarfSec
= DwarfSectionSubtypeFlags
.has_value();
785 assert((IsDwarfSec
!= CsectProp
.has_value()) && "Invalid XCOFF section!");
787 // Do the lookup. If we have a hit, return it.
788 auto IterBool
= XCOFFUniquingMap
.insert(std::make_pair(
789 IsDwarfSec
? XCOFFSectionKey(Section
.str(), *DwarfSectionSubtypeFlags
)
790 : XCOFFSectionKey(Section
.str(), CsectProp
->MappingClass
),
792 auto &Entry
= *IterBool
.first
;
793 if (!IterBool
.second
) {
794 MCSectionXCOFF
*ExistedEntry
= Entry
.second
;
795 if (ExistedEntry
->isMultiSymbolsAllowed() != MultiSymbolsAllowed
)
796 report_fatal_error("section's multiply symbols policy does not match");
801 // Otherwise, return a new section.
802 StringRef CachedName
= Entry
.first
.SectionName
;
803 MCSymbolXCOFF
*QualName
= nullptr;
804 // Debug section don't have storage class attribute.
806 QualName
= cast
<MCSymbolXCOFF
>(getOrCreateSymbol(CachedName
));
808 QualName
= cast
<MCSymbolXCOFF
>(getOrCreateSymbol(
810 XCOFF::getMappingClassString(CsectProp
->MappingClass
) + "]"));
812 MCSymbol
*Begin
= nullptr;
814 Begin
= createTempSymbol(BeginSymName
, false);
816 // QualName->getUnqualifiedName() and CachedName are the same except when
817 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
818 MCSectionXCOFF
*Result
= nullptr;
820 Result
= new (XCOFFAllocator
.Allocate()) MCSectionXCOFF(
821 QualName
->getUnqualifiedName(), Kind
, QualName
,
822 *DwarfSectionSubtypeFlags
, Begin
, CachedName
, MultiSymbolsAllowed
);
824 Result
= new (XCOFFAllocator
.Allocate())
825 MCSectionXCOFF(QualName
->getUnqualifiedName(), CsectProp
->MappingClass
,
826 CsectProp
->Type
, Kind
, QualName
, Begin
, CachedName
,
827 MultiSymbolsAllowed
);
829 Entry
.second
= Result
;
831 auto *F
= new MCDataFragment();
832 Result
->getFragmentList().insert(Result
->begin(), F
);
833 F
->setParent(Result
);
836 Begin
->setFragment(F
);
838 // We might miss calculating the symbols difference as absolute value before
839 // adding fixups when symbol_A without the fragment set is the csect itself
840 // and symbol_B is in it.
841 // TODO: Currently we only set the fragment for XMC_PR csects because we don't
842 // have other cases that hit this problem yet.
843 if (!IsDwarfSec
&& CsectProp
->MappingClass
== XCOFF::XMC_PR
)
844 QualName
->setFragment(F
);
849 MCSectionSPIRV
*MCContext::getSPIRVSection() {
850 MCSymbol
*Begin
= nullptr;
851 MCSectionSPIRV
*Result
= new (SPIRVAllocator
.Allocate())
852 MCSectionSPIRV(SectionKind::getText(), Begin
);
854 auto *F
= new MCDataFragment();
855 Result
->getFragmentList().insert(Result
->begin(), F
);
856 F
->setParent(Result
);
861 MCSectionDXContainer
*MCContext::getDXContainerSection(StringRef Section
,
863 // Do the lookup, if we have a hit, return it.
864 auto ItInsertedPair
= DXCUniquingMap
.try_emplace(Section
);
865 if (!ItInsertedPair
.second
)
866 return ItInsertedPair
.first
->second
;
868 auto MapIt
= ItInsertedPair
.first
;
869 // Grab the name from the StringMap. Since the Section is going to keep a
870 // copy of this StringRef we need to make sure the underlying string stays
871 // alive as long as we need it.
872 StringRef Name
= MapIt
->first();
874 new (DXCAllocator
.Allocate()) MCSectionDXContainer(Name
, K
, nullptr);
876 // The first fragment will store the header
877 auto *F
= new MCDataFragment();
878 MapIt
->second
->getFragmentList().insert(MapIt
->second
->begin(), F
);
879 F
->setParent(MapIt
->second
);
881 return MapIt
->second
;
884 MCSubtargetInfo
&MCContext::getSubtargetCopy(const MCSubtargetInfo
&STI
) {
885 return *new (MCSubtargetAllocator
.Allocate()) MCSubtargetInfo(STI
);
888 void MCContext::addDebugPrefixMapEntry(const std::string
&From
,
889 const std::string
&To
) {
890 DebugPrefixMap
.emplace_back(From
, To
);
893 void MCContext::remapDebugPath(SmallVectorImpl
<char> &Path
) {
894 for (const auto &[From
, To
] : llvm::reverse(DebugPrefixMap
))
895 if (llvm::sys::path::replace_path_prefix(Path
, From
, To
))
899 void MCContext::RemapDebugPaths() {
900 const auto &DebugPrefixMap
= this->DebugPrefixMap
;
901 if (DebugPrefixMap
.empty())
904 // Remap compilation directory.
905 remapDebugPath(CompilationDir
);
907 // Remap MCDwarfDirs and RootFile.Name in all compilation units.
909 for (auto &CUIDTablePair
: MCDwarfLineTablesCUMap
) {
910 for (auto &Dir
: CUIDTablePair
.second
.getMCDwarfDirs()) {
913 Dir
= std::string(P
);
916 // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
917 // DW_AT_decl_file for DWARF v5 generated for assembly source.
918 P
= CUIDTablePair
.second
.getRootFile().Name
;
920 CUIDTablePair
.second
.getRootFile().Name
= std::string(P
);
924 //===----------------------------------------------------------------------===//
926 //===----------------------------------------------------------------------===//
928 EmitDwarfUnwindType
MCContext::emitDwarfUnwindInfo() const {
930 return EmitDwarfUnwindType::Default
;
931 return TargetOptions
->EmitDwarfUnwind
;
934 bool MCContext::emitCompactUnwindNonCanonical() const {
936 return TargetOptions
->EmitCompactUnwindNonCanonical
;
940 void MCContext::setGenDwarfRootFile(StringRef InputFileName
, StringRef Buffer
) {
941 // MCDwarf needs the root file as well as the compilation directory.
942 // If we find a '.file 0' directive that will supersede these values.
943 std::optional
<MD5::MD5Result
> Cksum
;
944 if (getDwarfVersion() >= 5) {
951 // Canonicalize the root filename. It cannot be empty, and should not
952 // repeat the compilation dir.
953 // The MCContext ctor initializes MainFileName to the name associated with
954 // the SrcMgr's main file ID, which might be the same as InputFileName (and
955 // possibly include directory components).
956 // Or, MainFileName might have been overridden by a -main-file-name option,
957 // which is supposed to be just a base filename with no directory component.
958 // So, if the InputFileName and MainFileName are not equal, assume
959 // MainFileName is a substitute basename and replace the last component.
960 SmallString
<1024> FileNameBuf
= InputFileName
;
961 if (FileNameBuf
.empty() || FileNameBuf
== "-")
962 FileNameBuf
= "<stdin>";
963 if (!getMainFileName().empty() && FileNameBuf
!= getMainFileName()) {
964 llvm::sys::path::remove_filename(FileNameBuf
);
965 llvm::sys::path::append(FileNameBuf
, getMainFileName());
967 StringRef FileName
= FileNameBuf
;
968 if (FileName
.consume_front(getCompilationDir()))
969 if (llvm::sys::path::is_separator(FileName
.front()))
970 FileName
= FileName
.drop_front();
971 assert(!FileName
.empty());
972 setMCLineTableRootFile(
973 /*CUID=*/0, getCompilationDir(), FileName
, Cksum
, std::nullopt
);
976 /// getDwarfFile - takes a file name and number to place in the dwarf file and
977 /// directory tables. If the file number has already been allocated it is an
978 /// error and zero is returned and the client reports the error, else the
979 /// allocated file number is returned. The file numbers may be in any order.
981 MCContext::getDwarfFile(StringRef Directory
, StringRef FileName
,
983 std::optional
<MD5::MD5Result
> Checksum
,
984 std::optional
<StringRef
> Source
, unsigned CUID
) {
985 MCDwarfLineTable
&Table
= MCDwarfLineTablesCUMap
[CUID
];
986 return Table
.tryGetFile(Directory
, FileName
, Checksum
, Source
, DwarfVersion
,
990 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
991 /// currently is assigned and false otherwise.
992 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber
, unsigned CUID
) {
993 const MCDwarfLineTable
&LineTable
= getMCDwarfLineTable(CUID
);
995 return getDwarfVersion() >= 5;
996 if (FileNumber
>= LineTable
.getMCDwarfFiles().size())
999 return !LineTable
.getMCDwarfFiles()[FileNumber
].Name
.empty();
1002 /// Remove empty sections from SectionsForRanges, to avoid generating
1003 /// useless debug info for them.
1004 void MCContext::finalizeDwarfSections(MCStreamer
&MCOS
) {
1005 SectionsForRanges
.remove_if(
1006 [&](MCSection
*Sec
) { return !MCOS
.mayHaveInstructions(*Sec
); });
1009 CodeViewContext
&MCContext::getCVContext() {
1011 CVContext
.reset(new CodeViewContext
);
1015 //===----------------------------------------------------------------------===//
1017 //===----------------------------------------------------------------------===//
1019 void MCContext::diagnose(const SMDiagnostic
&SMD
) {
1020 assert(DiagHandler
&& "MCContext::DiagHandler is not set");
1021 bool UseInlineSrcMgr
= false;
1022 const SourceMgr
*SMP
= nullptr;
1025 } else if (InlineSrcMgr
) {
1026 SMP
= InlineSrcMgr
.get();
1027 UseInlineSrcMgr
= true;
1029 llvm_unreachable("Either SourceMgr should be available");
1030 DiagHandler(SMD
, UseInlineSrcMgr
, *SMP
, LocInfos
);
1033 void MCContext::reportCommon(
1035 std::function
<void(SMDiagnostic
&, const SourceMgr
*)> GetMessage
) {
1036 // * MCContext::SrcMgr is null when the MC layer emits machine code for input
1037 // other than assembly file, say, for .c/.cpp/.ll/.bc.
1038 // * MCContext::InlineSrcMgr is null when the inline asm is not used.
1039 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1040 // and MCContext::InlineSrcMgr are null.
1042 const SourceMgr
*SMP
= &SM
;
1043 bool UseInlineSrcMgr
= false;
1045 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1046 // For MC-only execution, only SrcMgr is used;
1047 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1048 // inline asm in the IR.
1049 if (Loc
.isValid()) {
1052 } else if (InlineSrcMgr
) {
1053 SMP
= InlineSrcMgr
.get();
1054 UseInlineSrcMgr
= true;
1056 llvm_unreachable("Either SourceMgr should be available");
1061 DiagHandler(D
, UseInlineSrcMgr
, *SMP
, LocInfos
);
1064 void MCContext::reportError(SMLoc Loc
, const Twine
&Msg
) {
1066 reportCommon(Loc
, [&](SMDiagnostic
&D
, const SourceMgr
*SMP
) {
1067 D
= SMP
->GetMessage(Loc
, SourceMgr::DK_Error
, Msg
);
1071 void MCContext::reportWarning(SMLoc Loc
, const Twine
&Msg
) {
1072 if (TargetOptions
&& TargetOptions
->MCNoWarn
)
1074 if (TargetOptions
&& TargetOptions
->MCFatalWarnings
) {
1075 reportError(Loc
, Msg
);
1077 reportCommon(Loc
, [&](SMDiagnostic
&D
, const SourceMgr
*SMP
) {
1078 D
= SMP
->GetMessage(Loc
, SourceMgr::DK_Warning
, Msg
);