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