1//===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
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#ifndef LLVM_MC_MCCONTEXT_H
10#define LLVM_MC_MCCONTEXT_H
11
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/SetVector.h"
14#include "llvm/ADT/SmallString.h"
15#include "llvm/ADT/StringMap.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/BinaryFormat/Dwarf.h"
19#include "llvm/BinaryFormat/XCOFF.h"
20#include "llvm/MC/MCAsmMacro.h"
21#include "llvm/MC/MCDwarf.h"
22#include "llvm/MC/MCGOFFAttributes.h"
23#include "llvm/MC/MCPseudoProbe.h"
24#include "llvm/MC/MCSection.h"
25#include "llvm/MC/MCSectionGOFF.h"
26#include "llvm/MC/MCSymbolTableEntry.h"
27#include "llvm/MC/SectionKind.h"
28#include "llvm/Support/Allocator.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/Error.h"
31#include "llvm/Support/MD5.h"
32#include "llvm/Support/StringSaver.h"
33#include "llvm/Support/raw_ostream.h"
34#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <cstdint>
38#include <functional>
39#include <map>
40#include <memory>
41#include <optional>
42#include <string>
43#include <utility>
44#include <vector>
45
46namespace llvm {
47
48class CodeViewContext;
49class MCAsmInfo;
50class MCDataFragment;
51class MCInst;
52class MCLabel;
53class MCObjectFileInfo;
54class MCRegisterInfo;
55class MCSection;
56class MCSectionCOFF;
57class MCSectionDXContainer;
58class MCSectionELF;
59class MCSectionMachO;
60class MCSectionSPIRV;
61class MCSectionWasm;
62class MCSectionXCOFF;
63class MCStreamer;
64class MCSubtargetInfo;
65class MCSymbol;
66class MCSymbolELF;
67class MCSymbolWasm;
68class MCSymbolXCOFF;
69class MCTargetOptions;
70class MDNode;
71template <typename T> class SmallVectorImpl;
72class SMDiagnostic;
73class SMLoc;
74class SourceMgr;
75enum class EmitDwarfUnwindType;
76
77namespace wasm {
78struct WasmSignature;
79}
80
81/// Context object for machine code objects. This class owns all of the
82/// sections that it creates.
83///
84class MCContext {
85public:
86 using SymbolTable = StringMap<MCSymbolTableValue, BumpPtrAllocator &>;
87 using DiagHandlerTy =
88 std::function<void(const SMDiagnostic &, bool, const SourceMgr &,
89 std::vector<const MDNode *> &)>;
90 enum Environment {
91 IsMachO,
92 IsELF,
93 IsGOFF,
94 IsCOFF,
95 IsSPIRV,
96 IsWasm,
97 IsXCOFF,
98 IsDXContainer
99 };
100
101private:
102 Environment Env;
103
104 /// The name of the Segment where Swift5 Reflection Section data will be
105 /// outputted
106 StringRef Swift5ReflectionSegmentName;
107
108 /// The triple for this object.
109 Triple TT;
110
111 /// The SourceMgr for this object, if any.
112 const SourceMgr *SrcMgr = nullptr;
113
114 /// The SourceMgr for inline assembly, if any.
115 std::unique_ptr<SourceMgr> InlineSrcMgr;
116 std::vector<const MDNode *> LocInfos;
117
118 DiagHandlerTy DiagHandler;
119
120 /// The MCAsmInfo for this target.
121 const MCAsmInfo *MAI = nullptr;
122
123 /// The MCRegisterInfo for this target.
124 const MCRegisterInfo *MRI = nullptr;
125
126 /// The MCObjectFileInfo for this target.
127 const MCObjectFileInfo *MOFI = nullptr;
128
129 /// The MCSubtargetInfo for this target.
130 const MCSubtargetInfo *MSTI = nullptr;
131
132 std::unique_ptr<CodeViewContext> CVContext;
133
134 /// Allocator object used for creating machine code objects.
135 ///
136 /// We use a bump pointer allocator to avoid the need to track all allocated
137 /// objects.
138 BumpPtrAllocator Allocator;
139
140 /// For MCFragment instances.
141 BumpPtrAllocator FragmentAllocator;
142
143 SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
144 SpecificBumpPtrAllocator<MCSectionDXContainer> DXCAllocator;
145 SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
146 SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
147 SpecificBumpPtrAllocator<MCSectionGOFF> GOFFAllocator;
148 SpecificBumpPtrAllocator<MCSectionSPIRV> SPIRVAllocator;
149 SpecificBumpPtrAllocator<MCSectionWasm> WasmAllocator;
150 SpecificBumpPtrAllocator<MCSectionXCOFF> XCOFFAllocator;
151 SpecificBumpPtrAllocator<MCInst> MCInstAllocator;
152
153 SpecificBumpPtrAllocator<wasm::WasmSignature> WasmSignatureAllocator;
154
155 /// Bindings of names to symbol table values.
156 SymbolTable Symbols;
157
158 /// A mapping from a local label number and an instance count to a symbol.
159 /// For example, in the assembly
160 /// 1:
161 /// 2:
162 /// 1:
163 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
164 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
165
166 /// Keeps track of labels that are used in inline assembly.
167 StringMap<MCSymbol *, BumpPtrAllocator &> InlineAsmUsedLabelNames;
168
169 /// Instances of directional local labels.
170 DenseMap<unsigned, MCLabel *> Instances;
171 /// NextInstance() creates the next instance of the directional local label
172 /// for the LocalLabelVal and adds it to the map if needed.
173 unsigned NextInstance(unsigned LocalLabelVal);
174 /// GetInstance() gets the current instance of the directional local label
175 /// for the LocalLabelVal and adds it to the map if needed.
176 unsigned GetInstance(unsigned LocalLabelVal);
177
178 /// LLVM_BB_ADDR_MAP version to emit.
179 uint8_t BBAddrMapVersion = 2;
180
181 /// The file name of the log file from the environment variable
182 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
183 /// directive is used or it is an error.
184 std::string SecureLogFile;
185 /// The stream that gets written to for the .secure_log_unique directive.
186 std::unique_ptr<raw_fd_ostream> SecureLog;
187 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
188 /// catch errors if .secure_log_unique appears twice without
189 /// .secure_log_reset appearing between them.
190 bool SecureLogUsed = false;
191
192 /// The compilation directory to use for DW_AT_comp_dir.
193 SmallString<128> CompilationDir;
194
195 /// Prefix replacement map for source file information.
196 SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;
197
198 /// The main file name if passed in explicitly.
199 std::string MainFileName;
200
201 /// The dwarf file and directory tables from the dwarf .file directive.
202 /// We now emit a line table for each compile unit. To reduce the prologue
203 /// size of each line table, the files and directories used by each compile
204 /// unit are separated.
205 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
206
207 /// The current dwarf line information from the last dwarf .loc directive.
208 MCDwarfLoc CurrentDwarfLoc;
209 bool DwarfLocSeen = false;
210
211 /// Generate dwarf debugging info for assembly source files.
212 bool GenDwarfForAssembly = false;
213
214 /// The current dwarf file number when generate dwarf debugging info for
215 /// assembly source files.
216 unsigned GenDwarfFileNumber = 0;
217
218 /// Sections for generating the .debug_ranges and .debug_aranges sections.
219 SetVector<MCSection *> SectionsForRanges;
220
221 /// The information gathered from labels that will have dwarf label
222 /// entries when generating dwarf assembly source files.
223 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
224
225 /// The string to embed in the debug information for the compile unit, if
226 /// non-empty.
227 StringRef DwarfDebugFlags;
228
229 /// The string to embed in as the dwarf AT_producer for the compile unit, if
230 /// non-empty.
231 StringRef DwarfDebugProducer;
232
233 /// The maximum version of dwarf that we should emit.
234 uint16_t DwarfVersion = 4;
235
236 /// The format of dwarf that we emit.
237 dwarf::DwarfFormat DwarfFormat = dwarf::DWARF32;
238
239 /// Honor temporary labels, this is useful for debugging semantic
240 /// differences between temporary and non-temporary labels (primarily on
241 /// Darwin).
242 bool SaveTempLabels = false;
243 bool UseNamesOnTempLabels = false;
244
245 /// The Compile Unit ID that we are currently processing.
246 unsigned DwarfCompileUnitID = 0;
247
248 /// A collection of MCPseudoProbe in the current module
249 MCPseudoProbeTable PseudoProbeTable;
250
251 struct COFFSectionKey {
252 std::string SectionName;
253 StringRef GroupName;
254 int SelectionKey;
255 unsigned UniqueID;
256
257 COFFSectionKey(StringRef SectionName, StringRef GroupName, int SelectionKey,
258 unsigned UniqueID)
259 : SectionName(SectionName), GroupName(GroupName),
260 SelectionKey(SelectionKey), UniqueID(UniqueID) {}
261
262 bool operator<(const COFFSectionKey &Other) const {
263 return std::tie(args: SectionName, args: GroupName, args: SelectionKey, args: UniqueID) <
264 std::tie(args: Other.SectionName, args: Other.GroupName, args: Other.SelectionKey,
265 args: Other.UniqueID);
266 }
267 };
268
269 struct WasmSectionKey {
270 std::string SectionName;
271 StringRef GroupName;
272 unsigned UniqueID;
273
274 WasmSectionKey(StringRef SectionName, StringRef GroupName,
275 unsigned UniqueID)
276 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {}
277
278 bool operator<(const WasmSectionKey &Other) const {
279 return std::tie(args: SectionName, args: GroupName, args: UniqueID) <
280 std::tie(args: Other.SectionName, args: Other.GroupName, args: Other.UniqueID);
281 }
282 };
283
284 struct XCOFFSectionKey {
285 // Section name.
286 std::string SectionName;
287 // Section property.
288 // For csect section, it is storage mapping class.
289 // For debug section, it is section type flags.
290 union {
291 XCOFF::StorageMappingClass MappingClass;
292 XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags;
293 };
294 bool IsCsect;
295
296 XCOFFSectionKey(StringRef SectionName,
297 XCOFF::StorageMappingClass MappingClass)
298 : SectionName(SectionName), MappingClass(MappingClass), IsCsect(true) {}
299
300 XCOFFSectionKey(StringRef SectionName,
301 XCOFF::DwarfSectionSubtypeFlags DwarfSubtypeFlags)
302 : SectionName(SectionName), DwarfSubtypeFlags(DwarfSubtypeFlags),
303 IsCsect(false) {}
304
305 bool operator<(const XCOFFSectionKey &Other) const {
306 if (IsCsect && Other.IsCsect)
307 return std::tie(args: SectionName, args: MappingClass) <
308 std::tie(args: Other.SectionName, args: Other.MappingClass);
309 if (IsCsect != Other.IsCsect)
310 return IsCsect;
311 return std::tie(args: SectionName, args: DwarfSubtypeFlags) <
312 std::tie(args: Other.SectionName, args: Other.DwarfSubtypeFlags);
313 }
314 };
315
316 StringMap<MCSectionMachO *> MachOUniquingMap;
317 std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
318 StringMap<MCSectionELF *> ELFUniquingMap;
319 std::map<std::string, MCSectionGOFF *> GOFFUniquingMap;
320 std::map<WasmSectionKey, MCSectionWasm *> WasmUniquingMap;
321 std::map<XCOFFSectionKey, MCSectionXCOFF *> XCOFFUniquingMap;
322 StringMap<MCSectionDXContainer *> DXCUniquingMap;
323 StringMap<bool> RelSecNames;
324
325 SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
326
327 /// Do automatic reset in destructor
328 bool AutoReset;
329
330 MCTargetOptions const *TargetOptions;
331
332 bool HadError = false;
333
334 void reportCommon(SMLoc Loc,
335 std::function<void(SMDiagnostic &, const SourceMgr *)>);
336
337 MCDataFragment *allocInitialFragment(MCSection &Sec);
338
339 MCSymbolTableEntry &getSymbolTableEntry(StringRef Name);
340
341 MCSymbol *createSymbolImpl(const MCSymbolTableEntry *Name, bool IsTemporary);
342 MCSymbol *createRenamableSymbol(const Twine &Name, bool AlwaysAddSuffix,
343 bool IsTemporary);
344
345 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
346 unsigned Instance);
347
348 template <typename Symbol>
349 Symbol *getOrCreateSectionSymbol(StringRef Section);
350
351 MCSectionELF *createELFSectionImpl(StringRef Section, unsigned Type,
352 unsigned Flags, unsigned EntrySize,
353 const MCSymbolELF *Group, bool IsComdat,
354 unsigned UniqueID,
355 const MCSymbolELF *LinkedToSym);
356
357 MCSymbolXCOFF *createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
358 bool IsTemporary);
359
360 template <typename TAttr>
361 MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
362 TAttr SDAttributes, MCSection *Parent,
363 bool IsVirtual);
364
365 /// Map of currently defined macros.
366 StringMap<MCAsmMacro> MacroMap;
367
368 // Symbols must be assigned to a section with a compatible entry size and
369 // flags. This map is used to assign unique IDs to sections to distinguish
370 // between sections with identical names but incompatible entry sizes and/or
371 // flags. This can occur when a symbol is explicitly assigned to a section,
372 // e.g. via __attribute__((section("myname"))). The map key is the tuple
373 // (section name, flags, entry size).
374 DenseMap<std::tuple<StringRef, unsigned, unsigned>, unsigned> ELFEntrySizeMap;
375
376 // This set is used to record the generic mergeable section names seen.
377 // These are sections that are created as mergeable e.g. .debug_str. We need
378 // to avoid assigning non-mergeable symbols to these sections. It is used
379 // to prevent non-mergeable symbols being explicitly assigned to mergeable
380 // sections (e.g. via _attribute_((section("myname")))).
381 DenseSet<StringRef> ELFSeenGenericMergeableSections;
382
383public:
384 LLVM_ABI explicit MCContext(const Triple &TheTriple, const MCAsmInfo *MAI,
385 const MCRegisterInfo *MRI,
386 const MCSubtargetInfo *MSTI,
387 const SourceMgr *Mgr = nullptr,
388 MCTargetOptions const *TargetOpts = nullptr,
389 bool DoAutoReset = true,
390 StringRef Swift5ReflSegmentName = {});
391 MCContext(const MCContext &) = delete;
392 MCContext &operator=(const MCContext &) = delete;
393 LLVM_ABI ~MCContext();
394
395 Environment getObjectFileType() const { return Env; }
396
397 const StringRef &getSwift5ReflectionSegmentName() const {
398 return Swift5ReflectionSegmentName;
399 }
400 const Triple &getTargetTriple() const { return TT; }
401 const SourceMgr *getSourceManager() const { return SrcMgr; }
402
403 LLVM_ABI void initInlineSourceManager();
404 SourceMgr *getInlineSourceManager() { return InlineSrcMgr.get(); }
405 std::vector<const MDNode *> &getLocInfos() { return LocInfos; }
406 void setDiagnosticHandler(DiagHandlerTy DiagHandler) {
407 this->DiagHandler = DiagHandler;
408 }
409
410 void setObjectFileInfo(const MCObjectFileInfo *Mofi) { MOFI = Mofi; }
411
412 const MCAsmInfo *getAsmInfo() const { return MAI; }
413
414 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
415
416 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
417
418 const MCSubtargetInfo *getSubtargetInfo() const { return MSTI; }
419
420 const MCTargetOptions *getTargetOptions() const { return TargetOptions; }
421
422 LLVM_ABI CodeViewContext &getCVContext();
423
424 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
425
426 /// \name Module Lifetime Management
427 /// @{
428
429 /// reset - return object to right after construction state to prepare
430 /// to process a new module
431 LLVM_ABI void reset();
432
433 /// @}
434
435 /// \name McInst Management
436
437 /// Create and return a new MC instruction.
438 LLVM_ABI MCInst *createMCInst();
439
440 template <typename F, typename... Args> F *allocFragment(Args &&...args) {
441 return new (FragmentAllocator.Allocate(Size: sizeof(F), Alignment: alignof(F)))
442 F(std::forward<Args>(args)...);
443 }
444
445 /// \name Symbol Management
446 /// @{
447
448 /// Create a new linker temporary symbol with the specified prefix (Name) or
449 /// "tmp". This creates a "l"-prefixed symbol for Mach-O and is identical to
450 /// createNamedTempSymbol for other object file formats.
451 LLVM_ABI MCSymbol *createLinkerPrivateTempSymbol();
452 LLVM_ABI MCSymbol *createLinkerPrivateSymbol(const Twine &Name);
453
454 /// Create a temporary symbol with a unique name. The name will be omitted
455 /// in the symbol table if UseNamesOnTempLabels is false (default except
456 /// MCAsmStreamer). The overload without Name uses an unspecified name.
457 LLVM_ABI MCSymbol *createTempSymbol();
458 LLVM_ABI MCSymbol *createTempSymbol(const Twine &Name,
459 bool AlwaysAddSuffix = true);
460
461 /// Create a temporary symbol with a unique name whose name cannot be
462 /// omitted in the symbol table. This is rarely used.
463 LLVM_ABI MCSymbol *createNamedTempSymbol();
464 LLVM_ABI MCSymbol *createNamedTempSymbol(const Twine &Name);
465
466 /// Get or create a symbol for a basic block. For non-always-emit symbols,
467 /// this behaves like createTempSymbol, except that it uses the
468 /// PrivateLabelPrefix instead of the PrivateGlobalPrefix. When AlwaysEmit is
469 /// true, behaves like getOrCreateSymbol, prefixed with PrivateLabelPrefix.
470 LLVM_ABI MCSymbol *createBlockSymbol(const Twine &Name,
471 bool AlwaysEmit = false);
472
473 /// Create a local, non-temporary symbol like an ELF mapping symbol. Calling
474 /// the function with the same name will generate new, unique instances.
475 LLVM_ABI MCSymbol *createLocalSymbol(StringRef Name);
476
477 /// Create the definition of a directional local symbol for numbered label
478 /// (used for "1:" definitions).
479 LLVM_ABI MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
480
481 /// Create and return a directional local symbol for numbered label (used
482 /// for "1b" or 1f" references).
483 LLVM_ABI MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal,
484 bool Before);
485
486 /// Lookup the symbol inside with the specified \p Name. If it exists,
487 /// return it. If not, create a forward reference and return it.
488 ///
489 /// \param Name - The symbol name, which must be unique across all symbols.
490 LLVM_ABI MCSymbol *getOrCreateSymbol(const Twine &Name);
491
492 /// Gets a symbol that will be defined to the final stack offset of a local
493 /// variable after codegen.
494 ///
495 /// \param Idx - The index of a local variable passed to \@llvm.localescape.
496 LLVM_ABI MCSymbol *getOrCreateFrameAllocSymbol(const Twine &FuncName,
497 unsigned Idx);
498
499 LLVM_ABI MCSymbol *getOrCreateParentFrameOffsetSymbol(const Twine &FuncName);
500
501 LLVM_ABI MCSymbol *getOrCreateLSDASymbol(const Twine &FuncName);
502
503 /// Get the symbol for \p Name, or null.
504 LLVM_ABI MCSymbol *lookupSymbol(const Twine &Name) const;
505
506 /// Clone a symbol for the .set directive, replacing it in the symbol table.
507 /// Existing references to the original symbol remain unchanged, and the
508 /// original symbol is not emitted to the symbol table.
509 LLVM_ABI MCSymbol *cloneSymbol(MCSymbol &Sym);
510
511 /// Set value for a symbol.
512 LLVM_ABI void setSymbolValue(MCStreamer &Streamer, const Twine &Sym,
513 uint64_t Val);
514
515 /// getSymbols - Get a reference for the symbol table for clients that
516 /// want to, for example, iterate over all symbols. 'const' because we
517 /// still want any modifications to the table itself to use the MCContext
518 /// APIs.
519 const SymbolTable &getSymbols() const { return Symbols; }
520
521 /// isInlineAsmLabel - Return true if the name is a label referenced in
522 /// inline assembly.
523 MCSymbol *getInlineAsmLabel(StringRef Name) const {
524 return InlineAsmUsedLabelNames.lookup(Key: Name);
525 }
526
527 /// registerInlineAsmLabel - Records that the name is a label referenced in
528 /// inline assembly.
529 LLVM_ABI void registerInlineAsmLabel(MCSymbol *Sym);
530
531 /// Allocates and returns a new `WasmSignature` instance (with empty parameter
532 /// and return type lists).
533 LLVM_ABI wasm::WasmSignature *createWasmSignature();
534
535 /// @}
536
537 /// \name Section Management
538 /// @{
539
540 /// Return the MCSection for the specified mach-o section. This requires
541 /// the operands to be valid.
542 LLVM_ABI MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
543 unsigned TypeAndAttributes,
544 unsigned Reserved2, SectionKind K,
545 const char *BeginSymName = nullptr);
546
547 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
548 unsigned TypeAndAttributes, SectionKind K,
549 const char *BeginSymName = nullptr) {
550 return getMachOSection(Segment, Section, TypeAndAttributes, Reserved2: 0, K,
551 BeginSymName);
552 }
553
554 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
555 unsigned Flags) {
556 return getELFSection(Section, Type, Flags, EntrySize: 0, Group: "", IsComdat: false);
557 }
558
559 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
560 unsigned Flags, unsigned EntrySize) {
561 return getELFSection(Section, Type, Flags, EntrySize, Group: "", IsComdat: false,
562 UniqueID: MCSection::NonUniqueID, LinkedToSym: nullptr);
563 }
564
565 MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
566 unsigned Flags, unsigned EntrySize,
567 const Twine &Group, bool IsComdat) {
568 return getELFSection(Section, Type, Flags, EntrySize, Group, IsComdat,
569 UniqueID: MCSection::NonUniqueID, LinkedToSym: nullptr);
570 }
571
572 LLVM_ABI MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
573 unsigned Flags, unsigned EntrySize,
574 const Twine &Group, bool IsComdat,
575 unsigned UniqueID,
576 const MCSymbolELF *LinkedToSym);
577
578 LLVM_ABI MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
579 unsigned Flags, unsigned EntrySize,
580 const MCSymbolELF *Group, bool IsComdat,
581 unsigned UniqueID,
582 const MCSymbolELF *LinkedToSym);
583
584 /// Get a section with the provided group identifier. This section is
585 /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
586 /// describes the type of the section and \p Flags are used to further
587 /// configure this named section.
588 LLVM_ABI MCSectionELF *getELFNamedSection(const Twine &Prefix,
589 const Twine &Suffix, unsigned Type,
590 unsigned Flags,
591 unsigned EntrySize = 0);
592
593 LLVM_ABI MCSectionELF *
594 createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
595 unsigned EntrySize, const MCSymbolELF *Group,
596 const MCSectionELF *RelInfoSection);
597
598 LLVM_ABI MCSectionELF *createELFGroupSection(const MCSymbolELF *Group,
599 bool IsComdat);
600
601 LLVM_ABI void recordELFMergeableSectionInfo(StringRef SectionName,
602 unsigned Flags, unsigned UniqueID,
603 unsigned EntrySize);
604
605 LLVM_ABI bool isELFImplicitMergeableSectionNamePrefix(StringRef Name);
606
607 LLVM_ABI bool isELFGenericMergeableSection(StringRef Name);
608
609 /// Return the unique ID of the section with the given name, flags and entry
610 /// size, if it exists.
611 LLVM_ABI std::optional<unsigned>
612 getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags,
613 unsigned EntrySize);
614
615 MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
616 GOFF::SDAttr SDAttributes);
617 MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
618 GOFF::EDAttr EDAttributes, MCSection *Parent);
619 MCSectionGOFF *getGOFFSection(SectionKind Kind, StringRef Name,
620 GOFF::PRAttr PRAttributes, MCSection *Parent);
621
622 LLVM_ABI MCSectionCOFF *
623 getCOFFSection(StringRef Section, unsigned Characteristics,
624 StringRef COMDATSymName, int Selection,
625 unsigned UniqueID = MCSection::NonUniqueID);
626
627 LLVM_ABI MCSectionCOFF *getCOFFSection(StringRef Section,
628 unsigned Characteristics);
629
630 /// Gets or creates a section equivalent to Sec that is associated with the
631 /// section containing KeySym. For example, to create a debug info section
632 /// associated with an inline function, pass the normal debug info section
633 /// as Sec and the function symbol as KeySym.
634 LLVM_ABI MCSectionCOFF *
635 getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
636 unsigned UniqueID = MCSection::NonUniqueID);
637
638 LLVM_ABI MCSectionSPIRV *getSPIRVSection();
639
640 MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
641 unsigned Flags = 0) {
642 return getWasmSection(Section, K, Flags, Group: "", UniqueID: ~0);
643 }
644
645 LLVM_ABI MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
646 unsigned Flags, const Twine &Group,
647 unsigned UniqueID);
648
649 LLVM_ABI MCSectionWasm *getWasmSection(const Twine &Section, SectionKind K,
650 unsigned Flags,
651 const MCSymbolWasm *Group,
652 unsigned UniqueID);
653
654 /// Get the section for the provided Section name
655 LLVM_ABI MCSectionDXContainer *getDXContainerSection(StringRef Section,
656 SectionKind K);
657
658 LLVM_ABI bool hasXCOFFSection(StringRef Section,
659 XCOFF::CsectProperties CsectProp) const;
660
661 LLVM_ABI MCSectionXCOFF *getXCOFFSection(
662 StringRef Section, SectionKind K,
663 std::optional<XCOFF::CsectProperties> CsectProp = std::nullopt,
664 bool MultiSymbolsAllowed = false,
665 std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSubtypeFlags =
666 std::nullopt);
667
668 // Create and save a copy of STI and return a reference to the copy.
669 LLVM_ABI MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
670
671 uint8_t getBBAddrMapVersion() const { return BBAddrMapVersion; }
672
673 /// @}
674
675 /// \name Dwarf Management
676 /// @{
677
678 /// Get the compilation directory for DW_AT_comp_dir
679 /// The compilation directory should be set with \c setCompilationDir before
680 /// calling this function. If it is unset, an empty string will be returned.
681 StringRef getCompilationDir() const { return CompilationDir; }
682
683 /// Set the compilation directory for DW_AT_comp_dir
684 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
685
686 /// Add an entry to the debug prefix map.
687 LLVM_ABI void addDebugPrefixMapEntry(const std::string &From,
688 const std::string &To);
689
690 /// Remap one path in-place as per the debug prefix map.
691 LLVM_ABI void remapDebugPath(SmallVectorImpl<char> &Path);
692
693 // Remaps all debug directory paths in-place as per the debug prefix map.
694 LLVM_ABI void RemapDebugPaths();
695
696 /// Get the main file name for use in error messages and debug
697 /// info. This can be set to ensure we've got the correct file name
698 /// after preprocessing or for -save-temps.
699 const std::string &getMainFileName() const { return MainFileName; }
700
701 /// Set the main file name and override the default.
702 void setMainFileName(StringRef S) { MainFileName = std::string(S); }
703
704 /// Creates an entry in the dwarf file and directory tables.
705 LLVM_ABI Expected<unsigned>
706 getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber,
707 std::optional<MD5::MD5Result> Checksum,
708 std::optional<StringRef> Source, unsigned CUID);
709
710 LLVM_ABI bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
711
712 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
713 return MCDwarfLineTablesCUMap;
714 }
715
716 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
717 return MCDwarfLineTablesCUMap[CUID];
718 }
719
720 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
721 auto I = MCDwarfLineTablesCUMap.find(x: CUID);
722 assert(I != MCDwarfLineTablesCUMap.end());
723 return I->second;
724 }
725
726 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
727 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
728 }
729
730 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
731 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
732 }
733
734 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
735
736 void setDwarfCompileUnitID(unsigned CUIndex) { DwarfCompileUnitID = CUIndex; }
737
738 /// Specifies the "root" file and directory of the compilation unit.
739 /// These are "file 0" and "directory 0" in DWARF v5.
740 void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir,
741 StringRef Filename,
742 std::optional<MD5::MD5Result> Checksum,
743 std::optional<StringRef> Source) {
744 getMCDwarfLineTable(CUID).setRootFile(Directory: CompilationDir, FileName: Filename, Checksum,
745 Source);
746 }
747
748 /// Reports whether MD5 checksum usage is consistent (all-or-none).
749 bool isDwarfMD5UsageConsistent(unsigned CUID) const {
750 return getMCDwarfLineTable(CUID).isMD5UsageConsistent();
751 }
752
753 /// Saves the information from the currently parsed dwarf .loc directive
754 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
755 /// in the line number table with this information and the address of the
756 /// instruction will be created.
757 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
758 unsigned Flags, unsigned Isa,
759 unsigned Discriminator) {
760 CurrentDwarfLoc.setFileNum(FileNum);
761 CurrentDwarfLoc.setLine(Line);
762 CurrentDwarfLoc.setColumn(Column);
763 CurrentDwarfLoc.setFlags(Flags);
764 CurrentDwarfLoc.setIsa(Isa);
765 CurrentDwarfLoc.setDiscriminator(Discriminator);
766 DwarfLocSeen = true;
767 }
768
769 void clearDwarfLocSeen() { DwarfLocSeen = false; }
770
771 bool getDwarfLocSeen() { return DwarfLocSeen; }
772 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
773
774 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
775 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
776 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
777 LLVM_ABI EmitDwarfUnwindType emitDwarfUnwindInfo() const;
778 LLVM_ABI bool emitCompactUnwindNonCanonical() const;
779
780 void setGenDwarfFileNumber(unsigned FileNumber) {
781 GenDwarfFileNumber = FileNumber;
782 }
783
784 /// Specifies information about the "root file" for assembler clients
785 /// (e.g., llvm-mc). Assumes compilation dir etc. have been set up.
786 LLVM_ABI void setGenDwarfRootFile(StringRef FileName, StringRef Buffer);
787
788 const SetVector<MCSection *> &getGenDwarfSectionSyms() {
789 return SectionsForRanges;
790 }
791
792 bool addGenDwarfSection(MCSection *Sec) {
793 return SectionsForRanges.insert(X: Sec);
794 }
795
796 LLVM_ABI void finalizeDwarfSections(MCStreamer &MCOS);
797
798 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
799 return MCGenDwarfLabelEntries;
800 }
801
802 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
803 MCGenDwarfLabelEntries.push_back(x: E);
804 }
805
806 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
807 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
808
809 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
810 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
811
812 void setDwarfFormat(dwarf::DwarfFormat f) { DwarfFormat = f; }
813 dwarf::DwarfFormat getDwarfFormat() const { return DwarfFormat; }
814
815 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
816 uint16_t getDwarfVersion() const { return DwarfVersion; }
817
818 /// @}
819
820 StringRef getSecureLogFile() { return SecureLogFile; }
821 raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
822
823 void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
824 SecureLog = std::move(Value);
825 }
826
827 bool getSecureLogUsed() { return SecureLogUsed; }
828 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
829
830 void *allocate(unsigned Size, unsigned Align = 8) {
831 return Allocator.Allocate(Size, Alignment: Align);
832 }
833
834 void deallocate(void *Ptr) {}
835
836 /// Allocates a copy of the given string on the allocator managed by this
837 /// context and returns the result.
838 StringRef allocateString(StringRef s) {
839 return StringSaver(Allocator).save(S: s);
840 }
841
842 bool hadError() { return HadError; }
843 LLVM_ABI void diagnose(const SMDiagnostic &SMD);
844 LLVM_ABI void reportError(SMLoc L, const Twine &Msg);
845 LLVM_ABI void reportWarning(SMLoc L, const Twine &Msg);
846
847 MCAsmMacro *lookupMacro(StringRef Name) {
848 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Key: Name);
849 return (I == MacroMap.end()) ? nullptr : &I->getValue();
850 }
851
852 void defineMacro(StringRef Name, MCAsmMacro Macro) {
853 MacroMap.insert(KV: std::make_pair(x&: Name, y: std::move(Macro)));
854 }
855
856 void undefineMacro(StringRef Name) { MacroMap.erase(Key: Name); }
857
858 MCPseudoProbeTable &getMCPseudoProbeTable() { return PseudoProbeTable; }
859};
860
861} // end namespace llvm
862
863// operator new and delete aren't allowed inside namespaces.
864// The throw specifications are mandated by the standard.
865/// Placement new for using the MCContext's allocator.
866///
867/// This placement form of operator new uses the MCContext's allocator for
868/// obtaining memory. It is a non-throwing new, which means that it returns
869/// null on error. (If that is what the allocator does. The current does, so if
870/// this ever changes, this operator will have to be changed, too.)
871/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
872/// \code
873/// // Default alignment (8)
874/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
875/// // Specific alignment
876/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
877/// \endcode
878/// Please note that you cannot use delete on the pointer; it must be
879/// deallocated using an explicit destructor call followed by
880/// \c Context.Deallocate(Ptr).
881///
882/// \param Bytes The number of bytes to allocate. Calculated by the compiler.
883/// \param C The MCContext that provides the allocator.
884/// \param Alignment The alignment of the allocated memory (if the underlying
885/// allocator supports it).
886/// \return The allocated memory. Could be NULL.
887inline void *operator new(size_t Bytes, llvm::MCContext &C,
888 size_t Alignment = 8) noexcept {
889 return C.allocate(Size: Bytes, Align: Alignment);
890}
891/// Placement delete companion to the new above.
892///
893/// This operator is just a companion to the new above. There is no way of
894/// invoking it directly; see the new operator for more details. This operator
895/// is called implicitly by the compiler if a placement new expression using
896/// the MCContext throws in the object constructor.
897inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) noexcept {
898 C.deallocate(Ptr);
899}
900
901/// This placement form of operator new[] uses the MCContext's allocator for
902/// obtaining memory. It is a non-throwing new[], which means that it returns
903/// null on error.
904/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
905/// \code
906/// // Default alignment (8)
907/// char *data = new (Context) char[10];
908/// // Specific alignment
909/// char *data = new (Context, 4) char[10];
910/// \endcode
911/// Please note that you cannot use delete on the pointer; it must be
912/// deallocated using an explicit destructor call followed by
913/// \c Context.Deallocate(Ptr).
914///
915/// \param Bytes The number of bytes to allocate. Calculated by the compiler.
916/// \param C The MCContext that provides the allocator.
917/// \param Alignment The alignment of the allocated memory (if the underlying
918/// allocator supports it).
919/// \return The allocated memory. Could be NULL.
920inline void *operator new[](size_t Bytes, llvm::MCContext &C,
921 size_t Alignment = 8) noexcept {
922 return C.allocate(Size: Bytes, Align: Alignment);
923}
924
925/// Placement delete[] companion to the new[] above.
926///
927/// This operator is just a companion to the new[] above. There is no way of
928/// invoking it directly; see the new[] operator for more details. This operator
929/// is called implicitly by the compiler if a placement new[] expression using
930/// the MCContext throws in the object constructor.
931inline void operator delete[](void *Ptr, llvm::MCContext &C) noexcept {
932 C.deallocate(Ptr);
933}
934
935#endif // LLVM_MC_MCCONTEXT_H
936