Prepare LLVM to fix PR14625, exposing a hook in MCContext to manage the
[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 dwarf file and directory tables from the dwarf .file directive.
101     std::vector<MCDwarfFile *> MCDwarfFiles;
102     std::vector<StringRef> MCDwarfDirs;
103
104     /// The current dwarf line information from the last dwarf .loc directive.
105     MCDwarfLoc CurrentDwarfLoc;
106     bool DwarfLocSeen;
107
108     /// Generate dwarf debugging info for assembly source files.
109     bool GenDwarfForAssembly;
110
111     /// The current dwarf file number when generate dwarf debugging info for
112     /// assembly source files.
113     unsigned GenDwarfFileNumber;
114
115     /// The default initial text section that we generate dwarf debugging line
116     /// info for when generating dwarf assembly source files.
117     const MCSection *GenDwarfSection;
118     /// Symbols created for the start and end of this section.
119     MCSymbol *GenDwarfSectionStartSym, *GenDwarfSectionEndSym;
120
121     /// The information gathered from labels that will have dwarf label
122     /// entries when generating dwarf assembly source files.
123     std::vector<const MCGenDwarfLabelEntry *> MCGenDwarfLabelEntries;
124
125     /// The string to embed in the debug information for the compile unit, if
126     /// non-empty.
127     StringRef DwarfDebugFlags;
128
129     /// Honor temporary labels, this is useful for debugging semantic
130     /// differences between temporary and non-temporary labels (primarily on
131     /// Darwin).
132     bool AllowTemporaryLabels;
133
134     /// The dwarf line information from the .loc directives for the sections
135     /// with assembled machine instructions have after seeing .loc directives.
136     DenseMap<const MCSection *, MCLineSection *> MCLineSections;
137     /// We need a deterministic iteration order, so we remember the order
138     /// the elements were added.
139     std::vector<const MCSection *> MCLineSectionOrder;
140
141     void *MachOUniquingMap, *ELFUniquingMap, *COFFUniquingMap;
142
143     /// Do automatic reset in destructor
144     bool AutoReset;
145
146     MCSymbol *CreateSymbol(StringRef Name);
147
148   public:
149     explicit MCContext(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
150                        const MCObjectFileInfo *MOFI, const SourceMgr *Mgr = 0,
151                        bool DoAutoReset = true);
152     ~MCContext();
153
154     const SourceMgr *getSourceManager() const { return SrcMgr; }
155
156     const MCAsmInfo &getAsmInfo() const { return MAI; }
157
158     const MCRegisterInfo &getRegisterInfo() const { return MRI; }
159
160     const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
161
162     void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
163
164     /// @name Module Lifetime Management
165     /// @{
166
167     /// reset - return object to right after construction state to prepare
168     /// to process a new module
169     void reset();
170
171     /// @}
172
173     /// @name Symbol Management
174     /// @{
175
176     /// CreateTempSymbol - Create and return a new assembler temporary symbol
177     /// with a unique but unspecified name.
178     MCSymbol *CreateTempSymbol();
179
180     /// getUniqueSymbolID() - Return a unique identifier for use in constructing
181     /// symbol names.
182     unsigned getUniqueSymbolID() { return NextUniqueID++; }
183
184     /// CreateDirectionalLocalSymbol - Create the definition of a directional
185     /// local symbol for numbered label (used for "1:" definitions).
186     MCSymbol *CreateDirectionalLocalSymbol(int64_t LocalLabelVal);
187
188     /// GetDirectionalLocalSymbol - Create and return a directional local
189     /// symbol for numbered label (used for "1b" or 1f" references).
190     MCSymbol *GetDirectionalLocalSymbol(int64_t LocalLabelVal, int bORf);
191
192     /// GetOrCreateSymbol - Lookup the symbol inside with the specified
193     /// @p Name.  If it exists, return it.  If not, create a forward
194     /// reference and return it.
195     ///
196     /// @param Name - The symbol name, which must be unique across all symbols.
197     MCSymbol *GetOrCreateSymbol(StringRef Name);
198     MCSymbol *GetOrCreateSymbol(const Twine &Name);
199
200     /// LookupSymbol - Get the symbol for \p Name, or null.
201     MCSymbol *LookupSymbol(StringRef Name) const;
202     MCSymbol *LookupSymbol(const Twine &Name) const;
203
204     /// getSymbols - Get a reference for the symbol table for clients that
205     /// want to, for example, iterate over all symbols. 'const' because we
206     /// still want any modifications to the table itself to use the MCContext
207     /// APIs.
208     const SymbolTable &getSymbols() const {
209       return Symbols;
210     }
211
212     /// @}
213
214     /// @name Section Management
215     /// @{
216
217     /// getMachOSection - Return the MCSection for the specified mach-o section.
218     /// This requires the operands to be valid.
219     const MCSectionMachO *getMachOSection(StringRef Segment,
220                                           StringRef Section,
221                                           unsigned TypeAndAttributes,
222                                           unsigned Reserved2,
223                                           SectionKind K);
224     const MCSectionMachO *getMachOSection(StringRef Segment,
225                                           StringRef Section,
226                                           unsigned TypeAndAttributes,
227                                           SectionKind K) {
228       return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
229     }
230
231     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
232                                       unsigned Flags, SectionKind Kind);
233
234     const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
235                                       unsigned Flags, SectionKind Kind,
236                                       unsigned EntrySize, StringRef Group);
237
238     const MCSectionELF *CreateELFGroupSection();
239
240     const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
241                                     int Selection, SectionKind Kind);
242
243     const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
244                                     SectionKind Kind) {
245       return getCOFFSection (Section, Characteristics, 0, Kind);
246     }
247
248
249     /// @}
250
251     /// @name Dwarf Management
252     /// @{
253
254     /// \brief Get the compilation directory for DW_AT_comp_dir
255     /// This can be overridden by clients which want to control the reported
256     /// compilation directory and have it be something other than the current
257     /// working directory.
258     const std::string &getCompilationDir() const { return CompilationDir; }
259
260     /// \brief Set the compilation directory for DW_AT_comp_dir
261     /// Override the default (CWD) compilation directory.
262     void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
263
264     /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
265     unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
266                           unsigned FileNumber);
267
268     bool isValidDwarfFileNumber(unsigned FileNumber);
269
270     bool hasDwarfFiles() const {
271       return !MCDwarfFiles.empty();
272     }
273
274     const std::vector<MCDwarfFile *> &getMCDwarfFiles() {
275       return MCDwarfFiles;
276     }
277     const std::vector<StringRef> &getMCDwarfDirs() {
278       return MCDwarfDirs;
279     }
280
281     const DenseMap<const MCSection *, MCLineSection *>
282     &getMCLineSections() const {
283       return MCLineSections;
284     }
285     const std::vector<const MCSection *> &getMCLineSectionOrder() const {
286       return MCLineSectionOrder;
287     }
288     void addMCLineSection(const MCSection *Sec, MCLineSection *Line) {
289       MCLineSections[Sec] = Line;
290       MCLineSectionOrder.push_back(Sec);
291     }
292
293     /// setCurrentDwarfLoc - saves the information from the currently parsed
294     /// dwarf .loc directive and sets DwarfLocSeen.  When the next instruction
295     /// is assembled an entry in the line number table with this information and
296     /// the address of the instruction will be created.
297     void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
298                             unsigned Flags, unsigned Isa,
299                             unsigned Discriminator) {
300       CurrentDwarfLoc.setFileNum(FileNum);
301       CurrentDwarfLoc.setLine(Line);
302       CurrentDwarfLoc.setColumn(Column);
303       CurrentDwarfLoc.setFlags(Flags);
304       CurrentDwarfLoc.setIsa(Isa);
305       CurrentDwarfLoc.setDiscriminator(Discriminator);
306       DwarfLocSeen = true;
307     }
308     void ClearDwarfLocSeen() { DwarfLocSeen = false; }
309
310     bool getDwarfLocSeen() { return DwarfLocSeen; }
311     const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
312
313     bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
314     void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
315     unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
316     unsigned nextGenDwarfFileNumber() { return ++GenDwarfFileNumber; }
317     const MCSection *getGenDwarfSection() { return GenDwarfSection; }
318     void setGenDwarfSection(const MCSection *Sec) { GenDwarfSection = Sec; }
319     MCSymbol *getGenDwarfSectionStartSym() { return GenDwarfSectionStartSym; }
320     void setGenDwarfSectionStartSym(MCSymbol *Sym) {
321       GenDwarfSectionStartSym = Sym;
322     }
323     MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
324     void setGenDwarfSectionEndSym(MCSymbol *Sym) {
325       GenDwarfSectionEndSym = Sym;
326     }
327     const std::vector<const MCGenDwarfLabelEntry *>
328       &getMCGenDwarfLabelEntries() const {
329       return MCGenDwarfLabelEntries;
330     }
331     void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry *E) {
332       MCGenDwarfLabelEntries.push_back(E);
333     }
334
335     void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
336     StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
337
338     /// @}
339
340     char *getSecureLogFile() { return SecureLogFile; }
341     raw_ostream *getSecureLog() { return SecureLog; }
342     bool getSecureLogUsed() { return SecureLogUsed; }
343     void setSecureLog(raw_ostream *Value) {
344       SecureLog = Value;
345     }
346     void setSecureLogUsed(bool Value) {
347       SecureLogUsed = Value;
348     }
349
350     void *Allocate(unsigned Size, unsigned Align = 8) {
351       return Allocator.Allocate(Size, Align);
352     }
353     void Deallocate(void *Ptr) {
354     }
355
356     // Unrecoverable error has occured. Display the best diagnostic we can
357     // and bail via exit(1). For now, most MC backend errors are unrecoverable.
358     // FIXME: We should really do something about that.
359     LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg);
360   };
361
362 } // end namespace llvm
363
364 // operator new and delete aren't allowed inside namespaces.
365 // The throw specifications are mandated by the standard.
366 /// @brief Placement new for using the MCContext's allocator.
367 ///
368 /// This placement form of operator new uses the MCContext's allocator for
369 /// obtaining memory. It is a non-throwing new, which means that it returns
370 /// null on error. (If that is what the allocator does. The current does, so if
371 /// this ever changes, this operator will have to be changed, too.)
372 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
373 /// @code
374 /// // Default alignment (16)
375 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
376 /// // Specific alignment
377 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
378 /// @endcode
379 /// Please note that you cannot use delete on the pointer; it must be
380 /// deallocated using an explicit destructor call followed by
381 /// @c Context.Deallocate(Ptr).
382 ///
383 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
384 /// @param C The MCContext that provides the allocator.
385 /// @param Alignment The alignment of the allocated memory (if the underlying
386 ///                  allocator supports it).
387 /// @return The allocated memory. Could be NULL.
388 inline void *operator new(size_t Bytes, llvm::MCContext &C,
389                           size_t Alignment = 16) throw () {
390   return C.Allocate(Bytes, Alignment);
391 }
392 /// @brief Placement delete companion to the new above.
393 ///
394 /// This operator is just a companion to the new above. There is no way of
395 /// invoking it directly; see the new operator for more details. This operator
396 /// is called implicitly by the compiler if a placement new expression using
397 /// the MCContext throws in the object constructor.
398 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
399               throw () {
400   C.Deallocate(Ptr);
401 }
402
403 /// This placement form of operator new[] uses the MCContext's allocator for
404 /// obtaining memory. It is a non-throwing new[], which means that it returns
405 /// null on error.
406 /// Usage looks like this (assuming there's an MCContext 'Context' in scope):
407 /// @code
408 /// // Default alignment (16)
409 /// char *data = new (Context) char[10];
410 /// // Specific alignment
411 /// char *data = new (Context, 8) char[10];
412 /// @endcode
413 /// Please note that you cannot use delete on the pointer; it must be
414 /// deallocated using an explicit destructor call followed by
415 /// @c Context.Deallocate(Ptr).
416 ///
417 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
418 /// @param C The MCContext that provides the allocator.
419 /// @param Alignment The alignment of the allocated memory (if the underlying
420 ///                  allocator supports it).
421 /// @return The allocated memory. Could be NULL.
422 inline void *operator new[](size_t Bytes, llvm::MCContext& C,
423                             size_t Alignment = 16) throw () {
424   return C.Allocate(Bytes, Alignment);
425 }
426
427 /// @brief Placement delete[] companion to the new[] above.
428 ///
429 /// This operator is just a companion to the new[] above. There is no way of
430 /// invoking it directly; see the new[] operator for more details. This operator
431 /// is called implicitly by the compiler if a placement new[] expression using
432 /// the MCContext throws in the object constructor.
433 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {
434   C.Deallocate(Ptr);
435 }
436
437 #endif