1//===- llvm/LLVMContext.h - Class for managing "global" state ---*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file declares LLVMContext, a container of "global" state in LLVM, such 11// as the global type and constant uniquing tables. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_IR_LLVMCONTEXT_H 16#define LLVM_IR_LLVMCONTEXT_H 17 18#include "llvm-c/Types.h" 19#include "llvm/IR/DiagnosticHandler.h" 20#include "llvm/Support/CBindingWrapping.h" 21#include "llvm/Support/Options.h" 22#include <cstdint> 23#include <memory> 24#include <string> 25 26namespace llvm { 27 28class DiagnosticInfo; 29enum DiagnosticSeverity : char; 30class Function; 31class Instruction; 32class LLVMContextImpl; 33class Module; 34class OptBisect; 35template <typename T> class SmallVectorImpl; 36class SMDiagnostic; 37class StringRef; 38class Twine; 39 40namespace yaml { 41 42class Output; 43 44} // end namespace yaml 45 46namespace SyncScope { 47 48typedef uint8_t ID; 49 50/// Known synchronization scope IDs, which always have the same value. All 51/// synchronization scope IDs that LLVM has special knowledge of are listed 52/// here. Additionally, this scheme allows LLVM to efficiently check for 53/// specific synchronization scope ID without comparing strings. 54enum { 55 /// Synchronized with respect to signal handlers executing in the same thread. 56 SingleThread = 0, 57 58 /// Synchronized with respect to all concurrently executing threads. 59 System = 1 60}; 61 62} // end namespace SyncScope 63 64/// This is an important class for using LLVM in a threaded context. It 65/// (opaquely) owns and manages the core "global" data of LLVM's core 66/// infrastructure, including the type and constant uniquing tables. 67/// LLVMContext itself provides no locking guarantees, so you should be careful 68/// to have one context per thread. 69class LLVMContext { 70public: 71 LLVMContextImpl *const pImpl; 72 LLVMContext(); 73 LLVMContext(LLVMContext &) = delete; 74 LLVMContext &operator=(const LLVMContext &) = delete; 75 ~LLVMContext(); 76 77 // Pinned metadata names, which always have the same value. This is a 78 // compile-time performance optimization, not a correctness optimization. 79 enum { 80 MD_dbg = 0, // "dbg" 81 MD_tbaa = 1, // "tbaa" 82 MD_prof = 2, // "prof" 83 MD_fpmath = 3, // "fpmath" 84 MD_range = 4, // "range" 85 MD_tbaa_struct = 5, // "tbaa.struct" 86 MD_invariant_load = 6, // "invariant.load" 87 MD_alias_scope = 7, // "alias.scope" 88 MD_noalias = 8, // "noalias", 89 MD_nontemporal = 9, // "nontemporal" 90 MD_mem_parallel_loop_access = 10, // "llvm.mem.parallel_loop_access" 91 MD_nonnull = 11, // "nonnull" 92 MD_dereferenceable = 12, // "dereferenceable" 93 MD_dereferenceable_or_null = 13, // "dereferenceable_or_null" 94 MD_make_implicit = 14, // "make.implicit" 95 MD_unpredictable = 15, // "unpredictable" 96 MD_invariant_group = 16, // "invariant.group" 97 MD_align = 17, // "align" 98 MD_loop = 18, // "llvm.loop" 99 MD_type = 19, // "type" 100 MD_section_prefix = 20, // "section_prefix" 101 MD_absolute_symbol = 21, // "absolute_symbol" 102 MD_associated = 22, // "associated" 103 MD_callees = 23, // "callees" 104 }; 105 106 /// Known operand bundle tag IDs, which always have the same value. All 107 /// operand bundle tags that LLVM has special knowledge of are listed here. 108 /// Additionally, this scheme allows LLVM to efficiently check for specific 109 /// operand bundle tags without comparing strings. 110 enum { 111 OB_deopt = 0, // "deopt" 112 OB_funclet = 1, // "funclet" 113 OB_gc_transition = 2, // "gc-transition" 114 }; 115 116 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 117 /// This ID is uniqued across modules in the current LLVMContext. 118 unsigned getMDKindID(StringRef Name) const; 119 120 /// getMDKindNames - Populate client supplied SmallVector with the name for 121 /// custom metadata IDs registered in this LLVMContext. 122 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const; 123 124 /// getOperandBundleTags - Populate client supplied SmallVector with the 125 /// bundle tags registered in this LLVMContext. The bundle tags are ordered 126 /// by increasing bundle IDs. 127 /// \see LLVMContext::getOperandBundleTagID 128 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const; 129 130 /// getOperandBundleTagID - Maps a bundle tag to an integer ID. Every bundle 131 /// tag registered with an LLVMContext has an unique ID. 132 uint32_t getOperandBundleTagID(StringRef Tag) const; 133 134 /// getOrInsertSyncScopeID - Maps synchronization scope name to 135 /// synchronization scope ID. Every synchronization scope registered with 136 /// LLVMContext has unique ID except pre-defined ones. 137 SyncScope::ID getOrInsertSyncScopeID(StringRef SSN); 138 139 /// getSyncScopeNames - Populates client supplied SmallVector with 140 /// synchronization scope names registered with LLVMContext. Synchronization 141 /// scope names are ordered by increasing synchronization scope IDs. 142 void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const; 143 144 /// Define the GC for a function 145 void setGC(const Function &Fn, std::string GCName); 146 147 /// Return the GC for a function 148 const std::string &getGC(const Function &Fn); 149 150 /// Remove the GC for a function 151 void deleteGC(const Function &Fn); 152 153 /// Return true if the Context runtime configuration is set to discard all 154 /// value names. When true, only GlobalValue names will be available in the 155 /// IR. 156 bool shouldDiscardValueNames() const; 157 158 /// Set the Context runtime configuration to discard all value name (but 159 /// GlobalValue). Clients can use this flag to save memory and runtime, 160 /// especially in release mode. 161 void setDiscardValueNames(bool Discard); 162 163 /// Whether there is a string map for uniquing debug info 164 /// identifiers across the context. Off by default. 165 bool isODRUniquingDebugTypes() const; 166 void enableDebugTypeODRUniquing(); 167 void disableDebugTypeODRUniquing(); 168 169 using InlineAsmDiagHandlerTy = void (*)(const SMDiagnostic&, void *Context, 170 unsigned LocCookie); 171 172 /// Defines the type of a yield callback. 173 /// \see LLVMContext::setYieldCallback. 174 using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle); 175 176 /// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked 177 /// when problems with inline asm are detected by the backend. The first 178 /// argument is a function pointer and the second is a context pointer that 179 /// gets passed into the DiagHandler. 180 /// 181 /// LLVMContext doesn't take ownership or interpret either of these 182 /// pointers. 183 void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler, 184 void *DiagContext = nullptr); 185 186 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by 187 /// setInlineAsmDiagnosticHandler. 188 InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const; 189 190 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by 191 /// setInlineAsmDiagnosticHandler. 192 void *getInlineAsmDiagnosticContext() const; 193 194 /// setDiagnosticHandlerCallBack - This method sets a handler call back 195 /// that is invoked when the backend needs to report anything to the user. 196 /// The first argument is a function pointer and the second is a context pointer 197 /// that gets passed into the DiagHandler. The third argument should be set to 198 /// true if the handler only expects enabled diagnostics. 199 /// 200 /// LLVMContext doesn't take ownership or interpret either of these 201 /// pointers. 202 void setDiagnosticHandlerCallBack( 203 DiagnosticHandler::DiagnosticHandlerTy DiagHandler, 204 void *DiagContext = nullptr, bool RespectFilters = false); 205 206 /// setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler 207 /// to provide custom diagnostic handling. The first argument is unique_ptr of object 208 /// of type DiagnosticHandler or a derived of that. The third argument should be 209 /// set to true if the handler only expects enabled diagnostics. 210 /// 211 /// Ownership of this pointer is moved to LLVMContextImpl. 212 void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH, 213 bool RespectFilters = false); 214 215 /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by 216 /// setDiagnosticHandlerCallBack. 217 DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const; 218 219 /// getDiagnosticContext - Return the diagnostic context set by 220 /// setDiagnosticContext. 221 void *getDiagnosticContext() const; 222 223 /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by 224 /// setDiagnosticHandler. 225 const DiagnosticHandler *getDiagHandlerPtr() const; 226 227 /// getDiagnosticHandler - transfers owenership of DiagnosticHandler unique_ptr 228 /// to caller. 229 std::unique_ptr<DiagnosticHandler> getDiagnosticHandler(); 230 231 /// \brief Return if a code hotness metric should be included in optimization 232 /// diagnostics. 233 bool getDiagnosticsHotnessRequested() const; 234 /// \brief Set if a code hotness metric should be included in optimization 235 /// diagnostics. 236 void setDiagnosticsHotnessRequested(bool Requested); 237 238 /// \brief Return the minimum hotness value a diagnostic would need in order 239 /// to be included in optimization diagnostics. If there is no minimum, this 240 /// returns None. 241 uint64_t getDiagnosticsHotnessThreshold() const; 242 243 /// \brief Set the minimum hotness value a diagnostic needs in order to be 244 /// included in optimization diagnostics. 245 void setDiagnosticsHotnessThreshold(uint64_t Threshold); 246 247 /// \brief Return the YAML file used by the backend to save optimization 248 /// diagnostics. If null, diagnostics are not saved in a file but only 249 /// emitted via the diagnostic handler. 250 yaml::Output *getDiagnosticsOutputFile(); 251 /// Set the diagnostics output file used for optimization diagnostics. 252 /// 253 /// By default or if invoked with null, diagnostics are not saved in a file 254 /// but only emitted via the diagnostic handler. Even if an output file is 255 /// set, the handler is invoked for each diagnostic message. 256 void setDiagnosticsOutputFile(std::unique_ptr<yaml::Output> F); 257 258 /// \brief Get the prefix that should be printed in front of a diagnostic of 259 /// the given \p Severity 260 static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity); 261 262 /// \brief Report a message to the currently installed diagnostic handler. 263 /// 264 /// This function returns, in particular in the case of error reporting 265 /// (DI.Severity == \a DS_Error), so the caller should leave the compilation 266 /// process in a self-consistent state, even though the generated code 267 /// need not be correct. 268 /// 269 /// The diagnostic message will be implicitly prefixed with a severity keyword 270 /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error, 271 /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note. 272 void diagnose(const DiagnosticInfo &DI); 273 274 /// \brief Registers a yield callback with the given context. 275 /// 276 /// The yield callback function may be called by LLVM to transfer control back 277 /// to the client that invoked the LLVM compilation. This can be used to yield 278 /// control of the thread, or perform periodic work needed by the client. 279 /// There is no guaranteed frequency at which callbacks must occur; in fact, 280 /// the client is not guaranteed to ever receive this callback. It is at the 281 /// sole discretion of LLVM to do so and only if it can guarantee that 282 /// suspending the thread won't block any forward progress in other LLVM 283 /// contexts in the same process. 284 /// 285 /// At a suspend point, the state of the current LLVM context is intentionally 286 /// undefined. No assumptions about it can or should be made. Only LLVM 287 /// context API calls that explicitly state that they can be used during a 288 /// yield callback are allowed to be used. Any other API calls into the 289 /// context are not supported until the yield callback function returns 290 /// control to LLVM. Other LLVM contexts are unaffected by this restriction. 291 void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle); 292 293 /// \brief Calls the yield callback (if applicable). 294 /// 295 /// This transfers control of the current thread back to the client, which may 296 /// suspend the current thread. Only call this method when LLVM doesn't hold 297 /// any global mutex or cannot block the execution in another LLVM context. 298 void yield(); 299 300 /// emitError - Emit an error message to the currently installed error handler 301 /// with optional location information. This function returns, so code should 302 /// be prepared to drop the erroneous construct on the floor and "not crash". 303 /// The generated code need not be correct. The error message will be 304 /// implicitly prefixed with "error: " and should not end with a ".". 305 void emitError(unsigned LocCookie, const Twine &ErrorStr); 306 void emitError(const Instruction *I, const Twine &ErrorStr); 307 void emitError(const Twine &ErrorStr); 308 309 /// \brief Query for a debug option's value. 310 /// 311 /// This function returns typed data populated from command line parsing. 312 template <typename ValT, typename Base, ValT(Base::*Mem)> 313 ValT getOption() const { 314 return OptionRegistry::instance().template get<ValT, Base, Mem>(); 315 } 316 317 /// \brief Access the object which manages optimization bisection for failure 318 /// analysis. 319 OptBisect &getOptBisect(); 320private: 321 // Module needs access to the add/removeModule methods. 322 friend class Module; 323 324 /// addModule - Register a module as being instantiated in this context. If 325 /// the context is deleted, the module will be deleted as well. 326 void addModule(Module*); 327 328 /// removeModule - Unregister a module from this context. 329 void removeModule(Module*); 330}; 331 332// Create wrappers for C Binding types (see CBindingWrapping.h). 333DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef) 334 335/* Specialized opaque context conversions. 336 */ 337inline LLVMContext **unwrap(LLVMContextRef* Tys) { 338 return reinterpret_cast<LLVMContext**>(Tys); 339} 340 341inline LLVMContextRef *wrap(const LLVMContext **Tys) { 342 return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys)); 343} 344 345} // end namespace llvm 346 347#endif // LLVM_IR_LLVMCONTEXT_H 348