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