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/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/MC/MCDwarf.h"
18 #include "llvm/MC/SectionKind.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/raw_ostream.h"
23 #include <vector> // FIXME: Shouldn't be needed.
33 class MCObjectFileInfo;
43 /// MCContext - Context object for machine code objects. This class owns all
44 /// of the sections that it creates.
47 MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
48 MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
50 typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
52 /// The SourceMgr for this object, if any.
53 const SourceMgr *SrcMgr;
55 /// The MCAsmInfo for this target.
58 /// The MCRegisterInfo for this target.
59 const MCRegisterInfo *MRI;
61 /// The MCObjectFileInfo for this target.
62 const MCObjectFileInfo *MOFI;
64 /// Allocator - Allocator object used for creating machine code objects.
66 /// We use a bump pointer allocator to avoid the need to track all allocated
68 BumpPtrAllocator Allocator;
70 /// Symbols - Bindings of names to symbols.
73 /// A maping from a local label number and an instance count to a symbol.
74 /// For example, in the assembly
78 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
79 DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
81 /// UsedNames - Keeps tracks of names that were used both for used declared
82 /// and artificial symbols.
83 StringMap<bool, BumpPtrAllocator&> UsedNames;
85 /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
87 unsigned NextUniqueID;
89 /// Instances of directional local labels.
90 DenseMap<unsigned, MCLabel *> Instances;
91 /// NextInstance() creates the next instance of the directional local label
92 /// for the LocalLabelVal and adds it to the map if needed.
93 unsigned NextInstance(unsigned LocalLabelVal);
94 /// GetInstance() gets the current instance of the directional local label
95 /// for the LocalLabelVal and adds it to the map if needed.
96 unsigned GetInstance(unsigned LocalLabelVal);
98 /// The file name of the log file from the environment variable
99 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
100 /// directive is used or it is an error.
102 /// The stream that gets written to for the .secure_log_unique directive.
103 raw_ostream *SecureLog;
104 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
105 /// catch errors if .secure_log_unique appears twice without
106 /// .secure_log_reset appearing between them.
109 /// The compilation directory to use for DW_AT_comp_dir.
110 SmallString<128> CompilationDir;
112 /// The main file name if passed in explicitly.
113 std::string MainFileName;
115 /// The dwarf file and directory tables from the dwarf .file directive.
116 /// We now emit a line table for each compile unit. To reduce the prologue
117 /// size of each line table, the files and directories used by each compile
118 /// unit are separated.
119 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
121 /// The current dwarf line information from the last dwarf .loc directive.
122 MCDwarfLoc CurrentDwarfLoc;
125 /// Generate dwarf debugging info for assembly source files.
126 bool GenDwarfForAssembly;
128 /// The current dwarf file number when generate dwarf debugging info for
129 /// assembly source files.
130 unsigned GenDwarfFileNumber;
132 /// The default initial text section that we generate dwarf debugging line
133 /// info for when generating dwarf assembly source files.
134 const MCSection *GenDwarfSection;
135 /// Symbols created for the start and end of this section.
136 MCSymbol *GenDwarfSectionStartSym, *GenDwarfSectionEndSym;
138 /// The information gathered from labels that will have dwarf label
139 /// entries when generating dwarf assembly source files.
140 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
142 /// The string to embed in the debug information for the compile unit, if
144 StringRef DwarfDebugFlags;
146 /// The string to embed in as the dwarf AT_producer for the compile unit, if
148 StringRef DwarfDebugProducer;
150 /// Honor temporary labels, this is useful for debugging semantic
151 /// differences between temporary and non-temporary labels (primarily on
153 bool AllowTemporaryLabels;
155 /// The Compile Unit ID that we are currently processing.
156 unsigned DwarfCompileUnitID;
158 typedef std::pair<std::string, std::string> SectionGroupPair;
160 StringMap<const MCSectionMachO*> MachOUniquingMap;
161 std::map<SectionGroupPair, const MCSectionELF *> ELFUniquingMap;
162 std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniquingMap;
164 /// Do automatic reset in destructor
167 MCSymbol *CreateSymbol(StringRef Name);
169 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
173 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
174 const MCObjectFileInfo *MOFI,
175 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
178 const SourceMgr *getSourceManager() const { return SrcMgr; }
180 const MCAsmInfo *getAsmInfo() const { return MAI; }
182 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
184 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
186 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
188 /// @name Module Lifetime Management
191 /// reset - return object to right after construction state to prepare
192 /// to process a new module
197 /// @name Symbol Management
200 /// CreateLinkerPrivateTempSymbol - Create and return a new linker temporary
201 /// symbol with a unique but unspecified name.
202 MCSymbol *CreateLinkerPrivateTempSymbol();
204 /// CreateTempSymbol - Create and return a new assembler temporary symbol
205 /// with a unique but unspecified name.
206 MCSymbol *CreateTempSymbol();
208 /// getUniqueSymbolID() - Return a unique identifier for use in constructing
210 unsigned getUniqueSymbolID() { return NextUniqueID++; }
212 /// Create the definition of a directional local symbol for numbered label
213 /// (used for "1:" definitions).
214 MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
216 /// Create and return a directional local symbol for numbered label (used
217 /// for "1b" or 1f" references).
218 MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
220 /// GetOrCreateSymbol - Lookup the symbol inside with the specified
221 /// @p Name. If it exists, return it. If not, create a forward
222 /// reference and return it.
224 /// @param Name - The symbol name, which must be unique across all symbols.
225 MCSymbol *GetOrCreateSymbol(StringRef Name);
226 MCSymbol *GetOrCreateSymbol(const Twine &Name);
228 /// LookupSymbol - Get the symbol for \p Name, or null.
229 MCSymbol *LookupSymbol(StringRef Name) const;
230 MCSymbol *LookupSymbol(const Twine &Name) const;
232 /// getSymbols - Get a reference for the symbol table for clients that
233 /// want to, for example, iterate over all symbols. 'const' because we
234 /// still want any modifications to the table itself to use the MCContext
236 const SymbolTable &getSymbols() const {
242 /// @name Section Management
245 /// getMachOSection - Return the MCSection for the specified mach-o section.
246 /// This requires the operands to be valid.
247 const MCSectionMachO *getMachOSection(StringRef Segment,
249 unsigned TypeAndAttributes,
252 const MCSectionMachO *getMachOSection(StringRef Segment,
254 unsigned TypeAndAttributes,
256 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
259 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
260 unsigned Flags, SectionKind Kind);
262 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
263 unsigned Flags, SectionKind Kind,
264 unsigned EntrySize, StringRef Group);
266 void renameELFSection(const MCSectionELF *Section, StringRef Name);
268 const MCSectionELF *CreateELFGroupSection();
270 const MCSectionCOFF *getCOFFSection(StringRef Section,
271 unsigned Characteristics,
273 StringRef COMDATSymName,
275 const MCSectionCOFF *Assoc = nullptr);
277 const MCSectionCOFF *getCOFFSection(StringRef Section,
278 unsigned Characteristics,
281 const MCSectionCOFF *getCOFFSection(StringRef Section);
285 /// @name Dwarf Management
288 /// \brief Get the compilation directory for DW_AT_comp_dir
289 /// This can be overridden by clients which want to control the reported
290 /// compilation directory and have it be something other than the current
291 /// working directory.
292 /// Returns an empty string if the current directory cannot be determined.
293 StringRef getCompilationDir() const { return CompilationDir; }
295 /// \brief Set the compilation directory for DW_AT_comp_dir
296 /// Override the default (CWD) compilation directory.
297 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
299 /// \brief Get the main file name for use in error messages and debug
300 /// info. This can be set to ensure we've got the correct file name
301 /// after preprocessing or for -save-temps.
302 const std::string &getMainFileName() const { return MainFileName; }
304 /// \brief Set the main file name and override the default.
305 void setMainFileName(StringRef S) { MainFileName = S; }
307 /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
308 unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
309 unsigned FileNumber, unsigned CUID);
311 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
313 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
314 return MCDwarfLineTablesCUMap;
317 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
318 return MCDwarfLineTablesCUMap[CUID];
321 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
322 auto I = MCDwarfLineTablesCUMap.find(CUID);
323 assert(I != MCDwarfLineTablesCUMap.end());
327 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
328 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
330 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
331 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
334 bool hasMCLineSections() const {
335 for (const auto &Table : MCDwarfLineTablesCUMap)
336 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
340 unsigned getDwarfCompileUnitID() {
341 return DwarfCompileUnitID;
343 void setDwarfCompileUnitID(unsigned CUIndex) {
344 DwarfCompileUnitID = CUIndex;
346 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
347 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
350 /// setCurrentDwarfLoc - saves the information from the currently parsed
351 /// dwarf .loc directive and sets DwarfLocSeen. When the next instruction
352 /// is assembled an entry in the line number table with this information and
353 /// the address of the instruction will be created.
354 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
355 unsigned Flags, unsigned Isa,
356 unsigned Discriminator) {
357 CurrentDwarfLoc.setFileNum(FileNum);
358 CurrentDwarfLoc.setLine(Line);
359 CurrentDwarfLoc.setColumn(Column);
360 CurrentDwarfLoc.setFlags(Flags);
361 CurrentDwarfLoc.setIsa(Isa);
362 CurrentDwarfLoc.setDiscriminator(Discriminator);
365 void ClearDwarfLocSeen() { DwarfLocSeen = false; }
367 bool getDwarfLocSeen() { return DwarfLocSeen; }
368 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
370 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
371 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
372 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
373 void setGenDwarfFileNumber(unsigned FileNumber) {
374 GenDwarfFileNumber = FileNumber;
376 const MCSection *getGenDwarfSection() { return GenDwarfSection; }
377 void setGenDwarfSection(const MCSection *Sec) { GenDwarfSection = Sec; }
378 MCSymbol *getGenDwarfSectionStartSym() { return GenDwarfSectionStartSym; }
379 void setGenDwarfSectionStartSym(MCSymbol *Sym) {
380 GenDwarfSectionStartSym = Sym;
382 MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
383 void setGenDwarfSectionEndSym(MCSymbol *Sym) {
384 GenDwarfSectionEndSym = Sym;
386 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
387 return MCGenDwarfLabelEntries;
389 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
390 MCGenDwarfLabelEntries.push_back(E);
393 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
394 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
396 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
397 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
401 char *getSecureLogFile() { return SecureLogFile; }
402 raw_ostream *getSecureLog() { return SecureLog; }
403 bool getSecureLogUsed() { return SecureLogUsed; }
404 void setSecureLog(raw_ostream *Value) {
407 void setSecureLogUsed(bool Value) {
408 SecureLogUsed = Value;
411 void *Allocate(unsigned Size, unsigned Align = 8) {
412 return Allocator.Allocate(Size, Align);
414 void Deallocate(void *Ptr) {
417 // Unrecoverable error has occurred. Display the best diagnostic we can
418 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
419 // FIXME: We should really do something about that.
420 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
423 } // end namespace llvm
425 // operator new and delete aren't allowed inside namespaces.
426 // The throw specifications are mandated by the standard.
427 /// @brief Placement new for using the MCContext's allocator.
429 /// This placement form of operator new uses the MCContext's allocator for
430 /// obtaining memory. It is a non-throwing new, which means that it returns
431 /// null on error. (If that is what the allocator does. The current does, so if
432 /// this ever changes, this operator will have to be changed, too.)
433 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
435 /// // Default alignment (16)
436 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
437 /// // Specific alignment
438 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
440 /// Please note that you cannot use delete on the pointer; it must be
441 /// deallocated using an explicit destructor call followed by
442 /// @c Context.Deallocate(Ptr).
444 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
445 /// @param C The MCContext that provides the allocator.
446 /// @param Alignment The alignment of the allocated memory (if the underlying
447 /// allocator supports it).
448 /// @return The allocated memory. Could be NULL.
449 inline void *operator new(size_t Bytes, llvm::MCContext &C,
450 size_t Alignment = 16) throw () {
451 return C.Allocate(Bytes, Alignment);
453 /// @brief Placement delete companion to the new above.
455 /// This operator is just a companion to the new above. There is no way of
456 /// invoking it directly; see the new operator for more details. This operator
457 /// is called implicitly by the compiler if a placement new expression using
458 /// the MCContext throws in the object constructor.
459 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
464 /// This placement form of operator new[] uses the MCContext's allocator for
465 /// obtaining memory. It is a non-throwing new[], which means that it returns
467 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
469 /// // Default alignment (16)
470 /// char *data = new (Context) char[10];
471 /// // Specific alignment
472 /// char *data = new (Context, 8) char[10];
474 /// Please note that you cannot use delete on the pointer; it must be
475 /// deallocated using an explicit destructor call followed by
476 /// @c Context.Deallocate(Ptr).
478 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
479 /// @param C The MCContext that provides the allocator.
480 /// @param Alignment The alignment of the allocated memory (if the underlying
481 /// allocator supports it).
482 /// @return The allocated memory. Could be NULL.
483 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
484 size_t Alignment = 16) throw () {
485 return C.Allocate(Bytes, Alignment);
488 /// @brief Placement delete[] companion to the new[] above.
490 /// This operator is just a companion to the new[] above. There is no way of
491 /// invoking it directly; see the new[] operator for more details. This operator
492 /// is called implicitly by the compiler if a placement new[] expression using
493 /// the MCContext throws in the object constructor.
494 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {