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;
40 template<typename> class AssertingVH;
42 class ExecutionEngineState {
44 /// GlobalAddressMap - A mapping between LLVM global values and their
45 /// actualized version...
46 std::map<AssertingVH<const GlobalValue>, void *> GlobalAddressMap;
48 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
49 /// used to convert raw addresses into the LLVM global value that is emitted
50 /// at the address. This map is not computed unless getGlobalValueAtAddress
51 /// is called at some point.
52 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
55 std::map<AssertingVH<const GlobalValue>, void *> &
56 getGlobalAddressMap(const MutexGuard &) {
57 return GlobalAddressMap;
60 std::map<void*, AssertingVH<const GlobalValue> > &
61 getGlobalAddressReverseMap(const MutexGuard &) {
62 return GlobalAddressReverseMap;
65 // Returns the address ToUnmap was mapped to.
66 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
70 class ExecutionEngine {
72 ExecutionEngineState state;
73 bool LazyCompilationDisabled;
74 bool GVCompilationDisabled;
75 bool SymbolSearchingDisabled;
76 bool DlsymStubsEnabled;
78 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
81 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
82 /// use a smallvector to optimize for the case where there is only one module.
83 SmallVector<ModuleProvider*, 1> Modules;
85 void setTargetData(const TargetData *td) {
89 /// getMemoryforGV - Allocate memory for a global variable.
90 virtual char* getMemoryForGV(const GlobalVariable* GV);
92 // To avoid having libexecutionengine depend on the JIT and interpreter
93 // libraries, the JIT and Interpreter set these functions to ctor pointers
94 // at startup time if they are linked in.
95 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
96 std::string *ErrorStr,
97 JITMemoryManager *JMM,
98 CodeGenOpt::Level OptLevel,
100 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
101 std::string *ErrorStr);
103 /// LazyFunctionCreator - If an unknown function is needed, this function
104 /// pointer is invoked to create it. If this returns null, the JIT will abort.
105 void* (*LazyFunctionCreator)(const std::string &);
107 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
108 /// register dwarf tables with this function
109 typedef void (*EERegisterFn)(void*);
110 static EERegisterFn ExceptionTableRegister;
113 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
114 /// JITEmitter classes. It must be held while changing the internal state of
115 /// any of those classes.
116 sys::Mutex lock; // Used to make this class and subclasses thread-safe
118 //===--------------------------------------------------------------------===//
119 // ExecutionEngine Startup
120 //===--------------------------------------------------------------------===//
122 virtual ~ExecutionEngine();
124 /// create - This is the factory method for creating an execution engine which
125 /// is appropriate for the current machine. This takes ownership of the
127 static ExecutionEngine *create(ModuleProvider *MP,
128 bool ForceInterpreter = false,
129 std::string *ErrorStr = 0,
130 CodeGenOpt::Level OptLevel =
132 // Allocating globals with code breaks
133 // freeMachineCodeForFunction and is probably
134 // unsafe and bad for performance. However,
135 // we have clients who depend on this
136 // behavior, so we must support it.
137 // Eventually, when we're willing to break
138 // some backwards compatability, this flag
139 // should be flipped to false, so that by
140 // default freeMachineCodeForFunction works.
141 bool GVsWithCode = true);
143 /// create - This is the factory method for creating an execution engine which
144 /// is appropriate for the current machine. This takes ownership of the
146 static ExecutionEngine *create(Module *M);
148 /// createJIT - This is the factory method for creating a JIT for the current
149 /// machine, it does not fall back to the interpreter. This takes ownership
150 /// of the ModuleProvider and JITMemoryManager if successful.
152 /// Clients should make sure to initialize targets prior to calling this
154 static ExecutionEngine *createJIT(ModuleProvider *MP,
155 std::string *ErrorStr = 0,
156 JITMemoryManager *JMM = 0,
157 CodeGenOpt::Level OptLevel =
159 bool GVsWithCode = true);
161 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
162 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
163 /// the ExecutionEngine is destroyed, it destroys the MP as well.
164 virtual void addModuleProvider(ModuleProvider *P) {
165 Modules.push_back(P);
168 //===----------------------------------------------------------------------===//
170 const TargetData *getTargetData() const { return TD; }
173 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
174 /// Relases the Module from the ModuleProvider, materializing it in the
175 /// process, and returns the materialized Module.
176 virtual Module* removeModuleProvider(ModuleProvider *P,
177 std::string *ErrInfo = 0);
179 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
180 /// and deletes the ModuleProvider and owned Module. Avoids materializing
181 /// the underlying module.
182 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
184 /// FindFunctionNamed - Search all of the active modules to find the one that
185 /// defines FnName. This is very slow operation and shouldn't be used for
187 Function *FindFunctionNamed(const char *FnName);
189 /// runFunction - Execute the specified function with the specified arguments,
190 /// and return the result.
192 virtual GenericValue runFunction(Function *F,
193 const std::vector<GenericValue> &ArgValues) = 0;
195 /// runStaticConstructorsDestructors - This method is used to execute all of
196 /// the static constructors or destructors for a program, depending on the
197 /// value of isDtors.
198 void runStaticConstructorsDestructors(bool isDtors);
199 /// runStaticConstructorsDestructors - This method is used to execute all of
200 /// the static constructors or destructors for a module, depending on the
201 /// value of isDtors.
202 void runStaticConstructorsDestructors(Module *module, bool isDtors);
205 /// runFunctionAsMain - This is a helper function which wraps runFunction to
206 /// handle the common task of starting up main with the specified argc, argv,
207 /// and envp parameters.
208 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
209 const char * const * envp);
212 /// addGlobalMapping - Tell the execution engine that the specified global is
213 /// at the specified location. This is used internally as functions are JIT'd
214 /// and as global variables are laid out in memory. It can and should also be
215 /// used by clients of the EE that want to have an LLVM global overlay
216 /// existing data in memory. After adding a mapping for GV, you must not
217 /// destroy it until you've removed the mapping.
218 void addGlobalMapping(const GlobalValue *GV, void *Addr);
220 /// clearAllGlobalMappings - Clear all global mappings and start over again
221 /// use in dynamic compilation scenarios when you want to move globals
222 void clearAllGlobalMappings();
224 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
225 /// particular module, because it has been removed from the JIT.
226 void clearGlobalMappingsFromModule(Module *M);
228 /// updateGlobalMapping - Replace an existing mapping for GV with a new
229 /// address. This updates both maps as required. If "Addr" is null, the
230 /// entry for the global is removed from the mappings. This returns the old
231 /// value of the pointer, or null if it was not in the map.
232 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
234 /// getPointerToGlobalIfAvailable - This returns the address of the specified
235 /// global value if it is has already been codegen'd, otherwise it returns
238 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
240 /// getPointerToGlobal - This returns the address of the specified global
241 /// value. This may involve code generation if it's a function. After
242 /// getting a pointer to GV, it and all globals it transitively refers to have
243 /// been passed to addGlobalMapping. You must clear the mapping for each
244 /// referred-to global before destroying it. If a referred-to global RTG is a
245 /// function and this ExecutionEngine is a JIT compiler, calling
246 /// updateGlobalMapping(RTG, 0) will leak the function's machine code, so you
247 /// should call freeMachineCodeForFunction(RTG) instead. Note that
248 /// optimizations can move and delete non-external GlobalValues without
249 /// notifying the ExecutionEngine.
251 void *getPointerToGlobal(const GlobalValue *GV);
253 /// getPointerToFunction - The different EE's represent function bodies in
254 /// different ways. They should each implement this to say what a function
255 /// pointer should look like. See getPointerToGlobal for the requirements on
256 /// destroying F and any GlobalValues it refers to.
258 virtual void *getPointerToFunction(Function *F) = 0;
260 /// getPointerToFunctionOrStub - If the specified function has been
261 /// code-gen'd, return a pointer to the function. If not, compile it, or use
262 /// a stub to implement lazy compilation if available. See getPointerToGlobal
263 /// for the requirements on destroying F and any GlobalValues it refers to.
265 virtual void *getPointerToFunctionOrStub(Function *F) {
266 // Default implementation, just codegen the function.
267 return getPointerToFunction(F);
270 // The JIT overrides a version that actually does this.
271 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
273 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
274 /// at the specified address.
276 const GlobalValue *getGlobalValueAtAddress(void *Addr);
279 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
281 void InitializeMemory(const Constant *Init, void *Addr);
283 /// recompileAndRelinkFunction - This method is used to force a function
284 /// which has already been compiled to be compiled again, possibly
285 /// after it has been modified. Then the entry to the old copy is overwritten
286 /// with a branch to the new copy. If there was no old copy, this acts
287 /// just like VM::getPointerToFunction().
289 virtual void *recompileAndRelinkFunction(Function *F) = 0;
291 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
292 /// corresponding to the machine code emitted to execute this function, useful
293 /// for garbage-collecting generated code.
295 virtual void freeMachineCodeForFunction(Function *F) = 0;
297 /// getOrEmitGlobalVariable - Return the address of the specified global
298 /// variable, possibly emitting it to memory if needed. This is used by the
299 /// Emitter. See getPointerToGlobal for the requirements on destroying GV and
300 /// any GlobalValues it refers to.
301 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
302 return getPointerToGlobal((GlobalValue*)GV);
305 /// Registers a listener to be called back on various events within
306 /// the JIT. See JITEventListener.h for more details. Does not
307 /// take ownership of the argument. The argument may be NULL, in
308 /// which case these functions do nothing.
309 virtual void RegisterJITEventListener(JITEventListener *) {}
310 virtual void UnregisterJITEventListener(JITEventListener *) {}
312 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
313 /// is ever attempted.
314 void DisableLazyCompilation(bool Disabled = true) {
315 LazyCompilationDisabled = Disabled;
317 bool isLazyCompilationDisabled() const {
318 return LazyCompilationDisabled;
321 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
322 /// allocate space and populate a GlobalVariable that is not internal to
324 void DisableGVCompilation(bool Disabled = true) {
325 GVCompilationDisabled = Disabled;
327 bool isGVCompilationDisabled() const {
328 return GVCompilationDisabled;
331 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
332 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
333 /// resolve symbols in a custom way.
334 void DisableSymbolSearching(bool Disabled = true) {
335 SymbolSearchingDisabled = Disabled;
337 bool isSymbolSearchingDisabled() const {
338 return SymbolSearchingDisabled;
341 /// EnableDlsymStubs -
342 void EnableDlsymStubs(bool Enabled = true) {
343 DlsymStubsEnabled = Enabled;
345 bool areDlsymStubsEnabled() const {
346 return DlsymStubsEnabled;
349 /// InstallLazyFunctionCreator - If an unknown function is needed, the
350 /// specified function pointer is invoked to create it. If it returns null,
351 /// the JIT will abort.
352 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
353 LazyFunctionCreator = P;
356 /// InstallExceptionTableRegister - The JIT will use the given function
357 /// to register the exception tables it generates.
358 static void InstallExceptionTableRegister(void (*F)(void*)) {
359 ExceptionTableRegister = F;
362 /// RegisterTable - Registers the given pointer as an exception table. It uses
363 /// the ExceptionTableRegister function.
364 static void RegisterTable(void* res) {
365 if (ExceptionTableRegister)
366 ExceptionTableRegister(res);
370 explicit ExecutionEngine(ModuleProvider *P);
374 // EmitGlobalVariable - This method emits the specified global variable to the
375 // address specified in GlobalAddresses, or allocates new memory if it's not
376 // already in the map.
377 void EmitGlobalVariable(const GlobalVariable *GV);
379 GenericValue getConstantValue(const Constant *C);
380 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
384 namespace EngineKind {
385 // These are actually bitmasks that get or-ed together.
390 const static Kind Either = (Kind)(JIT | Interpreter);
393 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
394 /// stack-allocating a builder, chaining the various set* methods, and
395 /// terminating it with a .create() call.
396 class EngineBuilder {
400 EngineKind::Kind WhichEngine;
401 std::string *ErrorStr;
402 CodeGenOpt::Level OptLevel;
403 JITMemoryManager *JMM;
404 bool AllocateGVsWithCode;
406 /// InitEngine - Does the common initialization of default options.
409 WhichEngine = EngineKind::Either;
411 OptLevel = CodeGenOpt::Default;
413 AllocateGVsWithCode = false;
417 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
418 /// is successful, the created engine takes ownership of the module
420 EngineBuilder(ModuleProvider *mp) : MP(mp) {
424 /// EngineBuilder - Overloaded constructor that automatically creates an
425 /// ExistingModuleProvider for an existing module.
426 EngineBuilder(Module *m);
428 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
429 /// or whichever engine works. This option defaults to EngineKind::Either.
430 EngineBuilder &setEngineKind(EngineKind::Kind w) {
435 /// setJITMemoryManager - Sets the memory manager to use. This allows
436 /// clients to customize their memory allocation policies. If create() is
437 /// called and is successful, the created engine takes ownership of the
438 /// memory manager. This option defaults to NULL.
439 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
444 /// setErrorStr - Set the error string to write to on error. This option
445 /// defaults to NULL.
446 EngineBuilder &setErrorStr(std::string *e) {
451 /// setOptLevel - Set the optimization level for the JIT. This option
452 /// defaults to CodeGenOpt::Default.
453 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
458 /// setAllocateGVsWithCode - Sets whether global values should be allocated
459 /// into the same buffer as code. For most applications this should be set
460 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
461 /// and is probably unsafe and bad for performance. However, we have clients
462 /// who depend on this behavior, so we must support it. This option defaults
463 /// to false so that users of the new API can safely use the new memory
464 /// manager and free machine code.
465 EngineBuilder &setAllocateGVsWithCode(bool a) {
466 AllocateGVsWithCode = a;
470 ExecutionEngine *create();
474 } // End llvm namespace