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/ADT/DenseMap.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/Support/Mutex.h"
27 #include "llvm/Target/TargetMachine.h"
33 class ExecutionEngine;
37 class JITEventListener;
38 class JITMemoryManager;
39 class MachineCodeInfo;
45 /// \brief Helper class for helping synchronize access to the global address map
47 class ExecutionEngineState {
49 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
50 typedef ExecutionEngineState *ExtraData;
51 static sys::Mutex *getMutex(ExecutionEngineState *EES);
52 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
53 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
57 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
63 /// GlobalAddressMap - A mapping between LLVM global values and their
64 /// actualized version...
65 GlobalAddressMapTy GlobalAddressMap;
67 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
68 /// used to convert raw addresses into the LLVM global value that is emitted
69 /// at the address. This map is not computed unless getGlobalValueAtAddress
70 /// is called at some point.
71 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
74 ExecutionEngineState(ExecutionEngine &EE);
76 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
77 return GlobalAddressMap;
80 std::map<void*, AssertingVH<const GlobalValue> > &
81 getGlobalAddressReverseMap(const MutexGuard &) {
82 return GlobalAddressReverseMap;
85 /// \brief Erase an entry from the mapping table.
87 /// \returns The address that \arg ToUnmap was happed to.
88 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
91 /// \brief Abstract interface for implementation execution of LLVM modules,
92 /// designed to support both interpreter and just-in-time (JIT) compiler
94 class ExecutionEngine {
95 /// The state object holding the global address mapping, which must be
96 /// accessed synchronously.
98 // FIXME: There is no particular need the entire map needs to be
99 // synchronized. Wouldn't a reader-writer design be better here?
100 ExecutionEngineState EEState;
102 /// The target data for the platform for which execution is being performed.
103 const TargetData *TD;
105 /// Whether lazy JIT compilation is enabled.
106 bool CompilingLazily;
108 /// Whether JIT compilation of external global variables is allowed.
109 bool GVCompilationDisabled;
111 /// Whether the JIT should perform lookups of external symbols (e.g.,
113 bool SymbolSearchingDisabled;
115 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
118 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
119 /// optimize for the case where there is only one module.
120 SmallVector<Module*, 1> Modules;
122 void setTargetData(const TargetData *td) {
126 /// getMemoryforGV - Allocate memory for a global variable.
127 virtual char *getMemoryForGV(const GlobalVariable *GV);
129 // To avoid having libexecutionengine depend on the JIT and interpreter
130 // libraries, the execution engine implementations set these functions to ctor
131 // pointers at startup time if they are linked in.
132 static ExecutionEngine *(*JITCtor)(
134 std::string *ErrorStr,
135 JITMemoryManager *JMM,
136 CodeGenOpt::Level OptLevel,
139 static ExecutionEngine *(*MCJITCtor)(
141 std::string *ErrorStr,
142 JITMemoryManager *JMM,
143 CodeGenOpt::Level OptLevel,
146 static ExecutionEngine *(*InterpCtor)(Module *M,
147 std::string *ErrorStr);
149 /// LazyFunctionCreator - If an unknown function is needed, this function
150 /// pointer is invoked to create it. If this returns null, the JIT will
152 void *(*LazyFunctionCreator)(const std::string &);
154 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
155 /// register dwarf tables with this function.
156 typedef void (*EERegisterFn)(void*);
157 EERegisterFn ExceptionTableRegister;
158 EERegisterFn ExceptionTableDeregister;
159 /// This maps functions to their exception tables frames.
160 DenseMap<const Function*, void*> AllExceptionTables;
164 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
165 /// JITEmitter classes. It must be held while changing the internal state of
166 /// any of those classes.
169 //===--------------------------------------------------------------------===//
170 // ExecutionEngine Startup
171 //===--------------------------------------------------------------------===//
173 virtual ~ExecutionEngine();
175 /// create - This is the factory method for creating an execution engine which
176 /// is appropriate for the current machine. This takes ownership of the
179 /// \param GVsWithCode - Allocating globals with code breaks
180 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
181 /// However, we have clients who depend on this behavior, so we must support
182 /// it. Eventually, when we're willing to break some backwards compatibility,
183 /// this flag should be flipped to false, so that by default
184 /// freeMachineCodeForFunction works.
185 static ExecutionEngine *create(Module *M,
186 bool ForceInterpreter = false,
187 std::string *ErrorStr = 0,
188 CodeGenOpt::Level OptLevel =
190 bool GVsWithCode = true);
192 /// createJIT - This is the factory method for creating a JIT for the current
193 /// machine, it does not fall back to the interpreter. This takes ownership
194 /// of the Module and JITMemoryManager if successful.
196 /// Clients should make sure to initialize targets prior to calling this
198 static ExecutionEngine *createJIT(Module *M,
199 std::string *ErrorStr = 0,
200 JITMemoryManager *JMM = 0,
201 CodeGenOpt::Level OptLevel =
203 bool GVsWithCode = true,
204 CodeModel::Model CMM =
207 /// addModule - Add a Module to the list of modules that we can JIT from.
208 /// Note that this takes ownership of the Module: when the ExecutionEngine is
209 /// destroyed, it destroys the Module as well.
210 virtual void addModule(Module *M) {
211 Modules.push_back(M);
214 //===--------------------------------------------------------------------===//
216 const TargetData *getTargetData() const { return TD; }
218 /// removeModule - Remove a Module from the list of modules. Returns true if
220 virtual bool removeModule(Module *M);
222 /// FindFunctionNamed - Search all of the active modules to find the one that
223 /// defines FnName. This is very slow operation and shouldn't be used for
225 Function *FindFunctionNamed(const char *FnName);
227 /// runFunction - Execute the specified function with the specified arguments,
228 /// and return the result.
229 virtual GenericValue runFunction(Function *F,
230 const std::vector<GenericValue> &ArgValues) = 0;
232 /// runStaticConstructorsDestructors - This method is used to execute all of
233 /// the static constructors or destructors for a program.
235 /// \param isDtors - Run the destructors instead of constructors.
236 void runStaticConstructorsDestructors(bool isDtors);
238 /// runStaticConstructorsDestructors - This method is used to execute all of
239 /// the static constructors or destructors for a particular module.
241 /// \param isDtors - Run the destructors instead of constructors.
242 void runStaticConstructorsDestructors(Module *module, bool isDtors);
245 /// runFunctionAsMain - This is a helper function which wraps runFunction to
246 /// handle the common task of starting up main with the specified argc, argv,
247 /// and envp parameters.
248 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
249 const char * const * envp);
252 /// addGlobalMapping - Tell the execution engine that the specified global is
253 /// at the specified location. This is used internally as functions are JIT'd
254 /// and as global variables are laid out in memory. It can and should also be
255 /// used by clients of the EE that want to have an LLVM global overlay
256 /// existing data in memory. Mappings are automatically removed when their
257 /// GlobalValue is destroyed.
258 void addGlobalMapping(const GlobalValue *GV, void *Addr);
260 /// clearAllGlobalMappings - Clear all global mappings and start over again,
261 /// for use in dynamic compilation scenarios to move globals.
262 void clearAllGlobalMappings();
264 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
265 /// particular module, because it has been removed from the JIT.
266 void clearGlobalMappingsFromModule(Module *M);
268 /// updateGlobalMapping - Replace an existing mapping for GV with a new
269 /// address. This updates both maps as required. If "Addr" is null, the
270 /// entry for the global is removed from the mappings. This returns the old
271 /// value of the pointer, or null if it was not in the map.
272 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
274 /// getPointerToGlobalIfAvailable - This returns the address of the specified
275 /// global value if it is has already been codegen'd, otherwise it returns
277 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
279 /// getPointerToGlobal - This returns the address of the specified global
280 /// value. This may involve code generation if it's a function.
281 void *getPointerToGlobal(const GlobalValue *GV);
283 /// getPointerToFunction - The different EE's represent function bodies in
284 /// different ways. They should each implement this to say what a function
285 /// pointer should look like. When F is destroyed, the ExecutionEngine will
286 /// remove its global mapping and free any machine code. Be sure no threads
287 /// are running inside F when that happens.
288 virtual void *getPointerToFunction(Function *F) = 0;
290 /// getPointerToBasicBlock - The different EE's represent basic blocks in
291 /// different ways. Return the representation for a blockaddress of the
293 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
295 /// getPointerToFunctionOrStub - If the specified function has been
296 /// code-gen'd, return a pointer to the function. If not, compile it, or use
297 /// a stub to implement lazy compilation if available. See
298 /// getPointerToFunction for the requirements on destroying F.
299 virtual void *getPointerToFunctionOrStub(Function *F) {
300 // Default implementation, just codegen the function.
301 return getPointerToFunction(F);
304 // The JIT overrides a version that actually does this.
305 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
307 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
308 /// at the specified address.
310 const GlobalValue *getGlobalValueAtAddress(void *Addr);
312 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
313 /// Ptr is the address of the memory at which to store Val, cast to
314 /// GenericValue *. It is not a pointer to a GenericValue containing the
315 /// address at which to store Val.
316 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
319 void InitializeMemory(const Constant *Init, void *Addr);
321 /// recompileAndRelinkFunction - This method is used to force a function which
322 /// has already been compiled to be compiled again, possibly after it has been
323 /// modified. Then the entry to the old copy is overwritten with a branch to
324 /// the new copy. If there was no old copy, this acts just like
325 /// VM::getPointerToFunction().
326 virtual void *recompileAndRelinkFunction(Function *F) = 0;
328 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
329 /// corresponding to the machine code emitted to execute this function, useful
330 /// for garbage-collecting generated code.
331 virtual void freeMachineCodeForFunction(Function *F) = 0;
333 /// getOrEmitGlobalVariable - Return the address of the specified global
334 /// variable, possibly emitting it to memory if needed. This is used by the
336 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
337 return getPointerToGlobal((GlobalValue*)GV);
340 /// Registers a listener to be called back on various events within
341 /// the JIT. See JITEventListener.h for more details. Does not
342 /// take ownership of the argument. The argument may be NULL, in
343 /// which case these functions do nothing.
344 virtual void RegisterJITEventListener(JITEventListener *) {}
345 virtual void UnregisterJITEventListener(JITEventListener *) {}
347 /// DisableLazyCompilation - When lazy compilation is off (the default), the
348 /// JIT will eagerly compile every function reachable from the argument to
349 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
350 /// compile the one function and emit stubs to compile the rest when they're
351 /// first called. If lazy compilation is turned off again while some lazy
352 /// stubs are still around, and one of those stubs is called, the program will
355 /// In order to safely compile lazily in a threaded program, the user must
356 /// ensure that 1) only one thread at a time can call any particular lazy
357 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
358 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
359 /// lazy stub. See http://llvm.org/PR5184 for details.
360 void DisableLazyCompilation(bool Disabled = true) {
361 CompilingLazily = !Disabled;
363 bool isCompilingLazily() const {
364 return CompilingLazily;
366 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
367 // Remove this in LLVM 2.8.
368 bool isLazyCompilationDisabled() const {
369 return !CompilingLazily;
372 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
373 /// allocate space and populate a GlobalVariable that is not internal to
375 void DisableGVCompilation(bool Disabled = true) {
376 GVCompilationDisabled = Disabled;
378 bool isGVCompilationDisabled() const {
379 return GVCompilationDisabled;
382 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
383 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
384 /// resolve symbols in a custom way.
385 void DisableSymbolSearching(bool Disabled = true) {
386 SymbolSearchingDisabled = Disabled;
388 bool isSymbolSearchingDisabled() const {
389 return SymbolSearchingDisabled;
392 /// InstallLazyFunctionCreator - If an unknown function is needed, the
393 /// specified function pointer is invoked to create it. If it returns null,
394 /// the JIT will abort.
395 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
396 LazyFunctionCreator = P;
399 /// InstallExceptionTableRegister - The JIT will use the given function
400 /// to register the exception tables it generates.
401 void InstallExceptionTableRegister(EERegisterFn F) {
402 ExceptionTableRegister = F;
404 void InstallExceptionTableDeregister(EERegisterFn F) {
405 ExceptionTableDeregister = F;
408 /// RegisterTable - Registers the given pointer as an exception table. It
409 /// uses the ExceptionTableRegister function.
410 void RegisterTable(const Function *fn, void* res) {
411 if (ExceptionTableRegister) {
412 ExceptionTableRegister(res);
413 AllExceptionTables[fn] = res;
417 /// DeregisterTable - Deregisters the exception frame previously registered
418 /// for the given function.
419 void DeregisterTable(const Function *Fn) {
420 if (ExceptionTableDeregister) {
421 DenseMap<const Function*, void*>::iterator frame =
422 AllExceptionTables.find(Fn);
423 if(frame != AllExceptionTables.end()) {
424 ExceptionTableDeregister(frame->second);
425 AllExceptionTables.erase(frame);
430 /// DeregisterAllTables - Deregisters all previously registered pointers to an
431 /// exception tables. It uses the ExceptionTableoDeregister function.
432 void DeregisterAllTables();
435 explicit ExecutionEngine(Module *M);
439 void EmitGlobalVariable(const GlobalVariable *GV);
441 GenericValue getConstantValue(const Constant *C);
442 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
446 namespace EngineKind {
447 // These are actually bitmasks that get or-ed together.
452 const static Kind Either = (Kind)(JIT | Interpreter);
455 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
456 /// stack-allocating a builder, chaining the various set* methods, and
457 /// terminating it with a .create() call.
458 class EngineBuilder {
461 EngineKind::Kind WhichEngine;
462 std::string *ErrorStr;
463 CodeGenOpt::Level OptLevel;
464 JITMemoryManager *JMM;
465 bool AllocateGVsWithCode;
466 CodeModel::Model CMModel;
469 SmallVector<std::string, 4> MAttrs;
472 /// InitEngine - Does the common initialization of default options.
474 WhichEngine = EngineKind::Either;
476 OptLevel = CodeGenOpt::Default;
478 AllocateGVsWithCode = false;
479 CMModel = CodeModel::Default;
484 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
485 /// is successful, the created engine takes ownership of the module.
486 EngineBuilder(Module *m) : M(m) {
490 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
491 /// or whichever engine works. This option defaults to EngineKind::Either.
492 EngineBuilder &setEngineKind(EngineKind::Kind w) {
497 /// setJITMemoryManager - Sets the memory manager to use. This allows
498 /// clients to customize their memory allocation policies. If create() is
499 /// called and is successful, the created engine takes ownership of the
500 /// memory manager. This option defaults to NULL.
501 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
506 /// setErrorStr - Set the error string to write to on error. This option
507 /// defaults to NULL.
508 EngineBuilder &setErrorStr(std::string *e) {
513 /// setOptLevel - Set the optimization level for the JIT. This option
514 /// defaults to CodeGenOpt::Default.
515 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
520 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
521 /// data is using. Defaults to target specific default "CodeModel::Default".
522 EngineBuilder &setCodeModel(CodeModel::Model M) {
527 /// setAllocateGVsWithCode - Sets whether global values should be allocated
528 /// into the same buffer as code. For most applications this should be set
529 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
530 /// and is probably unsafe and bad for performance. However, we have clients
531 /// who depend on this behavior, so we must support it. This option defaults
532 /// to false so that users of the new API can safely use the new memory
533 /// manager and free machine code.
534 EngineBuilder &setAllocateGVsWithCode(bool a) {
535 AllocateGVsWithCode = a;
539 /// setMArch - Override the architecture set by the Module's triple.
540 EngineBuilder &setMArch(StringRef march) {
541 MArch.assign(march.begin(), march.end());
545 /// setMCPU - Target a specific cpu type.
546 EngineBuilder &setMCPU(StringRef mcpu) {
547 MCPU.assign(mcpu.begin(), mcpu.end());
551 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
553 EngineBuilder &setUseMCJIT(bool Value) {
558 /// setMAttrs - Set cpu-specific attributes.
559 template<typename StringSequence>
560 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
562 MAttrs.append(mattrs.begin(), mattrs.end());
566 /// selectTarget - Pick a target either via -march or by guessing the native
567 /// arch. Add any CPU features specified via -mcpu or -mattr.
568 static TargetMachine *selectTarget(Module *M,
571 const SmallVectorImpl<std::string>& MAttrs,
574 ExecutionEngine *create();
577 } // End llvm namespace