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/MCCodeView.h"
20#include "llvm/MC/MCDwarf.h"
21#include "llvm/MC/MCSubtargetInfo.h"
22#include "llvm/MC/SectionKind.h"
23#include "llvm/Support/Allocator.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/raw_ostream.h"
26#include <map>
27#include <tuple>
28#include <vector> // FIXME: Shouldn't be needed.
29
30namespace llvm {
31  class MCAsmInfo;
32  class MCExpr;
33  class MCSection;
34  class MCSymbol;
35  class MCSymbolELF;
36  class MCLabel;
37  struct MCDwarfFile;
38  class MCDwarfLoc;
39  class MCObjectFileInfo;
40  class MCRegisterInfo;
41  class MCLineSection;
42  class SMLoc;
43  class MCSectionMachO;
44  class MCSectionELF;
45  class MCSectionCOFF;
46  class CodeViewContext;
47
48  /// Context object for machine code objects.  This class owns all of the
49  /// sections that it creates.
50  ///
51  class MCContext {
52    MCContext(const MCContext &) = delete;
53    MCContext &operator=(const MCContext &) = delete;
54
55  public:
56    typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
57
58  private:
59    /// The SourceMgr for this object, if any.
60    const SourceMgr *SrcMgr;
61
62    /// The MCAsmInfo for this target.
63    const MCAsmInfo *MAI;
64
65    /// The MCRegisterInfo for this target.
66    const MCRegisterInfo *MRI;
67
68    /// The MCObjectFileInfo for this target.
69    const MCObjectFileInfo *MOFI;
70
71    std::unique_ptr<CodeViewContext> CVContext;
72
73    /// Allocator object used for creating machine code objects.
74    ///
75    /// We use a bump pointer allocator to avoid the need to track all allocated
76    /// objects.
77    BumpPtrAllocator Allocator;
78
79    SpecificBumpPtrAllocator<MCSectionCOFF> COFFAllocator;
80    SpecificBumpPtrAllocator<MCSectionELF> ELFAllocator;
81    SpecificBumpPtrAllocator<MCSectionMachO> MachOAllocator;
82
83    /// Bindings of names to symbols.
84    SymbolTable Symbols;
85
86    /// ELF sections can have a corresponding symbol. This maps one to the
87    /// other.
88    DenseMap<const MCSectionELF *, MCSymbolELF *> SectionSymbols;
89
90    /// A mapping from a local label number and an instance count to a symbol.
91    /// For example, in the assembly
92    ///     1:
93    ///     2:
94    ///     1:
95    /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
96    DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
97
98    /// Keeps tracks of names that were used both for used declared and
99    /// artificial symbols. The value is "true" if the name has been used for a
100    /// non-section symbol (there can be at most one of those, plus an unlimited
101    /// number of section symbols with the same name).
102    StringMap<bool, BumpPtrAllocator &> UsedNames;
103
104    /// The next ID to dole out to an unnamed assembler temporary symbol with
105    /// a given prefix.
106    StringMap<unsigned> NextID;
107
108    /// Instances of directional local labels.
109    DenseMap<unsigned, MCLabel *> Instances;
110    /// NextInstance() creates the next instance of the directional local label
111    /// for the LocalLabelVal and adds it to the map if needed.
112    unsigned NextInstance(unsigned LocalLabelVal);
113    /// GetInstance() gets the current instance of the directional local label
114    /// for the LocalLabelVal and adds it to the map if needed.
115    unsigned GetInstance(unsigned LocalLabelVal);
116
117    /// The file name of the log file from the environment variable
118    /// AS_SECURE_LOG_FILE.  Which must be set before the .secure_log_unique
119    /// directive is used or it is an error.
120    char *SecureLogFile;
121    /// The stream that gets written to for the .secure_log_unique directive.
122    std::unique_ptr<raw_fd_ostream> SecureLog;
123    /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
124    /// catch errors if .secure_log_unique appears twice without
125    /// .secure_log_reset appearing between them.
126    bool SecureLogUsed;
127
128    /// The compilation directory to use for DW_AT_comp_dir.
129    SmallString<128> CompilationDir;
130
131    /// The main file name if passed in explicitly.
132    std::string MainFileName;
133
134    /// The dwarf file and directory tables from the dwarf .file directive.
135    /// We now emit a line table for each compile unit. To reduce the prologue
136    /// size of each line table, the files and directories used by each compile
137    /// unit are separated.
138    std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
139
140    /// The current dwarf line information from the last dwarf .loc directive.
141    MCDwarfLoc CurrentDwarfLoc;
142    bool DwarfLocSeen;
143
144    /// The current CodeView line information from the last .cv_loc directive.
145    MCCVLoc CurrentCVLoc = MCCVLoc(0, 0, 0, 0, false, true);
146    bool CVLocSeen = false;
147
148    /// Generate dwarf debugging info for assembly source files.
149    bool GenDwarfForAssembly;
150
151    /// The current dwarf file number when generate dwarf debugging info for
152    /// assembly source files.
153    unsigned GenDwarfFileNumber;
154
155    /// Sections for generating the .debug_ranges and .debug_aranges sections.
156    SetVector<MCSection *> SectionsForRanges;
157
158    /// The information gathered from labels that will have dwarf label
159    /// entries when generating dwarf assembly source files.
160    std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
161
162    /// The string to embed in the debug information for the compile unit, if
163    /// non-empty.
164    StringRef DwarfDebugFlags;
165
166    /// The string to embed in as the dwarf AT_producer for the compile unit, if
167    /// non-empty.
168    StringRef DwarfDebugProducer;
169
170    /// The maximum version of dwarf that we should emit.
171    uint16_t DwarfVersion;
172
173    /// Honor temporary labels, this is useful for debugging semantic
174    /// differences between temporary and non-temporary labels (primarily on
175    /// Darwin).
176    bool AllowTemporaryLabels;
177    bool UseNamesOnTempLabels = true;
178
179    /// The Compile Unit ID that we are currently processing.
180    unsigned DwarfCompileUnitID;
181
182    struct ELFSectionKey {
183      std::string SectionName;
184      StringRef GroupName;
185      unsigned UniqueID;
186      ELFSectionKey(StringRef SectionName, StringRef GroupName,
187                    unsigned UniqueID)
188          : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
189      }
190      bool operator<(const ELFSectionKey &Other) const {
191        if (SectionName != Other.SectionName)
192          return SectionName < Other.SectionName;
193        if (GroupName != Other.GroupName)
194          return GroupName < Other.GroupName;
195        return UniqueID < Other.UniqueID;
196      }
197    };
198
199    struct COFFSectionKey {
200      std::string SectionName;
201      StringRef GroupName;
202      int SelectionKey;
203      unsigned UniqueID;
204      COFFSectionKey(StringRef SectionName, StringRef GroupName,
205                     int SelectionKey, unsigned UniqueID)
206          : SectionName(SectionName), GroupName(GroupName),
207            SelectionKey(SelectionKey), UniqueID(UniqueID) {}
208      bool operator<(const COFFSectionKey &Other) const {
209        if (SectionName != Other.SectionName)
210          return SectionName < Other.SectionName;
211        if (GroupName != Other.GroupName)
212          return GroupName < Other.GroupName;
213        if (SelectionKey != Other.SelectionKey)
214          return SelectionKey < Other.SelectionKey;
215        return UniqueID < Other.UniqueID;
216      }
217    };
218
219    StringMap<MCSectionMachO *> MachOUniquingMap;
220    std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
221    std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
222    StringMap<bool> ELFRelSecNames;
223
224    SpecificBumpPtrAllocator<MCSubtargetInfo> MCSubtargetAllocator;
225
226    /// Do automatic reset in destructor
227    bool AutoReset;
228
229    bool HadError;
230
231    MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
232                               bool CanBeUnnamed);
233    MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
234                           bool IsTemporary);
235
236    MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
237                                                unsigned Instance);
238
239  public:
240    explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
241                       const MCObjectFileInfo *MOFI,
242                       const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
243    ~MCContext();
244
245    const SourceMgr *getSourceManager() const { return SrcMgr; }
246
247    const MCAsmInfo *getAsmInfo() const { return MAI; }
248
249    const MCRegisterInfo *getRegisterInfo() const { return MRI; }
250
251    const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
252
253    CodeViewContext &getCVContext();
254
255    void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
256    void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
257
258    /// \name Module Lifetime Management
259    /// @{
260
261    /// reset - return object to right after construction state to prepare
262    /// to process a new module
263    void reset();
264
265    /// @}
266
267    /// \name Symbol Management
268    /// @{
269
270    /// Create and return a new linker temporary symbol with a unique but
271    /// unspecified name.
272    MCSymbol *createLinkerPrivateTempSymbol();
273
274    /// Create and return a new assembler temporary symbol with a unique but
275    /// unspecified name.
276    MCSymbol *createTempSymbol(bool CanBeUnnamed = true);
277
278    MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
279                               bool CanBeUnnamed = true);
280
281    /// Create the definition of a directional local symbol for numbered label
282    /// (used for "1:" definitions).
283    MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
284
285    /// Create and return a directional local symbol for numbered label (used
286    /// for "1b" or 1f" references).
287    MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
288
289    /// Lookup the symbol inside with the specified \p Name.  If it exists,
290    /// return it.  If not, create a forward reference and return it.
291    ///
292    /// \param Name - The symbol name, which must be unique across all symbols.
293    MCSymbol *getOrCreateSymbol(const Twine &Name);
294
295    MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section);
296
297    /// Gets a symbol that will be defined to the final stack offset of a local
298    /// variable after codegen.
299    ///
300    /// \param Idx - The index of a local variable passed to @llvm.localescape.
301    MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
302
303    MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
304
305    MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
306
307    /// Get the symbol for \p Name, or null.
308    MCSymbol *lookupSymbol(const Twine &Name) const;
309
310    /// getSymbols - Get a reference for the symbol table for clients that
311    /// want to, for example, iterate over all symbols. 'const' because we
312    /// still want any modifications to the table itself to use the MCContext
313    /// APIs.
314    const SymbolTable &getSymbols() const { return Symbols; }
315
316    /// @}
317
318    /// \name Section Management
319    /// @{
320
321    enum : unsigned {
322      /// Pass this value as the UniqueID during section creation to get the
323      /// generic section with the given name and characteristics. The usual
324      /// sections such as .text use this ID.
325      GenericSectionID = ~0U
326    };
327
328    /// Return the MCSection for the specified mach-o section.  This requires
329    /// the operands to be valid.
330    MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
331                                    unsigned TypeAndAttributes,
332                                    unsigned Reserved2, SectionKind K,
333                                    const char *BeginSymName = nullptr);
334
335    MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
336                                    unsigned TypeAndAttributes, SectionKind K,
337                                    const char *BeginSymName = nullptr) {
338      return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
339                             BeginSymName);
340    }
341
342    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
343                                unsigned Flags) {
344      return getELFSection(Section, Type, Flags, nullptr);
345    }
346
347    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
348                                unsigned Flags, const char *BeginSymName) {
349      return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
350    }
351
352    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
353                                unsigned Flags, unsigned EntrySize,
354                                const Twine &Group) {
355      return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
356    }
357
358    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
359                                unsigned Flags, unsigned EntrySize,
360                                const Twine &Group, const char *BeginSymName) {
361      return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
362                           BeginSymName);
363    }
364
365    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
366                                unsigned Flags, unsigned EntrySize,
367                                const Twine &Group, unsigned UniqueID) {
368      return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
369                           nullptr);
370    }
371
372    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
373                                unsigned Flags, unsigned EntrySize,
374                                const Twine &Group, unsigned UniqueID,
375                                const char *BeginSymName);
376
377    MCSectionELF *getELFSection(const Twine &Section, unsigned Type,
378                                unsigned Flags, unsigned EntrySize,
379                                const MCSymbolELF *Group, unsigned UniqueID,
380                                const char *BeginSymName,
381                                const MCSectionELF *Associated);
382
383    /// Get a section with the provided group identifier. This section is
384    /// named by concatenating \p Prefix with '.' then \p Suffix. The \p Type
385    /// describes the type of the section and \p Flags are used to further
386    /// configure this named section.
387    MCSectionELF *getELFNamedSection(const Twine &Prefix, const Twine &Suffix,
388                                     unsigned Type, unsigned Flags,
389                                     unsigned EntrySize = 0);
390
391    MCSectionELF *createELFRelSection(const Twine &Name, unsigned Type,
392                                      unsigned Flags, unsigned EntrySize,
393                                      const MCSymbolELF *Group,
394                                      const MCSectionELF *Associated);
395
396    void renameELFSection(MCSectionELF *Section, StringRef Name);
397
398    MCSectionELF *createELFGroupSection(const MCSymbolELF *Group);
399
400    MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
401                                  SectionKind Kind, StringRef COMDATSymName,
402                                  int Selection,
403                                  unsigned UniqueID = GenericSectionID,
404                                  const char *BeginSymName = nullptr);
405
406    MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
407                                  SectionKind Kind,
408                                  const char *BeginSymName = nullptr);
409
410    MCSectionCOFF *getCOFFSection(StringRef Section);
411
412    /// Gets or creates a section equivalent to Sec that is associated with the
413    /// section containing KeySym. For example, to create a debug info section
414    /// associated with an inline function, pass the normal debug info section
415    /// as Sec and the function symbol as KeySym.
416    MCSectionCOFF *
417    getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym,
418                              unsigned UniqueID = GenericSectionID);
419
420    // Create and save a copy of STI and return a reference to the copy.
421    MCSubtargetInfo &getSubtargetCopy(const MCSubtargetInfo &STI);
422
423    /// @}
424
425    /// \name Dwarf Management
426    /// @{
427
428    /// \brief Get the compilation directory for DW_AT_comp_dir
429    /// The compilation directory should be set with \c setCompilationDir before
430    /// calling this function. If it is unset, an empty string will be returned.
431    StringRef getCompilationDir() const { return CompilationDir; }
432
433    /// \brief Set the compilation directory for DW_AT_comp_dir
434    void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
435
436    /// \brief Get the main file name for use in error messages and debug
437    /// info. This can be set to ensure we've got the correct file name
438    /// after preprocessing or for -save-temps.
439    const std::string &getMainFileName() const { return MainFileName; }
440
441    /// \brief Set the main file name and override the default.
442    void setMainFileName(StringRef S) { MainFileName = S; }
443
444    /// Creates an entry in the dwarf file and directory tables.
445    unsigned getDwarfFile(StringRef Directory, StringRef FileName,
446                          unsigned FileNumber, unsigned CUID);
447
448    bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
449
450    const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
451      return MCDwarfLineTablesCUMap;
452    }
453
454    MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
455      return MCDwarfLineTablesCUMap[CUID];
456    }
457
458    const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
459      auto I = MCDwarfLineTablesCUMap.find(CUID);
460      assert(I != MCDwarfLineTablesCUMap.end());
461      return I->second;
462    }
463
464    const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
465      return getMCDwarfLineTable(CUID).getMCDwarfFiles();
466    }
467    const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
468      return getMCDwarfLineTable(CUID).getMCDwarfDirs();
469    }
470
471    bool hasMCLineSections() const {
472      for (const auto &Table : MCDwarfLineTablesCUMap)
473        if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
474          return true;
475      return false;
476    }
477    unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
478    void setDwarfCompileUnitID(unsigned CUIndex) {
479      DwarfCompileUnitID = CUIndex;
480    }
481    void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
482      getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
483    }
484
485    /// Saves the information from the currently parsed dwarf .loc directive
486    /// and sets DwarfLocSeen.  When the next instruction is assembled an entry
487    /// in the line number table with this information and the address of the
488    /// instruction will be created.
489    void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
490                            unsigned Flags, unsigned Isa,
491                            unsigned Discriminator) {
492      CurrentDwarfLoc.setFileNum(FileNum);
493      CurrentDwarfLoc.setLine(Line);
494      CurrentDwarfLoc.setColumn(Column);
495      CurrentDwarfLoc.setFlags(Flags);
496      CurrentDwarfLoc.setIsa(Isa);
497      CurrentDwarfLoc.setDiscriminator(Discriminator);
498      DwarfLocSeen = true;
499    }
500    void clearDwarfLocSeen() { DwarfLocSeen = false; }
501
502    bool getDwarfLocSeen() { return DwarfLocSeen; }
503    const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
504
505    bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
506    void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
507    unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
508    void setGenDwarfFileNumber(unsigned FileNumber) {
509      GenDwarfFileNumber = FileNumber;
510    }
511    const SetVector<MCSection *> &getGenDwarfSectionSyms() {
512      return SectionsForRanges;
513    }
514    bool addGenDwarfSection(MCSection *Sec) {
515      return SectionsForRanges.insert(Sec);
516    }
517
518    void finalizeDwarfSections(MCStreamer &MCOS);
519    const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
520      return MCGenDwarfLabelEntries;
521    }
522    void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
523      MCGenDwarfLabelEntries.push_back(E);
524    }
525
526    void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
527    StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
528
529    void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
530    StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
531
532    void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
533    uint16_t getDwarfVersion() const { return DwarfVersion; }
534
535    /// @}
536
537
538    /// \name CodeView Management
539    /// @{
540
541    /// Creates an entry in the cv file table.
542    unsigned getCVFile(StringRef FileName, unsigned FileNumber);
543
544    /// Saves the information from the currently parsed .cv_loc directive
545    /// and sets CVLocSeen.  When the next instruction is assembled an entry
546    /// in the line number table with this information and the address of the
547    /// instruction will be created.
548    void setCurrentCVLoc(unsigned FunctionId, unsigned FileNo, unsigned Line,
549                         unsigned Column, bool PrologueEnd, bool IsStmt) {
550      CurrentCVLoc.setFunctionId(FunctionId);
551      CurrentCVLoc.setFileNum(FileNo);
552      CurrentCVLoc.setLine(Line);
553      CurrentCVLoc.setColumn(Column);
554      CurrentCVLoc.setPrologueEnd(PrologueEnd);
555      CurrentCVLoc.setIsStmt(IsStmt);
556      CVLocSeen = true;
557    }
558    void clearCVLocSeen() { CVLocSeen = false; }
559
560    bool getCVLocSeen() { return CVLocSeen; }
561    const MCCVLoc &getCurrentCVLoc() { return CurrentCVLoc; }
562
563    bool isValidCVFileNumber(unsigned FileNumber);
564    /// @}
565
566    char *getSecureLogFile() { return SecureLogFile; }
567    raw_fd_ostream *getSecureLog() { return SecureLog.get(); }
568    bool getSecureLogUsed() { return SecureLogUsed; }
569    void setSecureLog(std::unique_ptr<raw_fd_ostream> Value) {
570      SecureLog = std::move(Value);
571    }
572    void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
573
574    void *allocate(unsigned Size, unsigned Align = 8) {
575      return Allocator.Allocate(Size, Align);
576    }
577    void deallocate(void *Ptr) {}
578
579    bool hadError() { return HadError; }
580    void reportError(SMLoc L, const Twine &Msg);
581    // Unrecoverable error has occurred. Display the best diagnostic we can
582    // and bail via exit(1). For now, most MC backend errors are unrecoverable.
583    // FIXME: We should really do something about that.
584    LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
585                                                  const Twine &Msg);
586  };
587
588} // end namespace llvm
589
590// operator new and delete aren't allowed inside namespaces.
591// The throw specifications are mandated by the standard.
592/// \brief Placement new for using the MCContext's allocator.
593///
594/// This placement form of operator new uses the MCContext's allocator for
595/// obtaining memory. It is a non-throwing new, which means that it returns
596/// null on error. (If that is what the allocator does. The current does, so if
597/// this ever changes, this operator will have to be changed, too.)
598/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
599/// \code
600/// // Default alignment (8)
601/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
602/// // Specific alignment
603/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
604/// \endcode
605/// Please note that you cannot use delete on the pointer; it must be
606/// deallocated using an explicit destructor call followed by
607/// \c Context.Deallocate(Ptr).
608///
609/// \param Bytes The number of bytes to allocate. Calculated by the compiler.
610/// \param C The MCContext that provides the allocator.
611/// \param Alignment The alignment of the allocated memory (if the underlying
612///                  allocator supports it).
613/// \return The allocated memory. Could be NULL.
614inline void *operator new(size_t Bytes, llvm::MCContext &C,
615                          size_t Alignment = 8) LLVM_NOEXCEPT {
616  return C.allocate(Bytes, Alignment);
617}
618/// \brief Placement delete companion to the new above.
619///
620/// This operator is just a companion to the new above. There is no way of
621/// invoking it directly; see the new operator for more details. This operator
622/// is called implicitly by the compiler if a placement new expression using
623/// the MCContext throws in the object constructor.
624inline void operator delete(void *Ptr, llvm::MCContext &C,
625                            size_t) LLVM_NOEXCEPT {
626  C.deallocate(Ptr);
627}
628
629/// This placement form of operator new[] uses the MCContext's allocator for
630/// obtaining memory. It is a non-throwing new[], which means that it returns
631/// null on error.
632/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
633/// \code
634/// // Default alignment (8)
635/// char *data = new (Context) char[10];
636/// // Specific alignment
637/// char *data = new (Context, 4) char[10];
638/// \endcode
639/// Please note that you cannot use delete on the pointer; it must be
640/// deallocated using an explicit destructor call followed by
641/// \c Context.Deallocate(Ptr).
642///
643/// \param Bytes The number of bytes to allocate. Calculated by the compiler.
644/// \param C The MCContext that provides the allocator.
645/// \param Alignment The alignment of the allocated memory (if the underlying
646///                  allocator supports it).
647/// \return The allocated memory. Could be NULL.
648inline void *operator new[](size_t Bytes, llvm::MCContext &C,
649                            size_t Alignment = 8) LLVM_NOEXCEPT {
650  return C.allocate(Bytes, Alignment);
651}
652
653/// \brief Placement delete[] companion to the new[] above.
654///
655/// This operator is just a companion to the new[] above. There is no way of
656/// invoking it directly; see the new[] operator for more details. This operator
657/// is called implicitly by the compiler if a placement new[] expression using
658/// the MCContext throws in the object constructor.
659inline void operator delete[](void *Ptr, llvm::MCContext &C) LLVM_NOEXCEPT {
660  C.deallocate(Ptr);
661}
662
663#endif
664