xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/LLVMContext.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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"
18 #include "llvm/IR/DiagnosticHandler.h"
19 #include "llvm/Support/CBindingWrapping.h"
20 #include "llvm/Support/Compiler.h"
21 #include <cstdint>
22 #include <memory>
23 #include <optional>
24 #include <string>
25 
26 namespace llvm {
27 
28 class DiagnosticInfo;
29 enum DiagnosticSeverity : char;
30 class Function;
31 class Instruction;
32 class LLVMContextImpl;
33 class Module;
34 class OptPassGate;
35 template <typename T> class SmallVectorImpl;
36 template <typename T> class StringMapEntry;
37 class StringRef;
38 class Twine;
39 class LLVMRemarkStreamer;
40 
41 namespace remarks {
42 class RemarkStreamer;
43 }
44 
45 namespace SyncScope {
46 
47 typedef 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.
53 enum {
54   /// Synchronized with respect to signal handlers executing in the same thread.
55   SingleThread = 0,
56 
57   /// Synchronized with respect to all concurrently executing threads.
58   System = 1
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.
68 class LLVMContext {
69 public:
70   LLVMContextImpl *const pImpl;
71   LLVM_ABI LLVMContext();
72   LLVMContext(const LLVMContext &) = delete;
73   LLVMContext &operator=(const LLVMContext &) = delete;
74   LLVM_ABI ~LLVMContext();
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   };
101 
102   /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
103   /// This ID is uniqued across modules in the current LLVMContext.
104   LLVM_ABI unsigned getMDKindID(StringRef Name) const;
105 
106   /// getMDKindNames - Populate client supplied SmallVector with the name for
107   /// custom metadata IDs registered in this LLVMContext.
108   LLVM_ABI void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
109 
110   /// getOperandBundleTags - Populate client supplied SmallVector with the
111   /// bundle tags registered in this LLVMContext.  The bundle tags are ordered
112   /// by increasing bundle IDs.
113   /// \see LLVMContext::getOperandBundleTagID
114   LLVM_ABI void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
115 
116   /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
117   /// name TagName.
118   LLVM_ABI StringMapEntry<uint32_t> *
119   getOrInsertBundleTag(StringRef TagName) const;
120 
121   /// getOperandBundleTagID - Maps a bundle tag to an integer ID.  Every bundle
122   /// tag registered with an LLVMContext has an unique ID.
123   LLVM_ABI uint32_t getOperandBundleTagID(StringRef Tag) const;
124 
125   /// getOrInsertSyncScopeID - Maps synchronization scope name to
126   /// synchronization scope ID.  Every synchronization scope registered with
127   /// LLVMContext has unique ID except pre-defined ones.
128   LLVM_ABI SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
129 
130   /// getSyncScopeNames - Populates client supplied SmallVector with
131   /// synchronization scope names registered with LLVMContext.  Synchronization
132   /// scope names are ordered by increasing synchronization scope IDs.
133   LLVM_ABI void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
134 
135   /// getSyncScopeName - Returns the name of a SyncScope::ID
136   /// registered with LLVMContext, if any.
137   LLVM_ABI std::optional<StringRef> getSyncScopeName(SyncScope::ID Id) const;
138 
139   /// Define the GC for a function
140   LLVM_ABI void setGC(const Function &Fn, std::string GCName);
141 
142   /// Return the GC for a function
143   LLVM_ABI const std::string &getGC(const Function &Fn);
144 
145   /// Remove the GC for a function
146   LLVM_ABI void deleteGC(const Function &Fn);
147 
148   /// Return true if the Context runtime configuration is set to discard all
149   /// value names. When true, only GlobalValue names will be available in the
150   /// IR.
151   LLVM_ABI bool shouldDiscardValueNames() const;
152 
153   /// Set the Context runtime configuration to discard all value name (but
154   /// GlobalValue). Clients can use this flag to save memory and runtime,
155   /// especially in release mode.
156   LLVM_ABI void setDiscardValueNames(bool Discard);
157 
158   /// Whether there is a string map for uniquing debug info
159   /// identifiers across the context.  Off by default.
160   LLVM_ABI bool isODRUniquingDebugTypes() const;
161   LLVM_ABI void enableDebugTypeODRUniquing();
162   LLVM_ABI void disableDebugTypeODRUniquing();
163 
164   /// generateMachineFunctionNum - Get a unique number for MachineFunction
165   /// that associated with the given Function.
166   LLVM_ABI unsigned generateMachineFunctionNum(Function &);
167 
168   /// Defines the type of a yield callback.
169   /// \see LLVMContext::setYieldCallback.
170   using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
171 
172   /// setDiagnosticHandlerCallBack - This method sets a handler call back
173   /// that is invoked when the backend needs to report anything to the user.
174   /// The first argument is a function pointer and the second is a context pointer
175   /// that gets passed into the DiagHandler.  The third argument should be set to
176   /// true if the handler only expects enabled diagnostics.
177   ///
178   /// LLVMContext doesn't take ownership or interpret either of these
179   /// pointers.
180   LLVM_ABI void setDiagnosticHandlerCallBack(
181       DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
182       void *DiagContext = nullptr, bool RespectFilters = false);
183 
184   /// setDiagnosticHandler - This method sets unique_ptr to object of
185   /// DiagnosticHandler to provide custom diagnostic handling. The first
186   /// argument is unique_ptr of object of type DiagnosticHandler or a derived
187   /// of that. The second argument should be set to true if the handler only
188   /// expects enabled diagnostics.
189   ///
190   /// Ownership of this pointer is moved to LLVMContextImpl.
191   LLVM_ABI void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
192                                      bool RespectFilters = false);
193 
194   /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
195   /// setDiagnosticHandlerCallBack.
196   LLVM_ABI DiagnosticHandler::DiagnosticHandlerTy
197   getDiagnosticHandlerCallBack() const;
198 
199   /// getDiagnosticContext - Return the diagnostic context set by
200   /// setDiagnosticContext.
201   LLVM_ABI void *getDiagnosticContext() const;
202 
203   /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
204   /// setDiagnosticHandler.
205   LLVM_ABI const DiagnosticHandler *getDiagHandlerPtr() const;
206 
207   /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
208   /// to caller.
209   LLVM_ABI std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
210 
211   /// Return if a code hotness metric should be included in optimization
212   /// diagnostics.
213   LLVM_ABI bool getDiagnosticsHotnessRequested() const;
214   /// Set if a code hotness metric should be included in optimization
215   /// diagnostics.
216   LLVM_ABI void setDiagnosticsHotnessRequested(bool Requested);
217 
218   LLVM_ABI bool getMisExpectWarningRequested() const;
219   LLVM_ABI void setMisExpectWarningRequested(bool Requested);
220   LLVM_ABI void
221   setDiagnosticsMisExpectTolerance(std::optional<uint32_t> Tolerance);
222   LLVM_ABI uint32_t getDiagnosticsMisExpectTolerance() const;
223 
224   /// Return the minimum hotness value a diagnostic would need in order
225   /// to be included in optimization diagnostics.
226   ///
227   /// Three possible return values:
228   /// 0            - threshold is disabled. Everything will be printed out.
229   /// positive int - threshold is set.
230   /// UINT64_MAX   - threshold is not yet set, and needs to be synced from
231   ///                profile summary. Note that in case of missing profile
232   ///                summary, threshold will be kept at "MAX", effectively
233   ///                suppresses all remarks output.
234   LLVM_ABI uint64_t getDiagnosticsHotnessThreshold() const;
235 
236   /// Set the minimum hotness value a diagnostic needs in order to be
237   /// included in optimization diagnostics.
238   LLVM_ABI void
239   setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold);
240 
241   /// Return if hotness threshold is requested from PSI.
242   LLVM_ABI bool isDiagnosticsHotnessThresholdSetFromPSI() const;
243 
244   /// The "main remark streamer" used by all the specialized remark streamers.
245   /// This streamer keeps generic remark metadata in memory throughout the life
246   /// of the LLVMContext. This metadata may be emitted in a section in object
247   /// files depending on the format requirements.
248   ///
249   /// All specialized remark streamers should convert remarks to
250   /// llvm::remarks::Remark and emit them through this streamer.
251   LLVM_ABI remarks::RemarkStreamer *getMainRemarkStreamer();
252   LLVM_ABI const remarks::RemarkStreamer *getMainRemarkStreamer() const;
253   LLVM_ABI void setMainRemarkStreamer(
254       std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
255 
256   /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
257   /// comming from IR and MIR passes.
258   ///
259   /// If it does not exist, diagnostics are not saved in a file but only emitted
260   /// via the diagnostic handler.
261   LLVM_ABI LLVMRemarkStreamer *getLLVMRemarkStreamer();
262   LLVM_ABI const LLVMRemarkStreamer *getLLVMRemarkStreamer() const;
263   LLVM_ABI void
264   setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
265 
266   /// Get the prefix that should be printed in front of a diagnostic of
267   ///        the given \p Severity
268   LLVM_ABI static const char *
269   getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
270 
271   /// Report a message to the currently installed diagnostic handler.
272   ///
273   /// This function returns, in particular in the case of error reporting
274   /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
275   /// process in a self-consistent state, even though the generated code
276   /// need not be correct.
277   ///
278   /// The diagnostic message will be implicitly prefixed with a severity keyword
279   /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
280   /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
281   LLVM_ABI void diagnose(const DiagnosticInfo &DI);
282 
283   /// Registers a yield callback with the given context.
284   ///
285   /// The yield callback function may be called by LLVM to transfer control back
286   /// to the client that invoked the LLVM compilation. This can be used to yield
287   /// control of the thread, or perform periodic work needed by the client.
288   /// There is no guaranteed frequency at which callbacks must occur; in fact,
289   /// the client is not guaranteed to ever receive this callback. It is at the
290   /// sole discretion of LLVM to do so and only if it can guarantee that
291   /// suspending the thread won't block any forward progress in other LLVM
292   /// contexts in the same process.
293   ///
294   /// At a suspend point, the state of the current LLVM context is intentionally
295   /// undefined. No assumptions about it can or should be made. Only LLVM
296   /// context API calls that explicitly state that they can be used during a
297   /// yield callback are allowed to be used. Any other API calls into the
298   /// context are not supported until the yield callback function returns
299   /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
300   LLVM_ABI void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
301 
302   /// Calls the yield callback (if applicable).
303   ///
304   /// This transfers control of the current thread back to the client, which may
305   /// suspend the current thread. Only call this method when LLVM doesn't hold
306   /// any global mutex or cannot block the execution in another LLVM context.
307   LLVM_ABI void yield();
308 
309   /// emitError - Emit an error message to the currently installed error handler
310   /// with optional location information.  This function returns, so code should
311   /// be prepared to drop the erroneous construct on the floor and "not crash".
312   /// The generated code need not be correct.  The error message will be
313   /// implicitly prefixed with "error: " and should not end with a ".".
314   LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr);
315   LLVM_ABI void emitError(const Twine &ErrorStr);
316 
317   /// Access the object which can disable optional passes and individual
318   /// optimizations at compile time.
319   LLVM_ABI OptPassGate &getOptPassGate() const;
320 
321   /// Set the object which can disable optional passes and individual
322   /// optimizations at compile time.
323   ///
324   /// The lifetime of the object must be guaranteed to extend as long as the
325   /// LLVMContext is used by compilation.
326   LLVM_ABI void setOptPassGate(OptPassGate &);
327 
328   /// Get or set the current "default" target CPU (target-cpu function
329   /// attribute). The intent is that compiler frontends will set this to a value
330   /// that reflects the attribute that a function would get "by default" without
331   /// any specific function attributes, and compiler passes will attach the
332   /// attribute to newly created functions that are not associated with a
333   /// particular function, such as global initializers.
334   /// Function::createWithDefaultAttr() will create functions with this
335   /// attribute. This function should only be called by passes that run at
336   /// compile time and not by the backend or LTO passes.
337   LLVM_ABI StringRef getDefaultTargetCPU();
338   LLVM_ABI void setDefaultTargetCPU(StringRef CPU);
339 
340   /// Similar to {get,set}DefaultTargetCPU() but for default target-features.
341   LLVM_ABI StringRef getDefaultTargetFeatures();
342   LLVM_ABI void setDefaultTargetFeatures(StringRef Features);
343 
344   /// Key Instructions: update the highest number atom group emitted for any
345   /// function.
346   LLVM_ABI void updateDILocationAtomGroupWaterline(uint64_t G);
347 
348   /// Key Instructions: get the next free atom group number and increment
349   /// the global tracker.
350   LLVM_ABI uint64_t incNextDILocationAtomGroup();
351 
352 private:
353   // Module needs access to the add/removeModule methods.
354   friend class Module;
355 
356   /// addModule - Register a module as being instantiated in this context.  If
357   /// the context is deleted, the module will be deleted as well.
358   void addModule(Module*);
359 
360   /// removeModule - Unregister a module from this context.
361   void removeModule(Module *);
362 };
363 
364 // Create wrappers for C Binding types (see CBindingWrapping.h).
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext,LLVMContextRef)365 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
366 
367 /* Specialized opaque context conversions.
368  */
369 inline LLVMContext **unwrap(LLVMContextRef* Tys) {
370   return reinterpret_cast<LLVMContext**>(Tys);
371 }
372 
wrap(const LLVMContext ** Tys)373 inline LLVMContextRef *wrap(const LLVMContext **Tys) {
374   return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
375 }
376 
377 } // end namespace llvm
378 
379 #endif // LLVM_IR_LLVMCONTEXT_H
380