LLVM 19.0.0git
LLVMContext.h
Go to the documentation of this file.
1//===- llvm/LLVMContext.h - Class for managing "global" state ---*- C++ -*-===//
2//
3// 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
6//
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"
20#include <cstdint>
21#include <memory>
22#include <optional>
23#include <string>
24
25namespace llvm {
26
27class DiagnosticInfo;
29class Function;
30class Instruction;
31class LLVMContextImpl;
32class Module;
33class OptPassGate;
34template <typename T> class SmallVectorImpl;
35template <typename T> class StringMapEntry;
36class StringRef;
37class Twine;
38class LLVMRemarkStreamer;
39
40namespace remarks {
41class RemarkStreamer;
42}
43
44namespace SyncScope {
45
46typedef uint8_t ID;
47
48/// Known synchronization scope IDs, which always have the same value. All
49/// synchronization scope IDs that LLVM has special knowledge of are listed
50/// here. Additionally, this scheme allows LLVM to efficiently check for
51/// specific synchronization scope ID without comparing strings.
52enum {
53 /// Synchronized with respect to signal handlers executing in the same thread.
55
56 /// Synchronized with respect to all concurrently executing threads.
57 System = 1
58};
59
60} // end namespace SyncScope
61
62/// This is an important class for using LLVM in a threaded context. It
63/// (opaquely) owns and manages the core "global" data of LLVM's core
64/// infrastructure, including the type and constant uniquing tables.
65/// LLVMContext itself provides no locking guarantees, so you should be careful
66/// to have one context per thread.
68public:
71 LLVMContext(const LLVMContext &) = delete;
72 LLVMContext &operator=(const LLVMContext &) = delete;
74
75 // Pinned metadata names, which always have the same value. This is a
76 // compile-time performance optimization, not a correctness optimization.
77 enum : unsigned {
78#define LLVM_FIXED_MD_KIND(EnumID, Name, Value) EnumID = Value,
79#include "llvm/IR/FixedMetadataKinds.def"
80#undef LLVM_FIXED_MD_KIND
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. Keep this in sync with
87 /// LLVMContext::LLVMContext().
88 enum : unsigned {
89 OB_deopt = 0, // "deopt"
90 OB_funclet = 1, // "funclet"
91 OB_gc_transition = 2, // "gc-transition"
92 OB_cfguardtarget = 3, // "cfguardtarget"
93 OB_preallocated = 4, // "preallocated"
94 OB_gc_live = 5, // "gc-live"
95 OB_clang_arc_attachedcall = 6, // "clang.arc.attachedcall"
96 OB_ptrauth = 7, // "ptrauth"
97 OB_kcfi = 8, // "kcfi"
98 OB_convergencectrl = 9, // "convergencectrl"
99 };
100
101 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
102 /// This ID is uniqued across modules in the current LLVMContext.
103 unsigned getMDKindID(StringRef Name) const;
104
105 /// getMDKindNames - Populate client supplied SmallVector with the name for
106 /// custom metadata IDs registered in this LLVMContext.
107 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
108
109 /// getOperandBundleTags - Populate client supplied SmallVector with the
110 /// bundle tags registered in this LLVMContext. The bundle tags are ordered
111 /// by increasing bundle IDs.
112 /// \see LLVMContext::getOperandBundleTagID
114
115 /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
116 /// name TagName.
118
119 /// getOperandBundleTagID - Maps a bundle tag to an integer ID. Every bundle
120 /// tag registered with an LLVMContext has an unique ID.
122
123 /// getOrInsertSyncScopeID - Maps synchronization scope name to
124 /// synchronization scope ID. Every synchronization scope registered with
125 /// LLVMContext has unique ID except pre-defined ones.
127
128 /// getSyncScopeNames - Populates client supplied SmallVector with
129 /// synchronization scope names registered with LLVMContext. Synchronization
130 /// scope names are ordered by increasing synchronization scope IDs.
132
133 /// Define the GC for a function
134 void setGC(const Function &Fn, std::string GCName);
135
136 /// Return the GC for a function
137 const std::string &getGC(const Function &Fn);
138
139 /// Remove the GC for a function
140 void deleteGC(const Function &Fn);
141
142 /// Return true if the Context runtime configuration is set to discard all
143 /// value names. When true, only GlobalValue names will be available in the
144 /// IR.
145 bool shouldDiscardValueNames() const;
146
147 /// Set the Context runtime configuration to discard all value name (but
148 /// GlobalValue). Clients can use this flag to save memory and runtime,
149 /// especially in release mode.
150 void setDiscardValueNames(bool Discard);
151
152 /// Whether there is a string map for uniquing debug info
153 /// identifiers across the context. Off by default.
154 bool isODRUniquingDebugTypes() const;
157
158 /// generateMachineFunctionNum - Get a unique number for MachineFunction
159 /// that associated with the given Function.
161
162 /// Defines the type of a yield callback.
163 /// \see LLVMContext::setYieldCallback.
164 using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
165
166 /// setDiagnosticHandlerCallBack - This method sets a handler call back
167 /// that is invoked when the backend needs to report anything to the user.
168 /// The first argument is a function pointer and the second is a context pointer
169 /// that 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.
176 void *DiagContext = nullptr, bool RespectFilters = false);
177
178 /// setDiagnosticHandler - This method sets unique_ptr to object of
179 /// DiagnosticHandler to provide custom diagnostic handling. The first
180 /// argument is unique_ptr of object of type DiagnosticHandler or a derived
181 /// of that. The second argument should be set to true if the handler only
182 /// expects enabled diagnostics.
183 ///
184 /// Ownership of this pointer is moved to LLVMContextImpl.
185 void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
186 bool RespectFilters = false);
187
188 /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
189 /// setDiagnosticHandlerCallBack.
191
192 /// getDiagnosticContext - Return the diagnostic context set by
193 /// setDiagnosticContext.
194 void *getDiagnosticContext() const;
195
196 /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
197 /// setDiagnosticHandler.
199
200 /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
201 /// to caller.
202 std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
203
204 /// Return if a code hotness metric should be included in optimization
205 /// diagnostics.
207 /// Set if a code hotness metric should be included in optimization
208 /// diagnostics.
209 void setDiagnosticsHotnessRequested(bool Requested);
210
211 bool getMisExpectWarningRequested() const;
212 void setMisExpectWarningRequested(bool Requested);
213 void setDiagnosticsMisExpectTolerance(std::optional<uint32_t> Tolerance);
215
216 /// Return the minimum hotness value a diagnostic would need in order
217 /// to be included in optimization diagnostics.
218 ///
219 /// Three possible return values:
220 /// 0 - threshold is disabled. Everything will be printed out.
221 /// positive int - threshold is set.
222 /// UINT64_MAX - threshold is not yet set, and needs to be synced from
223 /// profile summary. Note that in case of missing profile
224 /// summary, threshold will be kept at "MAX", effectively
225 /// suppresses all remarks output.
227
228 /// Set the minimum hotness value a diagnostic needs in order to be
229 /// included in optimization diagnostics.
230 void setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold);
231
232 /// Return if hotness threshold is requested from PSI.
234
235 /// The "main remark streamer" used by all the specialized remark streamers.
236 /// This streamer keeps generic remark metadata in memory throughout the life
237 /// of the LLVMContext. This metadata may be emitted in a section in object
238 /// files depending on the format requirements.
239 ///
240 /// All specialized remark streamers should convert remarks to
241 /// llvm::remarks::Remark and emit them through this streamer.
245 std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
246
247 /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
248 /// comming from IR and MIR passes.
249 ///
250 /// If it does not exist, diagnostics are not saved in a file but only emitted
251 /// via the diagnostic handler.
254 void
255 setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
256
257 /// Get the prefix that should be printed in front of a diagnostic of
258 /// the given \p Severity
259 static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
260
261 /// Report a message to the currently installed diagnostic handler.
262 ///
263 /// This function returns, in particular in the case of error reporting
264 /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
265 /// process in a self-consistent state, even though the generated code
266 /// need not be correct.
267 ///
268 /// The diagnostic message will be implicitly prefixed with a severity keyword
269 /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
270 /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
271 void diagnose(const DiagnosticInfo &DI);
272
273 /// Registers a yield callback with the given context.
274 ///
275 /// The yield callback function may be called by LLVM to transfer control back
276 /// to the client that invoked the LLVM compilation. This can be used to yield
277 /// control of the thread, or perform periodic work needed by the client.
278 /// There is no guaranteed frequency at which callbacks must occur; in fact,
279 /// the client is not guaranteed to ever receive this callback. It is at the
280 /// sole discretion of LLVM to do so and only if it can guarantee that
281 /// suspending the thread won't block any forward progress in other LLVM
282 /// contexts in the same process.
283 ///
284 /// At a suspend point, the state of the current LLVM context is intentionally
285 /// undefined. No assumptions about it can or should be made. Only LLVM
286 /// context API calls that explicitly state that they can be used during a
287 /// yield callback are allowed to be used. Any other API calls into the
288 /// context are not supported until the yield callback function returns
289 /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
290 void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
291
292 /// Calls the yield callback (if applicable).
293 ///
294 /// This transfers control of the current thread back to the client, which may
295 /// suspend the current thread. Only call this method when LLVM doesn't hold
296 /// any global mutex or cannot block the execution in another LLVM context.
297 void yield();
298
299 /// emitError - Emit an error message to the currently installed error handler
300 /// with optional location information. This function returns, so code should
301 /// be prepared to drop the erroneous construct on the floor and "not crash".
302 /// The generated code need not be correct. The error message will be
303 /// implicitly prefixed with "error: " and should not end with a ".".
304 void emitError(uint64_t LocCookie, const Twine &ErrorStr);
305 void emitError(const Instruction *I, const Twine &ErrorStr);
306 void emitError(const Twine &ErrorStr);
307
308 /// Access the object which can disable optional passes and individual
309 /// optimizations at compile time.
311
312 /// Set the object which can disable optional passes and individual
313 /// optimizations at compile time.
314 ///
315 /// The lifetime of the object must be guaranteed to extend as long as the
316 /// LLVMContext is used by compilation.
318
319 /// Set whether opaque pointers are enabled. The method may be called multiple
320 /// times, but only with the same value. Note that creating a pointer type or
321 /// otherwise querying the opaque pointer mode performs an implicit set to
322 /// the default value.
323 [[deprecated("Opaque pointers are always enabled")]]
324 void setOpaquePointers(bool Enable) const;
325
326 /// Whether typed pointers are supported. If false, all pointers are opaque.
327 [[deprecated("Always returns false")]]
328 bool supportsTypedPointers() const;
329
330private:
331 // Module needs access to the add/removeModule methods.
332 friend class Module;
333
334 /// addModule - Register a module as being instantiated in this context. If
335 /// the context is deleted, the module will be deleted as well.
336 void addModule(Module*);
337
338 /// removeModule - Unregister a module from this context.
339 void removeModule(Module *);
340};
341
342// Create wrappers for C Binding types (see CBindingWrapping.h).
344
345/* Specialized opaque context conversions.
346 */
348 return reinterpret_cast<LLVMContext**>(Tys);
349}
350
351inline LLVMContextRef *wrap(const LLVMContext **Tys) {
352 return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
353}
354
355} // end namespace llvm
356
357#endif // LLVM_IR_LLVMCONTEXT_H
always inline
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
std::string Name
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Definition: TextStub.cpp:1060
This is the base abstract class for diagnostic reporting in the backend.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void setMisExpectWarningRequested(bool Requested)
remarks::RemarkStreamer * getMainRemarkStreamer()
The "main remark streamer" used by all the specialized remark streamers.
uint32_t getOperandBundleTagID(StringRef Tag) const
getOperandBundleTagID - Maps a bundle tag to an integer ID.
void disableDebugTypeODRUniquing()
void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
Registers a yield callback with the given context.
void deleteGC(const Function &Fn)
Remove the GC for a function.
const std::string & getGC(const Function &Fn)
Return the GC for a function.
DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const
getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by setDiagnosticHandlerCal...
void setLLVMRemarkStreamer(std::unique_ptr< LLVMRemarkStreamer > RemarkStreamer)
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
static const char * getDiagnosticMessagePrefix(DiagnosticSeverity Severity)
Get the prefix that should be printed in front of a diagnostic of the given Severity.
void enableDebugTypeODRUniquing()
std::unique_ptr< DiagnosticHandler > getDiagnosticHandler()
getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr to caller.
bool getDiagnosticsHotnessRequested() const
Return if a code hotness metric should be included in optimization diagnostics.
bool getMisExpectWarningRequested() const
void yield()
Calls the yield callback (if applicable).
void setDiagnosticsHotnessThreshold(std::optional< uint64_t > Threshold)
Set the minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
void setMainRemarkStreamer(std::unique_ptr< remarks::RemarkStreamer > MainRemarkStreamer)
bool isDiagnosticsHotnessThresholdSetFromPSI() const
Return if hotness threshold is requested from PSI.
bool supportsTypedPointers() const
Whether typed pointers are supported. If false, all pointers are opaque.
void setOptPassGate(OptPassGate &)
Set the object which can disable optional passes and individual optimizations at compile time.
StringMapEntry< uint32_t > * getOrInsertBundleTag(StringRef TagName) const
getOrInsertBundleTag - Returns the Tag to use for an operand bundle of name TagName.
LLVMContext & operator=(const LLVMContext &)=delete
void setDiagnosticsHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
void setGC(const Function &Fn, std::string GCName)
Define the GC for a function.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
void(*)(LLVMContext *Context, void *OpaqueHandle) YieldCallbackTy
Defines the type of a yield callback.
Definition: LLVMContext.h:164
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
unsigned generateMachineFunctionNum(Function &)
generateMachineFunctionNum - Get a unique number for MachineFunction that associated with the given F...
void setDiagnosticsMisExpectTolerance(std::optional< uint32_t > Tolerance)
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:69
LLVMContext(const LLVMContext &)=delete
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
getOperandBundleTags - Populate client supplied SmallVector with the bundle tags registered in this L...
void setDiagnosticHandlerCallBack(DiagnosticHandler::DiagnosticHandlerTy DiagHandler, void *DiagContext=nullptr, bool RespectFilters=false)
setDiagnosticHandlerCallBack - This method sets a handler call back that is invoked when the backend ...
void setOpaquePointers(bool Enable) const
Set whether opaque pointers are enabled.
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
getMDKindNames - Populate client supplied SmallVector with the name for custom metadata IDs registere...
void * getDiagnosticContext() const
getDiagnosticContext - Return the diagnostic context set by setDiagnosticContext.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
uint64_t getDiagnosticsHotnessThreshold() const
Return the minimum hotness value a diagnostic would need in order to be included in optimization diag...
const DiagnosticHandler * getDiagHandlerPtr() const
getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by setDiagnosticHandler.
void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time.
LLVMRemarkStreamer * getLLVMRemarkStreamer()
The "LLVM remark streamer" used by LLVM to serialize remark diagnostics comming from IR and MIR passe...
void emitError(uint64_t LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
uint32_t getDiagnosticsMisExpectTolerance() const
Streamer for LLVM remarks which has logic for dealing with DiagnosticInfo objects.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
Definition: OptBisect.h:24
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition: Types.h:53
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition: LLVMContext.h:54
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:303
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:298
@ Enable
Enable colors.
This is the base class for diagnostic handling in LLVM.
void(*)(const DiagnosticInfo *DI, void *Context) DiagnosticHandlerTy