1//===-- llvm/LLVMContext.h - Class for managing "global" state --*- 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// This file declares LLVMContext, a container of "global" state in LLVM, such
11// as the global type and constant uniquing tables.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_LLVMCONTEXT_H
16#define LLVM_IR_LLVMCONTEXT_H
17
18#include "llvm-c/Types.h"
19#include "llvm/Support/CBindingWrapping.h"
20#include "llvm/Support/Options.h"
21#include <cstdint>
22#include <memory>
23#include <string>
24
25namespace llvm {
26
27class DiagnosticInfo;
28enum DiagnosticSeverity : char;
29class Function;
30class Instruction;
31class LLVMContextImpl;
32class Module;
33class OptBisect;
34template <typename T> class SmallVectorImpl;
35class SMDiagnostic;
36class StringRef;
37class Twine;
38
39namespace yaml {
40class Output;
41} // end namespace yaml
42
43/// This is an important class for using LLVM in a threaded context.  It
44/// (opaquely) owns and manages the core "global" data of LLVM's core
45/// infrastructure, including the type and constant uniquing tables.
46/// LLVMContext itself provides no locking guarantees, so you should be careful
47/// to have one context per thread.
48class LLVMContext {
49public:
50  LLVMContextImpl *const pImpl;
51  LLVMContext();
52  LLVMContext(LLVMContext &) = delete;
53  LLVMContext &operator=(const LLVMContext &) = delete;
54  ~LLVMContext();
55
56  // Pinned metadata names, which always have the same value.  This is a
57  // compile-time performance optimization, not a correctness optimization.
58  enum {
59    MD_dbg = 0,                       // "dbg"
60    MD_tbaa = 1,                      // "tbaa"
61    MD_prof = 2,                      // "prof"
62    MD_fpmath = 3,                    // "fpmath"
63    MD_range = 4,                     // "range"
64    MD_tbaa_struct = 5,               // "tbaa.struct"
65    MD_invariant_load = 6,            // "invariant.load"
66    MD_alias_scope = 7,               // "alias.scope"
67    MD_noalias = 8,                   // "noalias",
68    MD_nontemporal = 9,               // "nontemporal"
69    MD_mem_parallel_loop_access = 10, // "llvm.mem.parallel_loop_access"
70    MD_nonnull = 11,                  // "nonnull"
71    MD_dereferenceable = 12,          // "dereferenceable"
72    MD_dereferenceable_or_null = 13,  // "dereferenceable_or_null"
73    MD_make_implicit = 14,            // "make.implicit"
74    MD_unpredictable = 15,            // "unpredictable"
75    MD_invariant_group = 16,          // "invariant.group"
76    MD_align = 17,                    // "align"
77    MD_loop = 18,                     // "llvm.loop"
78    MD_type = 19,                     // "type"
79    MD_section_prefix = 20,           // "section_prefix"
80    MD_absolute_symbol = 21,          // "absolute_symbol"
81  };
82
83  /// Known operand bundle tag IDs, which always have the same value.  All
84  /// operand bundle tags that LLVM has special knowledge of are listed here.
85  /// Additionally, this scheme allows LLVM to efficiently check for specific
86  /// operand bundle tags without comparing strings.
87  enum {
88    OB_deopt = 0,         // "deopt"
89    OB_funclet = 1,       // "funclet"
90    OB_gc_transition = 2, // "gc-transition"
91  };
92
93  /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
94  /// This ID is uniqued across modules in the current LLVMContext.
95  unsigned getMDKindID(StringRef Name) const;
96
97  /// getMDKindNames - Populate client supplied SmallVector with the name for
98  /// custom metadata IDs registered in this LLVMContext.
99  void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
100
101  /// getOperandBundleTags - Populate client supplied SmallVector with the
102  /// bundle tags registered in this LLVMContext.  The bundle tags are ordered
103  /// by increasing bundle IDs.
104  /// \see LLVMContext::getOperandBundleTagID
105  void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
106
107  /// getOperandBundleTagID - Maps a bundle tag to an integer ID.  Every bundle
108  /// tag registered with an LLVMContext has an unique ID.
109  uint32_t getOperandBundleTagID(StringRef Tag) const;
110
111  /// Define the GC for a function
112  void setGC(const Function &Fn, std::string GCName);
113
114  /// Return the GC for a function
115  const std::string &getGC(const Function &Fn);
116
117  /// Remove the GC for a function
118  void deleteGC(const Function &Fn);
119
120  /// Return true if the Context runtime configuration is set to discard all
121  /// value names. When true, only GlobalValue names will be available in the
122  /// IR.
123  bool shouldDiscardValueNames() const;
124
125  /// Set the Context runtime configuration to discard all value name (but
126  /// GlobalValue). Clients can use this flag to save memory and runtime,
127  /// especially in release mode.
128  void setDiscardValueNames(bool Discard);
129
130  /// Whether there is a string map for uniquing debug info
131  /// identifiers across the context.  Off by default.
132  bool isODRUniquingDebugTypes() const;
133  void enableDebugTypeODRUniquing();
134  void disableDebugTypeODRUniquing();
135
136  typedef void (*InlineAsmDiagHandlerTy)(const SMDiagnostic&, void *Context,
137                                         unsigned LocCookie);
138
139  /// Defines the type of a diagnostic handler.
140  /// \see LLVMContext::setDiagnosticHandler.
141  /// \see LLVMContext::diagnose.
142  typedef void (*DiagnosticHandlerTy)(const DiagnosticInfo &DI, void *Context);
143
144  /// Defines the type of a yield callback.
145  /// \see LLVMContext::setYieldCallback.
146  typedef void (*YieldCallbackTy)(LLVMContext *Context, void *OpaqueHandle);
147
148  /// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked
149  /// when problems with inline asm are detected by the backend.  The first
150  /// argument is a function pointer and the second is a context pointer that
151  /// gets passed into the DiagHandler.
152  ///
153  /// LLVMContext doesn't take ownership or interpret either of these
154  /// pointers.
155  void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
156                                     void *DiagContext = nullptr);
157
158  /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
159  /// setInlineAsmDiagnosticHandler.
160  InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const;
161
162  /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
163  /// setInlineAsmDiagnosticHandler.
164  void *getInlineAsmDiagnosticContext() const;
165
166  /// setDiagnosticHandler - This method sets a handler that is invoked
167  /// when the backend needs to report anything to the user.  The first
168  /// argument is a function pointer and the second is a context pointer that
169  /// gets passed into the DiagHandler.  The third argument should be set to
170  /// true if the handler only expects enabled diagnostics.
171  ///
172  /// LLVMContext doesn't take ownership or interpret either of these
173  /// pointers.
174  void setDiagnosticHandler(DiagnosticHandlerTy DiagHandler,
175                            void *DiagContext = nullptr,
176                            bool RespectFilters = false);
177
178  /// getDiagnosticHandler - Return the diagnostic handler set by
179  /// setDiagnosticHandler.
180  DiagnosticHandlerTy getDiagnosticHandler() const;
181
182  /// getDiagnosticContext - Return the diagnostic context set by
183  /// setDiagnosticContext.
184  void *getDiagnosticContext() const;
185
186  /// \brief Return if a code hotness metric should be included in optimization
187  /// diagnostics.
188  bool getDiagnosticHotnessRequested() const;
189  /// \brief Set if a code hotness metric should be included in optimization
190  /// diagnostics.
191  void setDiagnosticHotnessRequested(bool Requested);
192
193  /// \brief Return the YAML file used by the backend to save optimization
194  /// diagnostics.  If null, diagnostics are not saved in a file but only
195  /// emitted via the diagnostic handler.
196  yaml::Output *getDiagnosticsOutputFile();
197  /// Set the diagnostics output file used for optimization diagnostics.
198  ///
199  /// By default or if invoked with null, diagnostics are not saved in a file
200  /// but only emitted via the diagnostic handler.  Even if an output file is
201  /// set, the handler is invoked for each diagnostic message.
202  void setDiagnosticsOutputFile(std::unique_ptr<yaml::Output> F);
203
204  /// \brief Get the prefix that should be printed in front of a diagnostic of
205  ///        the given \p Severity
206  static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
207
208  /// \brief Report a message to the currently installed diagnostic handler.
209  ///
210  /// This function returns, in particular in the case of error reporting
211  /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
212  /// process in a self-consistent state, even though the generated code
213  /// need not be correct.
214  ///
215  /// The diagnostic message will be implicitly prefixed with a severity keyword
216  /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
217  /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
218  void diagnose(const DiagnosticInfo &DI);
219
220  /// \brief Registers a yield callback with the given context.
221  ///
222  /// The yield callback function may be called by LLVM to transfer control back
223  /// to the client that invoked the LLVM compilation. This can be used to yield
224  /// control of the thread, or perform periodic work needed by the client.
225  /// There is no guaranteed frequency at which callbacks must occur; in fact,
226  /// the client is not guaranteed to ever receive this callback. It is at the
227  /// sole discretion of LLVM to do so and only if it can guarantee that
228  /// suspending the thread won't block any forward progress in other LLVM
229  /// contexts in the same process.
230  ///
231  /// At a suspend point, the state of the current LLVM context is intentionally
232  /// undefined. No assumptions about it can or should be made. Only LLVM
233  /// context API calls that explicitly state that they can be used during a
234  /// yield callback are allowed to be used. Any other API calls into the
235  /// context are not supported until the yield callback function returns
236  /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
237  void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
238
239  /// \brief Calls the yield callback (if applicable).
240  ///
241  /// This transfers control of the current thread back to the client, which may
242  /// suspend the current thread. Only call this method when LLVM doesn't hold
243  /// any global mutex or cannot block the execution in another LLVM context.
244  void yield();
245
246  /// emitError - Emit an error message to the currently installed error handler
247  /// with optional location information.  This function returns, so code should
248  /// be prepared to drop the erroneous construct on the floor and "not crash".
249  /// The generated code need not be correct.  The error message will be
250  /// implicitly prefixed with "error: " and should not end with a ".".
251  void emitError(unsigned LocCookie, const Twine &ErrorStr);
252  void emitError(const Instruction *I, const Twine &ErrorStr);
253  void emitError(const Twine &ErrorStr);
254
255  /// \brief Query for a debug option's value.
256  ///
257  /// This function returns typed data populated from command line parsing.
258  template <typename ValT, typename Base, ValT(Base::*Mem)>
259  ValT getOption() const {
260    return OptionRegistry::instance().template get<ValT, Base, Mem>();
261  }
262
263  /// \brief Access the object which manages optimization bisection for failure
264  /// analysis.
265  OptBisect &getOptBisect();
266private:
267  // Module needs access to the add/removeModule methods.
268  friend class Module;
269
270  /// addModule - Register a module as being instantiated in this context.  If
271  /// the context is deleted, the module will be deleted as well.
272  void addModule(Module*);
273
274  /// removeModule - Unregister a module from this context.
275  void removeModule(Module*);
276};
277
278// Create wrappers for C Binding types (see CBindingWrapping.h).
279DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
280
281/* Specialized opaque context conversions.
282 */
283inline LLVMContext **unwrap(LLVMContextRef* Tys) {
284  return reinterpret_cast<LLVMContext**>(Tys);
285}
286
287inline LLVMContextRef *wrap(const LLVMContext **Tys) {
288  return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
289}
290
291} // end namespace llvm
292
293#endif // LLVM_IR_LLVMCONTEXT_H
294