1 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_MC_MCCONTEXT_H
11 #define LLVM_MC_MCCONTEXT_H
13 #include "llvm/ADT/DenseMap.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/Twine.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/SectionKind.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/raw_ostream.h"
27 #include <vector> // FIXME: Shouldn't be needed.
38 class MCObjectFileInfo;
46 /// Context object for machine code objects. This class owns all of the
47 /// sections that it creates.
50 MCContext(const MCContext &) = delete;
51 MCContext &operator=(const MCContext &) = delete;
54 typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
57 /// The SourceMgr for this object, if any.
58 const SourceMgr *SrcMgr;
60 /// The MCAsmInfo for this target.
63 /// The MCRegisterInfo for this target.
64 const MCRegisterInfo *MRI;
66 /// The MCObjectFileInfo for this target.
67 const MCObjectFileInfo *MOFI;
69 /// Allocator object used for creating machine code objects.
71 /// We use a bump pointer allocator to avoid the need to track all allocated
73 BumpPtrAllocator Allocator;
75 SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
76 SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
77 SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
79 /// Bindings of names to symbols.
82 /// ELF sections can have a corresponding symbol. This maps one to the
84 DenseMap<const MCSectionELF *, MCSymbolELF *> SectionSymbols;
86 /// A mapping from a local label number and an instance count to a symbol.
87 /// For example, in the assembly
91 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
92 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
94 /// Keeps tracks of names that were used both for used declared and
95 /// artificial symbols.
96 StringMap<bool, BumpPtrAllocator &> UsedNames;
98 /// The next ID to dole out to an unnamed assembler temporary symbol with
100 StringMap<unsigned> NextID;
102 /// Instances of directional local labels.
103 DenseMap<unsigned, MCLabel *> Instances;
104 /// NextInstance() creates the next instance of the directional local label
105 /// for the LocalLabelVal and adds it to the map if needed.
106 unsigned NextInstance(unsigned LocalLabelVal);
107 /// GetInstance() gets the current instance of the directional local label
108 /// for the LocalLabelVal and adds it to the map if needed.
109 unsigned GetInstance(unsigned LocalLabelVal);
111 /// The file name of the log file from the environment variable
112 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
113 /// directive is used or it is an error.
115 /// The stream that gets written to for the .secure_log_unique directive.
116 std::unique_ptr<raw_fd_ostream> SecureLog;
117 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
118 /// catch errors if .secure_log_unique appears twice without
119 /// .secure_log_reset appearing between them.
122 /// The compilation directory to use for DW_AT_comp_dir.
123 SmallString<128> CompilationDir;
125 /// The main file name if passed in explicitly.
126 std::string MainFileName;
128 /// The dwarf file and directory tables from the dwarf .file directive.
129 /// We now emit a line table for each compile unit. To reduce the prologue
130 /// size of each line table, the files and directories used by each compile
131 /// unit are separated.
132 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
134 /// The current dwarf line information from the last dwarf .loc directive.
135 MCDwarfLoc CurrentDwarfLoc;
138 /// Generate dwarf debugging info for assembly source files.
139 bool GenDwarfForAssembly;
141 /// The current dwarf file number when generate dwarf debugging info for
142 /// assembly source files.
143 unsigned GenDwarfFileNumber;
145 /// Sections for generating the .debug_ranges and .debug_aranges sections.
146 SetVector<MCSection *> SectionsForRanges;
148 /// The information gathered from labels that will have dwarf label
149 /// entries when generating dwarf assembly source files.
150 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
152 /// The string to embed in the debug information for the compile unit, if
154 StringRef DwarfDebugFlags;
156 /// The string to embed in as the dwarf AT_producer for the compile unit, if
158 StringRef DwarfDebugProducer;
160 /// The maximum version of dwarf that we should emit.
161 uint16_t DwarfVersion;
163 /// Honor temporary labels, this is useful for debugging semantic
164 /// differences between temporary and non-temporary labels (primarily on
166 bool AllowTemporaryLabels;
167 bool UseNamesOnTempLabels = true;
169 /// The Compile Unit ID that we are currently processing.
170 unsigned DwarfCompileUnitID;
172 struct ELFSectionKey {
173 std::string SectionName;
176 ELFSectionKey(StringRef SectionName, StringRef GroupName,
178 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
180 bool operator<(const ELFSectionKey &Other) const {
181 if (SectionName != Other.SectionName)
182 return SectionName < Other.SectionName;
183 if (GroupName != Other.GroupName)
184 return GroupName < Other.GroupName;
185 return UniqueID < Other.UniqueID;
189 struct COFFSectionKey {
190 std::string SectionName;
193 COFFSectionKey(StringRef SectionName, StringRef GroupName,
195 : SectionName(SectionName), GroupName(GroupName),
196 SelectionKey(SelectionKey) {}
197 bool operator<(const COFFSectionKey &Other) const {
198 if (SectionName != Other.SectionName)
199 return SectionName < Other.SectionName;
200 if (GroupName != Other.GroupName)
201 return GroupName < Other.GroupName;
202 return SelectionKey < Other.SelectionKey;
206 StringMap<MCSectionMachO *> MachOUniquingMap;
207 std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
208 std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
209 StringMap<bool> ELFRelSecNames;
211 SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
213 /// Do automatic reset in destructor
218 MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
220 MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
223 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
227 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
228 const MCObjectFileInfo *MOFI,
229 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
232 const SourceMgr *getSourceManager() const { return SrcMgr; }
234 const MCAsmInfo *getAsmInfo() const { return MAI; }
236 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
238 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
240 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
241 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
243 /// \name Module Lifetime Management
246 /// reset - return object to right after construction state to prepare
247 /// to process a new module
252 /// \name Symbol Management
255 /// Create and return a new linker temporary symbol with a unique but
256 /// unspecified name.
257 MCSymbol *createLinkerPrivateTempSymbol();
259 /// Create and return a new assembler temporary symbol with a unique but
260 /// unspecified name.
261 MCSymbol *createTempSymbol(bool CanBeUnnamed = true);
263 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
264 bool CanBeUnnamed = true);
266 /// Create the definition of a directional local symbol for numbered label
267 /// (used for "1:" definitions).
268 MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
270 /// Create and return a directional local symbol for numbered label (used
271 /// for "1b" or 1f" references).
272 MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
274 /// Lookup the symbol inside with the specified \p Name. If it exists,
275 /// return it. If not, create a forward reference and return it.
277 /// \param Name - The symbol name, which must be unique across all symbols.
278 MCSymbol *getOrCreateSymbol(const Twine &Name);
280 MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section);
282 /// Gets a symbol that will be defined to the final stack offset of a local
283 /// variable after codegen.
285 /// \param Idx - The index of a local variable passed to @llvm.localescape.
286 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
288 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
290 MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
292 /// Get the symbol for \p Name, or null.
293 MCSymbol *lookupSymbol(const Twine &Name) const;
295 /// getSymbols - Get a reference for the symbol table for clients that
296 /// want to, for example, iterate over all symbols. 'const' because we
297 /// still want any modifications to the table itself to use the MCContext
299 const SymbolTable &getSymbols() const { return Symbols; }
303 /// \name Section Management
306 /// Return the MCSection for the specified mach-o section. This requires
307 /// the operands to be valid.
308 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
309 unsigned TypeAndAttributes,
310 unsigned Reserved2, SectionKind K,
311 const char *BeginSymName = nullptr);
313 MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
314 unsigned TypeAndAttributes, SectionKind K,
315 const char *BeginSymName = nullptr) {
316 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
320 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
322 return getELFSection(Section, Type, Flags, nullptr);
325 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
326 unsigned Flags, const char *BeginSymName) {
327 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
330 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
331 unsigned Flags, unsigned EntrySize,
333 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
336 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
337 unsigned Flags, unsigned EntrySize,
338 StringRef Group, const char *BeginSymName) {
339 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
343 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
344 unsigned Flags, unsigned EntrySize,
345 StringRef Group, unsigned UniqueID) {
346 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
350 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
351 unsigned Flags, unsigned EntrySize,
352 StringRef Group, unsigned UniqueID,
353 const char *BeginSymName);
355 MCSectionELF *getELFSection(StringRef Section, unsigned Type,
356 unsigned Flags, unsigned EntrySize,
357 const MCSymbolELF *Group, unsigned UniqueID,
358 const char *BeginSymName,
359 const MCSectionELF *Associated);
361 MCSectionELF *createELFRelSection(StringRef Name, unsigned Type,
362 unsigned Flags, unsigned EntrySize,
363 const MCSymbolELF *Group,
364 const MCSectionELF *Associated);
366 void renameELFSection(MCSectionELF *Section, StringRef Name);
368 MCSectionELF *createELFGroupSection(const MCSymbolELF *Group);
370 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
371 SectionKind Kind, StringRef COMDATSymName,
373 const char *BeginSymName = nullptr);
375 MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
377 const char *BeginSymName = nullptr);
379 MCSectionCOFF *getCOFFSection(StringRef Section);
381 /// Gets or creates a section equivalent to Sec that is associated with the
382 /// section containing KeySym. For example, to create a debug info section
383 /// associated with an inline function, pass the normal debug info section
384 /// as Sec and the function symbol as KeySym.
385 MCSectionCOFF *getAssociativeCOFFSection(MCSectionCOFF *Sec,
386 const MCSymbol *KeySym);
388 // Create and save a copy of STI and return a reference to the copy.
389 MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
393 /// \name Dwarf Management
396 /// \brief Get the compilation directory for DW_AT_comp_dir
397 /// This can be overridden by clients which want to control the reported
398 /// compilation directory and have it be something other than the current
399 /// working directory.
400 /// Returns an empty string if the current directory cannot be determined.
401 StringRef getCompilationDir() const { return CompilationDir; }
403 /// \brief Set the compilation directory for DW_AT_comp_dir
404 /// Override the default (CWD) compilation directory.
405 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
407 /// \brief Get the main file name for use in error messages and debug
408 /// info. This can be set to ensure we've got the correct file name
409 /// after preprocessing or for -save-temps.
410 const std::string &getMainFileName() const { return MainFileName; }
412 /// \brief Set the main file name and override the default.
413 void setMainFileName(StringRef S) { MainFileName = S; }
415 /// Creates an entry in the dwarf file and directory tables.
416 unsigned getDwarfFile(StringRef Directory, StringRef FileName,
417 unsigned FileNumber, unsigned CUID);
419 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
421 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
422 return MCDwarfLineTablesCUMap;
425 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
426 return MCDwarfLineTablesCUMap[CUID];
429 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
430 auto I = MCDwarfLineTablesCUMap.find(CUID);
431 assert(I != MCDwarfLineTablesCUMap.end());
435 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
436 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
438 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
439 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
442 bool hasMCLineSections() const {
443 for (const auto &Table : MCDwarfLineTablesCUMap)
444 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
448 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
449 void setDwarfCompileUnitID(unsigned CUIndex) {
450 DwarfCompileUnitID = CUIndex;
452 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
453 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
456 /// Saves the information from the currently parsed dwarf .loc directive
457 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
458 /// in the line number table with this information and the address of the
459 /// instruction will be created.
460 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
461 unsigned Flags, unsigned Isa,
462 unsigned Discriminator) {
463 CurrentDwarfLoc.setFileNum(FileNum);
464 CurrentDwarfLoc.setLine(Line);
465 CurrentDwarfLoc.setColumn(Column);
466 CurrentDwarfLoc.setFlags(Flags);
467 CurrentDwarfLoc.setIsa(Isa);
468 CurrentDwarfLoc.setDiscriminator(Discriminator);
471 void clearDwarfLocSeen() { DwarfLocSeen = false; }
473 bool getDwarfLocSeen() { return DwarfLocSeen; }
474 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
476 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
477 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
478 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
479 void setGenDwarfFileNumber(unsigned FileNumber) {
480 GenDwarfFileNumber = FileNumber;
482 const SetVector<MCSection *> &getGenDwarfSectionSyms() {
483 return SectionsForRanges;
485 bool addGenDwarfSection(MCSection *Sec) {
486 return SectionsForRanges.insert(Sec);
489 void finalizeDwarfSections(MCStreamer &MCOS);
490 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
491 return MCGenDwarfLabelEntries;
493 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
494 MCGenDwarfLabelEntries.push_back(E);
497 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
498 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
500 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
501 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
503 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
504 uint16_t getDwarfVersion() const { return DwarfVersion; }
508 char *getSecureLogFile() { return SecureLogFile; }
509 raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
510 bool getSecureLogUsed() { return SecureLogUsed; }
511 void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
512 SecureLog = std::move(Value);
514 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
516 void *allocate(unsigned Size, unsigned Align = 8) {
517 return Allocator.Allocate(Size, Align);
519 void deallocate(void *Ptr) {}
521 bool hadError() { return HadError; }
522 void reportError(SMLoc L, const Twine &Msg);
523 // Unrecoverable error has occurred. Display the best diagnostic we can
524 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
525 // FIXME: We should really do something about that.
526 LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
530 } // end namespace llvm
532 // operator new and delete aren't allowed inside namespaces.
533 // The throw specifications are mandated by the standard.
534 /// \brief Placement new for using the MCContext's allocator.
536 /// This placement form of operator new uses the MCContext's allocator for
537 /// obtaining memory. It is a non-throwing new, which means that it returns
538 /// null on error. (If that is what the allocator does. The current does, so if
539 /// this ever changes, this operator will have to be changed, too.)
540 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
542 /// // Default alignment (8)
543 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
544 /// // Specific alignment
545 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
547 /// Please note that you cannot use delete on the pointer; it must be
548 /// deallocated using an explicit destructor call followed by
549 /// \c Context.Deallocate(Ptr).
551 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
552 /// \param C The MCContext that provides the allocator.
553 /// \param Alignment The alignment of the allocated memory (if the underlying
554 /// allocator supports it).
555 /// \return The allocated memory. Could be NULL.
556 inline void *operator new(size_t Bytes, llvm::MCContext &C,
557 size_t Alignment = 8) LLVM_NOEXCEPT {
558 return C.allocate(Bytes, Alignment);
560 /// \brief Placement delete companion to the new above.
562 /// This operator is just a companion to the new above. There is no way of
563 /// invoking it directly; see the new operator for more details. This operator
564 /// is called implicitly by the compiler if a placement new expression using
565 /// the MCContext throws in the object constructor.
566 inline void operator delete(void *Ptr, llvm::MCContext &C,
567 size_t) LLVM_NOEXCEPT {
571 /// This placement form of operator new[] uses the MCContext's allocator for
572 /// obtaining memory. It is a non-throwing new[], which means that it returns
574 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
576 /// // Default alignment (8)
577 /// char *data = new (Context) char[10];
578 /// // Specific alignment
579 /// char *data = new (Context, 4) char[10];
581 /// Please note that you cannot use delete on the pointer; it must be
582 /// deallocated using an explicit destructor call followed by
583 /// \c Context.Deallocate(Ptr).
585 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
586 /// \param C The MCContext that provides the allocator.
587 /// \param Alignment The alignment of the allocated memory (if the underlying
588 /// allocator supports it).
589 /// \return The allocated memory. Could be NULL.
590 inline void *operator new[](size_t Bytes, llvm::MCContext &C,
591 size_t Alignment = 8) LLVM_NOEXCEPT {
592 return C.allocate(Bytes, Alignment);
595 /// \brief Placement delete[] companion to the new[] above.
597 /// This operator is just a companion to the new[] above. There is no way of
598 /// invoking it directly; see the new[] operator for more details. This operator
599 /// is called implicitly by the compiler if a placement new[] expression using
600 /// the MCContext throws in the object constructor.
601 inline void operator delete[](void *Ptr, llvm::MCContext &C) LLVM_NOEXCEPT {