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