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/System/Mutex.h"
23 #include "llvm/Target/TargetMachine.h"
32 class JITEventListener;
33 class JITMemoryManager;
34 class MachineCodeInfo;
41 class ExecutionEngineState {
43 /// GlobalAddressMap - A mapping between LLVM global values and their
44 /// actualized version...
45 std::map<const GlobalValue*, void *> GlobalAddressMap;
47 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
48 /// used to convert raw addresses into the LLVM global value that is emitted
49 /// at the address. This map is not computed unless getGlobalValueAtAddress
50 /// is called at some point.
51 std::map<void *, const GlobalValue*> GlobalAddressReverseMap;
54 std::map<const GlobalValue*, void *> &
55 getGlobalAddressMap(const MutexGuard &) {
56 return GlobalAddressMap;
59 std::map<void*, const GlobalValue*> &
60 getGlobalAddressReverseMap(const MutexGuard &) {
61 return GlobalAddressReverseMap;
66 class ExecutionEngine {
68 ExecutionEngineState state;
69 bool LazyCompilationDisabled;
70 bool GVCompilationDisabled;
71 bool SymbolSearchingDisabled;
72 bool DlsymStubsEnabled;
74 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
77 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
78 /// use a smallvector to optimize for the case where there is only one module.
79 SmallVector<ModuleProvider*, 1> Modules;
81 void setTargetData(const TargetData *td) {
85 /// getMemoryforGV - Allocate memory for a global variable.
86 virtual char* getMemoryForGV(const GlobalVariable* GV);
88 // To avoid having libexecutionengine depend on the JIT and interpreter
89 // libraries, the JIT and Interpreter set these functions to ctor pointers
90 // at startup time if they are linked in.
91 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
92 std::string *ErrorStr,
93 JITMemoryManager *JMM,
94 CodeGenOpt::Level OptLevel,
96 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
97 std::string *ErrorStr);
99 /// LazyFunctionCreator - If an unknown function is needed, this function
100 /// pointer is invoked to create it. If this returns null, the JIT will abort.
101 void* (*LazyFunctionCreator)(const std::string &);
103 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
104 /// register dwarf tables with this function
105 typedef void (*EERegisterFn)(void*);
106 static EERegisterFn ExceptionTableRegister;
109 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
110 /// JITEmitter classes. It must be held while changing the internal state of
111 /// any of those classes.
112 sys::Mutex lock; // Used to make this class and subclasses thread-safe
114 //===--------------------------------------------------------------------===//
115 // ExecutionEngine Startup
116 //===--------------------------------------------------------------------===//
118 virtual ~ExecutionEngine();
120 /// create - This is the factory method for creating an execution engine which
121 /// is appropriate for the current machine. This takes ownership of the
123 static ExecutionEngine *create(ModuleProvider *MP,
124 bool ForceInterpreter = false,
125 std::string *ErrorStr = 0,
126 CodeGenOpt::Level OptLevel =
128 // Allocating globals with code breaks
129 // freeMachineCodeForFunction and is probably
130 // unsafe and bad for performance. However,
131 // we have clients who depend on this
132 // behavior, so we must support it.
133 // Eventually, when we're willing to break
134 // some backwards compatability, this flag
135 // should be flipped to false, so that by
136 // default freeMachineCodeForFunction works.
137 bool GVsWithCode = true);
139 /// create - This is the factory method for creating an execution engine which
140 /// is appropriate for the current machine. This takes ownership of the
142 static ExecutionEngine *create(Module *M);
144 /// createJIT - This is the factory method for creating a JIT for the current
145 /// machine, it does not fall back to the interpreter. This takes ownership
146 /// of the ModuleProvider and JITMemoryManager if successful.
148 /// Clients should make sure to initialize targets prior to calling this
150 static ExecutionEngine *createJIT(ModuleProvider *MP,
151 std::string *ErrorStr = 0,
152 JITMemoryManager *JMM = 0,
153 CodeGenOpt::Level OptLevel =
155 bool GVsWithCode = true);
157 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
158 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
159 /// the ExecutionEngine is destroyed, it destroys the MP as well.
160 virtual void addModuleProvider(ModuleProvider *P) {
161 Modules.push_back(P);
164 //===----------------------------------------------------------------------===//
166 const TargetData *getTargetData() const { return TD; }
169 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
170 /// Relases the Module from the ModuleProvider, materializing it in the
171 /// process, and returns the materialized Module.
172 virtual Module* removeModuleProvider(ModuleProvider *P,
173 std::string *ErrInfo = 0);
175 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
176 /// and deletes the ModuleProvider and owned Module. Avoids materializing
177 /// the underlying module.
178 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
180 /// FindFunctionNamed - Search all of the active modules to find the one that
181 /// defines FnName. This is very slow operation and shouldn't be used for
183 Function *FindFunctionNamed(const char *FnName);
185 /// runFunction - Execute the specified function with the specified arguments,
186 /// and return the result.
188 virtual GenericValue runFunction(Function *F,
189 const std::vector<GenericValue> &ArgValues) = 0;
191 /// runStaticConstructorsDestructors - This method is used to execute all of
192 /// the static constructors or destructors for a program, depending on the
193 /// value of isDtors.
194 void runStaticConstructorsDestructors(bool isDtors);
195 /// runStaticConstructorsDestructors - This method is used to execute all of
196 /// the static constructors or destructors for a module, depending on the
197 /// value of isDtors.
198 void runStaticConstructorsDestructors(Module *module, bool isDtors);
201 /// runFunctionAsMain - This is a helper function which wraps runFunction to
202 /// handle the common task of starting up main with the specified argc, argv,
203 /// and envp parameters.
204 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
205 const char * const * envp);
208 /// addGlobalMapping - Tell the execution engine that the specified global is
209 /// at the specified location. This is used internally as functions are JIT'd
210 /// and as global variables are laid out in memory. It can and should also be
211 /// used by clients of the EE that want to have an LLVM global overlay
212 /// existing data in memory. After adding a mapping for GV, you must not
213 /// destroy it until you've removed the mapping.
214 void addGlobalMapping(const GlobalValue *GV, void *Addr);
216 /// clearAllGlobalMappings - Clear all global mappings and start over again
217 /// use in dynamic compilation scenarios when you want to move globals
218 void clearAllGlobalMappings();
220 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
221 /// particular module, because it has been removed from the JIT.
222 void clearGlobalMappingsFromModule(Module *M);
224 /// updateGlobalMapping - Replace an existing mapping for GV with a new
225 /// address. This updates both maps as required. If "Addr" is null, the
226 /// entry for the global is removed from the mappings. This returns the old
227 /// value of the pointer, or null if it was not in the map.
228 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
230 /// getPointerToGlobalIfAvailable - This returns the address of the specified
231 /// global value if it is has already been codegen'd, otherwise it returns
234 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
236 /// getPointerToGlobal - This returns the address of the specified global
237 /// value. This may involve code generation if it's a function. After
238 /// getting a pointer to GV, it and all globals it transitively refers to have
239 /// been passed to addGlobalMapping. You must clear the mapping for each
240 /// referred-to global before destroying it. If a referred-to global RTG is a
241 /// function and this ExecutionEngine is a JIT compiler, calling
242 /// updateGlobalMapping(RTG, 0) will leak the function's machine code, so you
243 /// should call freeMachineCodeForFunction(RTG) instead. Note that
244 /// optimizations can move and delete non-external GlobalValues without
245 /// notifying the ExecutionEngine.
247 void *getPointerToGlobal(const GlobalValue *GV);
249 /// getPointerToFunction - The different EE's represent function bodies in
250 /// different ways. They should each implement this to say what a function
251 /// pointer should look like. See getPointerToGlobal for the requirements on
252 /// destroying F and any GlobalValues it refers to.
254 virtual void *getPointerToFunction(Function *F) = 0;
256 /// getPointerToFunctionOrStub - If the specified function has been
257 /// code-gen'd, return a pointer to the function. If not, compile it, or use
258 /// a stub to implement lazy compilation if available. See getPointerToGlobal
259 /// for the requirements on destroying F and any GlobalValues it refers to.
261 virtual void *getPointerToFunctionOrStub(Function *F) {
262 // Default implementation, just codegen the function.
263 return getPointerToFunction(F);
266 // The JIT overrides a version that actually does this.
267 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
269 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
270 /// at the specified address.
272 const GlobalValue *getGlobalValueAtAddress(void *Addr);
275 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
277 void InitializeMemory(const Constant *Init, void *Addr);
279 /// recompileAndRelinkFunction - This method is used to force a function
280 /// which has already been compiled to be compiled again, possibly
281 /// after it has been modified. Then the entry to the old copy is overwritten
282 /// with a branch to the new copy. If there was no old copy, this acts
283 /// just like VM::getPointerToFunction().
285 virtual void *recompileAndRelinkFunction(Function *F) = 0;
287 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
288 /// corresponding to the machine code emitted to execute this function, useful
289 /// for garbage-collecting generated code.
291 virtual void freeMachineCodeForFunction(Function *F) = 0;
293 /// getOrEmitGlobalVariable - Return the address of the specified global
294 /// variable, possibly emitting it to memory if needed. This is used by the
295 /// Emitter. See getPointerToGlobal for the requirements on destroying GV and
296 /// any GlobalValues it refers to.
297 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
298 return getPointerToGlobal((GlobalValue*)GV);
301 /// Registers a listener to be called back on various events within
302 /// the JIT. See JITEventListener.h for more details. Does not
303 /// take ownership of the argument. The argument may be NULL, in
304 /// which case these functions do nothing.
305 virtual void RegisterJITEventListener(JITEventListener *) {}
306 virtual void UnregisterJITEventListener(JITEventListener *) {}
308 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
309 /// is ever attempted.
310 void DisableLazyCompilation(bool Disabled = true) {
311 LazyCompilationDisabled = Disabled;
313 bool isLazyCompilationDisabled() const {
314 return LazyCompilationDisabled;
317 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
318 /// allocate space and populate a GlobalVariable that is not internal to
320 void DisableGVCompilation(bool Disabled = true) {
321 GVCompilationDisabled = Disabled;
323 bool isGVCompilationDisabled() const {
324 return GVCompilationDisabled;
327 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
328 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
329 /// resolve symbols in a custom way.
330 void DisableSymbolSearching(bool Disabled = true) {
331 SymbolSearchingDisabled = Disabled;
333 bool isSymbolSearchingDisabled() const {
334 return SymbolSearchingDisabled;
337 /// EnableDlsymStubs -
338 void EnableDlsymStubs(bool Enabled = true) {
339 DlsymStubsEnabled = Enabled;
341 bool areDlsymStubsEnabled() const {
342 return DlsymStubsEnabled;
345 /// InstallLazyFunctionCreator - If an unknown function is needed, the
346 /// specified function pointer is invoked to create it. If it returns null,
347 /// the JIT will abort.
348 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
349 LazyFunctionCreator = P;
352 /// InstallExceptionTableRegister - The JIT will use the given function
353 /// to register the exception tables it generates.
354 static void InstallExceptionTableRegister(void (*F)(void*)) {
355 ExceptionTableRegister = F;
358 /// RegisterTable - Registers the given pointer as an exception table. It uses
359 /// the ExceptionTableRegister function.
360 static void RegisterTable(void* res) {
361 if (ExceptionTableRegister)
362 ExceptionTableRegister(res);
366 explicit ExecutionEngine(ModuleProvider *P);
370 // EmitGlobalVariable - This method emits the specified global variable to the
371 // address specified in GlobalAddresses, or allocates new memory if it's not
372 // already in the map.
373 void EmitGlobalVariable(const GlobalVariable *GV);
375 GenericValue getConstantValue(const Constant *C);
376 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
380 namespace EngineKind {
381 // These are actually bitmasks that get or-ed together.
386 const static Kind Either = (Kind)(JIT | Interpreter);
389 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
390 /// stack-allocating a builder, chaining the various set* methods, and
391 /// terminating it with a .create() call.
392 class EngineBuilder {
396 EngineKind::Kind WhichEngine;
397 std::string *ErrorStr;
398 CodeGenOpt::Level OptLevel;
399 JITMemoryManager *JMM;
400 bool AllocateGVsWithCode;
402 /// InitEngine - Does the common initialization of default options.
405 WhichEngine = EngineKind::Either;
407 OptLevel = CodeGenOpt::Default;
409 AllocateGVsWithCode = false;
413 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
414 /// is successful, the created engine takes ownership of the module
416 EngineBuilder(ModuleProvider *mp) : MP(mp) {
420 /// EngineBuilder - Overloaded constructor that automatically creates an
421 /// ExistingModuleProvider for an existing module.
422 EngineBuilder(Module *m);
424 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
425 /// or whichever engine works. This option defaults to EngineKind::Either.
426 EngineBuilder &setEngineKind(EngineKind::Kind w) {
431 /// setJITMemoryManager - Sets the memory manager to use. This allows
432 /// clients to customize their memory allocation policies. If create() is
433 /// called and is successful, the created engine takes ownership of the
434 /// memory manager. This option defaults to NULL.
435 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
440 /// setErrorStr - Set the error string to write to on error. This option
441 /// defaults to NULL.
442 EngineBuilder &setErrorStr(std::string *e) {
447 /// setOptLevel - Set the optimization level for the JIT. This option
448 /// defaults to CodeGenOpt::Default.
449 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
454 /// setAllocateGVsWithCode - Sets whether global values should be allocated
455 /// into the same buffer as code. For most applications this should be set
456 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
457 /// and is probably unsafe and bad for performance. However, we have clients
458 /// who depend on this behavior, so we must support it. This option defaults
459 /// to false so that users of the new API can safely use the new memory
460 /// manager and free machine code.
461 EngineBuilder &setAllocateGVsWithCode(bool a) {
462 AllocateGVsWithCode = a;
466 ExecutionEngine *create();
470 } // End llvm namespace