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