2f9b32b984ec167ffe4653686366ff747bdad56a
[oota-llvm.git] / include / llvm / MC / MCContext.h
1 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_MC_MCCONTEXT_H
11 #define LLVM_MC_MCCONTEXT_H
12
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"
22 #include <map>
23 #include <vector> // FIXME: Shouldn't be needed.
24
25 namespace llvm {
26   class MCAsmInfo;
27   class MCExpr;
28   class MCSection;
29   class MCSymbol;
30   class MCLabel;
31   struct MCDwarfFile;
32   class MCDwarfLoc;
33   class MCObjectFileInfo;
34   class MCRegisterInfo;
35   class MCLineSection;
36   class SMLoc;
37   class StringRef;
38   class Twine;
39   class MCSectionMachO;
40   class MCSectionELF;
41   class MCSectionCOFF;
42
43   /// MCContext - Context object for machine code objects.  This class owns all
44   /// of the sections that it creates.
45   ///
46   class MCContext {
47     MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
48     MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
49   public:
50     typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
51   private:
52     /// The SourceMgr for this object, if any.
53     const SourceMgr *SrcMgr;
54
55     /// The MCAsmInfo for this target.
56     const MCAsmInfo *MAI;
57
58     /// The MCRegisterInfo for this target.
59     const MCRegisterInfo *MRI;
60
61     /// The MCObjectFileInfo for this target.
62     const MCObjectFileInfo *MOFI;
63
64     /// Allocator - Allocator object used for creating machine code objects.
65     ///
66     /// We use a bump pointer allocator to avoid the need to track all allocated
67     /// objects.
68     BumpPtrAllocator Allocator;
69
70     /// Symbols - Bindings of names to symbols.
71     SymbolTable Symbols;
72
73     /// A maping from a local label number and an instance count to a symbol.
74     /// For example, in the assembly
75     ///     1:
76     ///     2:
77     ///     1:
78     /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
79     DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols;
80
81     /// UsedNames - Keeps tracks of names that were used both for used declared
82     /// and artificial symbols.
83     StringMap<bool, BumpPtrAllocator&> UsedNames;
84
85     /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
86     /// symbol.
87     unsigned NextUniqueID;
88
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);
97
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.
101     char *SecureLogFile;
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.
107     bool SecureLogUsed;
108
109     /// The compilation directory to use for DW_AT_comp_dir.
110     SmallString<128> CompilationDir;
111
112     /// The main file name if passed in explicitly.
113     std::string MainFileName;
114
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;
120
121     /// The current dwarf line information from the last dwarf .loc directive.
122     MCDwarfLoc CurrentDwarfLoc;
123     bool DwarfLocSeen;
124
125     /// Generate dwarf debugging info for assembly source files.
126     bool GenDwarfForAssembly;
127
128     /// The current dwarf file number when generate dwarf debugging info for
129     /// assembly source files.
130     unsigned GenDwarfFileNumber;
131
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;
137
138     /// The information gathered from labels that will have dwarf label
139     /// entries when generating dwarf assembly source files.
140     std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
141
142     /// The string to embed in the debug information for the compile unit, if
143     /// non-empty.
144     StringRef DwarfDebugFlags;
145
146     /// The string to embed in as the dwarf AT_producer for the compile unit, if
147     /// non-empty.
148     StringRef DwarfDebugProducer;
149
150     /// The maximum version of dwarf that we should emit.
151     uint16_t DwarfVersion;
152
153     /// Honor temporary labels, this is useful for debugging semantic
154     /// differences between temporary and non-temporary labels (primarily on
155     /// Darwin).
156     bool AllowTemporaryLabels;
157
158     /// The Compile Unit ID that we are currently processing.
159     unsigned DwarfCompileUnitID;
160
161     typedef std::pair<std::string, std::string> SectionGroupPair;
162
163     StringMap<const MCSectionMachO*> MachOUniquingMap;
164     std::map<SectionGroupPair, const MCSectionELF *> ELFUniquingMap;
165     std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniquingMap;
166
167     /// Do automatic reset in destructor
168     bool AutoReset;
169
170     MCSymbol *CreateSymbol(StringRef Name);
171
172     MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
173                                                 unsigned Instance);
174
175   public:
176     explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
177                        const MCObjectFileInfo *MOFI,
178                        const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
179     ~MCContext();
180
181     const SourceMgr *getSourceManager() const { return SrcMgr; }
182
183     const MCAsmInfo *getAsmInfo() const { return MAI; }
184
185     const MCRegisterInfo *getRegisterInfo() const { return MRI; }
186
187     const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
188
189     void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
190
191     /// @name Module Lifetime Management
192     /// @{
193
194     /// reset - return object to right after construction state to prepare
195     /// to process a new module
196     void reset();
197
198     /// @}
199
200     /// @name Symbol Management
201     /// @{
202
203     /// CreateLinkerPrivateTempSymbol - Create and return a new linker temporary
204     /// symbol with a unique but unspecified name.
205     MCSymbol *CreateLinkerPrivateTempSymbol();
206
207     /// CreateTempSymbol - Create and return a new assembler temporary symbol
208     /// with a unique but unspecified name.
209     MCSymbol *CreateTempSymbol();
210
211     /// getUniqueSymbolID() - Return a unique identifier for use in constructing
212     /// symbol names.
213     unsigned getUniqueSymbolID() { return NextUniqueID++; }
214
215     /// Create the definition of a directional local symbol for numbered label
216     /// (used for "1:" definitions).
217     MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal);
218
219     /// Create and return a directional local symbol for numbered label (used
220     /// for "1b" or 1f" references).
221     MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
222
223     /// GetOrCreateSymbol - Lookup the symbol inside with the specified
224     /// @p Name.  If it exists, return it.  If not, create a forward
225     /// reference and return it.
226     ///
227     /// @param Name - The symbol name, which must be unique across all symbols.
228     MCSymbol *GetOrCreateSymbol(StringRef Name);
229     MCSymbol *GetOrCreateSymbol(const Twine &Name);
230
231     /// LookupSymbol - Get the symbol for \p Name, or null.
232     MCSymbol *LookupSymbol(StringRef Name) const;
233     MCSymbol *LookupSymbol(const Twine &Name) const;
234
235     /// getSymbols - Get a reference for the symbol table for clients that
236     /// want to, for example, iterate over all symbols. 'const' because we
237     /// still want any modifications to the table itself to use the MCContext
238     /// APIs.
239     const SymbolTable &getSymbols() const {
240       return Symbols;
241     }
242
243     /// @}
244
245     /// @name Section Management
246     /// @{
247
248     /// getMachOSection - Return the MCSection for the specified mach-o section.
249     /// This requires the operands to be valid.
250     const MCSectionMachO *getMachOSection(StringRef Segment,
251                                           StringRef Section,
252                                           unsigned TypeAndAttributes,
253                                           unsigned Reserved2,
254                                           SectionKind K);
255     const MCSectionMachO *getMachOSection(StringRef Segment,
256                                           StringRef Section,
257                                           unsigned TypeAndAttributes,
258                                           SectionKind K) {
259       return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
260     }
261
262     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
263                                       unsigned Flags, SectionKind Kind);
264
265     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
266                                       unsigned Flags, SectionKind Kind,
267                                       unsigned EntrySize, StringRef Group);
268
269     void renameELFSection(const MCSectionELF *Section, StringRef Name);
270
271     const MCSectionELF *CreateELFGroupSection();
272
273     const MCSectionCOFF *getCOFFSection(StringRef Section,
274                                         unsigned Characteristics,
275                                         SectionKind Kind,
276                                         StringRef COMDATSymName, int Selection);
277
278     const MCSectionCOFF *getCOFFSection(StringRef Section,
279                                         unsigned Characteristics,
280                                         SectionKind Kind);
281
282     const MCSectionCOFF *getCOFFSection(StringRef Section);
283
284     /// @}
285
286     /// @name Dwarf Management
287     /// @{
288
289     /// \brief Get the compilation directory for DW_AT_comp_dir
290     /// This can be overridden by clients which want to control the reported
291     /// compilation directory and have it be something other than the current
292     /// working directory.
293     /// Returns an empty string if the current directory cannot be determined.
294     StringRef getCompilationDir() const { return CompilationDir; }
295
296     /// \brief Set the compilation directory for DW_AT_comp_dir
297     /// Override the default (CWD) compilation directory.
298     void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
299
300     /// \brief Get the main file name for use in error messages and debug
301     /// info. This can be set to ensure we've got the correct file name
302     /// after preprocessing or for -save-temps.
303     const std::string &getMainFileName() const { return MainFileName; }
304
305     /// \brief Set the main file name and override the default.
306     void setMainFileName(StringRef S) { MainFileName = S; }
307
308     /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
309     unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
310                           unsigned FileNumber, unsigned CUID);
311
312     bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
313
314     const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
315       return MCDwarfLineTablesCUMap;
316     }
317
318     MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
319       return MCDwarfLineTablesCUMap[CUID];
320     }
321
322     const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
323       auto I = MCDwarfLineTablesCUMap.find(CUID);
324       assert(I != MCDwarfLineTablesCUMap.end());
325       return I->second;
326     }
327
328     const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
329       return getMCDwarfLineTable(CUID).getMCDwarfFiles();
330     }
331     const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
332       return getMCDwarfLineTable(CUID).getMCDwarfDirs();
333     }
334
335     bool hasMCLineSections() const {
336       for (const auto &Table : MCDwarfLineTablesCUMap)
337         if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
338           return true;
339       return false;
340     }
341     unsigned getDwarfCompileUnitID() {
342       return DwarfCompileUnitID;
343     }
344     void setDwarfCompileUnitID(unsigned CUIndex) {
345       DwarfCompileUnitID = CUIndex;
346     }
347     void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
348       getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
349     }
350
351     /// setCurrentDwarfLoc - saves the information from the currently parsed
352     /// dwarf .loc directive and sets DwarfLocSeen.  When the next instruction
353     /// is assembled an entry in the line number table with this information and
354     /// the address of the instruction will be created.
355     void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
356                             unsigned Flags, unsigned Isa,
357                             unsigned Discriminator) {
358       CurrentDwarfLoc.setFileNum(FileNum);
359       CurrentDwarfLoc.setLine(Line);
360       CurrentDwarfLoc.setColumn(Column);
361       CurrentDwarfLoc.setFlags(Flags);
362       CurrentDwarfLoc.setIsa(Isa);
363       CurrentDwarfLoc.setDiscriminator(Discriminator);
364       DwarfLocSeen = true;
365     }
366     void ClearDwarfLocSeen() { DwarfLocSeen = false; }
367
368     bool getDwarfLocSeen() { return DwarfLocSeen; }
369     const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
370
371     bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
372     void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
373     unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
374     void setGenDwarfFileNumber(unsigned FileNumber) {
375       GenDwarfFileNumber = FileNumber;
376     }
377     const MCSection *getGenDwarfSection() { return GenDwarfSection; }
378     void setGenDwarfSection(const MCSection *Sec) { GenDwarfSection = Sec; }
379     MCSymbol *getGenDwarfSectionStartSym() { return GenDwarfSectionStartSym; }
380     void setGenDwarfSectionStartSym(MCSymbol *Sym) {
381       GenDwarfSectionStartSym = Sym;
382     }
383     MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
384     void setGenDwarfSectionEndSym(MCSymbol *Sym) {
385       GenDwarfSectionEndSym = Sym;
386     }
387     const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
388       return MCGenDwarfLabelEntries;
389     }
390     void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
391       MCGenDwarfLabelEntries.push_back(E);
392     }
393
394     void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
395     StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
396
397     void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
398     StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
399
400     void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
401     uint16_t getDwarfVersion() const { return DwarfVersion; }
402
403     /// @}
404
405     char *getSecureLogFile() { return SecureLogFile; }
406     raw_ostream *getSecureLog() { return SecureLog; }
407     bool getSecureLogUsed() { return SecureLogUsed; }
408     void setSecureLog(raw_ostream *Value) {
409       SecureLog = Value;
410     }
411     void setSecureLogUsed(bool Value) {
412       SecureLogUsed = Value;
413     }
414
415     void *Allocate(unsigned Size, unsigned Align = 8) {
416       return Allocator.Allocate(Size, Align);
417     }
418     void Deallocate(void *Ptr) {
419     }
420
421     // Unrecoverable error has occurred. Display the best diagnostic we can
422     // and bail via exit(1). For now, most MC backend errors are unrecoverable.
423     // FIXME: We should really do something about that.
424     LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const;
425   };
426
427 } // end namespace llvm
428
429 // operator new and delete aren't allowed inside namespaces.
430 // The throw specifications are mandated by the standard.
431 /// @brief Placement new for using the MCContext's allocator.
432 ///
433 /// This placement form of operator new uses the MCContext's allocator for
434 /// obtaining memory. It is a non-throwing new, which means that it returns
435 /// null on error. (If that is what the allocator does. The current does, so if
436 /// this ever changes, this operator will have to be changed, too.)
437 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
438 /// @code
439 /// // Default alignment (16)
440 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
441 /// // Specific alignment
442 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
443 /// @endcode
444 /// Please note that you cannot use delete on the pointer; it must be
445 /// deallocated using an explicit destructor call followed by
446 /// @c Context.Deallocate(Ptr).
447 ///
448 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
449 /// @param C The MCContext that provides the allocator.
450 /// @param Alignment The alignment of the allocated memory (if the underlying
451 ///                  allocator supports it).
452 /// @return The allocated memory. Could be NULL.
453 inline void *operator new(size_t Bytes, llvm::MCContext &C,
454                           size_t Alignment = 16) throw () {
455   return C.Allocate(Bytes, Alignment);
456 }
457 /// @brief Placement delete companion to the new above.
458 ///
459 /// This operator is just a companion to the new above. There is no way of
460 /// invoking it directly; see the new operator for more details. This operator
461 /// is called implicitly by the compiler if a placement new expression using
462 /// the MCContext throws in the object constructor.
463 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
464               throw () {
465   C.Deallocate(Ptr);
466 }
467
468 /// This placement form of operator new[] uses the MCContext's allocator for
469 /// obtaining memory. It is a non-throwing new[], which means that it returns
470 /// null on error.
471 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
472 /// @code
473 /// // Default alignment (16)
474 /// char *data = new (Context) char[10];
475 /// // Specific alignment
476 /// char *data = new (Context, 8) char[10];
477 /// @endcode
478 /// Please note that you cannot use delete on the pointer; it must be
479 /// deallocated using an explicit destructor call followed by
480 /// @c Context.Deallocate(Ptr).
481 ///
482 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
483 /// @param C The MCContext that provides the allocator.
484 /// @param Alignment The alignment of the allocated memory (if the underlying
485 ///                  allocator supports it).
486 /// @return The allocated memory. Could be NULL.
487 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
488                             size_t Alignment = 16) throw () {
489   return C.Allocate(Bytes, Alignment);
490 }
491
492 /// @brief Placement delete[] companion to the new[] above.
493 ///
494 /// This operator is just a companion to the new[] above. There is no way of
495 /// invoking it directly; see the new[] operator for more details. This operator
496 /// is called implicitly by the compiler if a placement new[] expression using
497 /// the MCContext throws in the object constructor.
498 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {
499   C.Deallocate(Ptr);
500 }
501
502 #endif