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/StringRef.h"
23 #include "llvm/ADT/ValueMap.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/System/Mutex.h"
26 #include "llvm/Target/TargetMachine.h"
32 class ExecutionEngine;
36 class JITEventListener;
37 class JITMemoryManager;
38 class MachineCodeInfo;
44 class ExecutionEngineState {
46 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
47 typedef ExecutionEngineState *ExtraData;
48 static sys::Mutex *getMutex(ExecutionEngineState *EES);
49 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
50 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
54 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
60 /// GlobalAddressMap - A mapping between LLVM global values and their
61 /// actualized version...
62 GlobalAddressMapTy GlobalAddressMap;
64 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
65 /// used to convert raw addresses into the LLVM global value that is emitted
66 /// at the address. This map is not computed unless getGlobalValueAtAddress
67 /// is called at some point.
68 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
71 ExecutionEngineState(ExecutionEngine &EE);
74 getGlobalAddressMap(const MutexGuard &) {
75 return GlobalAddressMap;
78 std::map<void*, AssertingVH<const GlobalValue> > &
79 getGlobalAddressReverseMap(const MutexGuard &) {
80 return GlobalAddressReverseMap;
83 // Returns the address ToUnmap was mapped to.
84 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
88 class ExecutionEngine {
90 ExecutionEngineState EEState;
92 bool GVCompilationDisabled;
93 bool SymbolSearchingDisabled;
95 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
98 /// Modules - This is a list of Modules that we are JIT'ing from. We use a
99 /// smallvector to optimize for the case where there is only one module.
100 SmallVector<Module*, 1> Modules;
102 void setTargetData(const TargetData *td) {
106 /// getMemoryforGV - Allocate memory for a global variable.
107 virtual char* getMemoryForGV(const GlobalVariable* GV);
109 // To avoid having libexecutionengine depend on the JIT and interpreter
110 // libraries, the JIT and Interpreter set these functions to ctor pointers
111 // at startup time if they are linked in.
112 static ExecutionEngine *(*JITCtor)(
114 std::string *ErrorStr,
115 JITMemoryManager *JMM,
116 CodeGenOpt::Level OptLevel,
118 CodeModel::Model CMM,
121 const SmallVectorImpl<std::string>& MAttrs);
122 static ExecutionEngine *(*InterpCtor)(Module *M,
123 std::string *ErrorStr);
125 /// LazyFunctionCreator - If an unknown function is needed, this function
126 /// pointer is invoked to create it. If this returns null, the JIT will abort.
127 void* (*LazyFunctionCreator)(const std::string &);
129 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
130 /// register dwarf tables with this function.
131 typedef void (*EERegisterFn)(void*);
132 EERegisterFn ExceptionTableRegister;
133 EERegisterFn ExceptionTableDeregister;
134 std::vector<void*> AllExceptionTables;
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
142 //===--------------------------------------------------------------------===//
143 // ExecutionEngine Startup
144 //===--------------------------------------------------------------------===//
146 virtual ~ExecutionEngine();
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
151 static ExecutionEngine *create(Module *M,
152 bool ForceInterpreter = false,
153 std::string *ErrorStr = 0,
154 CodeGenOpt::Level OptLevel =
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);
167 /// createJIT - This is the factory method for creating a JIT for the current
168 /// machine, it does not fall back to the interpreter. This takes ownership
169 /// of the Module and JITMemoryManager if successful.
171 /// Clients should make sure to initialize targets prior to calling this
173 static ExecutionEngine *createJIT(Module *M,
174 std::string *ErrorStr = 0,
175 JITMemoryManager *JMM = 0,
176 CodeGenOpt::Level OptLevel =
178 bool GVsWithCode = true,
179 CodeModel::Model CMM =
182 /// addModule - Add a Module to the list of modules that we can JIT from.
183 /// Note that this takes ownership of the Module: when the ExecutionEngine is
184 /// destroyed, it destroys the Module as well.
185 virtual void addModule(Module *M) {
186 Modules.push_back(M);
189 //===----------------------------------------------------------------------===//
191 const TargetData *getTargetData() const { return TD; }
194 /// removeModule - Remove a Module from the list of modules. Returns true if
196 virtual bool removeModule(Module *M);
198 /// FindFunctionNamed - Search all of the active modules to find the one that
199 /// defines FnName. This is very slow operation and shouldn't be used for
201 Function *FindFunctionNamed(const char *FnName);
203 /// runFunction - Execute the specified function with the specified arguments,
204 /// and return the result.
206 virtual GenericValue runFunction(Function *F,
207 const std::vector<GenericValue> &ArgValues) = 0;
209 /// runStaticConstructorsDestructors - This method is used to execute all of
210 /// the static constructors or destructors for a program, depending on the
211 /// value of isDtors.
212 void runStaticConstructorsDestructors(bool isDtors);
213 /// runStaticConstructorsDestructors - This method is used to execute all of
214 /// the static constructors or destructors for a module, depending on the
215 /// value of isDtors.
216 void runStaticConstructorsDestructors(Module *module, bool isDtors);
219 /// runFunctionAsMain - This is a helper function which wraps runFunction to
220 /// handle the common task of starting up main with the specified argc, argv,
221 /// and envp parameters.
222 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
223 const char * const * envp);
226 /// addGlobalMapping - Tell the execution engine that the specified global is
227 /// at the specified location. This is used internally as functions are JIT'd
228 /// and as global variables are laid out in memory. It can and should also be
229 /// used by clients of the EE that want to have an LLVM global overlay
230 /// existing data in memory. Mappings are automatically removed when their
231 /// GlobalValue is destroyed.
232 void addGlobalMapping(const GlobalValue *GV, void *Addr);
234 /// clearAllGlobalMappings - Clear all global mappings and start over again
235 /// use in dynamic compilation scenarios when you want to move globals
236 void clearAllGlobalMappings();
238 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
239 /// particular module, because it has been removed from the JIT.
240 void clearGlobalMappingsFromModule(Module *M);
242 /// updateGlobalMapping - Replace an existing mapping for GV with a new
243 /// address. This updates both maps as required. If "Addr" is null, the
244 /// entry for the global is removed from the mappings. This returns the old
245 /// value of the pointer, or null if it was not in the map.
246 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
248 /// getPointerToGlobalIfAvailable - This returns the address of the specified
249 /// global value if it is has already been codegen'd, otherwise it returns
252 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
254 /// getPointerToGlobal - This returns the address of the specified global
255 /// value. This may involve code generation if it's a function.
257 void *getPointerToGlobal(const GlobalValue *GV);
259 /// getPointerToFunction - The different EE's represent function bodies in
260 /// different ways. They should each implement this to say what a function
261 /// pointer should look like. When F is destroyed, the ExecutionEngine will
262 /// remove its global mapping and free any machine code. Be sure no threads
263 /// are running inside F when that happens.
265 virtual void *getPointerToFunction(Function *F) = 0;
267 /// getPointerToBasicBlock - The different EE's represent basic blocks in
268 /// different ways. Return the representation for a blockaddress of the
271 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
273 /// getPointerToFunctionOrStub - If the specified function has been
274 /// code-gen'd, return a pointer to the function. If not, compile it, or use
275 /// a stub to implement lazy compilation if available. See
276 /// getPointerToFunction for the requirements on destroying F.
278 virtual void *getPointerToFunctionOrStub(Function *F) {
279 // Default implementation, just codegen the function.
280 return getPointerToFunction(F);
283 // The JIT overrides a version that actually does this.
284 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
286 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
287 /// at the specified address.
289 const GlobalValue *getGlobalValueAtAddress(void *Addr);
292 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
294 void InitializeMemory(const Constant *Init, void *Addr);
296 /// recompileAndRelinkFunction - This method is used to force a function
297 /// which has already been compiled to be compiled again, possibly
298 /// after it has been modified. Then the entry to the old copy is overwritten
299 /// with a branch to the new copy. If there was no old copy, this acts
300 /// just like VM::getPointerToFunction().
302 virtual void *recompileAndRelinkFunction(Function *F) = 0;
304 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
305 /// corresponding to the machine code emitted to execute this function, useful
306 /// for garbage-collecting generated code.
308 virtual void freeMachineCodeForFunction(Function *F) = 0;
310 /// getOrEmitGlobalVariable - Return the address of the specified global
311 /// variable, possibly emitting it to memory if needed. This is used by the
313 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
314 return getPointerToGlobal((GlobalValue*)GV);
317 /// Registers a listener to be called back on various events within
318 /// the JIT. See JITEventListener.h for more details. Does not
319 /// take ownership of the argument. The argument may be NULL, in
320 /// which case these functions do nothing.
321 virtual void RegisterJITEventListener(JITEventListener *) {}
322 virtual void UnregisterJITEventListener(JITEventListener *) {}
324 /// DisableLazyCompilation - When lazy compilation is off (the default), the
325 /// JIT will eagerly compile every function reachable from the argument to
326 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
327 /// compile the one function and emit stubs to compile the rest when they're
328 /// first called. If lazy compilation is turned off again while some lazy
329 /// stubs are still around, and one of those stubs is called, the program will
332 /// In order to safely compile lazily in a threaded program, the user must
333 /// ensure that 1) only one thread at a time can call any particular lazy
334 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
335 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
336 /// lazy stub. See http://llvm.org/PR5184 for details.
337 void DisableLazyCompilation(bool Disabled = true) {
338 CompilingLazily = !Disabled;
340 bool isCompilingLazily() const {
341 return CompilingLazily;
343 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
344 // Remove this in LLVM 2.8.
345 bool isLazyCompilationDisabled() const {
346 return !CompilingLazily;
349 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
350 /// allocate space and populate a GlobalVariable that is not internal to
352 void DisableGVCompilation(bool Disabled = true) {
353 GVCompilationDisabled = Disabled;
355 bool isGVCompilationDisabled() const {
356 return GVCompilationDisabled;
359 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
360 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
361 /// resolve symbols in a custom way.
362 void DisableSymbolSearching(bool Disabled = true) {
363 SymbolSearchingDisabled = Disabled;
365 bool isSymbolSearchingDisabled() const {
366 return SymbolSearchingDisabled;
369 /// InstallLazyFunctionCreator - If an unknown function is needed, the
370 /// specified function pointer is invoked to create it. If it returns null,
371 /// the JIT will abort.
372 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
373 LazyFunctionCreator = P;
376 /// InstallExceptionTableRegister - The JIT will use the given function
377 /// to register the exception tables it generates.
378 void InstallExceptionTableRegister(EERegisterFn F) {
379 ExceptionTableRegister = F;
381 void InstallExceptionTableDeregister(EERegisterFn F) {
382 ExceptionTableDeregister = F;
385 /// RegisterTable - Registers the given pointer as an exception table. It uses
386 /// the ExceptionTableRegister function.
387 void RegisterTable(void* res) {
388 if (ExceptionTableRegister) {
389 ExceptionTableRegister(res);
390 AllExceptionTables.push_back(res);
394 /// DeregisterAllTables - Deregisters all previously registered pointers to an
395 /// exception tables. It uses the ExceptionTableoDeregister function.
396 void DeregisterAllTables();
399 explicit ExecutionEngine(Module *M);
403 // EmitGlobalVariable - This method emits the specified global variable to the
404 // address specified in GlobalAddresses, or allocates new memory if it's not
405 // already in the map.
406 void EmitGlobalVariable(const GlobalVariable *GV);
408 GenericValue getConstantValue(const Constant *C);
409 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
413 namespace EngineKind {
414 // These are actually bitmasks that get or-ed together.
419 const static Kind Either = (Kind)(JIT | Interpreter);
422 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
423 /// stack-allocating a builder, chaining the various set* methods, and
424 /// terminating it with a .create() call.
425 class EngineBuilder {
429 EngineKind::Kind WhichEngine;
430 std::string *ErrorStr;
431 CodeGenOpt::Level OptLevel;
432 JITMemoryManager *JMM;
433 bool AllocateGVsWithCode;
434 CodeModel::Model CMModel;
437 SmallVector<std::string, 4> MAttrs;
439 /// InitEngine - Does the common initialization of default options.
442 WhichEngine = EngineKind::Either;
444 OptLevel = CodeGenOpt::Default;
446 AllocateGVsWithCode = false;
447 CMModel = CodeModel::Default;
451 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
452 /// is successful, the created engine takes ownership of the module.
453 EngineBuilder(Module *m) : M(m) {
457 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
458 /// or whichever engine works. This option defaults to EngineKind::Either.
459 EngineBuilder &setEngineKind(EngineKind::Kind w) {
464 /// setJITMemoryManager - Sets the memory manager to use. This allows
465 /// clients to customize their memory allocation policies. If create() is
466 /// called and is successful, the created engine takes ownership of the
467 /// memory manager. This option defaults to NULL.
468 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
473 /// setErrorStr - Set the error string to write to on error. This option
474 /// defaults to NULL.
475 EngineBuilder &setErrorStr(std::string *e) {
480 /// setOptLevel - Set the optimization level for the JIT. This option
481 /// defaults to CodeGenOpt::Default.
482 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
487 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
488 /// data is using. Defaults to target specific default "CodeModel::Default".
489 EngineBuilder &setCodeModel(CodeModel::Model M) {
494 /// setAllocateGVsWithCode - Sets whether global values should be allocated
495 /// into the same buffer as code. For most applications this should be set
496 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
497 /// and is probably unsafe and bad for performance. However, we have clients
498 /// who depend on this behavior, so we must support it. This option defaults
499 /// to false so that users of the new API can safely use the new memory
500 /// manager and free machine code.
501 EngineBuilder &setAllocateGVsWithCode(bool a) {
502 AllocateGVsWithCode = a;
506 /// setMArch - Override the architecture set by the Module's triple.
507 EngineBuilder &setMArch(StringRef march) {
508 MArch.assign(march.begin(), march.end());
512 /// setMCPU - Target a specific cpu type.
513 EngineBuilder &setMCPU(StringRef mcpu) {
514 MCPU.assign(mcpu.begin(), mcpu.end());
518 /// setMAttrs - Set cpu-specific attributes.
519 template<typename StringSequence>
520 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
522 MAttrs.append(mattrs.begin(), mattrs.end());
526 ExecutionEngine *create();
529 } // End llvm namespace