Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:07

0001 //===- llvm/LLVMContext.h - Class for managing "global" state ---*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file declares LLVMContext, a container of "global" state in LLVM, such
0010 // as the global type and constant uniquing tables.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_IR_LLVMCONTEXT_H
0015 #define LLVM_IR_LLVMCONTEXT_H
0016 
0017 #include "llvm-c/Types.h"
0018 #include "llvm/IR/DiagnosticHandler.h"
0019 #include "llvm/Support/CBindingWrapping.h"
0020 #include <cstdint>
0021 #include <memory>
0022 #include <optional>
0023 #include <string>
0024 
0025 namespace llvm {
0026 
0027 class DiagnosticInfo;
0028 enum DiagnosticSeverity : char;
0029 class Function;
0030 class Instruction;
0031 class LLVMContextImpl;
0032 class Module;
0033 class OptPassGate;
0034 template <typename T> class SmallVectorImpl;
0035 template <typename T> class StringMapEntry;
0036 class StringRef;
0037 class Twine;
0038 class LLVMRemarkStreamer;
0039 
0040 namespace remarks {
0041 class RemarkStreamer;
0042 }
0043 
0044 namespace SyncScope {
0045 
0046 typedef uint8_t ID;
0047 
0048 /// Known synchronization scope IDs, which always have the same value.  All
0049 /// synchronization scope IDs that LLVM has special knowledge of are listed
0050 /// here.  Additionally, this scheme allows LLVM to efficiently check for
0051 /// specific synchronization scope ID without comparing strings.
0052 enum {
0053   /// Synchronized with respect to signal handlers executing in the same thread.
0054   SingleThread = 0,
0055 
0056   /// Synchronized with respect to all concurrently executing threads.
0057   System = 1
0058 };
0059 
0060 } // end namespace SyncScope
0061 
0062 /// This is an important class for using LLVM in a threaded context.  It
0063 /// (opaquely) owns and manages the core "global" data of LLVM's core
0064 /// infrastructure, including the type and constant uniquing tables.
0065 /// LLVMContext itself provides no locking guarantees, so you should be careful
0066 /// to have one context per thread.
0067 class LLVMContext {
0068 public:
0069   LLVMContextImpl *const pImpl;
0070   LLVMContext();
0071   LLVMContext(const LLVMContext &) = delete;
0072   LLVMContext &operator=(const LLVMContext &) = delete;
0073   ~LLVMContext();
0074 
0075   // Pinned metadata names, which always have the same value.  This is a
0076   // compile-time performance optimization, not a correctness optimization.
0077   enum : unsigned {
0078 #define LLVM_FIXED_MD_KIND(EnumID, Name, Value) EnumID = Value,
0079 #include "llvm/IR/FixedMetadataKinds.def"
0080 #undef LLVM_FIXED_MD_KIND
0081   };
0082 
0083   /// Known operand bundle tag IDs, which always have the same value.  All
0084   /// operand bundle tags that LLVM has special knowledge of are listed here.
0085   /// Additionally, this scheme allows LLVM to efficiently check for specific
0086   /// operand bundle tags without comparing strings. Keep this in sync with
0087   /// LLVMContext::LLVMContext().
0088   enum : unsigned {
0089     OB_deopt = 0,                  // "deopt"
0090     OB_funclet = 1,                // "funclet"
0091     OB_gc_transition = 2,          // "gc-transition"
0092     OB_cfguardtarget = 3,          // "cfguardtarget"
0093     OB_preallocated = 4,           // "preallocated"
0094     OB_gc_live = 5,                // "gc-live"
0095     OB_clang_arc_attachedcall = 6, // "clang.arc.attachedcall"
0096     OB_ptrauth = 7,                // "ptrauth"
0097     OB_kcfi = 8,                   // "kcfi"
0098     OB_convergencectrl = 9,        // "convergencectrl"
0099   };
0100 
0101   /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
0102   /// This ID is uniqued across modules in the current LLVMContext.
0103   unsigned getMDKindID(StringRef Name) const;
0104 
0105   /// getMDKindNames - Populate client supplied SmallVector with the name for
0106   /// custom metadata IDs registered in this LLVMContext.
0107   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
0108 
0109   /// getOperandBundleTags - Populate client supplied SmallVector with the
0110   /// bundle tags registered in this LLVMContext.  The bundle tags are ordered
0111   /// by increasing bundle IDs.
0112   /// \see LLVMContext::getOperandBundleTagID
0113   void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
0114 
0115   /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
0116   /// name TagName.
0117   StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef TagName) const;
0118 
0119   /// getOperandBundleTagID - Maps a bundle tag to an integer ID.  Every bundle
0120   /// tag registered with an LLVMContext has an unique ID.
0121   uint32_t getOperandBundleTagID(StringRef Tag) const;
0122 
0123   /// getOrInsertSyncScopeID - Maps synchronization scope name to
0124   /// synchronization scope ID.  Every synchronization scope registered with
0125   /// LLVMContext has unique ID except pre-defined ones.
0126   SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
0127 
0128   /// getSyncScopeNames - Populates client supplied SmallVector with
0129   /// synchronization scope names registered with LLVMContext.  Synchronization
0130   /// scope names are ordered by increasing synchronization scope IDs.
0131   void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
0132 
0133   /// getSyncScopeName - Returns the name of a SyncScope::ID
0134   /// registered with LLVMContext, if any.
0135   std::optional<StringRef> getSyncScopeName(SyncScope::ID Id) const;
0136 
0137   /// Define the GC for a function
0138   void setGC(const Function &Fn, std::string GCName);
0139 
0140   /// Return the GC for a function
0141   const std::string &getGC(const Function &Fn);
0142 
0143   /// Remove the GC for a function
0144   void deleteGC(const Function &Fn);
0145 
0146   /// Return true if the Context runtime configuration is set to discard all
0147   /// value names. When true, only GlobalValue names will be available in the
0148   /// IR.
0149   bool shouldDiscardValueNames() const;
0150 
0151   /// Set the Context runtime configuration to discard all value name (but
0152   /// GlobalValue). Clients can use this flag to save memory and runtime,
0153   /// especially in release mode.
0154   void setDiscardValueNames(bool Discard);
0155 
0156   /// Whether there is a string map for uniquing debug info
0157   /// identifiers across the context.  Off by default.
0158   bool isODRUniquingDebugTypes() const;
0159   void enableDebugTypeODRUniquing();
0160   void disableDebugTypeODRUniquing();
0161 
0162   /// generateMachineFunctionNum - Get a unique number for MachineFunction
0163   /// that associated with the given Function.
0164   unsigned generateMachineFunctionNum(Function &);
0165 
0166   /// Defines the type of a yield callback.
0167   /// \see LLVMContext::setYieldCallback.
0168   using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
0169 
0170   /// setDiagnosticHandlerCallBack - This method sets a handler call back
0171   /// that is invoked when the backend needs to report anything to the user.
0172   /// The first argument is a function pointer and the second is a context pointer
0173   /// that gets passed into the DiagHandler.  The third argument should be set to
0174   /// true if the handler only expects enabled diagnostics.
0175   ///
0176   /// LLVMContext doesn't take ownership or interpret either of these
0177   /// pointers.
0178   void setDiagnosticHandlerCallBack(
0179       DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
0180       void *DiagContext = nullptr, bool RespectFilters = false);
0181 
0182   /// setDiagnosticHandler - This method sets unique_ptr to object of
0183   /// DiagnosticHandler to provide custom diagnostic handling. The first
0184   /// argument is unique_ptr of object of type DiagnosticHandler or a derived
0185   /// of that. The second argument should be set to true if the handler only
0186   /// expects enabled diagnostics.
0187   ///
0188   /// Ownership of this pointer is moved to LLVMContextImpl.
0189   void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
0190                             bool RespectFilters = false);
0191 
0192   /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
0193   /// setDiagnosticHandlerCallBack.
0194   DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;
0195 
0196   /// getDiagnosticContext - Return the diagnostic context set by
0197   /// setDiagnosticContext.
0198   void *getDiagnosticContext() const;
0199 
0200   /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
0201   /// setDiagnosticHandler.
0202   const DiagnosticHandler *getDiagHandlerPtr() const;
0203 
0204   /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
0205   /// to caller.
0206   std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
0207 
0208   /// Return if a code hotness metric should be included in optimization
0209   /// diagnostics.
0210   bool getDiagnosticsHotnessRequested() const;
0211   /// Set if a code hotness metric should be included in optimization
0212   /// diagnostics.
0213   void setDiagnosticsHotnessRequested(bool Requested);
0214 
0215   bool getMisExpectWarningRequested() const;
0216   void setMisExpectWarningRequested(bool Requested);
0217   void setDiagnosticsMisExpectTolerance(std::optional<uint32_t> Tolerance);
0218   uint32_t getDiagnosticsMisExpectTolerance() const;
0219 
0220   /// Return the minimum hotness value a diagnostic would need in order
0221   /// to be included in optimization diagnostics.
0222   ///
0223   /// Three possible return values:
0224   /// 0            - threshold is disabled. Everything will be printed out.
0225   /// positive int - threshold is set.
0226   /// UINT64_MAX   - threshold is not yet set, and needs to be synced from
0227   ///                profile summary. Note that in case of missing profile
0228   ///                summary, threshold will be kept at "MAX", effectively
0229   ///                suppresses all remarks output.
0230   uint64_t getDiagnosticsHotnessThreshold() const;
0231 
0232   /// Set the minimum hotness value a diagnostic needs in order to be
0233   /// included in optimization diagnostics.
0234   void setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold);
0235 
0236   /// Return if hotness threshold is requested from PSI.
0237   bool isDiagnosticsHotnessThresholdSetFromPSI() const;
0238 
0239   /// The "main remark streamer" used by all the specialized remark streamers.
0240   /// This streamer keeps generic remark metadata in memory throughout the life
0241   /// of the LLVMContext. This metadata may be emitted in a section in object
0242   /// files depending on the format requirements.
0243   ///
0244   /// All specialized remark streamers should convert remarks to
0245   /// llvm::remarks::Remark and emit them through this streamer.
0246   remarks::RemarkStreamer *getMainRemarkStreamer();
0247   const remarks::RemarkStreamer *getMainRemarkStreamer() const;
0248   void setMainRemarkStreamer(
0249       std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
0250 
0251   /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
0252   /// comming from IR and MIR passes.
0253   ///
0254   /// If it does not exist, diagnostics are not saved in a file but only emitted
0255   /// via the diagnostic handler.
0256   LLVMRemarkStreamer *getLLVMRemarkStreamer();
0257   const LLVMRemarkStreamer *getLLVMRemarkStreamer() const;
0258   void
0259   setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
0260 
0261   /// Get the prefix that should be printed in front of a diagnostic of
0262   ///        the given \p Severity
0263   static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
0264 
0265   /// Report a message to the currently installed diagnostic handler.
0266   ///
0267   /// This function returns, in particular in the case of error reporting
0268   /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
0269   /// process in a self-consistent state, even though the generated code
0270   /// need not be correct.
0271   ///
0272   /// The diagnostic message will be implicitly prefixed with a severity keyword
0273   /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
0274   /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
0275   void diagnose(const DiagnosticInfo &DI);
0276 
0277   /// Registers a yield callback with the given context.
0278   ///
0279   /// The yield callback function may be called by LLVM to transfer control back
0280   /// to the client that invoked the LLVM compilation. This can be used to yield
0281   /// control of the thread, or perform periodic work needed by the client.
0282   /// There is no guaranteed frequency at which callbacks must occur; in fact,
0283   /// the client is not guaranteed to ever receive this callback. It is at the
0284   /// sole discretion of LLVM to do so and only if it can guarantee that
0285   /// suspending the thread won't block any forward progress in other LLVM
0286   /// contexts in the same process.
0287   ///
0288   /// At a suspend point, the state of the current LLVM context is intentionally
0289   /// undefined. No assumptions about it can or should be made. Only LLVM
0290   /// context API calls that explicitly state that they can be used during a
0291   /// yield callback are allowed to be used. Any other API calls into the
0292   /// context are not supported until the yield callback function returns
0293   /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
0294   void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
0295 
0296   /// Calls the yield callback (if applicable).
0297   ///
0298   /// This transfers control of the current thread back to the client, which may
0299   /// suspend the current thread. Only call this method when LLVM doesn't hold
0300   /// any global mutex or cannot block the execution in another LLVM context.
0301   void yield();
0302 
0303   /// emitError - Emit an error message to the currently installed error handler
0304   /// with optional location information.  This function returns, so code should
0305   /// be prepared to drop the erroneous construct on the floor and "not crash".
0306   /// The generated code need not be correct.  The error message will be
0307   /// implicitly prefixed with "error: " and should not end with a ".".
0308   void emitError(const Instruction *I, const Twine &ErrorStr);
0309   void emitError(const Twine &ErrorStr);
0310 
0311   /// Access the object which can disable optional passes and individual
0312   /// optimizations at compile time.
0313   OptPassGate &getOptPassGate() const;
0314 
0315   /// Set the object which can disable optional passes and individual
0316   /// optimizations at compile time.
0317   ///
0318   /// The lifetime of the object must be guaranteed to extend as long as the
0319   /// LLVMContext is used by compilation.
0320   void setOptPassGate(OptPassGate&);
0321 
0322   /// Get or set the current "default" target CPU (target-cpu function
0323   /// attribute). The intent is that compiler frontends will set this to a value
0324   /// that reflects the attribute that a function would get "by default" without
0325   /// any specific function attributes, and compiler passes will attach the
0326   /// attribute to newly created functions that are not associated with a
0327   /// particular function, such as global initializers.
0328   /// Function::createWithDefaultAttr() will create functions with this
0329   /// attribute. This function should only be called by passes that run at
0330   /// compile time and not by the backend or LTO passes.
0331   StringRef getDefaultTargetCPU();
0332   void setDefaultTargetCPU(StringRef CPU);
0333 
0334   /// Similar to {get,set}DefaultTargetCPU() but for default target-features.
0335   StringRef getDefaultTargetFeatures();
0336   void setDefaultTargetFeatures(StringRef Features);
0337 
0338 private:
0339   // Module needs access to the add/removeModule methods.
0340   friend class Module;
0341 
0342   /// addModule - Register a module as being instantiated in this context.  If
0343   /// the context is deleted, the module will be deleted as well.
0344   void addModule(Module*);
0345 
0346   /// removeModule - Unregister a module from this context.
0347   void removeModule(Module *);
0348 };
0349 
0350 // Create wrappers for C Binding types (see CBindingWrapping.h).
0351 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
0352 
0353 /* Specialized opaque context conversions.
0354  */
0355 inline LLVMContext **unwrap(LLVMContextRef* Tys) {
0356   return reinterpret_cast<LLVMContext**>(Tys);
0357 }
0358 
0359 inline LLVMContextRef *wrap(const LLVMContext **Tys) {
0360   return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
0361 }
0362 
0363 } // end namespace llvm
0364 
0365 #endif // LLVM_IR_LLVMCONTEXT_H