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