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/ADT/Optional.h"
19 #include "llvm/IR/DiagnosticHandler.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include <cstdint>
22 #include <memory>
23 #include <string>
24 
25 namespace llvm {
26 
27 class Any;
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   LLVMContext();
72   LLVMContext(LLVMContext &) = delete;
73   LLVMContext &operator=(const LLVMContext &) = delete;
74   ~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   };
99 
100   /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
101   /// This ID is uniqued across modules in the current LLVMContext.
102   unsigned getMDKindID(StringRef Name) const;
103 
104   /// getMDKindNames - Populate client supplied SmallVector with the name for
105   /// custom metadata IDs registered in this LLVMContext.
106   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
107 
108   /// getOperandBundleTags - Populate client supplied SmallVector with the
109   /// bundle tags registered in this LLVMContext.  The bundle tags are ordered
110   /// by increasing bundle IDs.
111   /// \see LLVMContext::getOperandBundleTagID
112   void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
113 
114   /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
115   /// name TagName.
116   StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef TagName) const;
117 
118   /// getOperandBundleTagID - Maps a bundle tag to an integer ID.  Every bundle
119   /// tag registered with an LLVMContext has an unique ID.
120   uint32_t getOperandBundleTagID(StringRef Tag) const;
121 
122   /// getOrInsertSyncScopeID - Maps synchronization scope name to
123   /// synchronization scope ID.  Every synchronization scope registered with
124   /// LLVMContext has unique ID except pre-defined ones.
125   SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
126 
127   /// getSyncScopeNames - Populates client supplied SmallVector with
128   /// synchronization scope names registered with LLVMContext.  Synchronization
129   /// scope names are ordered by increasing synchronization scope IDs.
130   void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
131 
132   /// Define the GC for a function
133   void setGC(const Function &Fn, std::string GCName);
134 
135   /// Return the GC for a function
136   const std::string &getGC(const Function &Fn);
137 
138   /// Remove the GC for a function
139   void deleteGC(const Function &Fn);
140 
141   /// Return true if the Context runtime configuration is set to discard all
142   /// value names. When true, only GlobalValue names will be available in the
143   /// IR.
144   bool shouldDiscardValueNames() const;
145 
146   /// Set the Context runtime configuration to discard all value name (but
147   /// GlobalValue). Clients can use this flag to save memory and runtime,
148   /// especially in release mode.
149   void setDiscardValueNames(bool Discard);
150 
151   /// Whether there is a string map for uniquing debug info
152   /// identifiers across the context.  Off by default.
153   bool isODRUniquingDebugTypes() const;
154   void enableDebugTypeODRUniquing();
155   void disableDebugTypeODRUniquing();
156 
157   /// Defines the type of a yield callback.
158   /// \see LLVMContext::setYieldCallback.
159   using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
160 
161   /// setDiagnosticHandlerCallBack - This method sets a handler call back
162   /// that is invoked when the backend needs to report anything to the user.
163   /// The first argument is a function pointer and the second is a context pointer
164   /// that gets passed into the DiagHandler.  The third argument should be set to
165   /// true if the handler only expects enabled diagnostics.
166   ///
167   /// LLVMContext doesn't take ownership or interpret either of these
168   /// pointers.
169   void setDiagnosticHandlerCallBack(
170       DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
171       void *DiagContext = nullptr, bool RespectFilters = false);
172 
173   /// setDiagnosticHandler - This method sets unique_ptr to object of
174   /// DiagnosticHandler to provide custom diagnostic handling. The first
175   /// argument is unique_ptr of object of type DiagnosticHandler or a derived
176   /// of that. The second argument should be set to true if the handler only
177   /// expects enabled diagnostics.
178   ///
179   /// Ownership of this pointer is moved to LLVMContextImpl.
180   void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
181                             bool RespectFilters = false);
182 
183   /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
184   /// setDiagnosticHandlerCallBack.
185   DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;
186 
187   /// getDiagnosticContext - Return the diagnostic context set by
188   /// setDiagnosticContext.
189   void *getDiagnosticContext() const;
190 
191   /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
192   /// setDiagnosticHandler.
193   const DiagnosticHandler *getDiagHandlerPtr() const;
194 
195   /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
196   /// to caller.
197   std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
198 
199   /// Return if a code hotness metric should be included in optimization
200   /// diagnostics.
201   bool getDiagnosticsHotnessRequested() const;
202   /// Set if a code hotness metric should be included in optimization
203   /// diagnostics.
204   void setDiagnosticsHotnessRequested(bool Requested);
205 
206   bool getMisExpectWarningRequested() const;
207   void setMisExpectWarningRequested(bool Requested);
208   void setDiagnosticsMisExpectTolerance(Optional<uint64_t> Tolerance);
209   uint64_t getDiagnosticsMisExpectTolerance() const;
210 
211   /// Return the minimum hotness value a diagnostic would need in order
212   /// to be included in optimization diagnostics.
213   ///
214   /// Three possible return values:
215   /// 0            - threshold is disabled. Everything will be printed out.
216   /// positive int - threshold is set.
217   /// UINT64_MAX   - threshold is not yet set, and needs to be synced from
218   ///                profile summary. Note that in case of missing profile
219   ///                summary, threshold will be kept at "MAX", effectively
220   ///                suppresses all remarks output.
221   uint64_t getDiagnosticsHotnessThreshold() const;
222 
223   /// Set the minimum hotness value a diagnostic needs in order to be
224   /// included in optimization diagnostics.
225   void setDiagnosticsHotnessThreshold(Optional<uint64_t> Threshold);
226 
227   /// Return if hotness threshold is requested from PSI.
228   bool isDiagnosticsHotnessThresholdSetFromPSI() const;
229 
230   /// The "main remark streamer" used by all the specialized remark streamers.
231   /// This streamer keeps generic remark metadata in memory throughout the life
232   /// of the LLVMContext. This metadata may be emitted in a section in object
233   /// files depending on the format requirements.
234   ///
235   /// All specialized remark streamers should convert remarks to
236   /// llvm::remarks::Remark and emit them through this streamer.
237   remarks::RemarkStreamer *getMainRemarkStreamer();
238   const remarks::RemarkStreamer *getMainRemarkStreamer() const;
239   void setMainRemarkStreamer(
240       std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
241 
242   /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
243   /// comming from IR and MIR passes.
244   ///
245   /// If it does not exist, diagnostics are not saved in a file but only emitted
246   /// via the diagnostic handler.
247   LLVMRemarkStreamer *getLLVMRemarkStreamer();
248   const LLVMRemarkStreamer *getLLVMRemarkStreamer() const;
249   void
250   setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
251 
252   /// Get the prefix that should be printed in front of a diagnostic of
253   ///        the given \p Severity
254   static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
255 
256   /// Report a message to the currently installed diagnostic handler.
257   ///
258   /// This function returns, in particular in the case of error reporting
259   /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
260   /// process in a self-consistent state, even though the generated code
261   /// need not be correct.
262   ///
263   /// The diagnostic message will be implicitly prefixed with a severity keyword
264   /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
265   /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
266   void diagnose(const DiagnosticInfo &DI);
267 
268   /// Registers a yield callback with the given context.
269   ///
270   /// The yield callback function may be called by LLVM to transfer control back
271   /// to the client that invoked the LLVM compilation. This can be used to yield
272   /// control of the thread, or perform periodic work needed by the client.
273   /// There is no guaranteed frequency at which callbacks must occur; in fact,
274   /// the client is not guaranteed to ever receive this callback. It is at the
275   /// sole discretion of LLVM to do so and only if it can guarantee that
276   /// suspending the thread won't block any forward progress in other LLVM
277   /// contexts in the same process.
278   ///
279   /// At a suspend point, the state of the current LLVM context is intentionally
280   /// undefined. No assumptions about it can or should be made. Only LLVM
281   /// context API calls that explicitly state that they can be used during a
282   /// yield callback are allowed to be used. Any other API calls into the
283   /// context are not supported until the yield callback function returns
284   /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
285   void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
286 
287   /// Calls the yield callback (if applicable).
288   ///
289   /// This transfers control of the current thread back to the client, which may
290   /// suspend the current thread. Only call this method when LLVM doesn't hold
291   /// any global mutex or cannot block the execution in another LLVM context.
292   void yield();
293 
294   /// emitError - Emit an error message to the currently installed error handler
295   /// with optional location information.  This function returns, so code should
296   /// be prepared to drop the erroneous construct on the floor and "not crash".
297   /// The generated code need not be correct.  The error message will be
298   /// implicitly prefixed with "error: " and should not end with a ".".
299   void emitError(uint64_t LocCookie, const Twine &ErrorStr);
300   void emitError(const Instruction *I, const Twine &ErrorStr);
301   void emitError(const Twine &ErrorStr);
302 
303   /// Access the object which can disable optional passes and individual
304   /// optimizations at compile time.
305   OptPassGate &getOptPassGate() const;
306 
307   /// Set the object which can disable optional passes and individual
308   /// optimizations at compile time.
309   ///
310   /// The lifetime of the object must be guaranteed to extend as long as the
311   /// LLVMContext is used by compilation.
312   void setOptPassGate(OptPassGate&);
313 
314   /// Whether we've decided on using opaque pointers or typed pointers yet.
315   bool hasSetOpaquePointersValue() const;
316 
317   /// Set whether opaque pointers are enabled. The method may be called multiple
318   /// times, but only with the same value. Note that creating a pointer type or
319   /// otherwise querying the opaque pointer mode performs an implicit set to
320   /// the default value.
321   void setOpaquePointers(bool Enable) const;
322 
323   /// Whether typed pointers are supported. If false, all pointers are opaque.
324   bool supportsTypedPointers() const;
325 
326   /// Optionally target-spcific data can be attached to the context for lifetime
327   /// management and bypassing layering restrictions.
328   llvm::Any &getTargetData() const;
329 
330 private:
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).
343 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
344 
345 /* Specialized opaque context conversions.
346  */
347 inline LLVMContext **unwrap(LLVMContextRef* Tys) {
348   return reinterpret_cast<LLVMContext**>(Tys);
349 }
350 
351 inline 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
358