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 /// \brief Helper class for helping synchronize access to the global address map
46 class ExecutionEngineState {
48 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
49 typedef ExecutionEngineState *ExtraData;
50 static sys::Mutex *getMutex(ExecutionEngineState *EES);
51 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
52 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
56 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
62 /// GlobalAddressMap - A mapping between LLVM global values and their
63 /// actualized version...
64 GlobalAddressMapTy GlobalAddressMap;
66 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
67 /// used to convert raw addresses into the LLVM global value that is emitted
68 /// at the address. This map is not computed unless getGlobalValueAtAddress
69 /// is called at some point.
70 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
73 ExecutionEngineState(ExecutionEngine &EE);
75 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
76 return GlobalAddressMap;
79 std::map<void*, AssertingVH<const GlobalValue> > &
80 getGlobalAddressReverseMap(const MutexGuard &) {
81 return GlobalAddressReverseMap;
84 /// \brief Erase an entry from the mapping table.
86 /// \returns The address that \arg ToUnmap was happed to.
87 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
90 /// \brief Abstract interface for implementation execution of LLVM modules,
91 /// designed to support both interpreter and just-in-time (JIT) compiler
93 class ExecutionEngine {
94 /// The state object holding the global address mapping, which must be
95 /// accessed synchronously.
97 // FIXME: There is no particular need the entire map needs to be
98 // synchronized. Wouldn't a reader-writer design be better here?
99 ExecutionEngineState EEState;
101 /// The target data for the platform for which execution is being performed.
102 const TargetData *TD;
104 /// Whether lazy JIT compilation is enabled.
105 bool CompilingLazily;
107 /// Whether JIT compilation of external global variables is allowed.
108 bool GVCompilationDisabled;
110 /// Whether the JIT should perform lookups of external symbols (e.g.,
112 bool SymbolSearchingDisabled;
114 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
117 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
118 /// optimize for the case where there is only one module.
119 SmallVector<Module*, 1> Modules;
121 void setTargetData(const TargetData *td) {
125 /// getMemoryforGV - Allocate memory for a global variable.
126 virtual char *getMemoryForGV(const GlobalVariable *GV);
128 // To avoid having libexecutionengine depend on the JIT and interpreter
129 // libraries, the JIT and Interpreter set these functions to ctor pointers at
130 // startup time if they are linked in.
131 static ExecutionEngine *(*JITCtor)(
133 std::string *ErrorStr,
134 JITMemoryManager *JMM,
135 CodeGenOpt::Level OptLevel,
137 CodeModel::Model CMM,
140 const SmallVectorImpl<std::string>& MAttrs);
141 static ExecutionEngine *(*InterpCtor)(Module *M,
142 std::string *ErrorStr);
144 /// LazyFunctionCreator - If an unknown function is needed, this function
145 /// pointer is invoked to create it. If this returns null, the JIT will
147 void *(*LazyFunctionCreator)(const std::string &);
149 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
150 /// register dwarf tables with this function.
151 typedef void (*EERegisterFn)(void*);
152 EERegisterFn ExceptionTableRegister;
153 EERegisterFn ExceptionTableDeregister;
154 std::vector<void*> AllExceptionTables;
157 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
158 /// JITEmitter classes. It must be held while changing the internal state of
159 /// any of those classes.
162 //===--------------------------------------------------------------------===//
163 // ExecutionEngine Startup
164 //===--------------------------------------------------------------------===//
166 virtual ~ExecutionEngine();
168 /// create - This is the factory method for creating an execution engine which
169 /// is appropriate for the current machine. This takes ownership of the
172 /// \param GVsWithCode - Allocating globals with code breaks
173 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
174 /// However, we have clients who depend on this behavior, so we must support
175 /// it. Eventually, when we're willing to break some backwards compatability,
176 /// this flag should be flipped to false, so that by default
177 /// freeMachineCodeForFunction works.
178 static ExecutionEngine *create(Module *M,
179 bool ForceInterpreter = false,
180 std::string *ErrorStr = 0,
181 CodeGenOpt::Level OptLevel =
183 bool GVsWithCode = true);
185 /// createJIT - This is the factory method for creating a JIT for the current
186 /// machine, it does not fall back to the interpreter. This takes ownership
187 /// of the Module and JITMemoryManager if successful.
189 /// Clients should make sure to initialize targets prior to calling this
191 static ExecutionEngine *createJIT(Module *M,
192 std::string *ErrorStr = 0,
193 JITMemoryManager *JMM = 0,
194 CodeGenOpt::Level OptLevel =
196 bool GVsWithCode = true,
197 CodeModel::Model CMM =
200 /// addModule - Add a Module to the list of modules that we can JIT from.
201 /// Note that this takes ownership of the Module: when the ExecutionEngine is
202 /// destroyed, it destroys the Module as well.
203 virtual void addModule(Module *M) {
204 Modules.push_back(M);
207 //===--------------------------------------------------------------------===//
209 const TargetData *getTargetData() const { return TD; }
211 /// removeModule - Remove a Module from the list of modules. Returns true if
213 virtual bool removeModule(Module *M);
215 /// FindFunctionNamed - Search all of the active modules to find the one that
216 /// defines FnName. This is very slow operation and shouldn't be used for
218 Function *FindFunctionNamed(const char *FnName);
220 /// runFunction - Execute the specified function with the specified arguments,
221 /// and return the result.
222 virtual GenericValue runFunction(Function *F,
223 const std::vector<GenericValue> &ArgValues) = 0;
225 /// runStaticConstructorsDestructors - This method is used to execute all of
226 /// the static constructors or destructors for a program.
228 /// \param isDtors - Run the destructors instead of constructors.
229 void runStaticConstructorsDestructors(bool isDtors);
231 /// runStaticConstructorsDestructors - This method is used to execute all of
232 /// the static constructors or destructors for a particular module.
234 /// \param isDtors - Run the destructors instead of constructors.
235 void runStaticConstructorsDestructors(Module *module, bool isDtors);
238 /// runFunctionAsMain - This is a helper function which wraps runFunction to
239 /// handle the common task of starting up main with the specified argc, argv,
240 /// and envp parameters.
241 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
242 const char * const * envp);
245 /// addGlobalMapping - Tell the execution engine that the specified global is
246 /// at the specified location. This is used internally as functions are JIT'd
247 /// and as global variables are laid out in memory. It can and should also be
248 /// used by clients of the EE that want to have an LLVM global overlay
249 /// existing data in memory. Mappings are automatically removed when their
250 /// GlobalValue is destroyed.
251 void addGlobalMapping(const GlobalValue *GV, void *Addr);
253 /// clearAllGlobalMappings - Clear all global mappings and start over again,
254 /// for use in dynamic compilation scenarios to move globals.
255 void clearAllGlobalMappings();
257 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
258 /// particular module, because it has been removed from the JIT.
259 void clearGlobalMappingsFromModule(Module *M);
261 /// updateGlobalMapping - Replace an existing mapping for GV with a new
262 /// address. This updates both maps as required. If "Addr" is null, the
263 /// entry for the global is removed from the mappings. This returns the old
264 /// value of the pointer, or null if it was not in the map.
265 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
267 /// getPointerToGlobalIfAvailable - This returns the address of the specified
268 /// global value if it is has already been codegen'd, otherwise it returns
270 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
272 /// getPointerToGlobal - This returns the address of the specified global
273 /// value. This may involve code generation if it's a function.
274 void *getPointerToGlobal(const GlobalValue *GV);
276 /// getPointerToFunction - The different EE's represent function bodies in
277 /// different ways. They should each implement this to say what a function
278 /// pointer should look like. When F is destroyed, the ExecutionEngine will
279 /// remove its global mapping and free any machine code. Be sure no threads
280 /// are running inside F when that happens.
281 virtual void *getPointerToFunction(Function *F) = 0;
283 /// getPointerToBasicBlock - The different EE's represent basic blocks in
284 /// different ways. Return the representation for a blockaddress of the
286 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
288 /// getPointerToFunctionOrStub - If the specified function has been
289 /// code-gen'd, return a pointer to the function. If not, compile it, or use
290 /// a stub to implement lazy compilation if available. See
291 /// getPointerToFunction for the requirements on destroying F.
292 virtual void *getPointerToFunctionOrStub(Function *F) {
293 // Default implementation, just codegen the function.
294 return getPointerToFunction(F);
297 // The JIT overrides a version that actually does this.
298 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
300 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
301 /// at the specified address.
303 const GlobalValue *getGlobalValueAtAddress(void *Addr);
305 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
306 /// Ptr is the address of the memory at which to store Val, cast to
307 /// GenericValue *. It is not a pointer to a GenericValue containing the
308 /// address at which to store Val.
309 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
312 void InitializeMemory(const Constant *Init, void *Addr);
314 /// recompileAndRelinkFunction - This method is used to force a function which
315 /// has already been compiled to be compiled again, possibly after it has been
316 /// modified. Then the entry to the old copy is overwritten with a branch to
317 /// the new copy. If there was no old copy, this acts just like
318 /// VM::getPointerToFunction().
319 virtual void *recompileAndRelinkFunction(Function *F) = 0;
321 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
322 /// corresponding to the machine code emitted to execute this function, useful
323 /// for garbage-collecting generated code.
324 virtual void freeMachineCodeForFunction(Function *F) = 0;
326 /// getOrEmitGlobalVariable - Return the address of the specified global
327 /// variable, possibly emitting it to memory if needed. This is used by the
329 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
330 return getPointerToGlobal((GlobalValue*)GV);
333 /// Registers a listener to be called back on various events within
334 /// the JIT. See JITEventListener.h for more details. Does not
335 /// take ownership of the argument. The argument may be NULL, in
336 /// which case these functions do nothing.
337 virtual void RegisterJITEventListener(JITEventListener *) {}
338 virtual void UnregisterJITEventListener(JITEventListener *) {}
340 /// DisableLazyCompilation - When lazy compilation is off (the default), the
341 /// JIT will eagerly compile every function reachable from the argument to
342 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
343 /// compile the one function and emit stubs to compile the rest when they're
344 /// first called. If lazy compilation is turned off again while some lazy
345 /// stubs are still around, and one of those stubs is called, the program will
348 /// In order to safely compile lazily in a threaded program, the user must
349 /// ensure that 1) only one thread at a time can call any particular lazy
350 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
351 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
352 /// lazy stub. See http://llvm.org/PR5184 for details.
353 void DisableLazyCompilation(bool Disabled = true) {
354 CompilingLazily = !Disabled;
356 bool isCompilingLazily() const {
357 return CompilingLazily;
359 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
360 // Remove this in LLVM 2.8.
361 bool isLazyCompilationDisabled() const {
362 return !CompilingLazily;
365 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
366 /// allocate space and populate a GlobalVariable that is not internal to
368 void DisableGVCompilation(bool Disabled = true) {
369 GVCompilationDisabled = Disabled;
371 bool isGVCompilationDisabled() const {
372 return GVCompilationDisabled;
375 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
376 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
377 /// resolve symbols in a custom way.
378 void DisableSymbolSearching(bool Disabled = true) {
379 SymbolSearchingDisabled = Disabled;
381 bool isSymbolSearchingDisabled() const {
382 return SymbolSearchingDisabled;
385 /// InstallLazyFunctionCreator - If an unknown function is needed, the
386 /// specified function pointer is invoked to create it. If it returns null,
387 /// the JIT will abort.
388 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
389 LazyFunctionCreator = P;
392 /// InstallExceptionTableRegister - The JIT will use the given function
393 /// to register the exception tables it generates.
394 void InstallExceptionTableRegister(EERegisterFn F) {
395 ExceptionTableRegister = F;
397 void InstallExceptionTableDeregister(EERegisterFn F) {
398 ExceptionTableDeregister = F;
401 /// RegisterTable - Registers the given pointer as an exception table. It
402 /// uses the ExceptionTableRegister function.
403 void RegisterTable(void* res) {
404 if (ExceptionTableRegister) {
405 ExceptionTableRegister(res);
406 AllExceptionTables.push_back(res);
410 /// DeregisterAllTables - Deregisters all previously registered pointers to an
411 /// exception tables. It uses the ExceptionTableoDeregister function.
412 void DeregisterAllTables();
415 explicit ExecutionEngine(Module *M);
419 void EmitGlobalVariable(const GlobalVariable *GV);
421 GenericValue getConstantValue(const Constant *C);
422 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
426 namespace EngineKind {
427 // These are actually bitmasks that get or-ed together.
432 const static Kind Either = (Kind)(JIT | Interpreter);
435 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
436 /// stack-allocating a builder, chaining the various set* methods, and
437 /// terminating it with a .create() call.
438 class EngineBuilder {
441 EngineKind::Kind WhichEngine;
442 std::string *ErrorStr;
443 CodeGenOpt::Level OptLevel;
444 JITMemoryManager *JMM;
445 bool AllocateGVsWithCode;
446 CodeModel::Model CMModel;
449 SmallVector<std::string, 4> MAttrs;
451 /// InitEngine - Does the common initialization of default options.
453 WhichEngine = EngineKind::Either;
455 OptLevel = CodeGenOpt::Default;
457 AllocateGVsWithCode = false;
458 CMModel = CodeModel::Default;
462 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
463 /// is successful, the created engine takes ownership of the module.
464 EngineBuilder(Module *m) : M(m) {
468 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
469 /// or whichever engine works. This option defaults to EngineKind::Either.
470 EngineBuilder &setEngineKind(EngineKind::Kind w) {
475 /// setJITMemoryManager - Sets the memory manager to use. This allows
476 /// clients to customize their memory allocation policies. If create() is
477 /// called and is successful, the created engine takes ownership of the
478 /// memory manager. This option defaults to NULL.
479 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
484 /// setErrorStr - Set the error string to write to on error. This option
485 /// defaults to NULL.
486 EngineBuilder &setErrorStr(std::string *e) {
491 /// setOptLevel - Set the optimization level for the JIT. This option
492 /// defaults to CodeGenOpt::Default.
493 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
498 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
499 /// data is using. Defaults to target specific default "CodeModel::Default".
500 EngineBuilder &setCodeModel(CodeModel::Model M) {
505 /// setAllocateGVsWithCode - Sets whether global values should be allocated
506 /// into the same buffer as code. For most applications this should be set
507 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
508 /// and is probably unsafe and bad for performance. However, we have clients
509 /// who depend on this behavior, so we must support it. This option defaults
510 /// to false so that users of the new API can safely use the new memory
511 /// manager and free machine code.
512 EngineBuilder &setAllocateGVsWithCode(bool a) {
513 AllocateGVsWithCode = a;
517 /// setMArch - Override the architecture set by the Module's triple.
518 EngineBuilder &setMArch(StringRef march) {
519 MArch.assign(march.begin(), march.end());
523 /// setMCPU - Target a specific cpu type.
524 EngineBuilder &setMCPU(StringRef mcpu) {
525 MCPU.assign(mcpu.begin(), mcpu.end());
529 /// setMAttrs - Set cpu-specific attributes.
530 template<typename StringSequence>
531 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
533 MAttrs.append(mattrs.begin(), mattrs.end());
537 ExecutionEngine *create();
540 } // End llvm namespace