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