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/SectionKind.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/raw_ostream.h"
26 #include <vector> // FIXME: Shouldn't be needed.
36 class MCObjectFileInfo;
44 /// Context object for machine code objects. This class owns all of the
45 /// sections that it creates.
48 MCContext(const MCContext&) = delete;
49 MCContext &operator=(const MCContext&) = delete;
51 typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
53 /// The SourceMgr for this object, if any.
54 const SourceMgr *SrcMgr;
56 /// The MCAsmInfo for this target.
59 /// The MCRegisterInfo for this target.
60 const MCRegisterInfo *MRI;
62 /// The MCObjectFileInfo for this target.
63 const MCObjectFileInfo *MOFI;
65 /// Allocator object used for creating machine code objects.
67 /// We use a bump pointer allocator to avoid the need to track all allocated
69 BumpPtrAllocator Allocator;
71 /// Bindings of names to symbols.
74 /// ELF sections can have a corresponding symbol. This maps one to the
76 DenseMap<const MCSectionELF*, MCSymbol*> SectionSymbols;
78 /// A maping from a local label number and an instance count to a symbol.
79 /// For example, in the assembly
83 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
84 DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
86 /// Keeps tracks of names that were used both for used declared and
87 /// artificial symbols.
88 StringMap<bool, BumpPtrAllocator&> UsedNames;
90 /// The next ID to dole out to an unnamed assembler temporary symbol.
91 unsigned NextUniqueID;
93 /// Instances of directional local labels.
94 DenseMap<unsigned, MCLabel *> Instances;
95 /// NextInstance() creates the next instance of the directional local label
96 /// for the LocalLabelVal and adds it to the map if needed.
97 unsigned NextInstance(unsigned LocalLabelVal);
98 /// GetInstance() gets the current instance of the directional local label
99 /// for the LocalLabelVal and adds it to the map if needed.
100 unsigned GetInstance(unsigned LocalLabelVal);
102 /// The file name of the log file from the environment variable
103 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
104 /// directive is used or it is an error.
106 /// The stream that gets written to for the .secure_log_unique directive.
107 raw_ostream *SecureLog;
108 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
109 /// catch errors if .secure_log_unique appears twice without
110 /// .secure_log_reset appearing between them.
113 /// The compilation directory to use for DW_AT_comp_dir.
114 SmallString<128> CompilationDir;
116 /// The main file name if passed in explicitly.
117 std::string MainFileName;
119 /// The dwarf file and directory tables from the dwarf .file directive.
120 /// We now emit a line table for each compile unit. To reduce the prologue
121 /// size of each line table, the files and directories used by each compile
122 /// unit are separated.
123 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
125 /// The current dwarf line information from the last dwarf .loc directive.
126 MCDwarfLoc CurrentDwarfLoc;
129 /// Generate dwarf debugging info for assembly source files.
130 bool GenDwarfForAssembly;
132 /// The current dwarf file number when generate dwarf debugging info for
133 /// assembly source files.
134 unsigned GenDwarfFileNumber;
136 /// Symbols created for the start and end of each section, used for
137 /// generating the .debug_ranges and .debug_aranges sections.
138 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >
141 /// The information gathered from labels that will have dwarf label
142 /// entries when generating dwarf assembly source files.
143 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
145 /// The string to embed in the debug information for the compile unit, if
147 StringRef DwarfDebugFlags;
149 /// The string to embed in as the dwarf AT_producer for the compile unit, if
151 StringRef DwarfDebugProducer;
153 /// The maximum version of dwarf that we should emit.
154 uint16_t DwarfVersion;
156 /// Honor temporary labels, this is useful for debugging semantic
157 /// differences between temporary and non-temporary labels (primarily on
159 bool AllowTemporaryLabels;
161 /// The Compile Unit ID that we are currently processing.
162 unsigned DwarfCompileUnitID;
164 typedef std::pair<std::string, std::string> SectionGroupPair;
165 typedef std::tuple<std::string, std::string, int> SectionGroupTriple;
167 StringMap<const MCSectionMachO*> MachOUniquingMap;
168 std::map<SectionGroupPair, const MCSectionELF *> ELFUniquingMap;
169 std::map<SectionGroupTriple, const MCSectionCOFF *> COFFUniquingMap;
171 /// Do automatic reset in destructor
174 MCSymbol *CreateSymbol(StringRef Name);
176 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
180 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
181 const MCObjectFileInfo *MOFI,
182 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
185 const SourceMgr *getSourceManager() const { return SrcMgr; }
187 const MCAsmInfo *getAsmInfo() const { return MAI; }
189 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
191 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
193 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
195 /// @name Module Lifetime Management
198 /// reset - return object to right after construction state to prepare
199 /// to process a new module
204 /// @name Symbol Management
207 /// Create and return a new linker temporary symbol with a unique but
208 /// unspecified name.
209 MCSymbol *CreateLinkerPrivateTempSymbol();
211 /// Create and return a new assembler temporary symbol with a unique but
212 /// unspecified name.
213 MCSymbol *CreateTempSymbol();
215 MCSymbol *createTempSymbol(const Twine &Name);
217 /// Return a unique identifier for use in constructing symbol names.
218 unsigned getUniqueSymbolID() { return NextUniqueID++; }
220 /// Create the definition of a directional local symbol for numbered label
221 /// (used for "1:" definitions).
222 MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
224 /// Create and return a directional local symbol for numbered label (used
225 /// for "1b" or 1f" references).
226 MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
228 /// Lookup the symbol inside with the specified @p Name. If it exists,
229 /// return it. If not, create a forward reference and return it.
231 /// @param Name - The symbol name, which must be unique across all symbols.
232 MCSymbol *GetOrCreateSymbol(const Twine &Name);
234 MCSymbol *getOrCreateSectionSymbol(const MCSectionELF &Section);
236 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
238 /// Get the symbol for \p Name, or null.
239 MCSymbol *LookupSymbol(StringRef Name) const;
240 MCSymbol *LookupSymbol(const Twine &Name) const;
242 /// getSymbols - Get a reference for the symbol table for clients that
243 /// want to, for example, iterate over all symbols. 'const' because we
244 /// still want any modifications to the table itself to use the MCContext
246 const SymbolTable &getSymbols() const {
252 /// @name Section Management
255 /// Return the MCSection for the specified mach-o section. This requires
256 /// the operands to be valid.
257 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
258 unsigned TypeAndAttributes,
259 unsigned Reserved2, SectionKind K,
260 const char *BeginSymName = nullptr);
262 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
263 unsigned TypeAndAttributes,
265 const char *BeginSymName = nullptr) {
266 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
270 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
272 const char *BeginSymName = nullptr);
274 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
275 unsigned Flags, unsigned EntrySize,
277 const char *BeginSymName = nullptr);
279 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
280 unsigned Flags, unsigned EntrySize,
281 StringRef Group, bool Unique,
282 const char *BeginSymName = nullptr);
284 void renameELFSection(const MCSectionELF *Section, StringRef Name);
286 const MCSectionELF *CreateELFGroupSection();
288 const MCSectionCOFF *getCOFFSection(StringRef Section,
289 unsigned Characteristics,
291 StringRef COMDATSymName, int Selection,
292 const char *BeginSymName = nullptr);
294 const MCSectionCOFF *getCOFFSection(StringRef Section,
295 unsigned Characteristics,
297 const char *BeginSymName = nullptr);
299 const MCSectionCOFF *getCOFFSection(StringRef Section);
301 /// Gets or creates a section equivalent to Sec that is associated with the
302 /// section containing KeySym. For example, to create a debug info section
303 /// associated with an inline function, pass the normal debug info section
304 /// as Sec and the function symbol as KeySym.
305 const MCSectionCOFF *getAssociativeCOFFSection(const MCSectionCOFF *Sec,
306 const MCSymbol *KeySym);
310 /// @name Dwarf Management
313 /// \brief Get the compilation directory for DW_AT_comp_dir
314 /// This can be overridden by clients which want to control the reported
315 /// compilation directory and have it be something other than the current
316 /// working directory.
317 /// Returns an empty string if the current directory cannot be determined.
318 StringRef getCompilationDir() const { return CompilationDir; }
320 /// \brief Set the compilation directory for DW_AT_comp_dir
321 /// Override the default (CWD) compilation directory.
322 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
324 /// \brief Get the main file name for use in error messages and debug
325 /// info. This can be set to ensure we've got the correct file name
326 /// after preprocessing or for -save-temps.
327 const std::string &getMainFileName() const { return MainFileName; }
329 /// \brief Set the main file name and override the default.
330 void setMainFileName(StringRef S) { MainFileName = S; }
332 /// Creates an entry in the dwarf file and directory tables.
333 unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
334 unsigned FileNumber, unsigned CUID);
336 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
338 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
339 return MCDwarfLineTablesCUMap;
342 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
343 return MCDwarfLineTablesCUMap[CUID];
346 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
347 auto I = MCDwarfLineTablesCUMap.find(CUID);
348 assert(I != MCDwarfLineTablesCUMap.end());
352 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
353 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
355 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
356 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
359 bool hasMCLineSections() const {
360 for (const auto &Table : MCDwarfLineTablesCUMap)
361 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
365 unsigned getDwarfCompileUnitID() {
366 return DwarfCompileUnitID;
368 void setDwarfCompileUnitID(unsigned CUIndex) {
369 DwarfCompileUnitID = CUIndex;
371 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
372 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
375 /// Saves the information from the currently parsed dwarf .loc directive
376 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
377 /// in the line number table with this information and the address of the
378 /// instruction will be created.
379 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
380 unsigned Flags, unsigned Isa,
381 unsigned Discriminator) {
382 CurrentDwarfLoc.setFileNum(FileNum);
383 CurrentDwarfLoc.setLine(Line);
384 CurrentDwarfLoc.setColumn(Column);
385 CurrentDwarfLoc.setFlags(Flags);
386 CurrentDwarfLoc.setIsa(Isa);
387 CurrentDwarfLoc.setDiscriminator(Discriminator);
390 void ClearDwarfLocSeen() { DwarfLocSeen = false; }
392 bool getDwarfLocSeen() { return DwarfLocSeen; }
393 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
395 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
396 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
397 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
398 void setGenDwarfFileNumber(unsigned FileNumber) {
399 GenDwarfFileNumber = FileNumber;
401 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > &
402 getGenDwarfSectionSyms() {
403 return SectionStartEndSyms;
405 std::pair<MapVector<const MCSection *,
406 std::pair<MCSymbol *, MCSymbol *> >::iterator,
408 addGenDwarfSection(const MCSection *Sec) {
409 return SectionStartEndSyms.insert(
410 std::make_pair(Sec, std::make_pair(nullptr, nullptr)));
412 void finalizeDwarfSections(MCStreamer &MCOS);
413 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
414 return MCGenDwarfLabelEntries;
416 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
417 MCGenDwarfLabelEntries.push_back(E);
420 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
421 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
423 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
424 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
426 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
427 uint16_t getDwarfVersion() const { return DwarfVersion; }
431 char *getSecureLogFile() { return SecureLogFile; }
432 raw_ostream *getSecureLog() { return SecureLog; }
433 bool getSecureLogUsed() { return SecureLogUsed; }
434 void setSecureLog(raw_ostream *Value) {
437 void setSecureLogUsed(bool Value) {
438 SecureLogUsed = Value;
441 void *Allocate(unsigned Size, unsigned Align = 8) {
442 return Allocator.Allocate(Size, Align);
444 void Deallocate(void *Ptr) {
447 // Unrecoverable error has occurred. Display the best diagnostic we can
448 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
449 // FIXME: We should really do something about that.
450 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
453 } // end namespace llvm
455 // operator new and delete aren't allowed inside namespaces.
456 // The throw specifications are mandated by the standard.
457 /// @brief Placement new for using the MCContext's allocator.
459 /// This placement form of operator new uses the MCContext's allocator for
460 /// obtaining memory. It is a non-throwing new, which means that it returns
461 /// null on error. (If that is what the allocator does. The current does, so if
462 /// this ever changes, this operator will have to be changed, too.)
463 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
465 /// // Default alignment (16)
466 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
467 /// // Specific alignment
468 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
470 /// Please note that you cannot use delete on the pointer; it must be
471 /// deallocated using an explicit destructor call followed by
472 /// @c Context.Deallocate(Ptr).
474 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
475 /// @param C The MCContext that provides the allocator.
476 /// @param Alignment The alignment of the allocated memory (if the underlying
477 /// allocator supports it).
478 /// @return The allocated memory. Could be NULL.
479 inline void *operator new(size_t Bytes, llvm::MCContext &C,
480 size_t Alignment = 16) throw () {
481 return C.Allocate(Bytes, Alignment);
483 /// @brief Placement delete companion to the new above.
485 /// This operator is just a companion to the new above. There is no way of
486 /// invoking it directly; see the new operator for more details. This operator
487 /// is called implicitly by the compiler if a placement new expression using
488 /// the MCContext throws in the object constructor.
489 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
494 /// This placement form of operator new[] uses the MCContext's allocator for
495 /// obtaining memory. It is a non-throwing new[], which means that it returns
497 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
499 /// // Default alignment (16)
500 /// char *data = new (Context) char[10];
501 /// // Specific alignment
502 /// char *data = new (Context, 8) char[10];
504 /// Please note that you cannot use delete on the pointer; it must be
505 /// deallocated using an explicit destructor call followed by
506 /// @c Context.Deallocate(Ptr).
508 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
509 /// @param C The MCContext that provides the allocator.
510 /// @param Alignment The alignment of the allocated memory (if the underlying
511 /// allocator supports it).
512 /// @return The allocated memory. Could be NULL.
513 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
514 size_t Alignment = 16) throw () {
515 return C.Allocate(Bytes, Alignment);
518 /// @brief Placement delete[] companion to the new[] above.
520 /// This operator is just a companion to the new[] above. There is no way of
521 /// invoking it directly; see the new[] operator for more details. This operator
522 /// is called implicitly by the compiler if a placement new[] expression using
523 /// the MCContext throws in the object constructor.
524 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {