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