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;
52 typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
55 /// The SourceMgr for this object, if any.
56 const SourceMgr *SrcMgr;
58 /// The MCAsmInfo for this target.
61 /// The MCRegisterInfo for this target.
62 const MCRegisterInfo *MRI;
64 /// The MCObjectFileInfo for this target.
65 const MCObjectFileInfo *MOFI;
67 /// Allocator object used for creating machine code objects.
69 /// We use a bump pointer allocator to avoid the need to track all allocated
71 BumpPtrAllocator Allocator;
73 /// Bindings of names to symbols.
76 /// ELF sections can have a corresponding symbol. This maps one to the
78 DenseMap<const MCSectionELF *, MCSymbol *> SectionSymbols;
80 /// A mapping from a local label number and an instance count to a symbol.
81 /// For example, in the assembly
85 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
86 DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
88 /// Keeps tracks of names that were used both for used declared and
89 /// artificial symbols.
90 StringMap<bool, BumpPtrAllocator &> UsedNames;
92 /// The next ID to dole out to an unnamed assembler temporary symbol with
94 StringMap<unsigned> NextID;
96 /// Instances of directional local labels.
97 DenseMap<unsigned, MCLabel *> Instances;
98 /// NextInstance() creates the next instance of the directional local label
99 /// for the LocalLabelVal and adds it to the map if needed.
100 unsigned NextInstance(unsigned LocalLabelVal);
101 /// GetInstance() gets the current instance of the directional local label
102 /// for the LocalLabelVal and adds it to the map if needed.
103 unsigned GetInstance(unsigned LocalLabelVal);
105 /// The file name of the log file from the environment variable
106 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
107 /// directive is used or it is an error.
109 /// The stream that gets written to for the .secure_log_unique directive.
110 raw_ostream *SecureLog;
111 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
112 /// catch errors if .secure_log_unique appears twice without
113 /// .secure_log_reset appearing between them.
116 /// The compilation directory to use for DW_AT_comp_dir.
117 SmallString<128> CompilationDir;
119 /// The main file name if passed in explicitly.
120 std::string MainFileName;
122 /// The dwarf file and directory tables from the dwarf .file directive.
123 /// We now emit a line table for each compile unit. To reduce the prologue
124 /// size of each line table, the files and directories used by each compile
125 /// unit are separated.
126 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
128 /// The current dwarf line information from the last dwarf .loc directive.
129 MCDwarfLoc CurrentDwarfLoc;
132 /// Generate dwarf debugging info for assembly source files.
133 bool GenDwarfForAssembly;
135 /// The current dwarf file number when generate dwarf debugging info for
136 /// assembly source files.
137 unsigned GenDwarfFileNumber;
139 /// Symbols created for the start and end of each section, used for
140 /// generating the .debug_ranges and .debug_aranges sections.
141 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *>>
144 /// The information gathered from labels that will have dwarf label
145 /// entries when generating dwarf assembly source files.
146 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
148 /// The string to embed in the debug information for the compile unit, if
150 StringRef DwarfDebugFlags;
152 /// The string to embed in as the dwarf AT_producer for the compile unit, if
154 StringRef DwarfDebugProducer;
156 /// The maximum version of dwarf that we should emit.
157 uint16_t DwarfVersion;
159 /// Honor temporary labels, this is useful for debugging semantic
160 /// differences between temporary and non-temporary labels (primarily on
162 bool AllowTemporaryLabels;
163 bool UseNamesOnTempLabels = true;
165 /// The Compile Unit ID that we are currently processing.
166 unsigned DwarfCompileUnitID;
168 struct ELFSectionKey {
169 std::string SectionName;
172 ELFSectionKey(StringRef SectionName, StringRef GroupName,
174 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
176 bool operator<(const ELFSectionKey &Other) const {
177 if (SectionName != Other.SectionName)
178 return SectionName < Other.SectionName;
179 if (GroupName != Other.GroupName)
180 return GroupName < Other.GroupName;
181 return UniqueID < Other.UniqueID;
185 struct COFFSectionKey {
186 std::string SectionName;
189 COFFSectionKey(StringRef SectionName, StringRef GroupName,
191 : SectionName(SectionName), GroupName(GroupName),
192 SelectionKey(SelectionKey) {}
193 bool operator<(const COFFSectionKey &Other) const {
194 if (SectionName != Other.SectionName)
195 return SectionName < Other.SectionName;
196 if (GroupName != Other.GroupName)
197 return GroupName < Other.GroupName;
198 return SelectionKey < Other.SelectionKey;
202 StringMap<const MCSectionMachO *> MachOUniquingMap;
203 std::map<ELFSectionKey, const MCSectionELF *> ELFUniquingMap;
204 std::map<COFFSectionKey, const MCSectionCOFF *> COFFUniquingMap;
205 StringMap<bool> ELFRelSecNames;
207 /// Do automatic reset in destructor
210 MCSymbol *CreateSymbol(StringRef Name, bool AlwaysAddSuffix);
212 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
216 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
217 const MCObjectFileInfo *MOFI,
218 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
221 const SourceMgr *getSourceManager() const { return SrcMgr; }
223 const MCAsmInfo *getAsmInfo() const { return MAI; }
225 const MCRegisterInfo *getRegisterInfo() const { return MRI; }
227 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
229 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
230 void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
232 /// \name Module Lifetime Management
235 /// reset - return object to right after construction state to prepare
236 /// to process a new module
241 /// \name Symbol Management
244 /// Create and return a new linker temporary symbol with a unique but
245 /// unspecified name.
246 MCSymbol *createLinkerPrivateTempSymbol();
248 /// Create and return a new assembler temporary symbol with a unique but
249 /// unspecified name.
250 MCSymbol *createTempSymbol();
252 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix);
254 /// Create the definition of a directional local symbol for numbered label
255 /// (used for "1:" definitions).
256 MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
258 /// Create and return a directional local symbol for numbered label (used
259 /// for "1b" or 1f" references).
260 MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
262 /// Lookup the symbol inside with the specified \p Name. If it exists,
263 /// return it. If not, create a forward reference and return it.
265 /// \param Name - The symbol name, which must be unique across all symbols.
266 MCSymbol *getOrCreateSymbol(const Twine &Name);
268 MCSymbol *getOrCreateSectionSymbol(const MCSectionELF &Section);
270 /// Gets a symbol that will be defined to the final stack offset of a local
271 /// variable after codegen.
273 /// \param Idx - The index of a local variable passed to @llvm.frameescape.
274 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
276 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
278 /// Get the symbol for \p Name, or null.
279 MCSymbol *lookupSymbol(const Twine &Name) const;
281 /// getSymbols - Get a reference for the symbol table for clients that
282 /// want to, for example, iterate over all symbols. 'const' because we
283 /// still want any modifications to the table itself to use the MCContext
285 const SymbolTable &getSymbols() const { return Symbols; }
289 /// \name Section Management
292 /// Return the MCSection for the specified mach-o section. This requires
293 /// the operands to be valid.
294 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
295 unsigned TypeAndAttributes,
296 unsigned Reserved2, SectionKind K,
297 const char *BeginSymName = nullptr);
299 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
300 unsigned TypeAndAttributes,
302 const char *BeginSymName = nullptr) {
303 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
307 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
309 return getELFSection(Section, Type, Flags, nullptr);
312 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
314 const char *BeginSymName) {
315 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
318 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
319 unsigned Flags, unsigned EntrySize,
321 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
324 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
325 unsigned Flags, unsigned EntrySize,
327 const char *BeginSymName) {
328 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
332 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
333 unsigned Flags, unsigned EntrySize,
334 StringRef Group, unsigned UniqueID) {
335 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
339 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
340 unsigned Flags, unsigned EntrySize,
341 StringRef Group, unsigned UniqueID,
342 const char *BeginSymName);
344 const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
345 unsigned Flags, unsigned EntrySize,
346 const MCSymbol *Group, unsigned UniqueID,
347 const char *BeginSymName,
348 const MCSectionELF *Associated);
350 const MCSectionELF *createELFRelSection(StringRef Name, unsigned Type,
351 unsigned Flags, unsigned EntrySize,
352 const MCSymbol *Group,
353 const MCSectionELF *Associated);
355 void renameELFSection(const MCSectionELF *Section, StringRef Name);
357 const MCSectionELF *createELFGroupSection(const MCSymbol *Group);
359 const MCSectionCOFF *getCOFFSection(StringRef Section,
360 unsigned Characteristics,
362 StringRef COMDATSymName, int Selection,
363 const char *BeginSymName = nullptr);
365 const MCSectionCOFF *getCOFFSection(StringRef Section,
366 unsigned Characteristics,
368 const char *BeginSymName = nullptr);
370 const MCSectionCOFF *getCOFFSection(StringRef Section);
372 /// Gets or creates a section equivalent to Sec that is associated with the
373 /// section containing KeySym. For example, to create a debug info section
374 /// associated with an inline function, pass the normal debug info section
375 /// as Sec and the function symbol as KeySym.
376 const MCSectionCOFF *getAssociativeCOFFSection(const MCSectionCOFF *Sec,
377 const MCSymbol *KeySym);
381 /// \name Dwarf Management
384 /// \brief Get the compilation directory for DW_AT_comp_dir
385 /// This can be overridden by clients which want to control the reported
386 /// compilation directory and have it be something other than the current
387 /// working directory.
388 /// Returns an empty string if the current directory cannot be determined.
389 StringRef getCompilationDir() const { return CompilationDir; }
391 /// \brief Set the compilation directory for DW_AT_comp_dir
392 /// Override the default (CWD) compilation directory.
393 void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
395 /// \brief Get the main file name for use in error messages and debug
396 /// info. This can be set to ensure we've got the correct file name
397 /// after preprocessing or for -save-temps.
398 const std::string &getMainFileName() const { return MainFileName; }
400 /// \brief Set the main file name and override the default.
401 void setMainFileName(StringRef S) { MainFileName = S; }
403 /// Creates an entry in the dwarf file and directory tables.
404 unsigned getDwarfFile(StringRef Directory, StringRef FileName,
405 unsigned FileNumber, unsigned CUID);
407 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
409 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
410 return MCDwarfLineTablesCUMap;
413 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
414 return MCDwarfLineTablesCUMap[CUID];
417 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
418 auto I = MCDwarfLineTablesCUMap.find(CUID);
419 assert(I != MCDwarfLineTablesCUMap.end());
423 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
424 return getMCDwarfLineTable(CUID).getMCDwarfFiles();
426 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
427 return getMCDwarfLineTable(CUID).getMCDwarfDirs();
430 bool hasMCLineSections() const {
431 for (const auto &Table : MCDwarfLineTablesCUMap)
432 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
436 unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
437 void setDwarfCompileUnitID(unsigned CUIndex) {
438 DwarfCompileUnitID = CUIndex;
440 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
441 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
444 /// Saves the information from the currently parsed dwarf .loc directive
445 /// and sets DwarfLocSeen. When the next instruction is assembled an entry
446 /// in the line number table with this information and the address of the
447 /// instruction will be created.
448 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
449 unsigned Flags, unsigned Isa,
450 unsigned Discriminator) {
451 CurrentDwarfLoc.setFileNum(FileNum);
452 CurrentDwarfLoc.setLine(Line);
453 CurrentDwarfLoc.setColumn(Column);
454 CurrentDwarfLoc.setFlags(Flags);
455 CurrentDwarfLoc.setIsa(Isa);
456 CurrentDwarfLoc.setDiscriminator(Discriminator);
459 void clearDwarfLocSeen() { DwarfLocSeen = false; }
461 bool getDwarfLocSeen() { return DwarfLocSeen; }
462 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
464 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
465 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
466 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
467 void setGenDwarfFileNumber(unsigned FileNumber) {
468 GenDwarfFileNumber = FileNumber;
470 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *>> &
471 getGenDwarfSectionSyms() {
472 return SectionStartEndSyms;
474 std::pair<MapVector<const MCSection *,
475 std::pair<MCSymbol *, MCSymbol *>>::iterator,
477 addGenDwarfSection(const MCSection *Sec) {
478 return SectionStartEndSyms.insert(
479 std::make_pair(Sec, std::make_pair(nullptr, nullptr)));
481 void finalizeDwarfSections(MCStreamer &MCOS);
482 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
483 return MCGenDwarfLabelEntries;
485 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
486 MCGenDwarfLabelEntries.push_back(E);
489 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
490 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
492 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
493 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
495 void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
496 uint16_t getDwarfVersion() const { return DwarfVersion; }
500 char *getSecureLogFile() { return SecureLogFile; }
501 raw_ostream *getSecureLog() { return SecureLog; }
502 bool getSecureLogUsed() { return SecureLogUsed; }
503 void setSecureLog(raw_ostream *Value) { SecureLog = Value; }
504 void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
506 void *allocate(unsigned Size, unsigned Align = 8) {
507 return Allocator.Allocate(Size, Align);
509 void deallocate(void *Ptr) {}
511 // Unrecoverable error has occurred. Display the best diagnostic we can
512 // and bail via exit(1). For now, most MC backend errors are unrecoverable.
513 // FIXME: We should really do something about that.
514 LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
515 const Twine &Msg) const;
518 } // end namespace llvm
520 // operator new and delete aren't allowed inside namespaces.
521 // The throw specifications are mandated by the standard.
522 /// \brief Placement new for using the MCContext's allocator.
524 /// This placement form of operator new uses the MCContext's allocator for
525 /// obtaining memory. It is a non-throwing new, which means that it returns
526 /// null on error. (If that is what the allocator does. The current does, so if
527 /// this ever changes, this operator will have to be changed, too.)
528 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
530 /// // Default alignment (8)
531 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
532 /// // Specific alignment
533 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
535 /// Please note that you cannot use delete on the pointer; it must be
536 /// deallocated using an explicit destructor call followed by
537 /// \c Context.Deallocate(Ptr).
539 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
540 /// \param C The MCContext that provides the allocator.
541 /// \param Alignment The alignment of the allocated memory (if the underlying
542 /// allocator supports it).
543 /// \return The allocated memory. Could be NULL.
544 inline void *operator new(size_t Bytes, llvm::MCContext &C,
545 size_t Alignment = 8) throw() {
546 return C.allocate(Bytes, Alignment);
548 /// \brief Placement delete companion to the new above.
550 /// This operator is just a companion to the new above. There is no way of
551 /// invoking it directly; see the new operator for more details. This operator
552 /// is called implicitly by the compiler if a placement new expression using
553 /// the MCContext throws in the object constructor.
554 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
559 /// This placement form of operator new[] uses the MCContext's allocator for
560 /// obtaining memory. It is a non-throwing new[], which means that it returns
562 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
564 /// // Default alignment (8)
565 /// char *data = new (Context) char[10];
566 /// // Specific alignment
567 /// char *data = new (Context, 4) char[10];
569 /// Please note that you cannot use delete on the pointer; it must be
570 /// deallocated using an explicit destructor call followed by
571 /// \c Context.Deallocate(Ptr).
573 /// \param Bytes The number of bytes to allocate. Calculated by the compiler.
574 /// \param C The MCContext that provides the allocator.
575 /// \param Alignment The alignment of the allocated memory (if the underlying
576 /// allocator supports it).
577 /// \return The allocated memory. Could be NULL.
578 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
579 size_t Alignment = 8) throw() {
580 return C.allocate(Bytes, Alignment);
583 /// \brief Placement delete[] companion to the new[] above.
585 /// This operator is just a companion to the new[] above. There is no way of
586 /// invoking it directly; see the new[] operator for more details. This operator
587 /// is called implicitly by the compiler if a placement new[] expression using
588 /// the MCContext throws in the object constructor.
589 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {