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