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