LLVMContext.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. #ifndef LLVM_IR_LLVMCONTEXT_H
  14. #define LLVM_IR_LLVMCONTEXT_H
  15. #include "llvm-c/Types.h"
  16. #include "llvm/IR/DiagnosticHandler.h"
  17. #include "llvm/Support/CBindingWrapping.h"
  18. #include <cstdint>
  19. #include <memory>
  20. #include <string>
  21. namespace llvm {
  22. class DiagnosticInfo;
  23. enum DiagnosticSeverity : char;
  24. class Function;
  25. class Instruction;
  26. class LLVMContextImpl;
  27. class Module;
  28. class OptPassGate;
  29. template <typename T> class SmallVectorImpl;
  30. template <typename T> class StringMapEntry;
  31. class SMDiagnostic;
  32. class StringRef;
  33. class Twine;
  34. class LLVMRemarkStreamer;
  35. class raw_ostream;
  36. namespace remarks {
  37. class RemarkStreamer;
  38. }
  39. namespace SyncScope {
  40. typedef uint8_t ID;
  41. /// Known synchronization scope IDs, which always have the same value. All
  42. /// synchronization scope IDs that LLVM has special knowledge of are listed
  43. /// here. Additionally, this scheme allows LLVM to efficiently check for
  44. /// specific synchronization scope ID without comparing strings.
  45. enum {
  46. /// Synchronized with respect to signal handlers executing in the same thread.
  47. SingleThread = 0,
  48. /// Synchronized with respect to all concurrently executing threads.
  49. System = 1
  50. };
  51. } // end namespace SyncScope
  52. /// This is an important class for using LLVM in a threaded context. It
  53. /// (opaquely) owns and manages the core "global" data of LLVM's core
  54. /// infrastructure, including the type and constant uniquing tables.
  55. /// LLVMContext itself provides no locking guarantees, so you should be careful
  56. /// to have one context per thread.
  57. class LLVMContext {
  58. public:
  59. LLVMContextImpl *const pImpl;
  60. LLVMContext();
  61. LLVMContext(LLVMContext &) = delete;
  62. LLVMContext &operator=(const LLVMContext &) = delete;
  63. ~LLVMContext();
  64. // Pinned metadata names, which always have the same value. This is a
  65. // compile-time performance optimization, not a correctness optimization.
  66. enum : unsigned {
  67. #define LLVM_FIXED_MD_KIND(EnumID, Name, Value) EnumID = Value,
  68. #include "llvm/IR/FixedMetadataKinds.def"
  69. #undef LLVM_FIXED_MD_KIND
  70. };
  71. /// Known operand bundle tag IDs, which always have the same value. All
  72. /// operand bundle tags that LLVM has special knowledge of are listed here.
  73. /// Additionally, this scheme allows LLVM to efficiently check for specific
  74. /// operand bundle tags without comparing strings. Keep this in sync with
  75. /// LLVMContext::LLVMContext().
  76. enum : unsigned {
  77. OB_deopt = 0, // "deopt"
  78. OB_funclet = 1, // "funclet"
  79. OB_gc_transition = 2, // "gc-transition"
  80. OB_cfguardtarget = 3, // "cfguardtarget"
  81. OB_preallocated = 4, // "preallocated"
  82. OB_gc_live = 5, // "gc-live"
  83. OB_clang_arc_attachedcall = 6, // "clang.arc.attachedcall"
  84. };
  85. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  86. /// This ID is uniqued across modules in the current LLVMContext.
  87. unsigned getMDKindID(StringRef Name) const;
  88. /// getMDKindNames - Populate client supplied SmallVector with the name for
  89. /// custom metadata IDs registered in this LLVMContext.
  90. void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
  91. /// getOperandBundleTags - Populate client supplied SmallVector with the
  92. /// bundle tags registered in this LLVMContext. The bundle tags are ordered
  93. /// by increasing bundle IDs.
  94. /// \see LLVMContext::getOperandBundleTagID
  95. void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
  96. /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
  97. /// name TagName.
  98. StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef TagName) const;
  99. /// getOperandBundleTagID - Maps a bundle tag to an integer ID. Every bundle
  100. /// tag registered with an LLVMContext has an unique ID.
  101. uint32_t getOperandBundleTagID(StringRef Tag) const;
  102. /// getOrInsertSyncScopeID - Maps synchronization scope name to
  103. /// synchronization scope ID. Every synchronization scope registered with
  104. /// LLVMContext has unique ID except pre-defined ones.
  105. SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
  106. /// getSyncScopeNames - Populates client supplied SmallVector with
  107. /// synchronization scope names registered with LLVMContext. Synchronization
  108. /// scope names are ordered by increasing synchronization scope IDs.
  109. void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
  110. /// Define the GC for a function
  111. void setGC(const Function &Fn, std::string GCName);
  112. /// Return the GC for a function
  113. const std::string &getGC(const Function &Fn);
  114. /// Remove the GC for a function
  115. void deleteGC(const Function &Fn);
  116. /// Return true if the Context runtime configuration is set to discard all
  117. /// value names. When true, only GlobalValue names will be available in the
  118. /// IR.
  119. bool shouldDiscardValueNames() const;
  120. /// Set the Context runtime configuration to discard all value name (but
  121. /// GlobalValue). Clients can use this flag to save memory and runtime,
  122. /// especially in release mode.
  123. void setDiscardValueNames(bool Discard);
  124. /// Whether there is a string map for uniquing debug info
  125. /// identifiers across the context. Off by default.
  126. bool isODRUniquingDebugTypes() const;
  127. void enableDebugTypeODRUniquing();
  128. void disableDebugTypeODRUniquing();
  129. /// Defines the type of a yield callback.
  130. /// \see LLVMContext::setYieldCallback.
  131. using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
  132. /// setDiagnosticHandlerCallBack - This method sets a handler call back
  133. /// that is invoked when the backend needs to report anything to the user.
  134. /// The first argument is a function pointer and the second is a context pointer
  135. /// that gets passed into the DiagHandler. The third argument should be set to
  136. /// true if the handler only expects enabled diagnostics.
  137. ///
  138. /// LLVMContext doesn't take ownership or interpret either of these
  139. /// pointers.
  140. void setDiagnosticHandlerCallBack(
  141. DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
  142. void *DiagContext = nullptr, bool RespectFilters = false);
  143. /// setDiagnosticHandler - This method sets unique_ptr to object of
  144. /// DiagnosticHandler to provide custom diagnostic handling. The first
  145. /// argument is unique_ptr of object of type DiagnosticHandler or a derived
  146. /// of that. The second argument should be set to true if the handler only
  147. /// expects enabled diagnostics.
  148. ///
  149. /// Ownership of this pointer is moved to LLVMContextImpl.
  150. void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
  151. bool RespectFilters = false);
  152. /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
  153. /// setDiagnosticHandlerCallBack.
  154. DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;
  155. /// getDiagnosticContext - Return the diagnostic context set by
  156. /// setDiagnosticContext.
  157. void *getDiagnosticContext() const;
  158. /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
  159. /// setDiagnosticHandler.
  160. const DiagnosticHandler *getDiagHandlerPtr() const;
  161. /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
  162. /// to caller.
  163. std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
  164. /// Return if a code hotness metric should be included in optimization
  165. /// diagnostics.
  166. bool getDiagnosticsHotnessRequested() const;
  167. /// Set if a code hotness metric should be included in optimization
  168. /// diagnostics.
  169. void setDiagnosticsHotnessRequested(bool Requested);
  170. /// Return the minimum hotness value a diagnostic would need in order
  171. /// to be included in optimization diagnostics.
  172. ///
  173. /// Three possible return values:
  174. /// 0 - threshold is disabled. Everything will be printed out.
  175. /// positive int - threshold is set.
  176. /// UINT64_MAX - threshold is not yet set, and needs to be synced from
  177. /// profile summary. Note that in case of missing profile
  178. /// summary, threshold will be kept at "MAX", effectively
  179. /// suppresses all remarks output.
  180. uint64_t getDiagnosticsHotnessThreshold() const;
  181. /// Set the minimum hotness value a diagnostic needs in order to be
  182. /// included in optimization diagnostics.
  183. void setDiagnosticsHotnessThreshold(Optional<uint64_t> Threshold);
  184. /// Return if hotness threshold is requested from PSI.
  185. bool isDiagnosticsHotnessThresholdSetFromPSI() const;
  186. /// The "main remark streamer" used by all the specialized remark streamers.
  187. /// This streamer keeps generic remark metadata in memory throughout the life
  188. /// of the LLVMContext. This metadata may be emitted in a section in object
  189. /// files depending on the format requirements.
  190. ///
  191. /// All specialized remark streamers should convert remarks to
  192. /// llvm::remarks::Remark and emit them through this streamer.
  193. remarks::RemarkStreamer *getMainRemarkStreamer();
  194. const remarks::RemarkStreamer *getMainRemarkStreamer() const;
  195. void setMainRemarkStreamer(
  196. std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
  197. /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
  198. /// comming from IR and MIR passes.
  199. ///
  200. /// If it does not exist, diagnostics are not saved in a file but only emitted
  201. /// via the diagnostic handler.
  202. LLVMRemarkStreamer *getLLVMRemarkStreamer();
  203. const LLVMRemarkStreamer *getLLVMRemarkStreamer() const;
  204. void
  205. setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
  206. /// Get the prefix that should be printed in front of a diagnostic of
  207. /// the given \p Severity
  208. static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
  209. /// Report a message to the currently installed diagnostic handler.
  210. ///
  211. /// This function returns, in particular in the case of error reporting
  212. /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
  213. /// process in a self-consistent state, even though the generated code
  214. /// need not be correct.
  215. ///
  216. /// The diagnostic message will be implicitly prefixed with a severity keyword
  217. /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
  218. /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
  219. void diagnose(const DiagnosticInfo &DI);
  220. /// Registers a yield callback with the given context.
  221. ///
  222. /// The yield callback function may be called by LLVM to transfer control back
  223. /// to the client that invoked the LLVM compilation. This can be used to yield
  224. /// control of the thread, or perform periodic work needed by the client.
  225. /// There is no guaranteed frequency at which callbacks must occur; in fact,
  226. /// the client is not guaranteed to ever receive this callback. It is at the
  227. /// sole discretion of LLVM to do so and only if it can guarantee that
  228. /// suspending the thread won't block any forward progress in other LLVM
  229. /// contexts in the same process.
  230. ///
  231. /// At a suspend point, the state of the current LLVM context is intentionally
  232. /// undefined. No assumptions about it can or should be made. Only LLVM
  233. /// context API calls that explicitly state that they can be used during a
  234. /// yield callback are allowed to be used. Any other API calls into the
  235. /// context are not supported until the yield callback function returns
  236. /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
  237. void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
  238. /// Calls the yield callback (if applicable).
  239. ///
  240. /// This transfers control of the current thread back to the client, which may
  241. /// suspend the current thread. Only call this method when LLVM doesn't hold
  242. /// any global mutex or cannot block the execution in another LLVM context.
  243. void yield();
  244. /// emitError - Emit an error message to the currently installed error handler
  245. /// with optional location information. This function returns, so code should
  246. /// be prepared to drop the erroneous construct on the floor and "not crash".
  247. /// The generated code need not be correct. The error message will be
  248. /// implicitly prefixed with "error: " and should not end with a ".".
  249. void emitError(unsigned LocCookie, const Twine &ErrorStr);
  250. void emitError(const Instruction *I, const Twine &ErrorStr);
  251. void emitError(const Twine &ErrorStr);
  252. /// Access the object which can disable optional passes and individual
  253. /// optimizations at compile time.
  254. OptPassGate &getOptPassGate() const;
  255. /// Set the object which can disable optional passes and individual
  256. /// optimizations at compile time.
  257. ///
  258. /// The lifetime of the object must be guaranteed to extend as long as the
  259. /// LLVMContext is used by compilation.
  260. void setOptPassGate(OptPassGate&);
  261. private:
  262. // Module needs access to the add/removeModule methods.
  263. friend class Module;
  264. /// addModule - Register a module as being instantiated in this context. If
  265. /// the context is deleted, the module will be deleted as well.
  266. void addModule(Module*);
  267. /// removeModule - Unregister a module from this context.
  268. void removeModule(Module*);
  269. };
  270. // Create wrappers for C Binding types (see CBindingWrapping.h).
  271. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
  272. /* Specialized opaque context conversions.
  273. */
  274. inline LLVMContext **unwrap(LLVMContextRef* Tys) {
  275. return reinterpret_cast<LLVMContext**>(Tys);
  276. }
  277. inline LLVMContextRef *wrap(const LLVMContext **Tys) {
  278. return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
  279. }
  280. } // end namespace llvm
  281. #endif // LLVM_IR_LLVMCONTEXT_H