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