1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the abstract interface that implements execution support
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_EXECUTION_ENGINE_H
16 #define LLVM_EXECUTION_ENGINE_H
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/Support/ValueHandle.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/Target/TargetMachine.h"
31 class ExecutionEngine;
35 class JITEventListener;
36 class JITMemoryManager;
37 class MachineCodeInfo;
43 class ExecutionEngineState {
45 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
46 typedef ExecutionEngineState *ExtraData;
47 static sys::Mutex *getMutex(ExecutionEngineState *EES);
48 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
49 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
53 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
59 /// GlobalAddressMap - A mapping between LLVM global values and their
60 /// actualized version...
61 GlobalAddressMapTy GlobalAddressMap;
63 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
64 /// used to convert raw addresses into the LLVM global value that is emitted
65 /// at the address. This map is not computed unless getGlobalValueAtAddress
66 /// is called at some point.
67 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
70 ExecutionEngineState(ExecutionEngine &EE);
73 getGlobalAddressMap(const MutexGuard &) {
74 return GlobalAddressMap;
77 std::map<void*, AssertingVH<const GlobalValue> > &
78 getGlobalAddressReverseMap(const MutexGuard &) {
79 return GlobalAddressReverseMap;
82 // Returns the address ToUnmap was mapped to.
83 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
87 class ExecutionEngine {
89 ExecutionEngineState EEState;
91 bool GVCompilationDisabled;
92 bool SymbolSearchingDisabled;
94 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
97 /// Modules - This is a list of Modules that we are JIT'ing from. We use a
98 /// smallvector to optimize for the case where there is only one module.
99 SmallVector<Module*, 1> Modules;
101 void setTargetData(const TargetData *td) {
105 /// getMemoryforGV - Allocate memory for a global variable.
106 virtual char* getMemoryForGV(const GlobalVariable* GV);
108 // To avoid having libexecutionengine depend on the JIT and interpreter
109 // libraries, the JIT and Interpreter set these functions to ctor pointers
110 // at startup time if they are linked in.
111 static ExecutionEngine *(*JITCtor)(Module *M,
112 std::string *ErrorStr,
113 JITMemoryManager *JMM,
114 CodeGenOpt::Level OptLevel,
116 CodeModel::Model CMM);
117 static ExecutionEngine *(*InterpCtor)(Module *M,
118 std::string *ErrorStr);
120 /// LazyFunctionCreator - If an unknown function is needed, this function
121 /// pointer is invoked to create it. If this returns null, the JIT will abort.
122 void* (*LazyFunctionCreator)(const std::string &);
124 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
125 /// register dwarf tables with this function
126 typedef void (*EERegisterFn)(void*);
127 static EERegisterFn ExceptionTableRegister;
130 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
131 /// JITEmitter classes. It must be held while changing the internal state of
132 /// any of those classes.
133 sys::Mutex lock; // Used to make this class and subclasses thread-safe
135 //===--------------------------------------------------------------------===//
136 // ExecutionEngine Startup
137 //===--------------------------------------------------------------------===//
139 virtual ~ExecutionEngine();
141 /// create - This is the factory method for creating an execution engine which
142 /// is appropriate for the current machine. This takes ownership of the
144 static ExecutionEngine *create(Module *M,
145 bool ForceInterpreter = false,
146 std::string *ErrorStr = 0,
147 CodeGenOpt::Level OptLevel =
149 // Allocating globals with code breaks
150 // freeMachineCodeForFunction and is probably
151 // unsafe and bad for performance. However,
152 // we have clients who depend on this
153 // behavior, so we must support it.
154 // Eventually, when we're willing to break
155 // some backwards compatability, this flag
156 // should be flipped to false, so that by
157 // default freeMachineCodeForFunction works.
158 bool GVsWithCode = true);
160 /// createJIT - This is the factory method for creating a JIT for the current
161 /// machine, it does not fall back to the interpreter. This takes ownership
162 /// of the Module and JITMemoryManager if successful.
164 /// Clients should make sure to initialize targets prior to calling this
166 static ExecutionEngine *createJIT(Module *M,
167 std::string *ErrorStr = 0,
168 JITMemoryManager *JMM = 0,
169 CodeGenOpt::Level OptLevel =
171 bool GVsWithCode = true,
172 CodeModel::Model CMM =
175 /// addModule - Add a Module to the list of modules that we can JIT from.
176 /// Note that this takes ownership of the Module: when the ExecutionEngine is
177 /// destroyed, it destroys the Module as well.
178 virtual void addModule(Module *M) {
179 Modules.push_back(M);
182 //===----------------------------------------------------------------------===//
184 const TargetData *getTargetData() const { return TD; }
187 /// removeModule - Remove a Module from the list of modules. Returns true if
189 virtual bool removeModule(Module *M);
191 /// FindFunctionNamed - Search all of the active modules to find the one that
192 /// defines FnName. This is very slow operation and shouldn't be used for
194 Function *FindFunctionNamed(const char *FnName);
196 /// runFunction - Execute the specified function with the specified arguments,
197 /// and return the result.
199 virtual GenericValue runFunction(Function *F,
200 const std::vector<GenericValue> &ArgValues) = 0;
202 /// runStaticConstructorsDestructors - This method is used to execute all of
203 /// the static constructors or destructors for a program, depending on the
204 /// value of isDtors.
205 void runStaticConstructorsDestructors(bool isDtors);
206 /// runStaticConstructorsDestructors - This method is used to execute all of
207 /// the static constructors or destructors for a module, depending on the
208 /// value of isDtors.
209 void runStaticConstructorsDestructors(Module *module, bool isDtors);
212 /// runFunctionAsMain - This is a helper function which wraps runFunction to
213 /// handle the common task of starting up main with the specified argc, argv,
214 /// and envp parameters.
215 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
216 const char * const * envp);
219 /// addGlobalMapping - Tell the execution engine that the specified global is
220 /// at the specified location. This is used internally as functions are JIT'd
221 /// and as global variables are laid out in memory. It can and should also be
222 /// used by clients of the EE that want to have an LLVM global overlay
223 /// existing data in memory. Mappings are automatically removed when their
224 /// GlobalValue is destroyed.
225 void addGlobalMapping(const GlobalValue *GV, void *Addr);
227 /// clearAllGlobalMappings - Clear all global mappings and start over again
228 /// use in dynamic compilation scenarios when you want to move globals
229 void clearAllGlobalMappings();
231 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
232 /// particular module, because it has been removed from the JIT.
233 void clearGlobalMappingsFromModule(Module *M);
235 /// updateGlobalMapping - Replace an existing mapping for GV with a new
236 /// address. This updates both maps as required. If "Addr" is null, the
237 /// entry for the global is removed from the mappings. This returns the old
238 /// value of the pointer, or null if it was not in the map.
239 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
241 /// getPointerToGlobalIfAvailable - This returns the address of the specified
242 /// global value if it is has already been codegen'd, otherwise it returns
245 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
247 /// getPointerToGlobal - This returns the address of the specified global
248 /// value. This may involve code generation if it's a function.
250 void *getPointerToGlobal(const GlobalValue *GV);
252 /// getPointerToFunction - The different EE's represent function bodies in
253 /// different ways. They should each implement this to say what a function
254 /// pointer should look like. When F is destroyed, the ExecutionEngine will
255 /// remove its global mapping and free any machine code. Be sure no threads
256 /// are running inside F when that happens.
258 virtual void *getPointerToFunction(Function *F) = 0;
260 /// getPointerToBasicBlock - The different EE's represent basic blocks in
261 /// different ways. Return the representation for a blockaddress of the
264 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
266 /// getPointerToFunctionOrStub - If the specified function has been
267 /// code-gen'd, return a pointer to the function. If not, compile it, or use
268 /// a stub to implement lazy compilation if available. See
269 /// getPointerToFunction for the requirements on destroying F.
271 virtual void *getPointerToFunctionOrStub(Function *F) {
272 // Default implementation, just codegen the function.
273 return getPointerToFunction(F);
276 // The JIT overrides a version that actually does this.
277 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
279 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
280 /// at the specified address.
282 const GlobalValue *getGlobalValueAtAddress(void *Addr);
285 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
287 void InitializeMemory(const Constant *Init, void *Addr);
289 /// recompileAndRelinkFunction - This method is used to force a function
290 /// which has already been compiled to be compiled again, possibly
291 /// after it has been modified. Then the entry to the old copy is overwritten
292 /// with a branch to the new copy. If there was no old copy, this acts
293 /// just like VM::getPointerToFunction().
295 virtual void *recompileAndRelinkFunction(Function *F) = 0;
297 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
298 /// corresponding to the machine code emitted to execute this function, useful
299 /// for garbage-collecting generated code.
301 virtual void freeMachineCodeForFunction(Function *F) = 0;
303 /// getOrEmitGlobalVariable - Return the address of the specified global
304 /// variable, possibly emitting it to memory if needed. This is used by the
306 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
307 return getPointerToGlobal((GlobalValue*)GV);
310 /// Registers a listener to be called back on various events within
311 /// the JIT. See JITEventListener.h for more details. Does not
312 /// take ownership of the argument. The argument may be NULL, in
313 /// which case these functions do nothing.
314 virtual void RegisterJITEventListener(JITEventListener *) {}
315 virtual void UnregisterJITEventListener(JITEventListener *) {}
317 /// DisableLazyCompilation - When lazy compilation is off (the default), the
318 /// JIT will eagerly compile every function reachable from the argument to
319 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
320 /// compile the one function and emit stubs to compile the rest when they're
321 /// first called. If lazy compilation is turned off again while some lazy
322 /// stubs are still around, and one of those stubs is called, the program will
325 /// In order to safely compile lazily in a threaded program, the user must
326 /// ensure that 1) only one thread at a time can call any particular lazy
327 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
328 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
329 /// lazy stub. See http://llvm.org/PR5184 for details.
330 void DisableLazyCompilation(bool Disabled = true) {
331 CompilingLazily = !Disabled;
333 bool isCompilingLazily() const {
334 return CompilingLazily;
336 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
337 // Remove this in LLVM 2.8.
338 bool isLazyCompilationDisabled() const {
339 return !CompilingLazily;
342 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
343 /// allocate space and populate a GlobalVariable that is not internal to
345 void DisableGVCompilation(bool Disabled = true) {
346 GVCompilationDisabled = Disabled;
348 bool isGVCompilationDisabled() const {
349 return GVCompilationDisabled;
352 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
353 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
354 /// resolve symbols in a custom way.
355 void DisableSymbolSearching(bool Disabled = true) {
356 SymbolSearchingDisabled = Disabled;
358 bool isSymbolSearchingDisabled() const {
359 return SymbolSearchingDisabled;
362 /// InstallLazyFunctionCreator - If an unknown function is needed, the
363 /// specified function pointer is invoked to create it. If it returns null,
364 /// the JIT will abort.
365 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
366 LazyFunctionCreator = P;
369 /// InstallExceptionTableRegister - The JIT will use the given function
370 /// to register the exception tables it generates.
371 static void InstallExceptionTableRegister(void (*F)(void*)) {
372 ExceptionTableRegister = F;
375 /// RegisterTable - Registers the given pointer as an exception table. It uses
376 /// the ExceptionTableRegister function.
377 static void RegisterTable(void* res) {
378 if (ExceptionTableRegister)
379 ExceptionTableRegister(res);
383 explicit ExecutionEngine(Module *M);
387 // EmitGlobalVariable - This method emits the specified global variable to the
388 // address specified in GlobalAddresses, or allocates new memory if it's not
389 // already in the map.
390 void EmitGlobalVariable(const GlobalVariable *GV);
392 GenericValue getConstantValue(const Constant *C);
393 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
397 namespace EngineKind {
398 // These are actually bitmasks that get or-ed together.
403 const static Kind Either = (Kind)(JIT | Interpreter);
406 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
407 /// stack-allocating a builder, chaining the various set* methods, and
408 /// terminating it with a .create() call.
409 class EngineBuilder {
413 EngineKind::Kind WhichEngine;
414 std::string *ErrorStr;
415 CodeGenOpt::Level OptLevel;
416 JITMemoryManager *JMM;
417 bool AllocateGVsWithCode;
418 CodeModel::Model CMModel;
420 /// InitEngine - Does the common initialization of default options.
423 WhichEngine = EngineKind::Either;
425 OptLevel = CodeGenOpt::Default;
427 AllocateGVsWithCode = false;
428 CMModel = CodeModel::Default;
432 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
433 /// is successful, the created engine takes ownership of the module.
434 EngineBuilder(Module *m) : M(m) {
438 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
439 /// or whichever engine works. This option defaults to EngineKind::Either.
440 EngineBuilder &setEngineKind(EngineKind::Kind w) {
445 /// setJITMemoryManager - Sets the memory manager to use. This allows
446 /// clients to customize their memory allocation policies. If create() is
447 /// called and is successful, the created engine takes ownership of the
448 /// memory manager. This option defaults to NULL.
449 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
454 /// setErrorStr - Set the error string to write to on error. This option
455 /// defaults to NULL.
456 EngineBuilder &setErrorStr(std::string *e) {
461 /// setOptLevel - Set the optimization level for the JIT. This option
462 /// defaults to CodeGenOpt::Default.
463 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
468 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
469 /// data is using. Defaults to target specific default "CodeModel::Default".
470 EngineBuilder &setCodeModel(CodeModel::Model M) {
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;
487 ExecutionEngine *create();
490 } // End llvm namespace