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