blob: c8050450041870dd8a9407f01f98be49108125d7 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/LLVMContext.h - Class for managing "global" state ---*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// This file declares LLVMContext, a container of "global" state in LLVM, such
10// as the global type and constant uniquing tables.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_LLVMCONTEXT_H
15#define LLVM_IR_LLVMCONTEXT_H
16
17#include "llvm-c/Types.h"
18#include "llvm/IR/DiagnosticHandler.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 OptPassGate;
34template <typename T> class SmallVectorImpl;
35class SMDiagnostic;
36class StringRef;
37class Twine;
Andrew Walbran3d2c1972020-04-07 12:24:26 +010038class RemarkStreamer;
39class raw_ostream;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010040
41namespace SyncScope {
42
43typedef uint8_t ID;
44
45/// Known synchronization scope IDs, which always have the same value. All
46/// synchronization scope IDs that LLVM has special knowledge of are listed
47/// here. Additionally, this scheme allows LLVM to efficiently check for
48/// specific synchronization scope ID without comparing strings.
49enum {
50 /// Synchronized with respect to signal handlers executing in the same thread.
51 SingleThread = 0,
52
53 /// Synchronized with respect to all concurrently executing threads.
54 System = 1
55};
56
57} // end namespace SyncScope
58
59/// This is an important class for using LLVM in a threaded context. It
60/// (opaquely) owns and manages the core "global" data of LLVM's core
61/// infrastructure, including the type and constant uniquing tables.
62/// LLVMContext itself provides no locking guarantees, so you should be careful
63/// to have one context per thread.
64class LLVMContext {
65public:
66 LLVMContextImpl *const pImpl;
67 LLVMContext();
68 LLVMContext(LLVMContext &) = delete;
69 LLVMContext &operator=(const LLVMContext &) = delete;
70 ~LLVMContext();
71
72 // Pinned metadata names, which always have the same value. This is a
73 // compile-time performance optimization, not a correctness optimization.
74 enum : unsigned {
75 MD_dbg = 0, // "dbg"
76 MD_tbaa = 1, // "tbaa"
77 MD_prof = 2, // "prof"
78 MD_fpmath = 3, // "fpmath"
79 MD_range = 4, // "range"
80 MD_tbaa_struct = 5, // "tbaa.struct"
81 MD_invariant_load = 6, // "invariant.load"
82 MD_alias_scope = 7, // "alias.scope"
83 MD_noalias = 8, // "noalias",
84 MD_nontemporal = 9, // "nontemporal"
85 MD_mem_parallel_loop_access = 10, // "llvm.mem.parallel_loop_access"
86 MD_nonnull = 11, // "nonnull"
87 MD_dereferenceable = 12, // "dereferenceable"
88 MD_dereferenceable_or_null = 13, // "dereferenceable_or_null"
89 MD_make_implicit = 14, // "make.implicit"
90 MD_unpredictable = 15, // "unpredictable"
91 MD_invariant_group = 16, // "invariant.group"
92 MD_align = 17, // "align"
93 MD_loop = 18, // "llvm.loop"
94 MD_type = 19, // "type"
95 MD_section_prefix = 20, // "section_prefix"
96 MD_absolute_symbol = 21, // "absolute_symbol"
97 MD_associated = 22, // "associated"
98 MD_callees = 23, // "callees"
99 MD_irr_loop = 24, // "irr_loop"
Andrew Walbran16937d02019-10-22 13:54:20 +0100100 MD_access_group = 25, // "llvm.access.group"
101 MD_callback = 26, // "callback"
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100102 MD_preserve_access_index = 27, // "llvm.preserve.*.access.index"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100103 };
104
105 /// Known operand bundle tag IDs, which always have the same value. All
106 /// operand bundle tags that LLVM has special knowledge of are listed here.
107 /// Additionally, this scheme allows LLVM to efficiently check for specific
108 /// operand bundle tags without comparing strings.
109 enum : unsigned {
110 OB_deopt = 0, // "deopt"
111 OB_funclet = 1, // "funclet"
112 OB_gc_transition = 2, // "gc-transition"
113 };
114
115 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
116 /// This ID is uniqued across modules in the current LLVMContext.
117 unsigned getMDKindID(StringRef Name) const;
118
119 /// getMDKindNames - Populate client supplied SmallVector with the name for
120 /// custom metadata IDs registered in this LLVMContext.
121 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
122
123 /// getOperandBundleTags - Populate client supplied SmallVector with the
124 /// bundle tags registered in this LLVMContext. The bundle tags are ordered
125 /// by increasing bundle IDs.
126 /// \see LLVMContext::getOperandBundleTagID
127 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
128
129 /// getOperandBundleTagID - Maps a bundle tag to an integer ID. Every bundle
130 /// tag registered with an LLVMContext has an unique ID.
131 uint32_t getOperandBundleTagID(StringRef Tag) const;
132
133 /// getOrInsertSyncScopeID - Maps synchronization scope name to
134 /// synchronization scope ID. Every synchronization scope registered with
135 /// LLVMContext has unique ID except pre-defined ones.
136 SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
137
138 /// getSyncScopeNames - Populates client supplied SmallVector with
139 /// synchronization scope names registered with LLVMContext. Synchronization
140 /// scope names are ordered by increasing synchronization scope IDs.
141 void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
142
143 /// Define the GC for a function
144 void setGC(const Function &Fn, std::string GCName);
145
146 /// Return the GC for a function
147 const std::string &getGC(const Function &Fn);
148
149 /// Remove the GC for a function
150 void deleteGC(const Function &Fn);
151
152 /// Return true if the Context runtime configuration is set to discard all
153 /// value names. When true, only GlobalValue names will be available in the
154 /// IR.
155 bool shouldDiscardValueNames() const;
156
157 /// Set the Context runtime configuration to discard all value name (but
158 /// GlobalValue). Clients can use this flag to save memory and runtime,
159 /// especially in release mode.
160 void setDiscardValueNames(bool Discard);
161
162 /// Whether there is a string map for uniquing debug info
163 /// identifiers across the context. Off by default.
164 bool isODRUniquingDebugTypes() const;
165 void enableDebugTypeODRUniquing();
166 void disableDebugTypeODRUniquing();
167
168 using InlineAsmDiagHandlerTy = void (*)(const SMDiagnostic&, void *Context,
169 unsigned LocCookie);
170
171 /// Defines the type of a yield callback.
172 /// \see LLVMContext::setYieldCallback.
173 using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
174
175 /// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked
176 /// when problems with inline asm are detected by the backend. The first
177 /// argument is a function pointer and the second is a context pointer that
178 /// gets passed into the DiagHandler.
179 ///
180 /// LLVMContext doesn't take ownership or interpret either of these
181 /// pointers.
182 void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
183 void *DiagContext = nullptr);
184
185 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
186 /// setInlineAsmDiagnosticHandler.
187 InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const;
188
189 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
190 /// setInlineAsmDiagnosticHandler.
191 void *getInlineAsmDiagnosticContext() const;
192
193 /// setDiagnosticHandlerCallBack - This method sets a handler call back
194 /// that is invoked when the backend needs to report anything to the user.
195 /// The first argument is a function pointer and the second is a context pointer
196 /// that gets passed into the DiagHandler. The third argument should be set to
197 /// true if the handler only expects enabled diagnostics.
198 ///
199 /// LLVMContext doesn't take ownership or interpret either of these
200 /// pointers.
201 void setDiagnosticHandlerCallBack(
202 DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
203 void *DiagContext = nullptr, bool RespectFilters = false);
204
205 /// setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler
206 /// to provide custom diagnostic handling. The first argument is unique_ptr of object
207 /// of type DiagnosticHandler or a derived of that. The third argument should be
208 /// set to true if the handler only expects enabled diagnostics.
209 ///
210 /// Ownership of this pointer is moved to LLVMContextImpl.
211 void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
212 bool RespectFilters = false);
213
214 /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
215 /// setDiagnosticHandlerCallBack.
216 DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;
217
218 /// getDiagnosticContext - Return the diagnostic context set by
219 /// setDiagnosticContext.
220 void *getDiagnosticContext() const;
221
222 /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
223 /// setDiagnosticHandler.
224 const DiagnosticHandler *getDiagHandlerPtr() const;
225
226 /// getDiagnosticHandler - transfers owenership of DiagnosticHandler unique_ptr
227 /// to caller.
228 std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
229
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100230 /// Return if a code hotness metric should be included in optimization
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100231 /// diagnostics.
232 bool getDiagnosticsHotnessRequested() const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100233 /// Set if a code hotness metric should be included in optimization
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100234 /// diagnostics.
235 void setDiagnosticsHotnessRequested(bool Requested);
236
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100237 /// Return the minimum hotness value a diagnostic would need in order
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100238 /// to be included in optimization diagnostics. If there is no minimum, this
239 /// returns None.
240 uint64_t getDiagnosticsHotnessThreshold() const;
241
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100242 /// Set the minimum hotness value a diagnostic needs in order to be
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100243 /// included in optimization diagnostics.
244 void setDiagnosticsHotnessThreshold(uint64_t Threshold);
245
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100246 /// Return the streamer used by the backend to save remark diagnostics. If it
247 /// does not exist, diagnostics are not saved in a file but only emitted via
248 /// the diagnostic handler.
249 RemarkStreamer *getRemarkStreamer();
250 const RemarkStreamer *getRemarkStreamer() const;
251
252 /// Set the diagnostics output used for optimization diagnostics.
253 /// This filename may be embedded in a section for tools to find the
254 /// diagnostics whenever they're needed.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100255 ///
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100256 /// If a remark streamer is already set, it will be replaced with
257 /// \p RemarkStreamer.
258 ///
259 /// By default, diagnostics are not saved in a file but only emitted via the
260 /// diagnostic handler. Even if an output file is set, the handler is invoked
261 /// for each diagnostic message.
262 void setRemarkStreamer(std::unique_ptr<RemarkStreamer> RemarkStreamer);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100263
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100264 /// Get the prefix that should be printed in front of a diagnostic of
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100265 /// the given \p Severity
266 static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
267
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100268 /// Report a message to the currently installed diagnostic handler.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100269 ///
270 /// This function returns, in particular in the case of error reporting
271 /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
272 /// process in a self-consistent state, even though the generated code
273 /// need not be correct.
274 ///
275 /// The diagnostic message will be implicitly prefixed with a severity keyword
276 /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
277 /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
278 void diagnose(const DiagnosticInfo &DI);
279
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100280 /// Registers a yield callback with the given context.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100281 ///
282 /// The yield callback function may be called by LLVM to transfer control back
283 /// to the client that invoked the LLVM compilation. This can be used to yield
284 /// control of the thread, or perform periodic work needed by the client.
285 /// There is no guaranteed frequency at which callbacks must occur; in fact,
286 /// the client is not guaranteed to ever receive this callback. It is at the
287 /// sole discretion of LLVM to do so and only if it can guarantee that
288 /// suspending the thread won't block any forward progress in other LLVM
289 /// contexts in the same process.
290 ///
291 /// At a suspend point, the state of the current LLVM context is intentionally
292 /// undefined. No assumptions about it can or should be made. Only LLVM
293 /// context API calls that explicitly state that they can be used during a
294 /// yield callback are allowed to be used. Any other API calls into the
295 /// context are not supported until the yield callback function returns
296 /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
297 void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
298
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100299 /// Calls the yield callback (if applicable).
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100300 ///
301 /// This transfers control of the current thread back to the client, which may
302 /// suspend the current thread. Only call this method when LLVM doesn't hold
303 /// any global mutex or cannot block the execution in another LLVM context.
304 void yield();
305
306 /// emitError - Emit an error message to the currently installed error handler
307 /// with optional location information. This function returns, so code should
308 /// be prepared to drop the erroneous construct on the floor and "not crash".
309 /// The generated code need not be correct. The error message will be
310 /// implicitly prefixed with "error: " and should not end with a ".".
311 void emitError(unsigned LocCookie, const Twine &ErrorStr);
312 void emitError(const Instruction *I, const Twine &ErrorStr);
313 void emitError(const Twine &ErrorStr);
314
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100315 /// Query for a debug option's value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100316 ///
317 /// This function returns typed data populated from command line parsing.
318 template <typename ValT, typename Base, ValT(Base::*Mem)>
319 ValT getOption() const {
320 return OptionRegistry::instance().template get<ValT, Base, Mem>();
321 }
322
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100323 /// Access the object which can disable optional passes and individual
324 /// optimizations at compile time.
325 OptPassGate &getOptPassGate() const;
326
327 /// Set the object which can disable optional passes and individual
328 /// optimizations at compile time.
329 ///
330 /// The lifetime of the object must be guaranteed to extend as long as the
331 /// LLVMContext is used by compilation.
332 void setOptPassGate(OptPassGate&);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100333
334private:
335 // Module needs access to the add/removeModule methods.
336 friend class Module;
337
338 /// addModule - Register a module as being instantiated in this context. If
339 /// the context is deleted, the module will be deleted as well.
340 void addModule(Module*);
341
342 /// removeModule - Unregister a module from this context.
343 void removeModule(Module*);
344};
345
346// Create wrappers for C Binding types (see CBindingWrapping.h).
347DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
348
349/* Specialized opaque context conversions.
350 */
351inline LLVMContext **unwrap(LLVMContextRef* Tys) {
352 return reinterpret_cast<LLVMContext**>(Tys);
353}
354
355inline LLVMContextRef *wrap(const LLVMContext **Tys) {
356 return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
357}
358
359} // end namespace llvm
360
361#endif // LLVM_IR_LLVMCONTEXT_H