ExecutionEngine.h revision 198090
1//===- ExecutionEngine.h - Abstract Execution Engine Interface --*- 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 defines the abstract interface that implements execution support 11// for LLVM. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_EXECUTION_ENGINE_H 16#define LLVM_EXECUTION_ENGINE_H 17 18#include <vector> 19#include <map> 20#include <string> 21#include "llvm/ADT/SmallVector.h" 22#include "llvm/Support/ValueHandle.h" 23#include "llvm/System/Mutex.h" 24#include "llvm/Target/TargetMachine.h" 25 26namespace llvm { 27 28struct GenericValue; 29class Constant; 30class ExecutionEngine; 31class Function; 32class GlobalVariable; 33class GlobalValue; 34class JITEventListener; 35class JITMemoryManager; 36class MachineCodeInfo; 37class Module; 38class ModuleProvider; 39class MutexGuard; 40class TargetData; 41class Type; 42 43class ExecutionEngineState { 44public: 45 class MapUpdatingCVH : public CallbackVH { 46 ExecutionEngineState &EES; 47 48 public: 49 MapUpdatingCVH(ExecutionEngineState &EES, const GlobalValue *GV); 50 51 operator const GlobalValue*() const { 52 return cast<GlobalValue>(getValPtr()); 53 } 54 55 virtual void deleted(); 56 virtual void allUsesReplacedWith(Value *new_value); 57 }; 58 59private: 60 ExecutionEngine &EE; 61 62 /// GlobalAddressMap - A mapping between LLVM global values and their 63 /// actualized version... 64 std::map<MapUpdatingCVH, void *> GlobalAddressMap; 65 66 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap, 67 /// used to convert raw addresses into the LLVM global value that is emitted 68 /// at the address. This map is not computed unless getGlobalValueAtAddress 69 /// is called at some point. 70 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap; 71 72public: 73 ExecutionEngineState(ExecutionEngine &EE) : EE(EE) {} 74 75 MapUpdatingCVH getVH(const GlobalValue *GV) { 76 return MapUpdatingCVH(*this, GV); 77 } 78 79 std::map<MapUpdatingCVH, void *> & 80 getGlobalAddressMap(const MutexGuard &) { 81 return GlobalAddressMap; 82 } 83 84 std::map<void*, AssertingVH<const GlobalValue> > & 85 getGlobalAddressReverseMap(const MutexGuard &) { 86 return GlobalAddressReverseMap; 87 } 88 89 // Returns the address ToUnmap was mapped to. 90 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap); 91}; 92 93 94class ExecutionEngine { 95 const TargetData *TD; 96 ExecutionEngineState EEState; 97 bool LazyCompilationDisabled; 98 bool GVCompilationDisabled; 99 bool SymbolSearchingDisabled; 100 bool DlsymStubsEnabled; 101 102 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor. 103 104protected: 105 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We 106 /// use a smallvector to optimize for the case where there is only one module. 107 SmallVector<ModuleProvider*, 1> Modules; 108 109 void setTargetData(const TargetData *td) { 110 TD = td; 111 } 112 113 /// getMemoryforGV - Allocate memory for a global variable. 114 virtual char* getMemoryForGV(const GlobalVariable* GV); 115 116 // To avoid having libexecutionengine depend on the JIT and interpreter 117 // libraries, the JIT and Interpreter set these functions to ctor pointers 118 // at startup time if they are linked in. 119 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP, 120 std::string *ErrorStr, 121 JITMemoryManager *JMM, 122 CodeGenOpt::Level OptLevel, 123 bool GVsWithCode); 124 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP, 125 std::string *ErrorStr); 126 127 /// LazyFunctionCreator - If an unknown function is needed, this function 128 /// pointer is invoked to create it. If this returns null, the JIT will abort. 129 void* (*LazyFunctionCreator)(const std::string &); 130 131 /// ExceptionTableRegister - If Exception Handling is set, the JIT will 132 /// register dwarf tables with this function 133 typedef void (*EERegisterFn)(void*); 134 static EERegisterFn ExceptionTableRegister; 135 136public: 137 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and 138 /// JITEmitter classes. It must be held while changing the internal state of 139 /// any of those classes. 140 sys::Mutex lock; // Used to make this class and subclasses thread-safe 141 142 //===--------------------------------------------------------------------===// 143 // ExecutionEngine Startup 144 //===--------------------------------------------------------------------===// 145 146 virtual ~ExecutionEngine(); 147 148 /// create - This is the factory method for creating an execution engine which 149 /// is appropriate for the current machine. This takes ownership of the 150 /// module provider. 151 static ExecutionEngine *create(ModuleProvider *MP, 152 bool ForceInterpreter = false, 153 std::string *ErrorStr = 0, 154 CodeGenOpt::Level OptLevel = 155 CodeGenOpt::Default, 156 // Allocating globals with code breaks 157 // freeMachineCodeForFunction and is probably 158 // unsafe and bad for performance. However, 159 // we have clients who depend on this 160 // behavior, so we must support it. 161 // Eventually, when we're willing to break 162 // some backwards compatability, this flag 163 // should be flipped to false, so that by 164 // default freeMachineCodeForFunction works. 165 bool GVsWithCode = true); 166 167 /// create - This is the factory method for creating an execution engine which 168 /// is appropriate for the current machine. This takes ownership of the 169 /// module. 170 static ExecutionEngine *create(Module *M); 171 172 /// createJIT - This is the factory method for creating a JIT for the current 173 /// machine, it does not fall back to the interpreter. This takes ownership 174 /// of the ModuleProvider and JITMemoryManager if successful. 175 /// 176 /// Clients should make sure to initialize targets prior to calling this 177 /// function. 178 static ExecutionEngine *createJIT(ModuleProvider *MP, 179 std::string *ErrorStr = 0, 180 JITMemoryManager *JMM = 0, 181 CodeGenOpt::Level OptLevel = 182 CodeGenOpt::Default, 183 bool GVsWithCode = true); 184 185 /// addModuleProvider - Add a ModuleProvider to the list of modules that we 186 /// can JIT from. Note that this takes ownership of the ModuleProvider: when 187 /// the ExecutionEngine is destroyed, it destroys the MP as well. 188 virtual void addModuleProvider(ModuleProvider *P) { 189 Modules.push_back(P); 190 } 191 192 //===----------------------------------------------------------------------===// 193 194 const TargetData *getTargetData() const { return TD; } 195 196 197 /// removeModuleProvider - Remove a ModuleProvider from the list of modules. 198 /// Relases the Module from the ModuleProvider, materializing it in the 199 /// process, and returns the materialized Module. 200 virtual Module* removeModuleProvider(ModuleProvider *P, 201 std::string *ErrInfo = 0); 202 203 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules, 204 /// and deletes the ModuleProvider and owned Module. Avoids materializing 205 /// the underlying module. 206 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0); 207 208 /// FindFunctionNamed - Search all of the active modules to find the one that 209 /// defines FnName. This is very slow operation and shouldn't be used for 210 /// general code. 211 Function *FindFunctionNamed(const char *FnName); 212 213 /// runFunction - Execute the specified function with the specified arguments, 214 /// and return the result. 215 /// 216 virtual GenericValue runFunction(Function *F, 217 const std::vector<GenericValue> &ArgValues) = 0; 218 219 /// runStaticConstructorsDestructors - This method is used to execute all of 220 /// the static constructors or destructors for a program, depending on the 221 /// value of isDtors. 222 void runStaticConstructorsDestructors(bool isDtors); 223 /// runStaticConstructorsDestructors - This method is used to execute all of 224 /// the static constructors or destructors for a module, depending on the 225 /// value of isDtors. 226 void runStaticConstructorsDestructors(Module *module, bool isDtors); 227 228 229 /// runFunctionAsMain - This is a helper function which wraps runFunction to 230 /// handle the common task of starting up main with the specified argc, argv, 231 /// and envp parameters. 232 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv, 233 const char * const * envp); 234 235 236 /// addGlobalMapping - Tell the execution engine that the specified global is 237 /// at the specified location. This is used internally as functions are JIT'd 238 /// and as global variables are laid out in memory. It can and should also be 239 /// used by clients of the EE that want to have an LLVM global overlay 240 /// existing data in memory. Mappings are automatically removed when their 241 /// GlobalValue is destroyed. 242 void addGlobalMapping(const GlobalValue *GV, void *Addr); 243 244 /// clearAllGlobalMappings - Clear all global mappings and start over again 245 /// use in dynamic compilation scenarios when you want to move globals 246 void clearAllGlobalMappings(); 247 248 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a 249 /// particular module, because it has been removed from the JIT. 250 void clearGlobalMappingsFromModule(Module *M); 251 252 /// updateGlobalMapping - Replace an existing mapping for GV with a new 253 /// address. This updates both maps as required. If "Addr" is null, the 254 /// entry for the global is removed from the mappings. This returns the old 255 /// value of the pointer, or null if it was not in the map. 256 void *updateGlobalMapping(const GlobalValue *GV, void *Addr); 257 258 /// getPointerToGlobalIfAvailable - This returns the address of the specified 259 /// global value if it is has already been codegen'd, otherwise it returns 260 /// null. 261 /// 262 void *getPointerToGlobalIfAvailable(const GlobalValue *GV); 263 264 /// getPointerToGlobal - This returns the address of the specified global 265 /// value. This may involve code generation if it's a function. 266 /// 267 void *getPointerToGlobal(const GlobalValue *GV); 268 269 /// getPointerToFunction - The different EE's represent function bodies in 270 /// different ways. They should each implement this to say what a function 271 /// pointer should look like. When F is destroyed, the ExecutionEngine will 272 /// remove its global mapping but will not yet free its machine code. Call 273 /// freeMachineCodeForFunction(F) explicitly to do that. Note that global 274 /// optimizations can destroy Functions without notifying the ExecutionEngine. 275 /// 276 virtual void *getPointerToFunction(Function *F) = 0; 277 278 /// getPointerToFunctionOrStub - If the specified function has been 279 /// code-gen'd, return a pointer to the function. If not, compile it, or use 280 /// a stub to implement lazy compilation if available. See 281 /// getPointerToFunction for the requirements on destroying F. 282 /// 283 virtual void *getPointerToFunctionOrStub(Function *F) { 284 // Default implementation, just codegen the function. 285 return getPointerToFunction(F); 286 } 287 288 // The JIT overrides a version that actually does this. 289 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { } 290 291 /// getGlobalValueAtAddress - Return the LLVM global value object that starts 292 /// at the specified address. 293 /// 294 const GlobalValue *getGlobalValueAtAddress(void *Addr); 295 296 297 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr, 298 const Type *Ty); 299 void InitializeMemory(const Constant *Init, void *Addr); 300 301 /// recompileAndRelinkFunction - This method is used to force a function 302 /// which has already been compiled to be compiled again, possibly 303 /// after it has been modified. Then the entry to the old copy is overwritten 304 /// with a branch to the new copy. If there was no old copy, this acts 305 /// just like VM::getPointerToFunction(). 306 /// 307 virtual void *recompileAndRelinkFunction(Function *F) = 0; 308 309 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine 310 /// corresponding to the machine code emitted to execute this function, useful 311 /// for garbage-collecting generated code. 312 /// 313 virtual void freeMachineCodeForFunction(Function *F) = 0; 314 315 /// getOrEmitGlobalVariable - Return the address of the specified global 316 /// variable, possibly emitting it to memory if needed. This is used by the 317 /// Emitter. 318 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) { 319 return getPointerToGlobal((GlobalValue*)GV); 320 } 321 322 /// Registers a listener to be called back on various events within 323 /// the JIT. See JITEventListener.h for more details. Does not 324 /// take ownership of the argument. The argument may be NULL, in 325 /// which case these functions do nothing. 326 virtual void RegisterJITEventListener(JITEventListener *) {} 327 virtual void UnregisterJITEventListener(JITEventListener *) {} 328 329 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation 330 /// is ever attempted. 331 void DisableLazyCompilation(bool Disabled = true) { 332 LazyCompilationDisabled = Disabled; 333 } 334 bool isLazyCompilationDisabled() const { 335 return LazyCompilationDisabled; 336 } 337 338 /// DisableGVCompilation - If called, the JIT will abort if it's asked to 339 /// allocate space and populate a GlobalVariable that is not internal to 340 /// the module. 341 void DisableGVCompilation(bool Disabled = true) { 342 GVCompilationDisabled = Disabled; 343 } 344 bool isGVCompilationDisabled() const { 345 return GVCompilationDisabled; 346 } 347 348 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown 349 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to 350 /// resolve symbols in a custom way. 351 void DisableSymbolSearching(bool Disabled = true) { 352 SymbolSearchingDisabled = Disabled; 353 } 354 bool isSymbolSearchingDisabled() const { 355 return SymbolSearchingDisabled; 356 } 357 358 /// EnableDlsymStubs - 359 void EnableDlsymStubs(bool Enabled = true) { 360 DlsymStubsEnabled = Enabled; 361 } 362 bool areDlsymStubsEnabled() const { 363 return DlsymStubsEnabled; 364 } 365 366 /// InstallLazyFunctionCreator - If an unknown function is needed, the 367 /// specified function pointer is invoked to create it. If it returns null, 368 /// the JIT will abort. 369 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) { 370 LazyFunctionCreator = P; 371 } 372 373 /// InstallExceptionTableRegister - The JIT will use the given function 374 /// to register the exception tables it generates. 375 static void InstallExceptionTableRegister(void (*F)(void*)) { 376 ExceptionTableRegister = F; 377 } 378 379 /// RegisterTable - Registers the given pointer as an exception table. It uses 380 /// the ExceptionTableRegister function. 381 static void RegisterTable(void* res) { 382 if (ExceptionTableRegister) 383 ExceptionTableRegister(res); 384 } 385 386protected: 387 explicit ExecutionEngine(ModuleProvider *P); 388 389 void emitGlobals(); 390 391 // EmitGlobalVariable - This method emits the specified global variable to the 392 // address specified in GlobalAddresses, or allocates new memory if it's not 393 // already in the map. 394 void EmitGlobalVariable(const GlobalVariable *GV); 395 396 GenericValue getConstantValue(const Constant *C); 397 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 398 const Type *Ty); 399}; 400 401namespace EngineKind { 402 // These are actually bitmasks that get or-ed together. 403 enum Kind { 404 JIT = 0x1, 405 Interpreter = 0x2 406 }; 407 const static Kind Either = (Kind)(JIT | Interpreter); 408} 409 410/// EngineBuilder - Builder class for ExecutionEngines. Use this by 411/// stack-allocating a builder, chaining the various set* methods, and 412/// terminating it with a .create() call. 413class EngineBuilder { 414 415 private: 416 ModuleProvider *MP; 417 EngineKind::Kind WhichEngine; 418 std::string *ErrorStr; 419 CodeGenOpt::Level OptLevel; 420 JITMemoryManager *JMM; 421 bool AllocateGVsWithCode; 422 423 /// InitEngine - Does the common initialization of default options. 424 /// 425 void InitEngine() { 426 WhichEngine = EngineKind::Either; 427 ErrorStr = NULL; 428 OptLevel = CodeGenOpt::Default; 429 JMM = NULL; 430 AllocateGVsWithCode = false; 431 } 432 433 public: 434 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and 435 /// is successful, the created engine takes ownership of the module 436 /// provider. 437 EngineBuilder(ModuleProvider *mp) : MP(mp) { 438 InitEngine(); 439 } 440 441 /// EngineBuilder - Overloaded constructor that automatically creates an 442 /// ExistingModuleProvider for an existing module. 443 EngineBuilder(Module *m); 444 445 /// setEngineKind - Controls whether the user wants the interpreter, the JIT, 446 /// or whichever engine works. This option defaults to EngineKind::Either. 447 EngineBuilder &setEngineKind(EngineKind::Kind w) { 448 WhichEngine = w; 449 return *this; 450 } 451 452 /// setJITMemoryManager - Sets the memory manager to use. This allows 453 /// clients to customize their memory allocation policies. If create() is 454 /// called and is successful, the created engine takes ownership of the 455 /// memory manager. This option defaults to NULL. 456 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) { 457 JMM = jmm; 458 return *this; 459 } 460 461 /// setErrorStr - Set the error string to write to on error. This option 462 /// defaults to NULL. 463 EngineBuilder &setErrorStr(std::string *e) { 464 ErrorStr = e; 465 return *this; 466 } 467 468 /// setOptLevel - Set the optimization level for the JIT. This option 469 /// defaults to CodeGenOpt::Default. 470 EngineBuilder &setOptLevel(CodeGenOpt::Level l) { 471 OptLevel = l; 472 return *this; 473 } 474 475 /// setAllocateGVsWithCode - Sets whether global values should be allocated 476 /// into the same buffer as code. For most applications this should be set 477 /// to false. Allocating globals with code breaks freeMachineCodeForFunction 478 /// and is probably unsafe and bad for performance. However, we have clients 479 /// who depend on this behavior, so we must support it. This option defaults 480 /// to false so that users of the new API can safely use the new memory 481 /// manager and free machine code. 482 EngineBuilder &setAllocateGVsWithCode(bool a) { 483 AllocateGVsWithCode = a; 484 return *this; 485 } 486 487 ExecutionEngine *create(); 488 489}; 490 491inline bool operator<(const ExecutionEngineState::MapUpdatingCVH& lhs, 492 const ExecutionEngineState::MapUpdatingCVH& rhs) { 493 return static_cast<const GlobalValue*>(lhs) < 494 static_cast<const GlobalValue*>(rhs); 495} 496 497} // End llvm namespace 498 499#endif 500